@classytic/notifications 0.0.1 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +37 -0
- package/README.md +490 -280
- package/dist/channels/index.d.mts +2 -0
- package/dist/channels/index.mjs +3 -0
- package/dist/concurrency-CV_XyiBQ.d.mts +139 -0
- package/dist/console.channel-BoWi_5nH.d.mts +39 -0
- package/dist/console.channel-CfA4b_Er.mjs +246 -0
- package/dist/errors-DAIVZx_Q.mjs +36 -0
- package/dist/index.d.mts +116 -0
- package/dist/index.mjs +369 -0
- package/dist/merge-hooks-B4_uHR9x.mjs +233 -0
- package/dist/types-BnjZ7x2U.d.mts +297 -0
- package/dist/utils/index.d.mts +3 -0
- package/dist/utils/index.mjs +4 -0
- package/package.json +73 -55
- package/notifications.d.ts +0 -269
- package/src/core/channel.js +0 -71
- package/src/core/dispatcher.js +0 -73
- package/src/core/factory.js +0 -92
- package/src/index.js +0 -36
- package/src/utils/merge-hooks.js +0 -45
package/README.md
CHANGED
|
@@ -1,280 +1,490 @@
|
|
|
1
|
-
# @classytic/notifications
|
|
2
|
-
|
|
3
|
-
> Multi-channel notification system for
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
## Features
|
|
8
|
-
|
|
9
|
-
-
|
|
10
|
-
-
|
|
11
|
-
-
|
|
12
|
-
-
|
|
13
|
-
-
|
|
14
|
-
-
|
|
15
|
-
-
|
|
16
|
-
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
```
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
```
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
);
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
new
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
```
|
|
199
|
-
const
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
##
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
1
|
+
# @classytic/notifications
|
|
2
|
+
|
|
3
|
+
> Multi-channel notification system for TypeScript/Node.js
|
|
4
|
+
|
|
5
|
+
Pluggable channels, templates, retry with backoff, and user preferences. Zero required dependencies — bring your own providers.
|
|
6
|
+
|
|
7
|
+
## Features
|
|
8
|
+
|
|
9
|
+
- **Multi-Channel** — Email (Nodemailer — Gmail, SES, SMTP, any transport), Webhook, Console, or build your own
|
|
10
|
+
- **Zero Required Deps** — Nodemailer is an optional peer dependency, loaded lazily
|
|
11
|
+
- **Templates** — Plug any template engine (React Email, MJML, Handlebars, etc.)
|
|
12
|
+
- **Retry + Backoff** — Exponential, linear, or fixed backoff with jitter. Per-channel overrides
|
|
13
|
+
- **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
|
+
- **Idempotency** — Built-in deduplication with pluggable stores (memory, Redis, DB)
|
|
16
|
+
- **Lifecycle Events** — `before:send`, `after:send`, `send:success`, `send:failed`, `send:retry`
|
|
17
|
+
- **Hook Factories** — Generate event handlers for EventEmitter, MongoKit, or any hook system
|
|
18
|
+
- **Webhook Signing** — HMAC-SHA256 payload signing out of the box
|
|
19
|
+
- **TypeScript** — Full type definitions, ESM-only
|
|
20
|
+
|
|
21
|
+
## Installation
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
npm install @classytic/notifications
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
**For EmailChannel** (optional — only if you use email):
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
npm install nodemailer
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Quick Start
|
|
34
|
+
|
|
35
|
+
```typescript
|
|
36
|
+
import { NotificationService } from '@classytic/notifications';
|
|
37
|
+
import { EmailChannel, WebhookChannel, ConsoleChannel } from '@classytic/notifications/channels';
|
|
38
|
+
|
|
39
|
+
const notifications = new NotificationService({
|
|
40
|
+
channels: [
|
|
41
|
+
new EmailChannel({
|
|
42
|
+
from: 'App <noreply@app.com>',
|
|
43
|
+
transport: { host: 'smtp.gmail.com', port: 587, auth: { user, pass } },
|
|
44
|
+
}),
|
|
45
|
+
new WebhookChannel({
|
|
46
|
+
url: 'https://hooks.slack.com/services/...',
|
|
47
|
+
events: ['order.*'],
|
|
48
|
+
}),
|
|
49
|
+
new ConsoleChannel(), // dev/testing
|
|
50
|
+
],
|
|
51
|
+
templates: async (id, data) => ({
|
|
52
|
+
subject: `Notification: ${id}`,
|
|
53
|
+
html: `<p>${JSON.stringify(data)}</p>`,
|
|
54
|
+
}),
|
|
55
|
+
retry: { maxAttempts: 3, backoff: 'exponential' },
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
await notifications.send({
|
|
59
|
+
event: 'user.created',
|
|
60
|
+
recipient: { email: 'user@example.com', name: 'John' },
|
|
61
|
+
data: { name: 'John' },
|
|
62
|
+
template: 'welcome',
|
|
63
|
+
});
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## Channels
|
|
67
|
+
|
|
68
|
+
### Built-in Channels
|
|
69
|
+
|
|
70
|
+
#### EmailChannel (Nodemailer)
|
|
71
|
+
|
|
72
|
+
Requires: `npm install nodemailer`
|
|
73
|
+
|
|
74
|
+
```typescript
|
|
75
|
+
import { EmailChannel } from '@classytic/notifications/channels';
|
|
76
|
+
|
|
77
|
+
// SMTP
|
|
78
|
+
const email = new EmailChannel({
|
|
79
|
+
from: 'App <noreply@app.com>',
|
|
80
|
+
transport: { host: 'smtp.gmail.com', port: 587, auth: { user, pass } },
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
// Gmail shorthand
|
|
84
|
+
const gmail = new EmailChannel({
|
|
85
|
+
from: 'noreply@app.com',
|
|
86
|
+
transport: { service: 'gmail', auth: { user, pass } },
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
// Pre-created transporter (SES, custom)
|
|
90
|
+
import nodemailer from 'nodemailer';
|
|
91
|
+
const email = new EmailChannel({
|
|
92
|
+
from: 'noreply@app.com',
|
|
93
|
+
transporter: nodemailer.createTransport({ /* SES config */ }),
|
|
94
|
+
});
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
#### WebhookChannel
|
|
98
|
+
|
|
99
|
+
Zero dependencies — uses native `fetch`.
|
|
100
|
+
|
|
101
|
+
```typescript
|
|
102
|
+
import { WebhookChannel } from '@classytic/notifications/channels';
|
|
103
|
+
|
|
104
|
+
const slack = new WebhookChannel({
|
|
105
|
+
url: 'https://hooks.slack.com/services/...',
|
|
106
|
+
events: ['order.completed', 'user.created'],
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
// With HMAC-SHA256 signing
|
|
110
|
+
const signed = new WebhookChannel({
|
|
111
|
+
url: 'https://api.partner.com/webhooks',
|
|
112
|
+
secret: process.env.WEBHOOK_SECRET!,
|
|
113
|
+
headers: { 'X-API-Key': process.env.PARTNER_KEY! },
|
|
114
|
+
timeout: 5000,
|
|
115
|
+
});
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
#### ConsoleChannel
|
|
119
|
+
|
|
120
|
+
Logs to console. Useful for development and testing.
|
|
121
|
+
|
|
122
|
+
```typescript
|
|
123
|
+
import { ConsoleChannel } from '@classytic/notifications/channels';
|
|
124
|
+
|
|
125
|
+
const dev = new ConsoleChannel();
|
|
126
|
+
const scoped = new ConsoleChannel({ events: ['user.*'] });
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
### Custom Channels
|
|
130
|
+
|
|
131
|
+
Extend `BaseChannel` or implement the `Channel` interface directly:
|
|
132
|
+
|
|
133
|
+
```typescript
|
|
134
|
+
import { BaseChannel } from '@classytic/notifications/channels';
|
|
135
|
+
import type { NotificationPayload, SendResult, ChannelConfig } from '@classytic/notifications';
|
|
136
|
+
|
|
137
|
+
interface SlackConfig extends ChannelConfig {
|
|
138
|
+
webhookUrl: string;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
class SlackChannel extends BaseChannel<SlackConfig> {
|
|
142
|
+
constructor(config: SlackConfig) {
|
|
143
|
+
super({ name: 'slack', ...config });
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
async send(payload: NotificationPayload): Promise<SendResult> {
|
|
147
|
+
const res = await fetch(this.config.webhookUrl, {
|
|
148
|
+
method: 'POST',
|
|
149
|
+
headers: { 'Content-Type': 'application/json' },
|
|
150
|
+
body: JSON.stringify({ text: String(payload.data.message) }),
|
|
151
|
+
});
|
|
152
|
+
if (!res.ok) return { status: 'failed', channel: this.name, error: res.statusText };
|
|
153
|
+
return { status: 'sent', channel: this.name };
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
### Event Filtering
|
|
159
|
+
|
|
160
|
+
Channels only receive events matching their `events` whitelist. Supports wildcards:
|
|
161
|
+
|
|
162
|
+
```typescript
|
|
163
|
+
new WebhookChannel({
|
|
164
|
+
url: '...',
|
|
165
|
+
events: ['order.*'], // matches order.created, order.completed, etc.
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
new ConsoleChannel({
|
|
169
|
+
events: [], // empty = all events (default)
|
|
170
|
+
});
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
### Per-Channel Retry Override
|
|
174
|
+
|
|
175
|
+
Channels can override the global retry config, including disabling retry:
|
|
176
|
+
|
|
177
|
+
```typescript
|
|
178
|
+
const notifications = new NotificationService({
|
|
179
|
+
retry: { maxAttempts: 3, backoff: 'exponential' }, // global default
|
|
180
|
+
channels: [
|
|
181
|
+
new EmailChannel({
|
|
182
|
+
from: 'noreply@app.com',
|
|
183
|
+
transport: { ... },
|
|
184
|
+
retry: { maxAttempts: 5 }, // more retries for email
|
|
185
|
+
}),
|
|
186
|
+
new WebhookChannel({
|
|
187
|
+
url: '...',
|
|
188
|
+
retry: { maxAttempts: 1 }, // disable retry for webhooks
|
|
189
|
+
}),
|
|
190
|
+
],
|
|
191
|
+
});
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
## Templates
|
|
195
|
+
|
|
196
|
+
Plug any template engine via a resolver function:
|
|
197
|
+
|
|
198
|
+
```typescript
|
|
199
|
+
const notifications = new NotificationService({
|
|
200
|
+
templates: async (templateId, data) => {
|
|
201
|
+
const templates: Record<string, { subject: string; html: string }> = {
|
|
202
|
+
welcome: {
|
|
203
|
+
subject: `Welcome ${data.name}!`,
|
|
204
|
+
html: `<h1>Hello ${data.name}</h1>`,
|
|
205
|
+
},
|
|
206
|
+
};
|
|
207
|
+
return templates[templateId] ?? { subject: templateId, text: JSON.stringify(data) };
|
|
208
|
+
},
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
await notifications.send({
|
|
212
|
+
event: 'user.created',
|
|
213
|
+
recipient: { email: 'user@example.com' },
|
|
214
|
+
data: { name: 'John' },
|
|
215
|
+
template: 'welcome', // resolved before sending
|
|
216
|
+
});
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
Template values are merged into `payload.data`, with template values taking precedence.
|
|
220
|
+
|
|
221
|
+
## User Preferences
|
|
222
|
+
|
|
223
|
+
Filter channels per-user with a preference resolver:
|
|
224
|
+
|
|
225
|
+
```typescript
|
|
226
|
+
const notifications = new NotificationService({
|
|
227
|
+
preferences: async (recipientId, event) => {
|
|
228
|
+
const prefs = await db.getUserPrefs(recipientId);
|
|
229
|
+
return {
|
|
230
|
+
channels: { email: true, sms: false }, // opt-out of SMS
|
|
231
|
+
events: { 'marketing.promo': false }, // opt-out of promos
|
|
232
|
+
quiet: { // quiet hours
|
|
233
|
+
start: '22:00',
|
|
234
|
+
end: '07:00',
|
|
235
|
+
timezone: 'America/New_York',
|
|
236
|
+
},
|
|
237
|
+
};
|
|
238
|
+
},
|
|
239
|
+
});
|
|
240
|
+
```
|
|
241
|
+
|
|
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
|
+
## Idempotency / Deduplication
|
|
265
|
+
|
|
266
|
+
Prevent duplicate notifications by providing an `idempotencyKey` on the payload. The key is only recorded after at least one channel succeeds.
|
|
267
|
+
|
|
268
|
+
```typescript
|
|
269
|
+
const notifications = new NotificationService({
|
|
270
|
+
channels: [new EmailChannel({ ... })],
|
|
271
|
+
idempotency: {}, // uses MemoryIdempotencyStore, 24h TTL
|
|
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
|
|
279
|
+
});
|
|
280
|
+
|
|
281
|
+
// Second send with same key → skipped (sent: 0, skipped: 1)
|
|
282
|
+
await notifications.send({
|
|
283
|
+
event: 'order.completed',
|
|
284
|
+
recipient: { email: 'user@example.com' },
|
|
285
|
+
data: { orderId: '123' },
|
|
286
|
+
idempotencyKey: 'order-completed-123',
|
|
287
|
+
});
|
|
288
|
+
```
|
|
289
|
+
|
|
290
|
+
### Custom Store + TTL
|
|
291
|
+
|
|
292
|
+
```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
|
+
import type { IdempotencyStore } from '@classytic/notifications/utils';
|
|
304
|
+
|
|
305
|
+
class RedisIdempotencyStore implements IdempotencyStore {
|
|
306
|
+
async has(key: string): Promise<boolean> {
|
|
307
|
+
return !!(await redis.exists(`idemp:${key}`));
|
|
308
|
+
}
|
|
309
|
+
async set(key: string, ttlMs: number): Promise<void> {
|
|
310
|
+
await redis.set(`idemp:${key}`, '1', 'PX', ttlMs);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
const notifications = new NotificationService({
|
|
315
|
+
idempotency: { store: new RedisIdempotencyStore() },
|
|
316
|
+
});
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
## Batch Sending
|
|
320
|
+
|
|
321
|
+
Send thousands of notifications with controlled concurrency using a worker-pool pattern:
|
|
322
|
+
|
|
323
|
+
```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
|
+
const batch = await notifications.sendBatch(payloads, {
|
|
333
|
+
concurrency: 20, // max parallel sends (default: 10)
|
|
334
|
+
onProgress: ({ completed, total }) => {
|
|
335
|
+
console.log(`${completed}/${total}`);
|
|
336
|
+
},
|
|
337
|
+
});
|
|
338
|
+
|
|
339
|
+
console.log(`Sent: ${batch.sent}, Failed: ${batch.failed}, Skipped: ${batch.skipped}`);
|
|
340
|
+
```
|
|
341
|
+
|
|
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
|
+
## Retry + Backoff
|
|
359
|
+
|
|
360
|
+
```typescript
|
|
361
|
+
const notifications = new NotificationService({
|
|
362
|
+
retry: {
|
|
363
|
+
maxAttempts: 3, // default: 1 (no retry)
|
|
364
|
+
backoff: 'exponential', // 'exponential' | 'linear' | 'fixed'
|
|
365
|
+
initialDelay: 500, // ms, default: 500
|
|
366
|
+
maxDelay: 30_000, // ms, default: 30000
|
|
367
|
+
},
|
|
368
|
+
});
|
|
369
|
+
```
|
|
370
|
+
|
|
371
|
+
Jitter (+-25%) is applied automatically to prevent thundering herd.
|
|
372
|
+
|
|
373
|
+
## Lifecycle Events
|
|
374
|
+
|
|
375
|
+
```typescript
|
|
376
|
+
notifications.on('before:send', (payload) => {
|
|
377
|
+
console.log('Sending:', payload.event);
|
|
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) => { /* ... */ });
|
|
386
|
+
notifications.on('send:retry', ({ channel, attempt, error }) => { /* ... */ });
|
|
387
|
+
|
|
388
|
+
// Remove listener
|
|
389
|
+
notifications.off('send:failed', handler);
|
|
390
|
+
```
|
|
391
|
+
|
|
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
|
+
## Hook Factories
|
|
398
|
+
|
|
399
|
+
Generate event handlers for any hook/event system:
|
|
400
|
+
|
|
401
|
+
```typescript
|
|
402
|
+
const hooks = notifications.createHooks([
|
|
403
|
+
{
|
|
404
|
+
event: 'user.created',
|
|
405
|
+
getRecipient: (user) => ({ email: user.email, name: user.name }),
|
|
406
|
+
getData: (user) => ({ name: user.name }),
|
|
407
|
+
template: 'welcome',
|
|
408
|
+
},
|
|
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
|
+
]);
|
|
417
|
+
|
|
418
|
+
// With EventEmitter
|
|
419
|
+
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
|
+
```
|
|
451
|
+
|
|
452
|
+
## API Reference
|
|
453
|
+
|
|
454
|
+
### `NotificationService`
|
|
455
|
+
|
|
456
|
+
| Method | Description |
|
|
457
|
+
|--------|-------------|
|
|
458
|
+
| `send(payload)` | Send notification to all matching channels |
|
|
459
|
+
| `sendBatch(payloads, options?)` | Send multiple notifications with concurrency control |
|
|
460
|
+
| `addChannel(channel)` | Register a channel at runtime |
|
|
461
|
+
| `removeChannel(name)` | Remove a channel by name |
|
|
462
|
+
| `getChannel(name)` | Get a channel by name |
|
|
463
|
+
| `getChannelNames()` | List all registered channel names |
|
|
464
|
+
| `createHooks(configs)` | Create event-specific hook handlers |
|
|
465
|
+
| `on(event, handler)` | Listen to lifecycle events |
|
|
466
|
+
| `off(event, handler)` | Remove a lifecycle listener |
|
|
467
|
+
|
|
468
|
+
### `BaseChannel<TConfig>`
|
|
469
|
+
|
|
470
|
+
Abstract base class for channels. Provides `shouldHandle(event)` with wildcard support.
|
|
471
|
+
|
|
472
|
+
### Exports
|
|
473
|
+
|
|
474
|
+
```typescript
|
|
475
|
+
// Core
|
|
476
|
+
import { NotificationService } from '@classytic/notifications';
|
|
477
|
+
|
|
478
|
+
// Channels
|
|
479
|
+
import { BaseChannel, EmailChannel, WebhookChannel, ConsoleChannel } from '@classytic/notifications/channels';
|
|
480
|
+
|
|
481
|
+
// Utilities
|
|
482
|
+
import { mergeHooks, withRetry, resolveRetryConfig, calculateDelay, Emitter } from '@classytic/notifications/utils';
|
|
483
|
+
import { NotificationError, ChannelError, ProviderNotInstalledError } from '@classytic/notifications/utils';
|
|
484
|
+
import { isQuietHours, MemoryIdempotencyStore, pMap } from '@classytic/notifications/utils';
|
|
485
|
+
import type { IdempotencyStore, PMapOptions, QuietHoursConfig } from '@classytic/notifications/utils';
|
|
486
|
+
```
|
|
487
|
+
|
|
488
|
+
## License
|
|
489
|
+
|
|
490
|
+
MIT
|