@classytic/notifications 2.5.0 → 2.7.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,66 @@
2
2
 
3
3
  All notable changes to `@classytic/notifications` will be documented in this file.
4
4
 
5
+ ## [2.7.0] — 2026-10-18
6
+
7
+ ### Added — push delivery hints: `collapseKey`, `threadId`, `badge`
8
+
9
+ `PushProvider.send` receives three optional fields, read by `PushChannel` from the payload data
10
+ (`data.collapseKey`, `data.threadId`, `data.badge`): a replace-in-place key (a newer push with the
11
+ same key replaces the older one instead of stacking; FCM `android.collapseKey` + `notification.tag`,
12
+ APNs `apns-collapse-id`), a tray grouping id (APNs `thread-id`), and the app badge count. Only
13
+ well-typed values are forwarded (non-empty strings, a non-negative integer badge). Additive:
14
+ providers that ignore them deliver as before.
15
+
16
+ ### Added — atomic idempotency claims + `RedisIdempotencyStore`
17
+
18
+ `IdempotencyStore` gains an optional `claim(key, leaseMs)` / `release(key)` pair. When the
19
+ store has it, `NotificationService` claims the key before delivery instead of `has()`, so
20
+ concurrent or redelivered sends with the same `idempotencyKey` deliver once, across
21
+ processes. Success upgrades the claim to the full `ttl`; zero sent (or a thrown pipeline
22
+ error) releases it so a retry can deliver. New `idempotency.leaseMs` (default 5 min) bounds
23
+ how long a crashed sender holds a key. `MemoryIdempotencyStore` implements the pair, so
24
+ in-process concurrent duplicates are now also deduplicated. Stores without `claim` keep
25
+ the old `has` / `set` behaviour.
26
+
27
+ `RedisIdempotencyStore({ client, prefix? })` is `SET NX PX` over a structurally typed
28
+ client (`RedisIdempotencyClient`); ioredis fits as is, no Redis dependency.
29
+
30
+ ### Added — `PermanentDeliveryError` for push providers
31
+
32
+ A `PushProvider` can throw `PermanentDeliveryError` (or any error with `retryable: false`) for a
33
+ failure no retry fixes, such as an unregistered device token. `PushChannel` then returns `failed`
34
+ with `retryable: false` instead of throwing a `ChannelError`.
35
+
36
+ ### Fixed — `retryable: false` results were still retried
37
+
38
+ The service turned a non-retryable result into a sentinel error, but `withRetry` retried every
39
+ error, so a hard failure still used all `maxAttempts` (with backoff) before being reported.
40
+ `withRetry` takes an optional `shouldRetry(error)` (additive fourth argument) and the service
41
+ uses it, so non-retryable results stop after the first attempt.
42
+
43
+ ### Fixed — channels assignable to `Channel` under `exactOptionalPropertyTypes`
44
+
45
+ `Channel.rateLimit` / `Channel.retry` are now `?: T | undefined`, matching `BaseChannel`'s
46
+ getters. Strict hosts no longer need `as Channel` on `new PushChannel(...)` (or any built-in
47
+ channel). Guarded by `tests/types/channel-contract.ts`, compiled with
48
+ `exactOptionalPropertyTypes: true` against the built declarations in `npm run typecheck`.
49
+
50
+ ## [2.6.0] — 2026-10-09
51
+
52
+ ### Added — `TelegramChannel`
53
+
54
+ A Bot API channel over native `fetch`, no dependency. Sends to `recipient.telegramChatId`
55
+ (new optional field on `Recipient`), else the channel's default `chatId`. Text comes from
56
+ `data.text` / `data.message` / `data.subject`, like `SmsChannel`, with the same `canSend`
57
+ pre-check, so a payload with no destination or no text is skipped before it spends a
58
+ rate-limit token.
59
+
60
+ Failures are classified: a Bot API refusal (bad token, unknown chat, bot removed) returns
61
+ `failed` with `retryable: false`; 429, 5xx and network errors throw a `ChannelError`, which
62
+ the service retries. The token is part of the request URL, so no error message includes the
63
+ URL. `providerMessageId` is Telegram's `message_id`.
64
+
5
65
  ## [2.5.0] — 2026-08-26
