@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,268 @@
|
|
|
1
|
+
import { C as RetryConfig, S as ResolvedRetryConfig, d as HookMap, h as NotificationPayload, k as TemplateResolver, o as DispatchResult, u as HookHandler } from "./types-D94B3VNX.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/utils/merge-hooks.d.ts
|
|
4
|
+
type HookInput = Record<string, HookHandler | HookHandler[]>;
|
|
5
|
+
declare function mergeHooks(...hookConfigs: (HookInput | null | undefined)[]): HookMap;
|
|
6
|
+
//#endregion
|
|
7
|
+
//#region src/utils/retry.d.ts
|
|
8
|
+
/** Resolve retry config with defaults */
|
|
9
|
+
declare function resolveRetryConfig(config?: RetryConfig): ResolvedRetryConfig;
|
|
10
|
+
/** Calculate delay for a given attempt */
|
|
11
|
+
declare function calculateDelay(attempt: number, config: ResolvedRetryConfig): number;
|
|
12
|
+
/**
|
|
13
|
+
* Execute a function with retry and backoff
|
|
14
|
+
*
|
|
15
|
+
* @param fn - Async function to retry
|
|
16
|
+
* @param config - Retry configuration
|
|
17
|
+
* @param onRetry - Called before each retry attempt
|
|
18
|
+
* @returns Result of fn
|
|
19
|
+
* @throws Last error after all attempts exhausted
|
|
20
|
+
*/
|
|
21
|
+
declare function withRetry<T>(fn: () => Promise<T>, config: ResolvedRetryConfig, onRetry?: (attempt: number, error: Error) => void): Promise<T>;
|
|
22
|
+
//#endregion
|
|
23
|
+
//#region src/utils/emitter.d.ts
|
|
24
|
+
/**
|
|
25
|
+
* Lightweight typed event emitter
|
|
26
|
+
* @module @classytic/notifications
|
|
27
|
+
*
|
|
28
|
+
* Zero-dependency alternative to Node's EventEmitter.
|
|
29
|
+
* Keeps the library portable across runtimes.
|
|
30
|
+
*/
|
|
31
|
+
type Handler = (...args: unknown[]) => void | Promise<void>;
|
|
32
|
+
declare class Emitter {
|
|
33
|
+
private handlers;
|
|
34
|
+
/** Register an event handler */
|
|
35
|
+
on(event: string, handler: Handler): this;
|
|
36
|
+
/** Remove an event handler */
|
|
37
|
+
off(event: string, handler: Handler): this;
|
|
38
|
+
/** Emit an event (runs handlers sequentially, awaits async) */
|
|
39
|
+
emit(event: string, ...args: unknown[]): Promise<void>;
|
|
40
|
+
/** Remove all handlers for an event (or all events) */
|
|
41
|
+
removeAll(event?: string): this;
|
|
42
|
+
}
|
|
43
|
+
//#endregion
|
|
44
|
+
//#region src/utils/errors.d.ts
|
|
45
|
+
/**
|
|
46
|
+
* Notification Errors
|
|
47
|
+
* @module @classytic/notifications
|
|
48
|
+
*/
|
|
49
|
+
declare class NotificationError extends Error {
|
|
50
|
+
readonly code: string;
|
|
51
|
+
readonly channel?: string;
|
|
52
|
+
readonly cause?: Error;
|
|
53
|
+
constructor(message: string, options?: {
|
|
54
|
+
code?: string;
|
|
55
|
+
channel?: string;
|
|
56
|
+
cause?: Error;
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
declare class ChannelError extends NotificationError {
|
|
60
|
+
constructor(channel: string, message: string, cause?: Error);
|
|
61
|
+
}
|
|
62
|
+
declare class ProviderNotInstalledError extends NotificationError {
|
|
63
|
+
constructor(provider: string, installCmd: string);
|
|
64
|
+
}
|
|
65
|
+
//#endregion
|
|
66
|
+
//#region src/utils/quiet-hours.d.ts
|
|
67
|
+
/**
|
|
68
|
+
* Quiet hours utility
|
|
69
|
+
* @module @classytic/notifications/utils
|
|
70
|
+
*
|
|
71
|
+
* Checks if the current time falls within a user's quiet hours window.
|
|
72
|
+
* Uses Intl.DateTimeFormat for timezone conversion (zero dependencies, Node 18+).
|
|
73
|
+
*/
|
|
74
|
+
/** Quiet hours configuration */
|
|
75
|
+
interface QuietHoursConfig {
|
|
76
|
+
/** Start time in HH:MM format (e.g. "22:00") */
|
|
77
|
+
start?: string;
|
|
78
|
+
/** End time in HH:MM format (e.g. "07:00") */
|
|
79
|
+
end?: string;
|
|
80
|
+
/** IANA timezone (e.g. "America/New_York"). Defaults to UTC */
|
|
81
|
+
timezone?: string;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Check if the current time falls within quiet hours.
|
|
85
|
+
*
|
|
86
|
+
* Supports overnight ranges (e.g. 22:00 - 07:00).
|
|
87
|
+
* Returns false if start/end are missing or malformed.
|
|
88
|
+
*
|
|
89
|
+
* @param quiet - Quiet hours config with start, end, and optional timezone
|
|
90
|
+
* @param now - Current date (defaults to new Date(), injectable for testing)
|
|
91
|
+
*/
|
|
92
|
+
declare function isQuietHours(quiet: QuietHoursConfig, now?: Date): boolean;
|
|
93
|
+
//#endregion
|
|
94
|
+
//#region src/utils/concurrency.d.ts
|
|
95
|
+
/**
|
|
96
|
+
* Concurrency pool utility
|
|
97
|
+
* @module @classytic/notifications/utils
|
|
98
|
+
*
|
|
99
|
+
* Process items in parallel with controlled concurrency.
|
|
100
|
+
* Zero dependencies — uses a worker-pool pattern where N workers
|
|
101
|
+
* pull from a shared queue, keeping the pipeline full at all times.
|
|
102
|
+
*
|
|
103
|
+
* Unlike chunk-based approaches (process N, wait, process N, wait),
|
|
104
|
+
* the pool starts the next item as soon as any worker finishes,
|
|
105
|
+
* eliminating idle time from slow outliers.
|
|
106
|
+
*
|
|
107
|
+
* @example
|
|
108
|
+
* ```typescript
|
|
109
|
+
* import { pMap } from '@classytic/notifications/utils';
|
|
110
|
+
*
|
|
111
|
+
* const results = await pMap(
|
|
112
|
+
* urls,
|
|
113
|
+
* async (url) => fetch(url).then(r => r.json()),
|
|
114
|
+
* { concurrency: 5 },
|
|
115
|
+
* );
|
|
116
|
+
* ```
|
|
117
|
+
*/
|
|
118
|
+
/** Options for pMap */
|
|
119
|
+
interface PMapOptions {
|
|
120
|
+
/** Max parallel operations (default: 10) */
|
|
121
|
+
concurrency?: number;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Map over items with controlled concurrency.
|
|
125
|
+
*
|
|
126
|
+
* Like `Promise.all(items.map(fn))` but with a max number of
|
|
127
|
+
* parallel operations. Results are returned in input order.
|
|
128
|
+
*
|
|
129
|
+
* Uses a worker-pool pattern: N workers pull from a shared index,
|
|
130
|
+
* so the pipeline stays full even when some items are slower.
|
|
131
|
+
*
|
|
132
|
+
* @param items - Array of items to process
|
|
133
|
+
* @param fn - Async function to apply to each item
|
|
134
|
+
* @param options - Concurrency options
|
|
135
|
+
* @returns Array of results in the same order as input
|
|
136
|
+
*/
|
|
137
|
+
declare function pMap<T, R>(items: T[], fn: (item: T, index: number) => Promise<R>, options?: PMapOptions): Promise<R[]>;
|
|
138
|
+
//#endregion
|
|
139
|
+
//#region src/utils/template-engine.d.ts
|
|
140
|
+
/** Template definition with subject, html, and text fields */
|
|
141
|
+
interface TemplateDefinition {
|
|
142
|
+
subject?: string;
|
|
143
|
+
html?: string;
|
|
144
|
+
text?: string;
|
|
145
|
+
[key: string]: string | undefined;
|
|
146
|
+
}
|
|
147
|
+
/** Map of template ID to template definition */
|
|
148
|
+
type TemplateMap = Record<string, TemplateDefinition>;
|
|
149
|
+
/**
|
|
150
|
+
* Simple string interpolation resolver (zero dependencies).
|
|
151
|
+
*
|
|
152
|
+
* Replaces `${key}` patterns with values from the data object.
|
|
153
|
+
* Supports nested access: `${user.name}`.
|
|
154
|
+
*
|
|
155
|
+
* For advanced templating (loops, conditionals, partials),
|
|
156
|
+
* plug in any engine via the `TemplateResolver` interface.
|
|
157
|
+
*/
|
|
158
|
+
declare function createSimpleResolver(templates: TemplateMap): TemplateResolver;
|
|
159
|
+
//#endregion
|
|
160
|
+
//#region src/utils/fallback.d.ts
|
|
161
|
+
/** Service-like object that can send to specific channels */
|
|
162
|
+
interface Sendable {
|
|
163
|
+
send(payload: NotificationPayload): Promise<DispatchResult>;
|
|
164
|
+
}
|
|
165
|
+
/** Options for fallback behavior */
|
|
166
|
+
interface FallbackOptions {
|
|
167
|
+
/** Called when a channel fails and falls through to the next */
|
|
168
|
+
onFallback?: (failedChannel: string, error: string, nextChannel: string) => void;
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Try channels in priority order, stopping at the first successful delivery.
|
|
172
|
+
*
|
|
173
|
+
* Sends to one channel at a time. If it fails or is skipped (rate limited,
|
|
174
|
+
* no recipient field, etc.), tries the next channel in the list.
|
|
175
|
+
* Returns the result from the first channel that succeeds, or the
|
|
176
|
+
* last channel's result if all fail.
|
|
177
|
+
*
|
|
178
|
+
* Works with both direct and queued delivery modes.
|
|
179
|
+
*
|
|
180
|
+
* @param service - NotificationService instance
|
|
181
|
+
* @param payload - Notification payload (channels field is overridden per attempt)
|
|
182
|
+
* @param channelOrder - Channel names in priority order (e.g., ['push', 'sms', 'email'])
|
|
183
|
+
* @param options - Fallback behavior options
|
|
184
|
+
* @returns DispatchResult from the first accepted channel, or last failure
|
|
185
|
+
*/
|
|
186
|
+
declare function withFallback(service: Sendable, payload: NotificationPayload, channelOrder: string[], options?: FallbackOptions): Promise<DispatchResult>;
|
|
187
|
+
//#endregion
|
|
188
|
+
//#region src/utils/status-webhook.d.ts
|
|
189
|
+
/**
|
|
190
|
+
* Status Webhook Handler
|
|
191
|
+
* @module @classytic/notifications/utils
|
|
192
|
+
*
|
|
193
|
+
* Ingest delivery status updates from providers (Twilio, SES, SendGrid, etc.)
|
|
194
|
+
* into a normalized timeline. Provider-agnostic: you write a small mapper
|
|
195
|
+
* from the provider's webhook payload to our normalized status.
|
|
196
|
+
*
|
|
197
|
+
* Use `onStatusChange` to persist updates to your own storage (DB, delivery log, etc.).
|
|
198
|
+
*
|
|
199
|
+
* @example
|
|
200
|
+
* ```typescript
|
|
201
|
+
* import { createStatusHandler } from '@classytic/notifications/utils';
|
|
202
|
+
*
|
|
203
|
+
* const handler = createStatusHandler({
|
|
204
|
+
* onStatusChange: async (update) => {
|
|
205
|
+
* // Persist to your DB, delivery log, metrics, etc.
|
|
206
|
+
* await db.notificationStatuses.insert(update);
|
|
207
|
+
* console.log(`${update.channel} ${update.notificationId}: ${update.status}`);
|
|
208
|
+
* },
|
|
209
|
+
* });
|
|
210
|
+
*
|
|
211
|
+
* // In your Express/Fastify route:
|
|
212
|
+
* app.post('/webhooks/twilio', (req, res) => {
|
|
213
|
+
* handler.handle({
|
|
214
|
+
* provider: 'twilio',
|
|
215
|
+
* notificationId: req.body.MessageSid,
|
|
216
|
+
* channel: 'sms',
|
|
217
|
+
* status: mapTwilioStatus(req.body.MessageStatus),
|
|
218
|
+
* rawPayload: req.body,
|
|
219
|
+
* timestamp: new Date(),
|
|
220
|
+
* });
|
|
221
|
+
* res.sendStatus(200);
|
|
222
|
+
* });
|
|
223
|
+
* ```
|
|
224
|
+
*/
|
|
225
|
+
/** Normalized delivery status across all providers */
|
|
226
|
+
type DeliveryStatus = 'queued' | 'accepted' | 'sent' | 'delivered' | 'undelivered' | 'bounced' | 'opened' | 'clicked' | 'complained' | 'unsubscribed';
|
|
227
|
+
/** A normalized status update from a provider webhook */
|
|
228
|
+
interface StatusUpdate {
|
|
229
|
+
/** Provider name (e.g., 'twilio', 'ses', 'sendgrid', 'fcm') */
|
|
230
|
+
provider: string;
|
|
231
|
+
/** Notification or message ID from the provider */
|
|
232
|
+
notificationId: string;
|
|
233
|
+
/** Channel name (e.g., 'sms', 'email', 'push') */
|
|
234
|
+
channel: string;
|
|
235
|
+
/** Normalized delivery status */
|
|
236
|
+
status: DeliveryStatus;
|
|
237
|
+
/** When the status change occurred */
|
|
238
|
+
timestamp: Date;
|
|
239
|
+
/** Error message (for undelivered/bounced) */
|
|
240
|
+
error?: string;
|
|
241
|
+
/** Raw webhook payload from the provider (for debugging) */
|
|
242
|
+
rawPayload?: unknown;
|
|
243
|
+
/** Recipient identifier (email, phone, token) */
|
|
244
|
+
recipient?: string;
|
|
245
|
+
}
|
|
246
|
+
/** Configuration for the status handler */
|
|
247
|
+
interface StatusHandlerConfig {
|
|
248
|
+
/** Called on every status update */
|
|
249
|
+
onStatusChange?: (update: StatusUpdate) => void | Promise<void>;
|
|
250
|
+
}
|
|
251
|
+
/** Status handler instance */
|
|
252
|
+
interface StatusHandler {
|
|
253
|
+
/** Process a normalized status update */
|
|
254
|
+
handle(update: StatusUpdate): Promise<void>;
|
|
255
|
+
/** Get all recorded status updates (for testing/debugging) */
|
|
256
|
+
getUpdates(): StatusUpdate[];
|
|
257
|
+
/** Get updates for a specific notification */
|
|
258
|
+
getUpdatesFor(notificationId: string): StatusUpdate[];
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* Create a status webhook handler.
|
|
262
|
+
*
|
|
263
|
+
* Collects delivery status updates from provider webhooks.
|
|
264
|
+
* You normalize the provider's payload into a `StatusUpdate` and call `handle()`.
|
|
265
|
+
*/
|
|
266
|
+
declare function createStatusHandler(config?: StatusHandlerConfig): StatusHandler;
|
|
267
|
+
//#endregion
|
|
268
|
+
export { mergeHooks as S, ProviderNotInstalledError as _, createStatusHandler as a, resolveRetryConfig as b, TemplateDefinition as c, PMapOptions as d, pMap as f, NotificationError as g, ChannelError as h, StatusUpdate as i, TemplateMap as l, isQuietHours as m, StatusHandler as n, FallbackOptions as o, QuietHoursConfig as p, StatusHandlerConfig as r, withFallback as s, DeliveryStatus as t, createSimpleResolver as u, Emitter as v, withRetry as x, calculateDelay as y };
|