@classytic/notifications 0.0.1 → 2.0.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 +70 -0
- package/README.md +640 -280
- package/dist/channels/index.d.mts +2 -0
- package/dist/channels/index.mjs +3 -0
- package/dist/errors-FYJYmfvj.mjs +36 -0
- package/dist/index.d.mts +136 -0
- package/dist/index.mjs +458 -0
- package/dist/push.channel-4mRkzrEu.d.mts +55 -0
- package/dist/push.channel-D1FdTPUi.mjs +468 -0
- package/dist/status-webhook-BDaI1BMy.d.mts +268 -0
- package/dist/status-webhook-XY42DCj_.mjs +582 -0
- package/dist/types-D94B3VNX.d.mts +546 -0
- package/dist/utils/index.d.mts +3 -0
- package/dist/utils/index.mjs +4 -0
- package/package.json +75 -57
- 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
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
//#region src/utils/errors.ts
|
|
2
|
+
/**
|
|
3
|
+
* Notification Errors
|
|
4
|
+
* @module @classytic/notifications
|
|
5
|
+
*/
|
|
6
|
+
var NotificationError = class extends Error {
|
|
7
|
+
code;
|
|
8
|
+
channel;
|
|
9
|
+
cause;
|
|
10
|
+
constructor(message, options) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.name = "NotificationError";
|
|
13
|
+
this.code = options?.code ?? "NOTIFICATION_ERROR";
|
|
14
|
+
this.channel = options?.channel;
|
|
15
|
+
this.cause = options?.cause;
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
var ChannelError = class extends NotificationError {
|
|
19
|
+
constructor(channel, message, cause) {
|
|
20
|
+
super(`[${channel}] ${message}`, {
|
|
21
|
+
code: "CHANNEL_ERROR",
|
|
22
|
+
channel,
|
|
23
|
+
cause
|
|
24
|
+
});
|
|
25
|
+
this.name = "ChannelError";
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
var ProviderNotInstalledError = class extends NotificationError {
|
|
29
|
+
constructor(provider, installCmd) {
|
|
30
|
+
super(`${provider} is required but not installed. Install it: ${installCmd}`, { code: "PROVIDER_NOT_INSTALLED" });
|
|
31
|
+
this.name = "ProviderNotInstalledError";
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
//#endregion
|
|
36
|
+
export { NotificationError as n, ProviderNotInstalledError as r, ChannelError as t };
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
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-D94B3VNX.mjs";
|
|
2
|
+
import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "./push.channel-4mRkzrEu.mjs";
|
|
3
|
+
import { S as mergeHooks, _ as ProviderNotInstalledError, a as createStatusHandler, b as resolveRetryConfig, c as TemplateDefinition, d as PMapOptions, f as pMap, g as NotificationError, h as ChannelError, i as StatusUpdate, l as TemplateMap, m as isQuietHours, n as StatusHandler, o as FallbackOptions, p as QuietHoursConfig, r as StatusHandlerConfig, s as withFallback, t as DeliveryStatus, u as createSimpleResolver, v as Emitter, x as withRetry, y as calculateDelay } from "./status-webhook-BDaI1BMy.mjs";
|
|
4
|
+
|
|
5
|
+
//#region src/NotificationService.d.ts
|
|
6
|
+
declare class NotificationService {
|
|
7
|
+
private channels;
|
|
8
|
+
private templateResolver?;
|
|
9
|
+
private preferenceResolver?;
|
|
10
|
+
private retryConfig;
|
|
11
|
+
private logger;
|
|
12
|
+
private emitter;
|
|
13
|
+
private idempotencyStore?;
|
|
14
|
+
private idempotencyTtl;
|
|
15
|
+
private deliveryLog?;
|
|
16
|
+
private rateLimitStore?;
|
|
17
|
+
private queueAdapter?;
|
|
18
|
+
constructor(config?: NotificationServiceConfig);
|
|
19
|
+
/** Add a channel at runtime */
|
|
20
|
+
addChannel(channel: Channel): this;
|
|
21
|
+
/** Remove a channel by name */
|
|
22
|
+
removeChannel(name: string): this;
|
|
23
|
+
/** Get a registered channel by name */
|
|
24
|
+
getChannel(name: string): Channel | undefined;
|
|
25
|
+
/** List all registered channel names */
|
|
26
|
+
getChannelNames(): string[];
|
|
27
|
+
/** Get the delivery log instance (for querying history) */
|
|
28
|
+
getDeliveryLog(): DeliveryLog | undefined;
|
|
29
|
+
/**
|
|
30
|
+
* Send a notification to all matching channels.
|
|
31
|
+
*
|
|
32
|
+
* When a queue adapter is configured, notifications are enqueued
|
|
33
|
+
* for crash-resilient delivery instead of sending immediately.
|
|
34
|
+
*
|
|
35
|
+
* Flow:
|
|
36
|
+
* 1. Emit `before:send` (awaited — listeners can block or throw to abort)
|
|
37
|
+
* 2. If queue is configured, enqueue and return early
|
|
38
|
+
* 3. Resolve template (if provided)
|
|
39
|
+
* 4. Filter channels by event + target list
|
|
40
|
+
* 5. Apply user preference filtering
|
|
41
|
+
* 6. Check per-channel rate limits
|
|
42
|
+
* 7. Send to all channels in parallel (with retry)
|
|
43
|
+
* 8. Record to delivery log
|
|
44
|
+
* 9. Emit `after:send` / `send:success` / `send:failed`
|
|
45
|
+
*/
|
|
46
|
+
send(payload: NotificationPayload): Promise<DispatchResult>;
|
|
47
|
+
/**
|
|
48
|
+
* Internal send pipeline (used by both direct sends and queue processor).
|
|
49
|
+
*
|
|
50
|
+
* Every code path — including skips for idempotency, quiet hours, and
|
|
51
|
+
* preferences — flows through finalize() so delivery logging and
|
|
52
|
+
* lifecycle events are always emitted.
|
|
53
|
+
*/
|
|
54
|
+
private sendDirect;
|
|
55
|
+
/**
|
|
56
|
+
* Single exit path for all send outcomes.
|
|
57
|
+
* Records to delivery log and emits lifecycle events regardless of
|
|
58
|
+
* whether the notification was sent, skipped, or failed.
|
|
59
|
+
*/
|
|
60
|
+
private finalize;
|
|
61
|
+
/** Send to a single channel with rate limiting and retry */
|
|
62
|
+
private sendToChannel;
|
|
63
|
+
/** Extract rate limit config from a channel */
|
|
64
|
+
private getChannelRateLimit;
|
|
65
|
+
/**
|
|
66
|
+
* Send multiple notifications with controlled concurrency.
|
|
67
|
+
*
|
|
68
|
+
* Uses a worker-pool pattern: N workers pull from a shared queue,
|
|
69
|
+
* keeping the pipeline full at all times. Unlike chunk-and-wait,
|
|
70
|
+
* there's no idle time from slow outliers.
|
|
71
|
+
*
|
|
72
|
+
* Each notification goes through the full `send()` pipeline
|
|
73
|
+
* (lifecycle events, templates, preferences, retry). Errors in
|
|
74
|
+
* individual notifications are caught and reported — they never
|
|
75
|
+
* abort the batch.
|
|
76
|
+
*
|
|
77
|
+
* @example
|
|
78
|
+
* ```typescript
|
|
79
|
+
* const payloads = students.map(s => ({
|
|
80
|
+
* event: 'birthday',
|
|
81
|
+
* recipient: { id: s.id, email: s.email },
|
|
82
|
+
* data: { name: s.name },
|
|
83
|
+
* template: 'birthday',
|
|
84
|
+
* idempotencyKey: `birthday-${s.id}-2024`,
|
|
85
|
+
* }));
|
|
86
|
+
*
|
|
87
|
+
* const batch = await notifications.sendBatch(payloads, {
|
|
88
|
+
* concurrency: 20,
|
|
89
|
+
* onProgress: ({ completed, total }) => {
|
|
90
|
+
* console.log(`${completed}/${total}`);
|
|
91
|
+
* },
|
|
92
|
+
* });
|
|
93
|
+
*
|
|
94
|
+
* console.log(`Sent: ${batch.sent}, Failed: ${batch.failed}`);
|
|
95
|
+
* ```
|
|
96
|
+
*/
|
|
97
|
+
sendBatch(payloads: NotificationPayload[], options?: BatchOptions): Promise<BatchResult>;
|
|
98
|
+
/**
|
|
99
|
+
* Create event-specific hook handlers
|
|
100
|
+
*
|
|
101
|
+
* Returns a map of event name -> handler functions that can be plugged
|
|
102
|
+
* into any event system (EventEmitter, MongoKit hooks, custom).
|
|
103
|
+
*
|
|
104
|
+
* @example
|
|
105
|
+
* ```typescript
|
|
106
|
+
* const hooks = notifications.createHooks([
|
|
107
|
+
* {
|
|
108
|
+
* event: 'user.created',
|
|
109
|
+
* getRecipient: (user) => ({ email: user.email, name: user.name }),
|
|
110
|
+
* getData: (user) => ({ name: user.name }),
|
|
111
|
+
* template: 'welcome',
|
|
112
|
+
* },
|
|
113
|
+
* {
|
|
114
|
+
* event: 'order.completed',
|
|
115
|
+
* getRecipient: (order) => ({ email: order.customer.email }),
|
|
116
|
+
* getData: (order) => ({ orderId: order.id, total: order.total }),
|
|
117
|
+
* template: 'order-confirmation',
|
|
118
|
+
* channels: ['email'], // only email for this event
|
|
119
|
+
* },
|
|
120
|
+
* ]);
|
|
121
|
+
*
|
|
122
|
+
* // Plug into EventEmitter
|
|
123
|
+
* emitter.on('user.created', hooks['user.created'][0]);
|
|
124
|
+
*
|
|
125
|
+
* // Plug into MongoKit
|
|
126
|
+
* repo.on('after:create', hooks['user.created'][0]);
|
|
127
|
+
* ```
|
|
128
|
+
*/
|
|
129
|
+
createHooks(configs: NotificationHookConfig[]): HookMap;
|
|
130
|
+
/** Listen to service lifecycle events */
|
|
131
|
+
on(event: ServiceEvent, handler: EventHandler): this;
|
|
132
|
+
/** Remove an event listener */
|
|
133
|
+
off(event: ServiceEvent, handler: EventHandler): this;
|
|
134
|
+
}
|
|
135
|
+
//#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 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, 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, isQuietHours, mergeHooks, pMap, resolveRetryConfig, withFallback, withRetry };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,458 @@
|
|
|
1
|
+
import { a as MemoryDeliveryLog, c as MemoryRateLimitStore, d as isQuietHours, f as calculateDelay, h as Emitter, i as MemoryQueue, l as IDEMPOTENCY_DEFAULT_TTL, m as withRetry, n as withFallback, o as mergeHooks, p as resolveRetryConfig, r as createSimpleResolver, s as pMap, t as createStatusHandler, u as MemoryIdempotencyStore } from "./status-webhook-XY42DCj_.mjs";
|
|
2
|
+
import { n as NotificationError, r as ProviderNotInstalledError, t as ChannelError } from "./errors-FYJYmfvj.mjs";
|
|
3
|
+
import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "./push.channel-D1FdTPUi.mjs";
|
|
4
|
+
|
|
5
|
+
//#region src/NotificationService.ts
|
|
6
|
+
/**
|
|
7
|
+
* Notification Service
|
|
8
|
+
* @module @classytic/notifications
|
|
9
|
+
*
|
|
10
|
+
* Central orchestrator for multi-channel notifications.
|
|
11
|
+
* Routes notifications to channels, resolves templates,
|
|
12
|
+
* applies user preferences, retries on failure, and emits lifecycle events.
|
|
13
|
+
*
|
|
14
|
+
* v2 additions: rate limiting, delivery log, queue adapter, BCC batching.
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```typescript
|
|
18
|
+
* import { NotificationService } from '@classytic/notifications';
|
|
19
|
+
* import { EmailChannel, ConsoleChannel } from '@classytic/notifications/channels';
|
|
20
|
+
* import { MemoryDeliveryLog } from '@classytic/notifications/utils';
|
|
21
|
+
*
|
|
22
|
+
* const notifications = new NotificationService({
|
|
23
|
+
* channels: [
|
|
24
|
+
* new EmailChannel({
|
|
25
|
+
* from: 'noreply@app.com',
|
|
26
|
+
* transport: { service: 'gmail', auth: { user, pass } },
|
|
27
|
+
* rateLimit: { maxPerWindow: 500, windowMs: 86_400_000 }, // Gmail 500/day
|
|
28
|
+
* }),
|
|
29
|
+
* new ConsoleChannel(),
|
|
30
|
+
* ],
|
|
31
|
+
* templates: async (id, data) => {
|
|
32
|
+
* const templates = { welcome: { subject: `Welcome ${data.name}!`, html: `<p>Hi ${data.name}</p>` } };
|
|
33
|
+
* return templates[id] ?? { subject: id, text: JSON.stringify(data) };
|
|
34
|
+
* },
|
|
35
|
+
* retry: { maxAttempts: 3, backoff: 'exponential' },
|
|
36
|
+
* deliveryLog: new MemoryDeliveryLog(),
|
|
37
|
+
* });
|
|
38
|
+
*
|
|
39
|
+
* // Send a notification
|
|
40
|
+
* const result = await notifications.send({
|
|
41
|
+
* event: 'user.created',
|
|
42
|
+
* recipient: { email: 'user@example.com', name: 'John' },
|
|
43
|
+
* data: { name: 'John' },
|
|
44
|
+
* template: 'welcome',
|
|
45
|
+
* });
|
|
46
|
+
*
|
|
47
|
+
* // Listen to lifecycle events
|
|
48
|
+
* notifications.on('send:failed', ({ channel, error }) => {
|
|
49
|
+
* alertOps(`Notification channel ${channel} failed: ${error}`);
|
|
50
|
+
* });
|
|
51
|
+
* ```
|
|
52
|
+
*/
|
|
53
|
+
/** Silent logger (no output) */
|
|
54
|
+
const SILENT_LOGGER = {
|
|
55
|
+
info() {},
|
|
56
|
+
warn() {},
|
|
57
|
+
error() {},
|
|
58
|
+
debug() {}
|
|
59
|
+
};
|
|
60
|
+
var NotificationService = class {
|
|
61
|
+
channels = [];
|
|
62
|
+
templateResolver;
|
|
63
|
+
preferenceResolver;
|
|
64
|
+
retryConfig;
|
|
65
|
+
logger;
|
|
66
|
+
emitter = new Emitter();
|
|
67
|
+
idempotencyStore;
|
|
68
|
+
idempotencyTtl;
|
|
69
|
+
deliveryLog;
|
|
70
|
+
rateLimitStore;
|
|
71
|
+
queueAdapter;
|
|
72
|
+
constructor(config = {}) {
|
|
73
|
+
this.channels = config.channels ?? [];
|
|
74
|
+
this.templateResolver = config.templates;
|
|
75
|
+
this.preferenceResolver = config.preferences;
|
|
76
|
+
this.retryConfig = resolveRetryConfig(config.retry);
|
|
77
|
+
this.logger = config.logger ?? SILENT_LOGGER;
|
|
78
|
+
if (config.idempotency) {
|
|
79
|
+
this.idempotencyStore = config.idempotency.store ?? new MemoryIdempotencyStore();
|
|
80
|
+
this.idempotencyTtl = config.idempotency.ttl ?? 864e5;
|
|
81
|
+
} else this.idempotencyTtl = IDEMPOTENCY_DEFAULT_TTL;
|
|
82
|
+
this.deliveryLog = config.deliveryLog;
|
|
83
|
+
if (config.rateLimitStore) this.rateLimitStore = config.rateLimitStore;
|
|
84
|
+
else if (this.channels.some((ch) => this.getChannelRateLimit(ch))) this.rateLimitStore = new MemoryRateLimitStore();
|
|
85
|
+
if (config.queue) {
|
|
86
|
+
this.queueAdapter = config.queue;
|
|
87
|
+
this.queueAdapter.process(async (payload) => {
|
|
88
|
+
await this.sendDirect(payload);
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
/** Add a channel at runtime */
|
|
93
|
+
addChannel(channel) {
|
|
94
|
+
this.channels.push(channel);
|
|
95
|
+
if (!this.rateLimitStore && this.getChannelRateLimit(channel)) this.rateLimitStore = new MemoryRateLimitStore();
|
|
96
|
+
return this;
|
|
97
|
+
}
|
|
98
|
+
/** Remove a channel by name */
|
|
99
|
+
removeChannel(name) {
|
|
100
|
+
this.channels = this.channels.filter((c) => c.name !== name);
|
|
101
|
+
return this;
|
|
102
|
+
}
|
|
103
|
+
/** Get a registered channel by name */
|
|
104
|
+
getChannel(name) {
|
|
105
|
+
return this.channels.find((c) => c.name === name);
|
|
106
|
+
}
|
|
107
|
+
/** List all registered channel names */
|
|
108
|
+
getChannelNames() {
|
|
109
|
+
return this.channels.map((c) => c.name);
|
|
110
|
+
}
|
|
111
|
+
/** Get the delivery log instance (for querying history) */
|
|
112
|
+
getDeliveryLog() {
|
|
113
|
+
return this.deliveryLog;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Send a notification to all matching channels.
|
|
117
|
+
*
|
|
118
|
+
* When a queue adapter is configured, notifications are enqueued
|
|
119
|
+
* for crash-resilient delivery instead of sending immediately.
|
|
120
|
+
*
|
|
121
|
+
* Flow:
|
|
122
|
+
* 1. Emit `before:send` (awaited — listeners can block or throw to abort)
|
|
123
|
+
* 2. If queue is configured, enqueue and return early
|
|
124
|
+
* 3. Resolve template (if provided)
|
|
125
|
+
* 4. Filter channels by event + target list
|
|
126
|
+
* 5. Apply user preference filtering
|
|
127
|
+
* 6. Check per-channel rate limits
|
|
128
|
+
* 7. Send to all channels in parallel (with retry)
|
|
129
|
+
* 8. Record to delivery log
|
|
130
|
+
* 9. Emit `after:send` / `send:success` / `send:failed`
|
|
131
|
+
*/
|
|
132
|
+
async send(payload) {
|
|
133
|
+
if (this.queueAdapter) {
|
|
134
|
+
const enqueueOptions = payload.delay ? { delay: payload.delay } : void 0;
|
|
135
|
+
const jobId = await this.queueAdapter.enqueue(payload, enqueueOptions);
|
|
136
|
+
this.logger.debug?.(`Notification queued (job: ${jobId}${payload.delay ? `, delay: ${payload.delay}ms` : ""})`);
|
|
137
|
+
try {
|
|
138
|
+
await this.emitter.emit("send:queued", {
|
|
139
|
+
jobId,
|
|
140
|
+
payload
|
|
141
|
+
});
|
|
142
|
+
} catch {}
|
|
143
|
+
return {
|
|
144
|
+
event: payload.event,
|
|
145
|
+
results: [],
|
|
146
|
+
sent: 0,
|
|
147
|
+
failed: 0,
|
|
148
|
+
skipped: 0,
|
|
149
|
+
duration: 0,
|
|
150
|
+
queued: true
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
if (payload.delay) this.logger.warn("payload.delay requires a queue adapter — sending immediately");
|
|
154
|
+
return this.sendDirect(payload);
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Internal send pipeline (used by both direct sends and queue processor).
|
|
158
|
+
*
|
|
159
|
+
* Every code path — including skips for idempotency, quiet hours, and
|
|
160
|
+
* preferences — flows through finalize() so delivery logging and
|
|
161
|
+
* lifecycle events are always emitted.
|
|
162
|
+
*/
|
|
163
|
+
async sendDirect(payload) {
|
|
164
|
+
const start = Date.now();
|
|
165
|
+
await this.emitter.emit("before:send", payload);
|
|
166
|
+
if (payload.idempotencyKey && this.idempotencyStore) {
|
|
167
|
+
if (await this.idempotencyStore.has(payload.idempotencyKey)) {
|
|
168
|
+
this.logger.debug?.(`Duplicate notification skipped (key: ${payload.idempotencyKey})`);
|
|
169
|
+
return this.finalize(payload, {
|
|
170
|
+
event: payload.event,
|
|
171
|
+
results: [],
|
|
172
|
+
sent: 0,
|
|
173
|
+
failed: 0,
|
|
174
|
+
skipped: 1,
|
|
175
|
+
duration: Date.now() - start
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
let enrichedPayload = payload;
|
|
180
|
+
if (payload.template && this.templateResolver) try {
|
|
181
|
+
const rendered = await this.templateResolver(payload.template, payload.data);
|
|
182
|
+
enrichedPayload = {
|
|
183
|
+
...payload,
|
|
184
|
+
data: {
|
|
185
|
+
...payload.data,
|
|
186
|
+
...rendered
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
} catch (err) {
|
|
190
|
+
this.logger.error(`Template resolution failed for "${payload.template}"`, err);
|
|
191
|
+
throw new NotificationError(`Template "${payload.template}" failed: ${err instanceof Error ? err.message : err}`, { code: "TEMPLATE_ERROR" });
|
|
192
|
+
}
|
|
193
|
+
let activeChannels = this.channels.filter((ch) => ch.shouldHandle(payload.event));
|
|
194
|
+
if (payload.channels?.length) {
|
|
195
|
+
const targetSet = new Set(payload.channels);
|
|
196
|
+
activeChannels = activeChannels.filter((ch) => targetSet.has(ch.name));
|
|
197
|
+
}
|
|
198
|
+
if (enrichedPayload.recipient.id && this.preferenceResolver) try {
|
|
199
|
+
const prefs = await this.preferenceResolver(enrichedPayload.recipient.id, enrichedPayload.event);
|
|
200
|
+
if (prefs) {
|
|
201
|
+
if (prefs.quiet && isQuietHours(prefs.quiet)) {
|
|
202
|
+
this.logger.debug?.(`Notification skipped: quiet hours active for ${enrichedPayload.recipient.id}`);
|
|
203
|
+
return this.finalize(payload, {
|
|
204
|
+
event: enrichedPayload.event,
|
|
205
|
+
results: [],
|
|
206
|
+
sent: 0,
|
|
207
|
+
failed: 0,
|
|
208
|
+
skipped: activeChannels.length,
|
|
209
|
+
duration: Date.now() - start
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
if (prefs.channels) activeChannels = activeChannels.filter((ch) => prefs.channels[ch.name] !== false);
|
|
213
|
+
if (prefs.events?.[enrichedPayload.event] === false) return this.finalize(payload, {
|
|
214
|
+
event: enrichedPayload.event,
|
|
215
|
+
results: [],
|
|
216
|
+
sent: 0,
|
|
217
|
+
failed: 0,
|
|
218
|
+
skipped: activeChannels.length,
|
|
219
|
+
duration: Date.now() - start
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
} catch (err) {
|
|
223
|
+
this.logger.warn("Preference resolution failed, sending to all channels", err);
|
|
224
|
+
}
|
|
225
|
+
if (!activeChannels.length) return this.finalize(payload, {
|
|
226
|
+
event: enrichedPayload.event,
|
|
227
|
+
results: [],
|
|
228
|
+
sent: 0,
|
|
229
|
+
failed: 0,
|
|
230
|
+
skipped: 0,
|
|
231
|
+
duration: Date.now() - start
|
|
232
|
+
});
|
|
233
|
+
const results = await Promise.all(activeChannels.map((channel) => this.sendToChannel(channel, enrichedPayload)));
|
|
234
|
+
const dispatch = {
|
|
235
|
+
event: enrichedPayload.event,
|
|
236
|
+
results,
|
|
237
|
+
sent: results.filter((r) => r.status === "sent").length,
|
|
238
|
+
failed: results.filter((r) => r.status === "failed").length,
|
|
239
|
+
skipped: results.filter((r) => r.status === "skipped").length,
|
|
240
|
+
duration: Date.now() - start
|
|
241
|
+
};
|
|
242
|
+
if (payload.idempotencyKey && this.idempotencyStore && dispatch.sent > 0) try {
|
|
243
|
+
await this.idempotencyStore.set(payload.idempotencyKey, this.idempotencyTtl);
|
|
244
|
+
} catch (err) {
|
|
245
|
+
this.logger.warn(`Idempotency store error: ${err instanceof Error ? err.message : err}`);
|
|
246
|
+
}
|
|
247
|
+
return this.finalize(payload, dispatch);
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Single exit path for all send outcomes.
|
|
251
|
+
* Records to delivery log and emits lifecycle events regardless of
|
|
252
|
+
* whether the notification was sent, skipped, or failed.
|
|
253
|
+
*/
|
|
254
|
+
async finalize(payload, dispatch) {
|
|
255
|
+
if (this.deliveryLog) try {
|
|
256
|
+
await this.deliveryLog.record(payload, dispatch);
|
|
257
|
+
} catch (err) {
|
|
258
|
+
this.logger.warn(`Delivery log error: ${err instanceof Error ? err.message : err}`);
|
|
259
|
+
}
|
|
260
|
+
try {
|
|
261
|
+
await this.emitter.emit("after:send", dispatch);
|
|
262
|
+
if (dispatch.failed > 0) await this.emitter.emit("send:failed", dispatch);
|
|
263
|
+
if (dispatch.sent > 0) await this.emitter.emit("send:success", dispatch);
|
|
264
|
+
} catch (err) {
|
|
265
|
+
this.logger.error(`Lifecycle listener error: ${err instanceof Error ? err.message : err}`);
|
|
266
|
+
}
|
|
267
|
+
return dispatch;
|
|
268
|
+
}
|
|
269
|
+
/** Send to a single channel with rate limiting and retry */
|
|
270
|
+
async sendToChannel(channel, payload) {
|
|
271
|
+
const rateLimit = this.getChannelRateLimit(channel);
|
|
272
|
+
if (rateLimit && this.rateLimitStore) {
|
|
273
|
+
if (!await this.rateLimitStore.consume(channel.name, rateLimit)) {
|
|
274
|
+
this.logger.warn(`[${channel.name}] Rate limited — skipping`);
|
|
275
|
+
this.emitter.emit("send:rate_limited", {
|
|
276
|
+
channel: channel.name,
|
|
277
|
+
event: payload.event
|
|
278
|
+
}).catch((err) => {
|
|
279
|
+
this.logger.error(`[${channel.name}] send:rate_limited listener error: ${err instanceof Error ? err.message : err}`);
|
|
280
|
+
});
|
|
281
|
+
return {
|
|
282
|
+
status: "skipped",
|
|
283
|
+
channel: channel.name,
|
|
284
|
+
error: "Rate limited"
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
const channelRetryRaw = channel.config?.retry;
|
|
289
|
+
const retryConfig = channelRetryRaw ? resolveRetryConfig(channelRetryRaw) : this.retryConfig;
|
|
290
|
+
const start = Date.now();
|
|
291
|
+
try {
|
|
292
|
+
return {
|
|
293
|
+
...await withRetry(() => channel.send(payload), retryConfig, (attempt, error) => {
|
|
294
|
+
this.logger.warn(`[${channel.name}] Retry ${attempt}/${retryConfig.maxAttempts}: ${error.message}`);
|
|
295
|
+
this.emitter.emit("send:retry", {
|
|
296
|
+
channel: channel.name,
|
|
297
|
+
attempt,
|
|
298
|
+
error: error.message
|
|
299
|
+
}).catch((emitErr) => {
|
|
300
|
+
this.logger.error(`[${channel.name}] send:retry listener error: ${emitErr instanceof Error ? emitErr.message : emitErr}`);
|
|
301
|
+
});
|
|
302
|
+
}),
|
|
303
|
+
duration: Date.now() - start
|
|
304
|
+
};
|
|
305
|
+
} catch (err) {
|
|
306
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
307
|
+
this.logger.error(`[${channel.name}] Failed: ${message}`);
|
|
308
|
+
return {
|
|
309
|
+
status: "failed",
|
|
310
|
+
channel: channel.name,
|
|
311
|
+
error: message,
|
|
312
|
+
duration: Date.now() - start
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
/** Extract rate limit config from a channel */
|
|
317
|
+
getChannelRateLimit(channel) {
|
|
318
|
+
return channel.config?.rateLimit;
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* Send multiple notifications with controlled concurrency.
|
|
322
|
+
*
|
|
323
|
+
* Uses a worker-pool pattern: N workers pull from a shared queue,
|
|
324
|
+
* keeping the pipeline full at all times. Unlike chunk-and-wait,
|
|
325
|
+
* there's no idle time from slow outliers.
|
|
326
|
+
*
|
|
327
|
+
* Each notification goes through the full `send()` pipeline
|
|
328
|
+
* (lifecycle events, templates, preferences, retry). Errors in
|
|
329
|
+
* individual notifications are caught and reported — they never
|
|
330
|
+
* abort the batch.
|
|
331
|
+
*
|
|
332
|
+
* @example
|
|
333
|
+
* ```typescript
|
|
334
|
+
* const payloads = students.map(s => ({
|
|
335
|
+
* event: 'birthday',
|
|
336
|
+
* recipient: { id: s.id, email: s.email },
|
|
337
|
+
* data: { name: s.name },
|
|
338
|
+
* template: 'birthday',
|
|
339
|
+
* idempotencyKey: `birthday-${s.id}-2024`,
|
|
340
|
+
* }));
|
|
341
|
+
*
|
|
342
|
+
* const batch = await notifications.sendBatch(payloads, {
|
|
343
|
+
* concurrency: 20,
|
|
344
|
+
* onProgress: ({ completed, total }) => {
|
|
345
|
+
* console.log(`${completed}/${total}`);
|
|
346
|
+
* },
|
|
347
|
+
* });
|
|
348
|
+
*
|
|
349
|
+
* console.log(`Sent: ${batch.sent}, Failed: ${batch.failed}`);
|
|
350
|
+
* ```
|
|
351
|
+
*/
|
|
352
|
+
async sendBatch(payloads, options = {}) {
|
|
353
|
+
const { concurrency = 10, onProgress } = options;
|
|
354
|
+
const start = Date.now();
|
|
355
|
+
let completed = 0;
|
|
356
|
+
const results = await pMap(payloads, async (payload) => {
|
|
357
|
+
let result;
|
|
358
|
+
try {
|
|
359
|
+
result = await this.send(payload);
|
|
360
|
+
} catch (err) {
|
|
361
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
362
|
+
this.logger.error(`[batch] Notification failed for event "${payload.event}": ${message}`);
|
|
363
|
+
result = {
|
|
364
|
+
event: payload.event,
|
|
365
|
+
results: [],
|
|
366
|
+
sent: 0,
|
|
367
|
+
failed: 1,
|
|
368
|
+
skipped: 0,
|
|
369
|
+
duration: 0
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
completed++;
|
|
373
|
+
onProgress?.({
|
|
374
|
+
completed,
|
|
375
|
+
total: payloads.length,
|
|
376
|
+
result
|
|
377
|
+
});
|
|
378
|
+
return result;
|
|
379
|
+
}, { concurrency });
|
|
380
|
+
return {
|
|
381
|
+
total: payloads.length,
|
|
382
|
+
sent: results.reduce((sum, r) => sum + r.sent, 0),
|
|
383
|
+
failed: results.reduce((sum, r) => sum + r.failed, 0),
|
|
384
|
+
skipped: results.reduce((sum, r) => sum + r.skipped, 0),
|
|
385
|
+
duration: Date.now() - start,
|
|
386
|
+
results
|
|
387
|
+
};
|
|
388
|
+
}
|
|
389
|
+
/**
|
|
390
|
+
* Create event-specific hook handlers
|
|
391
|
+
*
|
|
392
|
+
* Returns a map of event name -> handler functions that can be plugged
|
|
393
|
+
* into any event system (EventEmitter, MongoKit hooks, custom).
|
|
394
|
+
*
|
|
395
|
+
* @example
|
|
396
|
+
* ```typescript
|
|
397
|
+
* const hooks = notifications.createHooks([
|
|
398
|
+
* {
|
|
399
|
+
* event: 'user.created',
|
|
400
|
+
* getRecipient: (user) => ({ email: user.email, name: user.name }),
|
|
401
|
+
* getData: (user) => ({ name: user.name }),
|
|
402
|
+
* template: 'welcome',
|
|
403
|
+
* },
|
|
404
|
+
* {
|
|
405
|
+
* event: 'order.completed',
|
|
406
|
+
* getRecipient: (order) => ({ email: order.customer.email }),
|
|
407
|
+
* getData: (order) => ({ orderId: order.id, total: order.total }),
|
|
408
|
+
* template: 'order-confirmation',
|
|
409
|
+
* channels: ['email'], // only email for this event
|
|
410
|
+
* },
|
|
411
|
+
* ]);
|
|
412
|
+
*
|
|
413
|
+
* // Plug into EventEmitter
|
|
414
|
+
* emitter.on('user.created', hooks['user.created'][0]);
|
|
415
|
+
*
|
|
416
|
+
* // Plug into MongoKit
|
|
417
|
+
* repo.on('after:create', hooks['user.created'][0]);
|
|
418
|
+
* ```
|
|
419
|
+
*/
|
|
420
|
+
createHooks(configs) {
|
|
421
|
+
const hooks = {};
|
|
422
|
+
for (const config of configs) {
|
|
423
|
+
if (config.enabled === false) continue;
|
|
424
|
+
const handler = async (eventData) => {
|
|
425
|
+
try {
|
|
426
|
+
const recipient = await config.getRecipient(eventData);
|
|
427
|
+
if (!recipient) return void 0;
|
|
428
|
+
return await this.send({
|
|
429
|
+
event: config.event,
|
|
430
|
+
recipient,
|
|
431
|
+
data: config.getData(eventData),
|
|
432
|
+
template: config.template,
|
|
433
|
+
channels: config.channels
|
|
434
|
+
});
|
|
435
|
+
} catch (err) {
|
|
436
|
+
this.logger.error(`[hook:${config.event}] ${err instanceof Error ? err.message : err}`);
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
439
|
+
};
|
|
440
|
+
if (!hooks[config.event]) hooks[config.event] = [];
|
|
441
|
+
hooks[config.event].push(handler);
|
|
442
|
+
}
|
|
443
|
+
return hooks;
|
|
444
|
+
}
|
|
445
|
+
/** Listen to service lifecycle events */
|
|
446
|
+
on(event, handler) {
|
|
447
|
+
this.emitter.on(event, handler);
|
|
448
|
+
return this;
|
|
449
|
+
}
|
|
450
|
+
/** Remove an event listener */
|
|
451
|
+
off(event, handler) {
|
|
452
|
+
this.emitter.off(event, handler);
|
|
453
|
+
return this;
|
|
454
|
+
}
|
|
455
|
+
};
|
|
456
|
+
|
|
457
|
+
//#endregion
|
|
458
|
+
export { BaseChannel, ChannelError, ConsoleChannel, EmailChannel, Emitter, IDEMPOTENCY_DEFAULT_TTL, MemoryDeliveryLog, MemoryIdempotencyStore, MemoryQueue, MemoryRateLimitStore, NotificationError, NotificationService, ProviderNotInstalledError, PushChannel, SmsChannel, WebhookChannel, calculateDelay, createSimpleResolver, createStatusHandler, isQuietHours, mergeHooks, pMap, resolveRetryConfig, withFallback, withRetry };
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { E as SmsChannelConfig, a as ChannelConfig, c as EmailChannelConfig, h as NotificationPayload, i as Channel, j as WebhookChannelConfig, w as SendResult, y as PushChannelConfig } from "./types-D94B3VNX.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/channels/BaseChannel.d.ts
|
|
4
|
+
declare abstract class BaseChannel<TConfig extends ChannelConfig = ChannelConfig> implements Channel {
|
|
5
|
+
readonly name: string;
|
|
6
|
+
protected config: TConfig;
|
|
7
|
+
constructor(config: TConfig);
|
|
8
|
+
/** Check if this channel should handle a given event */
|
|
9
|
+
shouldHandle(event: string): boolean;
|
|
10
|
+
/** Send notification - must be implemented by subclass */
|
|
11
|
+
abstract send(payload: NotificationPayload): Promise<SendResult>;
|
|
12
|
+
}
|
|
13
|
+
//#endregion
|
|
14
|
+
//#region src/channels/email.channel.d.ts
|
|
15
|
+
declare class EmailChannel extends BaseChannel<EmailChannelConfig> {
|
|
16
|
+
private transporter;
|
|
17
|
+
constructor(config: EmailChannelConfig);
|
|
18
|
+
/** Lazily initialize the Nodemailer transporter */
|
|
19
|
+
private getTransporter;
|
|
20
|
+
/** Fields that defaults must never override */
|
|
21
|
+
private static readonly PROTECTED_FIELDS;
|
|
22
|
+
send(payload: NotificationPayload): Promise<SendResult>;
|
|
23
|
+
/** Verify the SMTP connection (useful for health checks) */
|
|
24
|
+
verify(): Promise<boolean>;
|
|
25
|
+
/** Close the transporter connection */
|
|
26
|
+
close(): void;
|
|
27
|
+
}
|
|
28
|
+
//#endregion
|
|
29
|
+
//#region src/channels/webhook.channel.d.ts
|
|
30
|
+
declare class WebhookChannel extends BaseChannel<WebhookChannelConfig> {
|
|
31
|
+
constructor(config: WebhookChannelConfig);
|
|
32
|
+
send(payload: NotificationPayload): Promise<SendResult>;
|
|
33
|
+
}
|
|
34
|
+
//#endregion
|
|
35
|
+
//#region src/channels/console.channel.d.ts
|
|
36
|
+
declare class ConsoleChannel extends BaseChannel<ChannelConfig> {
|
|
37
|
+
constructor(config?: ChannelConfig);
|
|
38
|
+
send(payload: NotificationPayload): Promise<SendResult>;
|
|
39
|
+
}
|
|
40
|
+
//#endregion
|
|
41
|
+
//#region src/channels/sms.channel.d.ts
|
|
42
|
+
declare class SmsChannel extends BaseChannel<SmsChannelConfig> {
|
|
43
|
+
private provider;
|
|
44
|
+
constructor(config: SmsChannelConfig);
|
|
45
|
+
send(payload: NotificationPayload): Promise<SendResult>;
|
|
46
|
+
}
|
|
47
|
+
//#endregion
|
|
48
|
+
//#region src/channels/push.channel.d.ts
|
|
49
|
+
declare class PushChannel extends BaseChannel<PushChannelConfig> {
|
|
50
|
+
private provider;
|
|
51
|
+
constructor(config: PushChannelConfig);
|
|
52
|
+
send(payload: NotificationPayload): Promise<SendResult>;
|
|
53
|
+
}
|
|
54
|
+
//#endregion
|
|
55
|
+
export { EmailChannel as a, WebhookChannel as i, SmsChannel as n, BaseChannel as o, ConsoleChannel as r, PushChannel as t };
|