6
66
 
7
67
  ### Fixed — send-failure log now walks the `cause` chain
package/README.md CHANGED
@@ -236,6 +236,26 @@ const snsSms = new SmsChannel({
236
236
  });
237
237
  ```
238
238
 
239
+ ### TelegramChannel
240
+
241
+ Bot API over `fetch`, no SDK. Messages go to `recipient.telegramChatId`, else the channel's
242
+ default `chatId` (usually a team group), so it suits a team's own alerts.
243
+
244
+ ```typescript
245
+ import { TelegramChannel } from '@classytic/notifications/channels';
246
+
247
+ new TelegramChannel({
248
+ botToken: process.env.TELEGRAM_BOT_TOKEN!, // from @BotFather
249
+ chatId: process.env.TELEGRAM_CHAT_ID!, // e.g. -1001234567890 for a group
250
+ events: ['order.placed'],
251
+ parseMode: 'HTML', // optional
252
+ });
253
+ ```
254
+
255
+ Text comes from `data.text`, `data.message` or `data.subject`. A refusal (bad token,
256
+ unknown chat, bot removed from the group) fails without retry; a rate limit, a server
257
+ error or a network failure is retried. The token never appears in an error.
258
+
239
259
  ### PushChannel (BYOP)
240
260
 
241
261
  Zero dependencies — bring your own push SDK.
@@ -589,21 +609,31 @@ await notifications.send({
589
609
  });
590
610
  ```
591
611
 
592
- For distributed systems, implement `IdempotencyStore` with Redis:
612
+ For multiple processes or replicas use the built-in `RedisIdempotencyStore`. It
613
+ claims each key atomically (`SET key 1 PX lease NX`) before delivery, so a redelivered
614
+ event sends once across restarts and replicas. On success the key gets the full `ttl`;
615
+ if nothing was sent (or the pipeline threw) the claim is released so a retry can deliver.
616
+ A crashed sender holds the key only for `leaseMs`. The client is typed structurally
617
+ (no Redis dependency): ioredis fits as is.
593
618
 
594
619
  ```typescript
595
- import type { IdempotencyStore } from '@classytic/notifications/utils';
620
+ import { Redis } from 'ioredis';
621
+ import { NotificationService, RedisIdempotencyStore } from '@classytic/notifications';
596
622
 
597
- class RedisIdempotencyStore implements IdempotencyStore {
598
- async has(key: string): Promise<boolean> {
599
- return !!(await redis.exists(`idemp:${key}`));
600
- }
601
- async set(key: string, ttlMs: number): Promise<void> {
602
- await redis.set(`idemp:${key}`, '1', 'PX', ttlMs);
603
- }
604
- }
623
+ const notifications = new NotificationService({
624
+ channels: [...],
625
+ idempotency: {
626
+ store: new RedisIdempotencyStore({ client: new Redis(process.env.REDIS_URL!), prefix: 'notif:idem:' }),
627
+ ttl: 24 * 60 * 60 * 1000, // remembered after a successful send
628
+ leaseMs: 5 * 60 * 1000, // in-flight claim (default)
629
+ },
630
+ });
605
631
  ```
606
632
 
633
+ A custom `IdempotencyStore` gets the same guarantee by implementing the optional
634
+ `claim(key, leaseMs)` / `release(key)` pair; stores with only `has` / `set` keep the
635
+ previous check-then-record behaviour (fine in one process, racy across several).
636
+
607
637
  ## Batch Sending
608
638
 
609
639
  Send thousands of notifications with controlled concurrency:
@@ -689,7 +719,7 @@ emitter.on('user.created', hooks['user.created'][0]);
689
719
  | `RateLimitStore` | Rate limit state | `MemoryRateLimitStore` |
690
720
  | `DeliveryLog` | Audit trail | `MemoryDeliveryLog` |
691
721
  | `QueueAdapter` | Crash-resilient queue | `MemoryQueue` |
692
- | `IdempotencyStore` | Deduplication | `MemoryIdempotencyStore` |
722
+ | `IdempotencyStore` | Deduplication | `MemoryIdempotencyStore` (`RedisIdempotencyStore` for multi-process) |
693
723
  | `PreferenceResolver` | User preference filtering | — (BYOP) |
