@classytic/notifications 1.2.0 → 2.1.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 +154 -37
- package/README.md +437 -201
- package/dist/channels/index.d.mts +2 -2
- package/dist/channels/index.mjs +2 -2
- package/dist/index.d.mts +39 -18
- package/dist/index.mjs +129 -28
- package/dist/providers/index.d.mts +136 -0
- package/dist/providers/index.mjs +280 -0
- package/dist/push.channel-OkjPEVTN.mjs +519 -0
- package/dist/push.channel-YtZrCCH1.d.mts +73 -0
- package/dist/status-webhook-Bb4UoinT.d.mts +268 -0
- package/dist/status-webhook-XY42DCj_.mjs +582 -0
- package/dist/types-BMs4UhKD.d.mts +572 -0
- package/dist/utils/index.d.mts +3 -3
- package/dist/utils/index.mjs +3 -3
- package/package.json +30 -13
- package/dist/concurrency-CV_XyiBQ.d.mts +0 -139
- package/dist/console.channel-BoWi_5nH.d.mts +0 -39
- package/dist/console.channel-CfA4b_Er.mjs +0 -246
- package/dist/merge-hooks-B4_uHR9x.mjs +0 -233
- package/dist/types-BnjZ7x2U.d.mts +0 -297
- /package/dist/{errors-DAIVZx_Q.mjs → errors-FYJYmfvj.mjs} +0 -0
package/README.md
CHANGED
|
@@ -2,20 +2,21 @@
|
|
|
2
2
|
|
|
3
3
|
> Multi-channel notification system for TypeScript/Node.js
|
|
4
4
|
|
|
5
|
-
Pluggable channels, templates, retry with backoff, and user preferences. Zero required dependencies — bring your own providers.
|
|
5
|
+
Pluggable channels, templates, retry with backoff, rate limiting, delivery tracking, and user preferences. Zero required dependencies — bring your own providers.
|
|
6
6
|
|
|
7
7
|
## Features
|
|
8
8
|
|
|
9
|
-
- **Multi-Channel** — Email
|
|
10
|
-
- **Zero Required Deps** — Nodemailer is
|
|
11
|
-
- **
|
|
9
|
+
- **Multi-Channel** — Email, SMS, Push, Webhook, Console, or build your own
|
|
10
|
+
- **Zero Required Deps** — Nodemailer is the only optional peer dep; SMS/Push use BYOP (Bring Your Own Provider)
|
|
11
|
+
- **Rate Limiting** — Per-channel token bucket (e.g., Gmail 500/day, SendGrid 100/sec)
|
|
12
|
+
- **Delivery Tracking** — Built-in audit log for every send attempt (sent, skipped, failed)
|
|
13
|
+
- **Queue Adapter** — Crash-resilient delivery with pluggable queue backends
|
|
14
|
+
- **Templates** — Built-in `${var}` interpolation or plug any engine (React Email, MJML, etc.)
|
|
12
15
|
- **Retry + Backoff** — Exponential, linear, or fixed backoff with jitter. Per-channel overrides
|
|
13
16
|
- **User Preferences** — Per-user, per-event, per-channel opt-in/out with quiet hours
|
|
14
|
-
- **Quiet Hours** — Timezone-aware quiet period enforcement (no external deps)
|
|
15
17
|
- **Idempotency** — Built-in deduplication with pluggable stores (memory, Redis, DB)
|
|
16
|
-
- **Lifecycle Events** — `before:send`, `after:send`, `send:success`, `send:failed`, `send:retry`
|
|
18
|
+
- **Lifecycle Events** — `before:send`, `after:send`, `send:success`, `send:failed`, `send:retry`, `send:rate_limited`, `send:queued`
|
|
17
19
|
- **Hook Factories** — Generate event handlers for EventEmitter, MongoKit, or any hook system
|
|
18
|
-
- **Webhook Signing** — HMAC-SHA256 payload signing out of the box
|
|
19
20
|
- **TypeScript** — Full type definitions, ESM-only
|
|
20
21
|
|
|
21
22
|
## Installation
|
|
@@ -30,34 +31,69 @@ npm install @classytic/notifications
|
|
|
30
31
|
npm install nodemailer
|
|
31
32
|
```
|
|
32
33
|
|
|
34
|
+
### Module Format
|
|
35
|
+
|
|
36
|
+
This package is **ESM-only** (`"type": "module"`, Node 18+, no CJS build).
|
|
37
|
+
That means:
|
|
38
|
+
|
|
39
|
+
- ✅ ESM consumers — `import { ... } from '@classytic/notifications'` just works.
|
|
40
|
+
- ⚠️ CommonJS consumers — you must use a dynamic import:
|
|
41
|
+
```js
|
|
42
|
+
const { NotificationService } = await import('@classytic/notifications');
|
|
43
|
+
```
|
|
44
|
+
A top-level `require('@classytic/notifications')` will fail with
|
|
45
|
+
`ERR_REQUIRE_ESM`. If you're starting a new project, prefer ESM
|
|
46
|
+
(`"type": "module"` in your `package.json`) or use a bundler/runtime
|
|
47
|
+
that handles ESM natively (Vite, Next.js, Bun, modern Node).
|
|
48
|
+
- TypeScript declarations are emitted as `.d.mts`. `typesVersions` is
|
|
49
|
+
configured so node10-style resolvers still resolve subpaths.
|
|
50
|
+
|
|
33
51
|
## Quick Start
|
|
34
52
|
|
|
35
53
|
```typescript
|
|
36
54
|
import { NotificationService } from '@classytic/notifications';
|
|
37
|
-
import { EmailChannel,
|
|
55
|
+
import { EmailChannel, SmsChannel, PushChannel, ConsoleChannel } from '@classytic/notifications/channels';
|
|
56
|
+
import { MemoryDeliveryLog, createSimpleResolver } from '@classytic/notifications/utils';
|
|
38
57
|
|
|
39
58
|
const notifications = new NotificationService({
|
|
40
59
|
channels: [
|
|
41
60
|
new EmailChannel({
|
|
42
61
|
from: 'App <noreply@app.com>',
|
|
43
62
|
transport: { host: 'smtp.gmail.com', port: 587, auth: { user, pass } },
|
|
63
|
+
rateLimit: { maxPerWindow: 500, windowMs: 86_400_000 }, // Gmail 500/day
|
|
44
64
|
}),
|
|
45
|
-
new
|
|
46
|
-
|
|
47
|
-
|
|
65
|
+
new SmsChannel({
|
|
66
|
+
from: '+15551234567',
|
|
67
|
+
provider: {
|
|
68
|
+
send: async ({ to, from, body }) => {
|
|
69
|
+
const msg = await twilioClient.messages.create({ to, from, body });
|
|
70
|
+
return { sid: msg.sid };
|
|
71
|
+
},
|
|
72
|
+
},
|
|
73
|
+
}),
|
|
74
|
+
new PushChannel({
|
|
75
|
+
provider: {
|
|
76
|
+
send: async ({ token, title, body, data }) => {
|
|
77
|
+
const result = await admin.messaging().send({ token, notification: { title, body }, data });
|
|
78
|
+
return { messageId: result };
|
|
79
|
+
},
|
|
80
|
+
},
|
|
48
81
|
}),
|
|
49
82
|
new ConsoleChannel(), // dev/testing
|
|
50
83
|
],
|
|
51
|
-
templates:
|
|
52
|
-
|
|
53
|
-
|
|
84
|
+
templates: createSimpleResolver({
|
|
85
|
+
welcome: {
|
|
86
|
+
subject: 'Welcome, ${name}!',
|
|
87
|
+
html: '<h1>Hi ${name}</h1><p>Thanks for joining.</p>',
|
|
88
|
+
},
|
|
54
89
|
}),
|
|
55
90
|
retry: { maxAttempts: 3, backoff: 'exponential' },
|
|
91
|
+
deliveryLog: new MemoryDeliveryLog(),
|
|
56
92
|
});
|
|
57
93
|
|
|
58
94
|
await notifications.send({
|
|
59
95
|
event: 'user.created',
|
|
60
|
-
recipient: { email: 'user@example.com', name: 'John' },
|
|
96
|
+
recipient: { email: 'user@example.com', phone: '+15559876543', name: 'John' },
|
|
61
97
|
data: { name: 'John' },
|
|
62
98
|
template: 'welcome',
|
|
63
99
|
});
|
|
@@ -65,9 +101,7 @@ await notifications.send({
|
|
|
65
101
|
|
|
66
102
|
## Channels
|
|
67
103
|
|
|
68
|
-
###
|
|
69
|
-
|
|
70
|
-
#### EmailChannel (Nodemailer)
|
|
104
|
+
### EmailChannel (Nodemailer)
|
|
71
105
|
|
|
72
106
|
Requires: `npm install nodemailer`
|
|
73
107
|
|
|
@@ -78,6 +112,7 @@ import { EmailChannel } from '@classytic/notifications/channels';
|
|
|
78
112
|
const email = new EmailChannel({
|
|
79
113
|
from: 'App <noreply@app.com>',
|
|
80
114
|
transport: { host: 'smtp.gmail.com', port: 587, auth: { user, pass } },
|
|
115
|
+
rateLimit: { maxPerWindow: 500, windowMs: 86_400_000 }, // Gmail 500/day
|
|
81
116
|
});
|
|
82
117
|
|
|
83
118
|
// Gmail shorthand
|
|
@@ -94,7 +129,152 @@ const email = new EmailChannel({
|
|
|
94
129
|
});
|
|
95
130
|
```
|
|
96
131
|
|
|
97
|
-
|
|
132
|
+
### Email Providers (`/providers`)
|
|
133
|
+
|
|
134
|
+
For multi-tenant apps where each org brings its own email provider, use the
|
|
135
|
+
`/providers` surface to render a credential form, validate the connection,
|
|
136
|
+
and build a transporter from the stored blob — no per-provider branching
|
|
137
|
+
in your host code.
|
|
138
|
+
|
|
139
|
+
```typescript
|
|
140
|
+
import {
|
|
141
|
+
EMAIL_PRESETS,
|
|
142
|
+
EMAIL_PROVIDER_OPTIONS,
|
|
143
|
+
buildEmailTransport,
|
|
144
|
+
buildFromHeader,
|
|
145
|
+
getEmailCredentialSchema,
|
|
146
|
+
testEmailCredential,
|
|
147
|
+
type EmailCredentialData,
|
|
148
|
+
type EmailProviderName,
|
|
149
|
+
} from '@classytic/notifications/providers';
|
|
150
|
+
import { EmailChannel } from '@classytic/notifications/channels';
|
|
151
|
+
|
|
152
|
+
// 1. Render a dynamic form from the schema (provider select + the union
|
|
153
|
+
// of all provider-specific fields — UI hides what's not relevant).
|
|
154
|
+
const fields = getEmailCredentialSchema();
|
|
155
|
+
|
|
156
|
+
// 2. "Test Connection" — opens an SMTP connection and runs `verify()`.
|
|
157
|
+
// Returns `{ status: 'OK' | 'Error', message }` instead of throwing.
|
|
158
|
+
const result = await testEmailCredential({
|
|
159
|
+
provider: 'resend',
|
|
160
|
+
fromEmail: 'hello@yourdomain.com',
|
|
161
|
+
fromName: 'Your Brand',
|
|
162
|
+
apiKey: 're_xxx',
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
// 3. At send time, turn the encrypted DB blob into a transporter and
|
|
166
|
+
// plug it straight into EmailChannel.
|
|
167
|
+
const data: EmailCredentialData = /* decrypted from DB */;
|
|
168
|
+
const transporter = await buildEmailTransport(data);
|
|
169
|
+
const channel = new EmailChannel({
|
|
170
|
+
from: buildFromHeader(data), // '"Brand" <hello@…>' or bare email
|
|
171
|
+
transporter,
|
|
172
|
+
});
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
**Supported providers** — every one is SMTP under the hood:
|
|
176
|
+
|
|
177
|
+
| `provider` | Host | Auth fields | Notes |
|
|
178
|
+
|---|---|---|---|
|
|
179
|
+
| `resend` | `smtp.resend.com:465` | `apiKey` | User is the literal `resend` |
|
|
180
|
+
| `gmail` | `smtp.gmail.com:465` | `user`, `password` | App Password, NOT account password |
|
|
181
|
+
| `sendgrid` | `smtp.sendgrid.net:587` | `apiKey` | User is the literal `apikey` |
|
|
182
|
+
| `mailgun` | `smtp.mailgun.org:465` | `user`, `password` | Per-domain SMTP creds |
|
|
183
|
+
| `ses` | `email-smtp.us-east-1.amazonaws.com:465` | `user`, `password` | SES IAM SMTP creds. Override `host` for other regions |
|
|
184
|
+
| `smtp` | user-supplied | `host`, `port`, `secure`, `user`, `password` | Any auth-SMTP server |
|
|
185
|
+
|
|
186
|
+
Host override is allowed only for `smtp` and `ses` (regional). Other
|
|
187
|
+
presets pin the host to prevent footguns like "I changed the host but
|
|
188
|
+
kept the Resend API key".
|
|
189
|
+
|
|
190
|
+
```typescript
|
|
191
|
+
// SES in eu-west-1
|
|
192
|
+
await buildEmailTransport({
|
|
193
|
+
provider: 'ses',
|
|
194
|
+
fromEmail: 'support@yourdomain.com',
|
|
195
|
+
user: 'AKIAxxxx',
|
|
196
|
+
password: 'BFxxxx',
|
|
197
|
+
host: 'email-smtp.eu-west-1.amazonaws.com',
|
|
198
|
+
});
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
### SmsChannel (BYOP)
|
|
202
|
+
|
|
203
|
+
Zero dependencies — bring your own SMS SDK.
|
|
204
|
+
|
|
205
|
+
```typescript
|
|
206
|
+
import { SmsChannel } from '@classytic/notifications/channels';
|
|
207
|
+
|
|
208
|
+
// Twilio
|
|
209
|
+
import twilio from 'twilio';
|
|
210
|
+
const client = twilio(process.env.TWILIO_SID, process.env.TWILIO_TOKEN);
|
|
211
|
+
|
|
212
|
+
const sms = new SmsChannel({
|
|
213
|
+
from: '+15551234567',
|
|
214
|
+
provider: {
|
|
215
|
+
send: async ({ to, from, body }) => {
|
|
216
|
+
const msg = await client.messages.create({ to, from, body });
|
|
217
|
+
return { sid: msg.sid };
|
|
218
|
+
},
|
|
219
|
+
},
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
// AWS SNS
|
|
223
|
+
import { SNSClient, PublishCommand } from '@aws-sdk/client-sns';
|
|
224
|
+
const sns = new SNSClient({ region: 'us-east-1' });
|
|
225
|
+
|
|
226
|
+
const snsSms = new SmsChannel({
|
|
227
|
+
from: 'MyApp',
|
|
228
|
+
provider: {
|
|
229
|
+
send: async ({ to, body }) => {
|
|
230
|
+
const res = await sns.send(new PublishCommand({ PhoneNumber: to, Message: body }));
|
|
231
|
+
return { sid: res.MessageId ?? '' };
|
|
232
|
+
},
|
|
233
|
+
},
|
|
234
|
+
});
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
### PushChannel (BYOP)
|
|
238
|
+
|
|
239
|
+
Zero dependencies — bring your own push SDK.
|
|
240
|
+
|
|
241
|
+
```typescript
|
|
242
|
+
import { PushChannel } from '@classytic/notifications/channels';
|
|
243
|
+
|
|
244
|
+
// Firebase Cloud Messaging
|
|
245
|
+
import admin from 'firebase-admin';
|
|
246
|
+
|
|
247
|
+
const push = new PushChannel({
|
|
248
|
+
provider: {
|
|
249
|
+
send: async ({ token, title, body, data }) => {
|
|
250
|
+
const result = await admin.messaging().send({
|
|
251
|
+
token,
|
|
252
|
+
notification: { title, body },
|
|
253
|
+
data,
|
|
254
|
+
});
|
|
255
|
+
return { messageId: result };
|
|
256
|
+
},
|
|
257
|
+
},
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
// Expo Push
|
|
261
|
+
import { Expo } from 'expo-server-sdk';
|
|
262
|
+
const expo = new Expo();
|
|
263
|
+
|
|
264
|
+
const expoPush = new PushChannel({
|
|
265
|
+
name: 'expo-push',
|
|
266
|
+
provider: {
|
|
267
|
+
send: async ({ token, title, body, data }) => {
|
|
268
|
+
const [receipt] = await expo.sendPushNotificationsAsync([
|
|
269
|
+
{ to: token, title, body, data },
|
|
270
|
+
]);
|
|
271
|
+
return { messageId: receipt.id };
|
|
272
|
+
},
|
|
273
|
+
},
|
|
274
|
+
});
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
### WebhookChannel
|
|
98
278
|
|
|
99
279
|
Zero dependencies — uses native `fetch`.
|
|
100
280
|
|
|
@@ -115,7 +295,7 @@ const signed = new WebhookChannel({
|
|
|
115
295
|
});
|
|
116
296
|
```
|
|
117
297
|
|
|
118
|
-
|
|
298
|
+
### ConsoleChannel
|
|
119
299
|
|
|
120
300
|
Logs to console. Useful for development and testing.
|
|
121
301
|
|
|
@@ -155,68 +335,218 @@ class SlackChannel extends BaseChannel<SlackConfig> {
|
|
|
155
335
|
}
|
|
156
336
|
```
|
|
157
337
|
|
|
158
|
-
|
|
338
|
+
## Rate Limiting
|
|
159
339
|
|
|
160
|
-
|
|
340
|
+
Prevent exceeding provider limits with per-channel rate limiting:
|
|
161
341
|
|
|
162
342
|
```typescript
|
|
163
|
-
new
|
|
164
|
-
|
|
165
|
-
|
|
343
|
+
new EmailChannel({
|
|
344
|
+
from: 'noreply@app.com',
|
|
345
|
+
transport: { service: 'gmail', auth: { user, pass } },
|
|
346
|
+
rateLimit: {
|
|
347
|
+
maxPerWindow: 500, // max 500 emails
|
|
348
|
+
windowMs: 86_400_000, // per 24 hours
|
|
349
|
+
},
|
|
166
350
|
});
|
|
351
|
+
```
|
|
352
|
+
|
|
353
|
+
Rate-limited sends return `status: 'skipped'` with `error: 'Rate limited'` and emit a `send:rate_limited` event. The built-in `MemoryRateLimitStore` is created automatically. For distributed systems, implement `RateLimitStore`:
|
|
354
|
+
|
|
355
|
+
```typescript
|
|
356
|
+
import type { RateLimitStore, RateLimitConfig } from '@classytic/notifications/utils';
|
|
357
|
+
|
|
358
|
+
class RedisRateLimitStore implements RateLimitStore {
|
|
359
|
+
async consume(channel: string, config: RateLimitConfig): Promise<boolean> {
|
|
360
|
+
// Sliding window rate limiter with Redis
|
|
361
|
+
}
|
|
362
|
+
async remaining(channel: string, config: RateLimitConfig): Promise<number> { /* ... */ }
|
|
363
|
+
async reset(channel: string): Promise<void> { /* ... */ }
|
|
364
|
+
}
|
|
167
365
|
|
|
168
|
-
new
|
|
169
|
-
|
|
366
|
+
const service = new NotificationService({
|
|
367
|
+
channels: [...],
|
|
368
|
+
rateLimitStore: new RedisRateLimitStore(),
|
|
170
369
|
});
|
|
171
370
|
```
|
|
172
371
|
|
|
173
|
-
|
|
372
|
+
## Delivery Tracking
|
|
174
373
|
|
|
175
|
-
|
|
374
|
+
Every notification attempt — sent, skipped, or failed — is logged:
|
|
176
375
|
|
|
177
376
|
```typescript
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
377
|
+
import { MemoryDeliveryLog } from '@classytic/notifications/utils';
|
|
378
|
+
|
|
379
|
+
const log = new MemoryDeliveryLog();
|
|
380
|
+
const service = new NotificationService({
|
|
381
|
+
channels: [...],
|
|
382
|
+
deliveryLog: log,
|
|
383
|
+
});
|
|
384
|
+
|
|
385
|
+
// Query history
|
|
386
|
+
const entries = log.query({
|
|
387
|
+
recipientId: 'u1',
|
|
388
|
+
event: 'user.created',
|
|
389
|
+
status: 'delivered',
|
|
390
|
+
after: new Date('2026-01-01'),
|
|
391
|
+
limit: 50,
|
|
191
392
|
});
|
|
393
|
+
|
|
394
|
+
// Get a specific entry
|
|
395
|
+
const entry = log.get(entries[0].id);
|
|
192
396
|
```
|
|
193
397
|
|
|
194
|
-
|
|
398
|
+
For production, implement `DeliveryLog` with your database:
|
|
195
399
|
|
|
196
|
-
|
|
400
|
+
```typescript
|
|
401
|
+
import type { DeliveryLog } from '@classytic/notifications/utils';
|
|
402
|
+
|
|
403
|
+
class MongoDeliveryLog implements DeliveryLog {
|
|
404
|
+
async record(payload, dispatch) { /* insert to MongoDB */ }
|
|
405
|
+
async query(filter) { /* query MongoDB */ }
|
|
406
|
+
async get(id) { /* findById */ }
|
|
407
|
+
}
|
|
408
|
+
```
|
|
409
|
+
|
|
410
|
+
## Queue Adapter
|
|
411
|
+
|
|
412
|
+
For crash-resilient delivery, attach a queue. The service owns the queue — it calls `process()` on construction. When configured, `send()` enqueues and returns immediately:
|
|
197
413
|
|
|
198
414
|
```typescript
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
415
|
+
import { MemoryQueue } from '@classytic/notifications/utils';
|
|
416
|
+
|
|
417
|
+
const service = new NotificationService({
|
|
418
|
+
channels: [...],
|
|
419
|
+
queue: new MemoryQueue(),
|
|
420
|
+
});
|
|
421
|
+
|
|
422
|
+
// Sends are now queued and processed async
|
|
423
|
+
await service.send({ ... }); // Returns immediately with { queued: true }
|
|
424
|
+
```
|
|
425
|
+
|
|
426
|
+
> **Note:** If your app already has its own queue (BullMQ, SQS, etc.), don't pass it here. The service owns its queue. Instead, have your existing worker call `service.send()` directly when it picks up a job.
|
|
427
|
+
|
|
428
|
+
For production, implement `QueueAdapter` with BullMQ, Redis, or your database:
|
|
429
|
+
|
|
430
|
+
```typescript
|
|
431
|
+
import type { QueueAdapter } from '@classytic/notifications/utils';
|
|
432
|
+
|
|
433
|
+
class BullMQAdapter implements QueueAdapter {
|
|
434
|
+
async enqueue(payload, options?) { /* add to BullMQ */ }
|
|
435
|
+
async process(processor) { /* worker.on('job', ...) */ }
|
|
436
|
+
async getJob(id) { /* ... */ }
|
|
437
|
+
size() { /* ... */ }
|
|
438
|
+
pause() { /* ... */ }
|
|
439
|
+
resume() { /* ... */ }
|
|
440
|
+
drain() { /* ... */ }
|
|
441
|
+
}
|
|
442
|
+
```
|
|
443
|
+
|
|
444
|
+
## Scheduled / Delayed Delivery
|
|
445
|
+
|
|
446
|
+
Add `delay` (milliseconds) to any payload. Requires a queue adapter:
|
|
447
|
+
|
|
448
|
+
```typescript
|
|
449
|
+
// Send reminder in 1 hour
|
|
450
|
+
await service.send({
|
|
451
|
+
event: 'interview.reminder',
|
|
452
|
+
recipient: { email: 'candidate@example.com' },
|
|
453
|
+
data: { subject: 'Interview in 1 hour' },
|
|
454
|
+
delay: 3_600_000,
|
|
455
|
+
});
|
|
456
|
+
```
|
|
457
|
+
|
|
458
|
+
Without a queue adapter, `delay` is ignored with a warning log.
|
|
459
|
+
|
|
460
|
+
> **For long-delay scheduling** (days/weeks), use a persistent queue backend (BullMQ with Redis) or a workflow engine like `@classytic/streamline` which survives process restarts.
|
|
461
|
+
|
|
462
|
+
## Channel Fallback
|
|
463
|
+
|
|
464
|
+
Try channels in priority order, stopping at the first success:
|
|
465
|
+
|
|
466
|
+
```typescript
|
|
467
|
+
import { withFallback } from '@classytic/notifications/utils';
|
|
468
|
+
|
|
469
|
+
// Try push first, fall back to SMS, then email
|
|
470
|
+
const result = await withFallback(service, payload, ['push', 'sms', 'email'], {
|
|
471
|
+
onFallback: (failed, error, next) => {
|
|
472
|
+
console.log(`${failed} failed (${error}), trying ${next}`);
|
|
208
473
|
},
|
|
209
474
|
});
|
|
475
|
+
```
|
|
210
476
|
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
477
|
+
Works with both direct and queued delivery. In queue mode, the first accepted enqueue stops the fallback (no duplicate jobs).
|
|
478
|
+
|
|
479
|
+
## Status Webhook Handler
|
|
480
|
+
|
|
481
|
+
Ingest delivery status updates from providers (Twilio, SES, SendGrid, FCM):
|
|
482
|
+
|
|
483
|
+
```typescript
|
|
484
|
+
import { createStatusHandler } from '@classytic/notifications/utils';
|
|
485
|
+
|
|
486
|
+
const handler = createStatusHandler({
|
|
487
|
+
onStatusChange: async (update) => {
|
|
488
|
+
// Persist to your DB, metrics, delivery log, etc.
|
|
489
|
+
await db.notificationStatuses.insert(update);
|
|
490
|
+
},
|
|
491
|
+
});
|
|
492
|
+
|
|
493
|
+
// In your Express/Fastify route:
|
|
494
|
+
app.post('/webhooks/twilio', (req, res) => {
|
|
495
|
+
handler.handle({
|
|
496
|
+
provider: 'twilio',
|
|
497
|
+
notificationId: req.body.MessageSid,
|
|
498
|
+
channel: 'sms',
|
|
499
|
+
status: mapTwilioStatus(req.body.MessageStatus), // from examples/providers.ts
|
|
500
|
+
timestamp: new Date(),
|
|
501
|
+
rawPayload: req.body,
|
|
502
|
+
});
|
|
503
|
+
res.sendStatus(200);
|
|
216
504
|
});
|
|
217
505
|
```
|
|
218
506
|
|
|
219
|
-
|
|
507
|
+
**Delivery statuses:** `queued` | `accepted` | `sent` | `delivered` | `undelivered` | `bounced` | `opened` | `clicked` | `complained` | `unsubscribed`
|
|
508
|
+
|
|
509
|
+
## Templates
|
|
510
|
+
|
|
511
|
+
### Built-in Simple Resolver
|
|
512
|
+
|
|
513
|
+
Zero-dependency `${var}` interpolation with nested access:
|
|
514
|
+
|
|
515
|
+
```typescript
|
|
516
|
+
import { createSimpleResolver } from '@classytic/notifications/utils';
|
|
517
|
+
|
|
518
|
+
const service = new NotificationService({
|
|
519
|
+
templates: createSimpleResolver({
|
|
520
|
+
welcome: {
|
|
521
|
+
subject: 'Welcome, ${name}!',
|
|
522
|
+
html: '<h1>Hi ${name}</h1><p>From ${company}.</p>',
|
|
523
|
+
},
|
|
524
|
+
'order-confirmation': {
|
|
525
|
+
subject: 'Order #${orderId} confirmed',
|
|
526
|
+
html: '<p>Hi ${user.name}, your ${total} order is confirmed.</p>',
|
|
527
|
+
},
|
|
528
|
+
}),
|
|
529
|
+
});
|
|
530
|
+
```
|
|
531
|
+
|
|
532
|
+
### Custom Template Engine
|
|
533
|
+
|
|
534
|
+
Plug any engine via the `TemplateResolver` interface:
|
|
535
|
+
|
|
536
|
+
```typescript
|
|
537
|
+
// React Email
|
|
538
|
+
import { render } from '@react-email/render';
|
|
539
|
+
import WelcomeEmail from './emails/welcome';
|
|
540
|
+
|
|
541
|
+
const service = new NotificationService({
|
|
542
|
+
templates: async (id, data) => {
|
|
543
|
+
if (id === 'welcome') {
|
|
544
|
+
return { subject: `Welcome ${data.name}!`, html: render(WelcomeEmail(data)) };
|
|
545
|
+
}
|
|
546
|
+
throw new Error(`Unknown template: ${id}`);
|
|
547
|
+
},
|
|
548
|
+
});
|
|
549
|
+
```
|
|
220
550
|
|
|
221
551
|
## User Preferences
|
|
222
552
|
|
|
@@ -229,7 +559,7 @@ const notifications = new NotificationService({
|
|
|
229
559
|
return {
|
|
230
560
|
channels: { email: true, sms: false }, // opt-out of SMS
|
|
231
561
|
events: { 'marketing.promo': false }, // opt-out of promos
|
|
232
|
-
quiet: {
|
|
562
|
+
quiet: {
|
|
233
563
|
start: '22:00',
|
|
234
564
|
end: '07:00',
|
|
235
565
|
timezone: 'America/New_York',
|
|
@@ -239,67 +569,27 @@ const notifications = new NotificationService({
|
|
|
239
569
|
});
|
|
240
570
|
```
|
|
241
571
|
|
|
242
|
-
### Quiet Hours
|
|
243
|
-
|
|
244
|
-
Notifications are automatically skipped when the recipient is in their quiet period. Times use `HH:MM` format, timezone uses IANA names. Overnight ranges (e.g. 22:00–07:00) are supported.
|
|
245
|
-
|
|
246
|
-
```typescript
|
|
247
|
-
// Quiet hours are returned from the preference resolver
|
|
248
|
-
preferences: async (recipientId) => ({
|
|
249
|
-
quiet: {
|
|
250
|
-
start: '22:00', // inclusive
|
|
251
|
-
end: '07:00', // exclusive
|
|
252
|
-
timezone: 'Asia/Dhaka', // IANA timezone (defaults to UTC)
|
|
253
|
-
},
|
|
254
|
-
});
|
|
255
|
-
|
|
256
|
-
// You can also use the utility directly
|
|
257
|
-
import { isQuietHours } from '@classytic/notifications/utils';
|
|
258
|
-
|
|
259
|
-
if (isQuietHours({ start: '22:00', end: '07:00', timezone: 'Asia/Dhaka' })) {
|
|
260
|
-
console.log('Shhh!');
|
|
261
|
-
}
|
|
262
|
-
```
|
|
263
|
-
|
|
264
572
|
## Idempotency / Deduplication
|
|
265
573
|
|
|
266
|
-
Prevent duplicate notifications
|
|
574
|
+
Prevent duplicate notifications with idempotency keys:
|
|
267
575
|
|
|
268
576
|
```typescript
|
|
269
577
|
const notifications = new NotificationService({
|
|
270
|
-
channels: [
|
|
271
|
-
idempotency: {},
|
|
272
|
-
});
|
|
273
|
-
|
|
274
|
-
await notifications.send({
|
|
275
|
-
event: 'order.completed',
|
|
276
|
-
recipient: { email: 'user@example.com' },
|
|
277
|
-
data: { orderId: '123' },
|
|
278
|
-
idempotencyKey: 'order-completed-123', // duplicate sends are skipped
|
|
578
|
+
channels: [...],
|
|
579
|
+
idempotency: {}, // uses MemoryIdempotencyStore, 24h TTL
|
|
279
580
|
});
|
|
280
581
|
|
|
281
|
-
// Second send with same key → skipped (sent: 0, skipped: 1)
|
|
282
582
|
await notifications.send({
|
|
283
583
|
event: 'order.completed',
|
|
284
584
|
recipient: { email: 'user@example.com' },
|
|
285
585
|
data: { orderId: '123' },
|
|
286
|
-
idempotencyKey: 'order-completed-123',
|
|
586
|
+
idempotencyKey: 'order-completed-123', // duplicate sends are skipped
|
|
287
587
|
});
|
|
288
588
|
```
|
|
289
589
|
|
|
290
|
-
|
|
590
|
+
For distributed systems, implement `IdempotencyStore` with Redis:
|
|
291
591
|
|
|
292
592
|
```typescript
|
|
293
|
-
import { MemoryIdempotencyStore } from '@classytic/notifications/utils';
|
|
294
|
-
|
|
295
|
-
// Custom TTL (1 hour)
|
|
296
|
-
const notifications = new NotificationService({
|
|
297
|
-
idempotency: {
|
|
298
|
-
ttl: 60 * 60 * 1000, // 1 hour in ms (default: 24h)
|
|
299
|
-
},
|
|
300
|
-
});
|
|
301
|
-
|
|
302
|
-
// Custom store (e.g. Redis for distributed systems)
|
|
303
593
|
import type { IdempotencyStore } from '@classytic/notifications/utils';
|
|
304
594
|
|
|
305
595
|
class RedisIdempotencyStore implements IdempotencyStore {
|
|
@@ -310,51 +600,21 @@ class RedisIdempotencyStore implements IdempotencyStore {
|
|
|
310
600
|
await redis.set(`idemp:${key}`, '1', 'PX', ttlMs);
|
|
311
601
|
}
|
|
312
602
|
}
|
|
313
|
-
|
|
314
|
-
const notifications = new NotificationService({
|
|
315
|
-
idempotency: { store: new RedisIdempotencyStore() },
|
|
316
|
-
});
|
|
317
603
|
```
|
|
318
604
|
|
|
319
605
|
## Batch Sending
|
|
320
606
|
|
|
321
|
-
Send thousands of notifications with controlled concurrency
|
|
607
|
+
Send thousands of notifications with controlled concurrency:
|
|
322
608
|
|
|
323
609
|
```typescript
|
|
324
|
-
const payloads = students.map(s => ({
|
|
325
|
-
event: 'birthday',
|
|
326
|
-
recipient: { id: s.id, email: s.email },
|
|
327
|
-
data: { name: s.name },
|
|
328
|
-
template: 'birthday',
|
|
329
|
-
idempotencyKey: `birthday-${s.id}-2024`,
|
|
330
|
-
}));
|
|
331
|
-
|
|
332
610
|
const batch = await notifications.sendBatch(payloads, {
|
|
333
|
-
concurrency: 20,
|
|
334
|
-
onProgress: ({ completed, total }) => {
|
|
335
|
-
console.log(`${completed}/${total}`);
|
|
336
|
-
},
|
|
611
|
+
concurrency: 20,
|
|
612
|
+
onProgress: ({ completed, total }) => console.log(`${completed}/${total}`),
|
|
337
613
|
});
|
|
338
614
|
|
|
339
615
|
console.log(`Sent: ${batch.sent}, Failed: ${batch.failed}, Skipped: ${batch.skipped}`);
|
|
340
616
|
```
|
|
341
617
|
|
|
342
|
-
Each notification goes through the full `send()` pipeline (lifecycle events, templates, preferences, retry). Errors in individual notifications are caught and reported — they never abort the batch.
|
|
343
|
-
|
|
344
|
-
### Concurrency Utility
|
|
345
|
-
|
|
346
|
-
The underlying `pMap` concurrency pool is exported for reuse:
|
|
347
|
-
|
|
348
|
-
```typescript
|
|
349
|
-
import { pMap } from '@classytic/notifications/utils';
|
|
350
|
-
|
|
351
|
-
const results = await pMap(
|
|
352
|
-
urls,
|
|
353
|
-
async (url) => fetch(url).then(r => r.json()),
|
|
354
|
-
{ concurrency: 5 },
|
|
355
|
-
);
|
|
356
|
-
```
|
|
357
|
-
|
|
358
618
|
## Retry + Backoff
|
|
359
619
|
|
|
360
620
|
```typescript
|
|
@@ -368,32 +628,20 @@ const notifications = new NotificationService({
|
|
|
368
628
|
});
|
|
369
629
|
```
|
|
370
630
|
|
|
371
|
-
Jitter (+-25%) is applied automatically to prevent thundering herd.
|
|
631
|
+
Jitter (+-25%) is applied automatically to prevent thundering herd. Per-channel overrides are supported.
|
|
372
632
|
|
|
373
633
|
## Lifecycle Events
|
|
374
634
|
|
|
375
635
|
```typescript
|
|
376
|
-
notifications.on('before:send', (payload) => {
|
|
377
|
-
|
|
378
|
-
});
|
|
379
|
-
|
|
380
|
-
notifications.on('after:send', (result) => {
|
|
381
|
-
console.log(`Sent ${result.sent}/${result.results.length}`);
|
|
382
|
-
});
|
|
383
|
-
|
|
384
|
-
notifications.on('send:success', (result) => { /* ... */ });
|
|
385
|
-
notifications.on('send:failed', (result) => { /* ... */ });
|
|
636
|
+
notifications.on('before:send', (payload) => { /* validation, rate limiting */ });
|
|
637
|
+
notifications.on('after:send', (result) => { /* always fires, even for skipped */ });
|
|
638
|
+
notifications.on('send:success', (result) => { /* at least one channel sent */ });
|
|
639
|
+
notifications.on('send:failed', (result) => { /* at least one channel failed */ });
|
|
386
640
|
notifications.on('send:retry', ({ channel, attempt, error }) => { /* ... */ });
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
notifications.off('send:failed', handler);
|
|
641
|
+
notifications.on('send:rate_limited', ({ channel, event }) => { /* ... */ });
|
|
642
|
+
notifications.on('send:queued', ({ jobId, payload }) => { /* ... */ });
|
|
390
643
|
```
|
|
391
644
|
|
|
392
|
-
**Lifecycle contract:**
|
|
393
|
-
- `before:send` is **fail-fast** — a throwing listener aborts the send and propagates the error. Use this for validation or rate limiting.
|
|
394
|
-
- `after:send`, `send:success`, `send:failed` are **safe** — listener errors are caught and logged, never masking the dispatch result.
|
|
395
|
-
- `send:retry` errors are caught and logged.
|
|
396
|
-
|
|
397
645
|
## Hook Factories
|
|
398
646
|
|
|
399
647
|
Generate event handlers for any hook/event system:
|
|
@@ -406,47 +654,10 @@ const hooks = notifications.createHooks([
|
|
|
406
654
|
getData: (user) => ({ name: user.name }),
|
|
407
655
|
template: 'welcome',
|
|
408
656
|
},
|
|
409
|
-
{
|
|
410
|
-
event: 'order.completed',
|
|
411
|
-
getRecipient: (order) => ({ email: order.customer.email }),
|
|
412
|
-
getData: (order) => ({ orderId: order.id, total: order.total }),
|
|
413
|
-
template: 'order-confirmation',
|
|
414
|
-
channels: ['email'],
|
|
415
|
-
},
|
|
416
657
|
]);
|
|
417
658
|
|
|
418
659
|
// With EventEmitter
|
|
419
660
|
emitter.on('user.created', hooks['user.created'][0]);
|
|
420
|
-
|
|
421
|
-
// With MongoKit
|
|
422
|
-
repo.on('after:create', hooks['user.created'][0]);
|
|
423
|
-
```
|
|
424
|
-
|
|
425
|
-
Hooks are fire-and-forget: errors are logged but never thrown to avoid breaking the caller's flow.
|
|
426
|
-
|
|
427
|
-
### Merging Hooks
|
|
428
|
-
|
|
429
|
-
Combine hooks from multiple sources:
|
|
430
|
-
|
|
431
|
-
```typescript
|
|
432
|
-
import { mergeHooks } from '@classytic/notifications/utils';
|
|
433
|
-
|
|
434
|
-
const combined = mergeHooks(
|
|
435
|
-
notifications.createHooks(userHookConfigs),
|
|
436
|
-
notifications.createHooks(orderHookConfigs),
|
|
437
|
-
);
|
|
438
|
-
```
|
|
439
|
-
|
|
440
|
-
## Channel Management
|
|
441
|
-
|
|
442
|
-
```typescript
|
|
443
|
-
// Add/remove channels at runtime
|
|
444
|
-
notifications.addChannel(new ConsoleChannel());
|
|
445
|
-
notifications.removeChannel('console');
|
|
446
|
-
|
|
447
|
-
// Inspect registered channels
|
|
448
|
-
notifications.getChannel('email'); // Channel | undefined
|
|
449
|
-
notifications.getChannelNames(); // ['email', 'webhook']
|
|
450
661
|
```
|
|
451
662
|
|
|
452
663
|
## API Reference
|
|
@@ -461,13 +672,23 @@ notifications.getChannelNames(); // ['email', 'webhook']
|
|
|
461
672
|
| `removeChannel(name)` | Remove a channel by name |
|
|
462
673
|
| `getChannel(name)` | Get a channel by name |
|
|
463
674
|
| `getChannelNames()` | List all registered channel names |
|
|
675
|
+
| `getDeliveryLog()` | Get the delivery log instance |
|
|
464
676
|
| `createHooks(configs)` | Create event-specific hook handlers |
|
|
465
677
|
| `on(event, handler)` | Listen to lifecycle events |
|
|
466
678
|
| `off(event, handler)` | Remove a lifecycle listener |
|
|
467
679
|
|
|
468
|
-
###
|
|
680
|
+
### Pluggable Interfaces
|
|
469
681
|
|
|
470
|
-
|
|
682
|
+
| Interface | Purpose | Built-in |
|
|
683
|
+
|-----------|---------|----------|
|
|
684
|
+
| `SmsProvider` | SMS delivery | — (BYOP) |
|
|
685
|
+
| `PushProvider` | Push notification delivery | — (BYOP) |
|
|
686
|
+
| `TemplateResolver` | Template rendering | `createSimpleResolver()` |
|
|
687
|
+
| `RateLimitStore` | Rate limit state | `MemoryRateLimitStore` |
|
|
688
|
+
| `DeliveryLog` | Audit trail | `MemoryDeliveryLog` |
|
|
689
|
+
| `QueueAdapter` | Crash-resilient queue | `MemoryQueue` |
|
|
690
|
+
| `IdempotencyStore` | Deduplication | `MemoryIdempotencyStore` |
|
|
691
|
+
| `PreferenceResolver` | User preference filtering | — (BYOP) |
|
|
471
692
|
|
|
472
693
|
### Exports
|
|
473
694
|
|
|
@@ -476,13 +697,28 @@ Abstract base class for channels. Provides `shouldHandle(event)` with wildcard s
|
|
|
476
697
|
import { NotificationService } from '@classytic/notifications';
|
|
477
698
|
|
|
478
699
|
// Channels
|
|
479
|
-
import {
|
|
700
|
+
import {
|
|
701
|
+
BaseChannel, EmailChannel, WebhookChannel,
|
|
702
|
+
ConsoleChannel, SmsChannel, PushChannel,
|
|
703
|
+
} from '@classytic/notifications/channels';
|
|
480
704
|
|
|
481
705
|
// Utilities
|
|
482
|
-
import {
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
706
|
+
import {
|
|
707
|
+
createSimpleResolver, withFallback, createStatusHandler,
|
|
708
|
+
MemoryDeliveryLog, MemoryRateLimitStore, MemoryQueue,
|
|
709
|
+
MemoryIdempotencyStore, mergeHooks, pMap,
|
|
710
|
+
withRetry, Emitter, isQuietHours,
|
|
711
|
+
NotificationError, ChannelError, ProviderNotInstalledError,
|
|
712
|
+
} from '@classytic/notifications/utils';
|
|
713
|
+
|
|
714
|
+
// Types
|
|
715
|
+
import type {
|
|
716
|
+
SmsProvider, PushProvider, DeliveryLog, DeliveryStatus,
|
|
717
|
+
StatusUpdate, StatusHandler, RateLimitStore, FallbackOptions,
|
|
718
|
+
QueueAdapter, IdempotencyStore, TemplateResolver,
|
|
719
|
+
Channel, ChannelConfig, NotificationPayload, SendResult,
|
|
720
|
+
DispatchResult, BatchOptions, BatchResult,
|
|
721
|
+
} from '@classytic/notifications';
|
|
486
722
|
```
|
|
487
723
|
|
|
488
724
|
## License
|