694
724
 
695
725
  ### Exports
@@ -1,2 +1,2 @@
1
- import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "../push.channel-1tNMyaXl.mjs";
2
- export { BaseChannel, ConsoleChannel, EmailChannel, PushChannel, SmsChannel, WebhookChannel };
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
+ export { BaseChannel, ConsoleChannel, EmailChannel, PushChannel, SmsChannel, TelegramChannel, WebhookChannel };
@@ -1,3 +1,3 @@
1
- import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "../push.channel-BkgxUc82.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
- export { BaseChannel, ConsoleChannel, EmailChannel, PushChannel, SmsChannel, WebhookChannel };
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 TemplateResult, B as DeliveryLogQuery, C as RetryConfig, D as SmsProvider, E as SmsChannelConfig, F as QueueJob, G as MemoryRateLimitStore, H as IDEMPOTENCY_DEFAULT_TTL, I as QueueJobStatus, K as RateLimitConfig, L as QueueProcessor, M as MemoryQueue, N as QueueAdapter, O as SmtpTransportOptions, P as QueueEnqueueOptions, R as DeliveryLog, S as ResolvedRetryConfig, T as ServiceEvent, U as IdempotencyStore, V as MemoryDeliveryLog, W as MemoryIdempotencyStore, _ 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 WebhookChannelConfig, k as TemplateResolver, l as EventHandler, m as NotificationHookConfig, n as BatchProgress, o as DispatchResult, p as NodemailerTransporter, q as RateLimitStore, 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 DeliveryLogEntry } from "./types-DkFudalo.mjs";
2
- import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "./push.channel-1tNMyaXl.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-CuCdFeVN.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, 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 EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "./push.channel-BkgxUc82.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) {
@@ -508,7 +531,7 @@ var NotificationService = class {
508
531
  * Zero required dependencies - bring your own providers.
509
532
  *
510
533
  * v2: Rate limiting, delivery tracking, queue adapter,
511
- * BCC batching, template engines, SMS & push channels.
534
+ * BCC batching, template engines, SMS, push and Telegram channels.
512
535
  *
513
536
  * @module @classytic/notifications
514
537
  * @author Classytic (https://github.com/classytic)
@@ -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, 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 };
@@ -48,9 +48,9 @@ interface EmailPreset {
48
48
  /** Setup instructions surfaced in the Integrations UI. */
49
49
  setupHint: string;
50
50
  }
51
- declare const EMAIL_PRESETS: Record<EmailProviderName, EmailPreset>;
51
+ export declare const EMAIL_PRESETS: Record<EmailProviderName, EmailPreset>;
52
52
  /** Convenience dropdown options for the credential UI. */
53
- declare const EMAIL_PROVIDER_OPTIONS: {
53
+ export declare const EMAIL_PROVIDER_OPTIONS: {
54
54
  value: EmailProviderName;
55
55
  label: string;
56
56
  }[];
@@ -81,13 +81,13 @@ interface EmailCredentialData {
81
81
  * @throws `Error` when required fields are missing for the chosen provider.
82
82
  * @throws `Error` when `nodemailer` is not installed (optional peer).
83
83
  */
84
- declare function buildEmailTransport(data: EmailCredentialData): Promise<Transporter>;
84
+ export declare function buildEmailTransport(data: EmailCredentialData): Promise<Transporter>;
85
85
  /**
86
86
  * Compose the RFC-5322 `From` header value from the credential blob.
87
87
  * Returns `"Display Name" <email@example.com>` when `fromName` is set,
88
88
  * otherwise just `email@example.com`.
89
89
  */
90
- declare function buildFromHeader(data: EmailCredentialData): string;
90
+ export declare function buildFromHeader(data: EmailCredentialData): string;
91
91
  //#endregion
92
92
  //#region src/providers/email/schema.d.ts
93
93
  /**
@@ -117,7 +117,7 @@ interface EmailCredentialField {
117
117
  }
118
118
  /** Union-of-fields schema — every field appears; the UI hides what's
119
119
  * not relevant for the chosen `provider`. */
120
- declare function getEmailCredentialSchema(): EmailCredentialField[];
120
+ export declare function getEmailCredentialSchema(): EmailCredentialField[];
121
121
  //#endregion
122
122
  //#region src/providers/email/test.d.ts
123
123
  type EmailTestStatus = 'OK' | 'Error';
@@ -130,6 +130,6 @@ interface EmailTestResult {
130
130
  fromEmail: string;
131
131
  };
132
132
  }
133
- declare function testEmailCredential(data: EmailCredentialData): Promise<EmailTestResult>;
133
+ export declare function testEmailCredential(data: EmailCredentialData): Promise<EmailTestResult>;
134
134
  //#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 };
135
+ export type { EmailCredentialData, EmailCredentialField, EmailCredentialFieldType, EmailPreset, EmailProviderName, EmailTestResult, EmailTestStatus };
@@ -1,4 +1,4 @@
1
- import { C as RetryConfig, S as ResolvedRetryConfig, d as HookMap, h as NotificationPayload, k as TemplateResolver, o as DispatchResult, u as HookHandler } from "./types-DkFudalo.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, K as RateLimitConfig, a as ChannelConfig, c as EmailChannelConfig, h as NotificationPayload, i as Channel, j as WebhookChannelConfig, w as SendResult, y as PushChannelConfig } from "./types-DkFudalo.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;
@@ -73,4 +73,17 @@ declare class PushChannel extends BaseChannel<PushChannelConfig> {
73
73
  send(payload: NotificationPayload): Promise<SendResult>;
74
74
  }
75
75
  //#endregion
76
- export { EmailChannel as a, WebhookChannel as i, SmsChannel as n, BaseChannel as o, ConsoleChannel as r, PushChannel as t };
76
+ //#region src/channels/telegram.channel.d.ts
77
+ declare class TelegramChannel extends BaseChannel<TelegramChannelConfig> {
78
+ constructor(config: TelegramChannelConfig);
79
+ private destinationOf;
80
+ private textOf;
81
+ /**
82
+ * Deterministic skips, checked before the service spends a rate-limit token:
83
+ * nowhere to send, or nothing to say.
84
+ */
85
+ canSend(payload: NotificationPayload): SendResult | null;
86
+ send(payload: NotificationPayload): Promise<SendResult>;
87
+ }
88
+ //#endregion
89
+ export { WebhookChannel as a, ConsoleChannel as i, PushChannel as n, EmailChannel as o, SmsChannel as r, BaseChannel as s, TelegramChannel as t };
@@ -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,10 +591,123 @@ 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
  }
591
603
  };
592
604
 
593
605
  //#endregion
594
- export { EmailChannel as a, WebhookChannel as i, SmsChannel as n, BaseChannel as o, ConsoleChannel as r, PushChannel as t };
606
+ //#region src/channels/telegram.channel.ts
607
+ /**
608
+ * Telegram Channel
609
+ * @module @classytic/notifications
610
+ *
611
+ * Sends a text message through the Telegram Bot API. Zero dependencies: one
612
+ * `fetch` to `sendMessage`.
613
+ *
614
+ * Telegram is the simple messaging case: no template approval, no service
615
+ * window, no business verification. A bot may message any chat it has been
616
+ * added to, immediately, which makes it the natural channel for a team's own
617
+ * alerts ("a new order is waiting for confirmation").
618
+ *
619
+ * ## Where a message goes
620
+ *
621
+ * `recipient.telegramChatId` when the recipient has one, else the channel's
622
+ * default `chatId` (typically the team's group). Telegram addresses chats by
623
+ * numeric id or `@channelname`; there is no phone-to-chat lookup, so a phone
624
+ * number is never used as a destination.
625
+ *
626
+ * @example
627
+ * ```typescript
628
+ * import { TelegramChannel } from '@classytic/notifications/channels';
629
+ *
630
+ * const ops = new TelegramChannel({
631
+ * botToken: process.env.TELEGRAM_BOT_TOKEN!,
632
+ * chatId: process.env.TELEGRAM_CHAT_ID!, // the team group
633
+ * events: ['order.placed'],
634
+ * });
635
+ * ```
636
+ */
637
+ const DEFAULT_API = "https://api.telegram.org";
638
+ var TelegramChannel = class extends BaseChannel {
639
+ constructor(config) {
640
+ if (!config.botToken) throw new ChannelError(config.name ?? "telegram", "TelegramChannel requires a botToken.");
641
+ super({
642
+ name: "telegram",
643
+ ...config
644
+ });
645
+ }
646
+ destinationOf(payload) {
647
+ return payload.recipient.telegramChatId || this.config.chatId || void 0;
648
+ }
649
+ textOf(payload) {
650
+ const { data } = payload;
651
+ return data.text ?? data.message ?? data.subject ?? "";
652
+ }
653
+ /**
654
+ * Deterministic skips, checked before the service spends a rate-limit token:
655
+ * nowhere to send, or nothing to say.
656
+ */
657
+ canSend(payload) {
658
+ if (!this.destinationOf(payload)) return {
659
+ status: "skipped",
660
+ channel: this.name,
661
+ error: "No Telegram chat id (recipient.telegramChatId or the channel chatId)"
662
+ };
663
+ if (!this.textOf(payload)) return {
664
+ status: "skipped",
665
+ channel: this.name,
666
+ error: "No message body (data.text, data.message, or data.subject)"
667
+ };
668
+ return null;
669
+ }
670
+ async send(payload) {
671
+ const skip = this.canSend(payload);
672
+ if (skip) return skip;
673
+ const body = {
674
+ chat_id: this.destinationOf(payload),
675
+ text: this.textOf(payload),
676
+ ...this.config.parseMode ? { parse_mode: this.config.parseMode } : {},
677
+ ...this.config.silent ? { disable_notification: true } : {},
678
+ link_preview_options: { is_disabled: true }
679
+ };
680
+ let response;
681
+ try {
682
+ response = await fetch(`${this.config.apiBaseUrl ?? DEFAULT_API}/bot${this.config.botToken}/sendMessage`, {
683
+ method: "POST",
684
+ headers: { "Content-Type": "application/json" },
685
+ body: JSON.stringify(body),
686
+ signal: AbortSignal.timeout(this.config.timeout ?? 1e4)
687
+ });
688
+ } catch (err) {
689
+ const message = err instanceof Error ? err.message : String(err);
690
+ throw new ChannelError(this.name, `Telegram unreachable: ${message}`, err instanceof Error ? err : void 0);
691
+ }
692
+ const json = await response.json().catch(() => ({}));
693
+ if (response.ok && json.ok) {
694
+ const id = json.result?.message_id;
695
+ return {
696
+ status: "sent",
697
+ channel: this.name,
698
+ ...id !== void 0 ? { providerMessageId: String(id) } : {}
699
+ };
700
+ }
701
+ const reason = `Telegram ${response.status}: ${json.description ?? response.statusText}`;
702
+ if (response.status === 429 || response.status >= 500) throw new ChannelError(this.name, reason);
703
+ return {
704
+ status: "failed",
705
+ channel: this.name,
706
+ error: reason,
707
+ retryable: false
708
+ };
709
+ }
710
+ };
711
+
712
+ //#endregion
713
+ export { WebhookChannel as a, ConsoleChannel as i, PushChannel as n, EmailChannel as o, SmsChannel as r, BaseChannel as s, TelegramChannel as t };
@@ -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 */
@@ -336,6 +379,8 @@ interface Recipient {
336
379
  phone?: string;
337
380
  name?: string;
338
381
  deviceToken?: string;
382
+ /** Telegram chat id (numeric, or `@channelname`) — `TelegramChannel`'s destination. */
383
+ telegramChatId?: string;
339
384
  metadata?: Record<string, unknown>;
340
385
  }
341
386
  /** Notification payload sent through the service */
@@ -468,13 +513,13 @@ interface Channel {
468
513
  * implement `Channel` directly should surface it here so the service
469
514
  * applies the limit (otherwise the channel is treated as unlimited).
470
515
  */
471
- readonly rateLimit?: RateLimitConfig;
516
+ readonly rateLimit?: RateLimitConfig | undefined;
472
517
  /**
473
518
  * Optional per-channel retry override, read by the service. When unset the
474
519
  * service's global retry config applies. `BaseChannel` exposes this from
475
520
  * `config.retry`.
476
521
  */
477
- readonly retry?: RetryConfig;
522
+ readonly retry?: RetryConfig | undefined;
478
523
  shouldHandle(event: string): boolean;
479
524
  send(payload: NotificationPayload): Promise<SendResult>;
480
525
  /**
@@ -574,6 +619,21 @@ interface WebhookChannelConfig extends ChannelConfig {
574
619
  /** Request timeout in ms (default: 10000) */
575
620
  timeout?: number;
576
621
  }
622
+ /** TelegramChannel configuration — Bot API, no SDK. */
623
+ interface TelegramChannelConfig extends ChannelConfig {
624
+ /** The bot's token from @BotFather. Secret: it never appears in an error. */
625
+ botToken: string;
626
+ /** Default chat (a group id like `-1001234567890`, or `@channel`) when the recipient has none. */
627
+ chatId?: string;
628
+ /** Telegram formatting for `text`. Omit for plain text. */
629
+ parseMode?: 'HTML' | 'MarkdownV2';
630
+ /** Deliver without a notification sound. */
631
+ silent?: boolean;
632
+ /** Request timeout in ms (default: 10000) */
633
+ timeout?: number;
634
+ /** Bot API origin (default `https://api.telegram.org`); for a local Bot API server or tests. */
635
+ apiBaseUrl?: string;
636
+ }
577
637
  /** SMS provider interface (Twilio or custom) */
578
638
  interface SmsProvider {
579
639
  send(message: {
@@ -591,7 +651,11 @@ interface SmsChannelConfig extends ChannelConfig {
591
651
  /** SMS provider implementation (Twilio, SNS, Vonage, etc.) */
592
652
  provider: SmsProvider;
593
653
  }
594
- /** 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
+ */
595
659
  interface PushProvider {
596
660
  send(message: {
597
661
  token: string;
@@ -599,6 +663,16 @@ interface PushProvider {
599
663
  body: string;
600
664
  data?: Record<string, string>;
601
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;
602
676
  }): Promise<{
603
677
  messageId: string;
604
678
  }>;
@@ -681,6 +755,8 @@ interface NotificationServiceConfig {
681
755
  store?: IdempotencyStore;
682
756
  /** TTL in milliseconds (default: 86400000 = 24h) */
683
757
  ttl?: number;
758
+ /** In-flight lease for stores with an atomic `claim()` (default: 300000 = 5 min) */
759
+ leaseMs?: number;
684
760
  };
685
761
  /** Delivery log for audit trail — records every send attempt */
686
762
  deliveryLog?: DeliveryLog;
@@ -758,4 +834,4 @@ interface BatchResult {
758
834
  results: DispatchResult[];
759
835
  }
760
836
  //#endregion
761
- export { TemplateResult as A, DeliveryLogQuery as B, RetryConfig as C, SmsProvider as D, SmsChannelConfig as E, QueueJob as F, MemoryRateLimitStore as G, IDEMPOTENCY_DEFAULT_TTL as H, QueueJobStatus as I, RateLimitConfig as K, QueueProcessor as L, MemoryQueue as M, QueueAdapter as N, SmtpTransportOptions as O, QueueEnqueueOptions as P, DeliveryLog as R, ResolvedRetryConfig as S, ServiceEvent as T, IdempotencyStore as U, MemoryDeliveryLog as V, MemoryIdempotencyStore 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, WebhookChannelConfig as j, TemplateResolver as k, EventHandler as l, NotificationHookConfig as m, BatchProgress as n, DispatchResult as o, NodemailerTransporter as p, RateLimitStore 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, DeliveryLogEntry 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 DeliveryLogQuery, F as QueueJob, G as MemoryRateLimitStore, H as IDEMPOTENCY_DEFAULT_TTL, I as QueueJobStatus, K as RateLimitConfig, L as QueueProcessor, M as MemoryQueue, N as QueueAdapter, P as QueueEnqueueOptions, R as DeliveryLog, U as IdempotencyStore, V as MemoryDeliveryLog, W as MemoryIdempotencyStore, q as RateLimitStore, z as DeliveryLogEntry } from "../types-DkFudalo.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-CuCdFeVN.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,117 +1,119 @@
1
- {
2
- "name": "@classytic/notifications",
3
- "version": "2.5.0",
4
- "description": "Multi-channel notifications (Email, SMS, Push, Webhook) with rate limiting, delivery tracking, queue adapters, channel fallback, templates, retry — zero required dependencies",
5
- "type": "module",
6
- "sideEffects": false,
7
- "main": "./dist/index.mjs",
8
- "module": "./dist/index.mjs",
9
- "types": "./dist/index.d.mts",
10
- "exports": {
11
- ".": {
12
- "types": "./dist/index.d.mts",
13
- "default": "./dist/index.mjs"
14
- },
15
- "./channels": {
16
- "types": "./dist/channels/index.d.mts",
17
- "default": "./dist/channels/index.mjs"
18
- },
19
- "./providers": {
20
- "types": "./dist/providers/index.d.mts",
21
- "default": "./dist/providers/index.mjs"
22
- },
23
- "./utils": {
24
- "types": "./dist/utils/index.d.mts",
25
- "default": "./dist/utils/index.mjs"
26
- }
27
- },
28
- "typesVersions": {
29
- "*": {
30
- "channels": ["./dist/channels/index.d.mts"],
31
- "providers": ["./dist/providers/index.d.mts"],
32
- "utils": ["./dist/utils/index.d.mts"]
33
- }
34
- },
35
- "files": [
36
- "dist",
37
- "README.md",
38
- "CHANGELOG.md",
39
- "LICENSE"
40
- ],
41
- "keywords": [
42
- "notifications",
43
- "multi-channel",
44
- "email",
45
- "sms",
46
- "push-notifications",
47
- "webhook",
48
- "nodemailer",
49
- "smtp",
50
- "ses",
51
- "rate-limiting",
52
- "delivery-tracking",
53
- "queue",
54
- "channel-fallback",
55
- "templates",
56
- "retry",
57
- "idempotency",
58
- "pluggable",
59
- "framework-agnostic",
60
- "typescript",
61
- "zero-dependencies"
62
- ],
63
- "author": "Classytic <classytic.dev@gmail.com> (https://github.com/classytic)",
64
- "contributors": [
65
- "Sadman Chowdhury (https://github.com/siam923)"
66
- ],
67
- "license": "MIT",
68
- "publishConfig": {
69
- "access": "public"
70
- },
71
- "repository": {
72
- "type": "git",
73
- "url": "git+https://github.com/classytic/notifications.git"
74
- },
75
- "bugs": {
76
- "url": "https://github.com/classytic/notifications/issues"
77
- },
78
- "homepage": "https://github.com/classytic/notifications#readme",
79
- "peerDependencies": {
80
- "nodemailer": ">=6"
81
- },
82
- "peerDependenciesMeta": {
83
- "nodemailer": {
84
- "optional": true
85
- }
86
- },
87
- "engines": {
88
- "node": ">=18"
89
- },
90
- "scripts": {
91
- "build": "tsdown",
92
- "dev": "tsdown --watch",
93
- "test": "vitest run",
94
- "test:watch": "vitest",
95
- "test:coverage": "vitest run --coverage",
96
- "test:live": "vitest run --config vitest.live.config.ts",
97
- "typecheck": "tsc --noEmit",
98
- "prepublishOnly": "npm run build && npm run typecheck && npm test",
99
- "push": "classytic-push",
100
- "publish:dry": "npm publish --dry-run --access public",
101
- "publish:npm": "npm publish --access public",
102
- "release": "npm run build && npm run typecheck && npm test && npm publish --access public",
103
- "release:patch": "npm version patch && npm run release",
104
- "release:minor": "npm version minor && npm run release",
105
- "release:major": "npm version major && npm run release"
106
- },
107
- "devDependencies": {
108
- "@classytic/dev-tools": "^0.2.0",
109
- "@types/node": "^22.0.0",
110
- "@types/nodemailer": "^8.0.0",
111
- "@vitest/coverage-v8": "4.1.8",
112
- "nodemailer": "^8.0.10",
113
- "tsdown": "^0.22.14",
114
- "typescript": "^6.0.3",
115
- "vitest": "^4.1.8"
116
- }
117
- }
1
+ {
2
+ "name": "@classytic/notifications",
3
+ "version": "2.7.0",
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
+ "type": "module",
6
+ "sideEffects": false,
7
+ "main": "./dist/index.mjs",
8
+ "module": "./dist/index.mjs",
9
+ "types": "./dist/index.d.mts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.mts",
13
+ "default": "./dist/index.mjs"
14
+ },
15
+ "./channels": {
16
+ "types": "./dist/channels/index.d.mts",
17
+ "default": "./dist/channels/index.mjs"
18
+ },
19
+ "./providers": {
20
+ "types": "./dist/providers/index.d.mts",
21
+ "default": "./dist/providers/index.mjs"
22
+ },
23
+ "./utils": {
24
+ "types": "./dist/utils/index.d.mts",
25
+ "default": "./dist/utils/index.mjs"
26
+ }
27
+ },
28
+ "typesVersions": {
29
+ "*": {
30
+ "channels": ["./dist/channels/index.d.mts"],
31
+ "providers": ["./dist/providers/index.d.mts"],
32
+ "utils": ["./dist/utils/index.d.mts"]
33
+ }
34
+ },
35
+ "files": [
36
+ "dist",
37
+ "README.md",
38
+ "CHANGELOG.md",
39
+ "LICENSE"
40
+ ],
41
+ "keywords": [
42
+ "notifications",
43
+ "multi-channel",
44
+ "email",
45
+ "sms",
46
+ "push-notifications",
47
+ "webhook",
48
+ "telegram",
49
+ "nodemailer",
50
+ "smtp",
51
+ "ses",
52
+ "rate-limiting",
53
+ "delivery-tracking",
54
+ "queue",
55
+ "channel-fallback",
56
+ "templates",
57
+ "retry",
58
+ "idempotency",
59
+ "pluggable",
60
+ "framework-agnostic",
61
+ "typescript",
62
+ "zero-dependencies"
63
+ ],
64
+ "author": "Classytic <classytic.dev@gmail.com> (https://github.com/classytic)",
65
+ "contributors": [
66
+ "Sadman Chowdhury (https://github.com/siam923)"
67
+ ],
68
+ "license": "MIT",
69
+ "publishConfig": {
70
+ "access": "public"
71
+ },
72
+ "repository": {
73
+ "type": "git",
74
+ "url": "git+https://github.com/classytic/notifications.git"
75
+ },
76
+ "bugs": {
77
+ "url": "https://github.com/classytic/notifications/issues"
78
+ },
79
+ "homepage": "https://github.com/classytic/notifications#readme",
80
+ "peerDependencies": {
81
+ "nodemailer": ">=6"
82
+ },
83
+ "peerDependenciesMeta": {
84
+ "nodemailer": {
85
+ "optional": true
86
+ }
87
+ },
88
+ "engines": {
89
+ "node": ">=18"
90
+ },
91
+ "scripts": {
92
+ "build": "tsdown",
93
+ "dev": "tsdown --watch",
94
+ "test": "vitest run",
95
+ "test:watch": "vitest",
96
+ "test:coverage": "vitest run --coverage",
97
+ "test:live": "vitest run --config vitest.live.config.ts",
98
+ "typecheck": "tsc --noEmit && npm run typecheck:consumer",
99
+ "typecheck:consumer": "tsdown --logLevel warn && tsc --noEmit -p tsconfig.types.json",
100
+ "prepublishOnly": "npm run build && npm run typecheck && npm test",
101
+ "push": "classytic-push",
102
+ "publish:dry": "npm publish --dry-run --access public",
103
+ "publish:npm": "npm publish --access public",
104
+ "release": "npm run build && npm run typecheck && npm test && npm publish --access public",
105
+ "release:patch": "npm version patch && npm run release",
106
+ "release:minor": "npm version minor && npm run release",
107
+ "release:major": "npm version major && npm run release"
108
+ },
109
+ "devDependencies": {
110
+ "@classytic/dev-tools": "^0.2.1",
111
+ "@types/node": "^26.6.5",
112
+ "@types/nodemailer": "^8.0.2",
113
+ "@vitest/coverage-v8": "5.0.5",
114
+ "nodemailer": "^10.1.2",
115
+ "tsdown": "^0.23.1",
116
+ "typescript": "^7.0.2",
117
+ "vitest": "^5.0.5"
118
+ }
119
+ }