@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.
@@ -1,233 +0,0 @@
1
- //#region src/utils/emitter.ts
2
- var Emitter = class {
3
- handlers = /* @__PURE__ */ new Map();
4
- /** Register an event handler */
5
- on(event, handler) {
6
- const list = this.handlers.get(event) ?? [];
7
- list.push(handler);
8
- this.handlers.set(event, list);
9
- return this;
10
- }
11
- /** Remove an event handler */
12
- off(event, handler) {
13
- const list = this.handlers.get(event);
14
- if (list) this.handlers.set(event, list.filter((h) => h !== handler));
15
- return this;
16
- }
17
- /** Emit an event (runs handlers sequentially, awaits async) */
18
- async emit(event, ...args) {
19
- const list = this.handlers.get(event);
20
- if (!list) return;
21
- for (const handler of list) await handler(...args);
22
- }
23
- /** Remove all handlers for an event (or all events) */
24
- removeAll(event) {
25
- if (event) this.handlers.delete(event);
26
- else this.handlers.clear();
27
- return this;
28
- }
29
- };
30
-
31
- //#endregion
32
- //#region src/utils/retry.ts
33
- /** Resolve retry config with defaults */
34
- function resolveRetryConfig(config) {
35
- return {
36
- maxAttempts: config?.maxAttempts ?? 1,
37
- backoff: config?.backoff ?? "exponential",
38
- initialDelay: config?.initialDelay ?? 500,
39
- maxDelay: config?.maxDelay ?? 3e4
40
- };
41
- }
42
- /** Calculate delay for a given attempt */
43
- function calculateDelay(attempt, config) {
44
- let delay;
45
- switch (config.backoff) {
46
- case "exponential":
47
- delay = config.initialDelay * Math.pow(2, attempt - 1);
48
- break;
49
- case "linear":
50
- delay = config.initialDelay * attempt;
51
- break;
52
- default: delay = config.initialDelay;
53
- }
54
- const jitter = delay * .25 * (Math.random() * 2 - 1);
55
- delay = Math.min(delay + jitter, config.maxDelay);
56
- return Math.max(0, Math.round(delay));
57
- }
58
- /** Sleep for a given duration */
59
- function sleep(ms) {
60
- return new Promise((resolve) => setTimeout(resolve, ms));
61
- }
62
- /**
63
- * Execute a function with retry and backoff
64
- *
65
- * @param fn - Async function to retry
66
- * @param config - Retry configuration
67
- * @param onRetry - Called before each retry attempt
68
- * @returns Result of fn
69
- * @throws Last error after all attempts exhausted
70
- */
71
- async function withRetry(fn, config, onRetry) {
72
- let lastError;
73
- for (let attempt = 1; attempt <= config.maxAttempts; attempt++) try {
74
- return await fn();
75
- } catch (err) {
76
- lastError = err instanceof Error ? err : new Error(String(err));
77
- if (attempt === config.maxAttempts) break;
78
- const delay = calculateDelay(attempt, config);
79
- onRetry?.(attempt, lastError);
80
- await sleep(delay);
81
- }
82
- throw lastError;
83
- }
84
-
85
- //#endregion
86
- //#region src/utils/quiet-hours.ts
87
- /**
88
- * Check if the current time falls within quiet hours.
89
- *
90
- * Supports overnight ranges (e.g. 22:00 - 07:00).
91
- * Returns false if start/end are missing or malformed.
92
- *
93
- * @param quiet - Quiet hours config with start, end, and optional timezone
94
- * @param now - Current date (defaults to new Date(), injectable for testing)
95
- */
96
- function isQuietHours(quiet, now = /* @__PURE__ */ new Date()) {
97
- if (!quiet.start || !quiet.end) return false;
98
- const startMinutes = parseTimeToMinutes(quiet.start);
99
- const endMinutes = parseTimeToMinutes(quiet.end);
100
- if (startMinutes === -1 || endMinutes === -1) return false;
101
- const currentMinutes = getCurrentMinutes(now, quiet.timezone);
102
- if (startMinutes <= endMinutes) return currentMinutes >= startMinutes && currentMinutes < endMinutes;
103
- return currentMinutes >= startMinutes || currentMinutes < endMinutes;
104
- }
105
- /** Parse "HH:MM" to minutes since midnight. Returns -1 on invalid input. */
106
- function parseTimeToMinutes(time) {
107
- const match = time.match(/^(\d{1,2}):(\d{2})$/);
108
- if (!match) return -1;
109
- const hours = parseInt(match[1], 10);
110
- const minutes = parseInt(match[2], 10);
111
- if (hours < 0 || hours > 23 || minutes < 0 || minutes > 59) return -1;
112
- return hours * 60 + minutes;
113
- }
114
- /** Get current minutes-since-midnight in the given timezone (or UTC). */
115
- function getCurrentMinutes(now, timezone) {
116
- if (!timezone) return now.getUTCHours() * 60 + now.getUTCMinutes();
117
- const parts = new Intl.DateTimeFormat("en-US", {
118
- timeZone: timezone,
119
- hour: "numeric",
120
- minute: "numeric",
121
- hour12: false
122
- }).formatToParts(now);
123
- const hour = parseInt(parts.find((p) => p.type === "hour")?.value ?? "0", 10);
124
- const minute = parseInt(parts.find((p) => p.type === "minute")?.value ?? "0", 10);
125
- return hour * 60 + minute;
126
- }
127
-
128
- //#endregion
129
- //#region src/utils/idempotency.ts
130
- /**
131
- * Idempotency / deduplication utilities
132
- * @module @classytic/notifications/utils
133
- *
134
- * Prevents duplicate notification delivery using idempotency keys.
135
- * Ships with an in-memory store; implement IdempotencyStore for
136
- * Redis, database, or other distributed backends.
137
- */
138
- /** Default TTL: 24 hours */
139
- const DEFAULT_TTL = 1440 * 60 * 1e3;
140
- /**
141
- * In-memory idempotency store with TTL-based expiry.
142
- *
143
- * Suitable for single-process apps. For distributed systems,
144
- * implement `IdempotencyStore` with Redis or your database.
145
- *
146
- * Expired entries are lazily cleaned up every `cleanupInterval` writes.
147
- */
148
- var MemoryIdempotencyStore = class {
149
- store = /* @__PURE__ */ new Map();
150
- cleanupCounter = 0;
151
- cleanupInterval;
152
- constructor(options) {
153
- this.cleanupInterval = options?.cleanupInterval ?? 100;
154
- }
155
- has(key) {
156
- const expiry = this.store.get(key);
157
- if (expiry === void 0) return false;
158
- if (Date.now() > expiry) {
159
- this.store.delete(key);
160
- return false;
161
- }
162
- return true;
163
- }
164
- set(key, ttlMs) {
165
- this.store.set(key, Date.now() + ttlMs);
166
- this.maybeCleanup();
167
- }
168
- /** Number of entries (including possibly expired) */
169
- get size() {
170
- return this.store.size;
171
- }
172
- /** Remove all entries */
173
- clear() {
174
- this.store.clear();
175
- }
176
- maybeCleanup() {
177
- if (++this.cleanupCounter < this.cleanupInterval) return;
178
- this.cleanupCounter = 0;
179
- const now = Date.now();
180
- for (const [key, expiry] of this.store) if (now > expiry) this.store.delete(key);
181
- }
182
- };
183
- /** Default TTL for idempotency keys (24 hours) */
184
- const IDEMPOTENCY_DEFAULT_TTL = DEFAULT_TTL;
185
-
186
- //#endregion
187
- //#region src/utils/concurrency.ts
188
- /**
189
- * Map over items with controlled concurrency.
190
- *
191
- * Like `Promise.all(items.map(fn))` but with a max number of
192
- * parallel operations. Results are returned in input order.
193
- *
194
- * Uses a worker-pool pattern: N workers pull from a shared index,
195
- * so the pipeline stays full even when some items are slower.
196
- *
197
- * @param items - Array of items to process
198
- * @param fn - Async function to apply to each item
199
- * @param options - Concurrency options
200
- * @returns Array of results in the same order as input
201
- */
202
- async function pMap(items, fn, options = {}) {
203
- const { concurrency = 10 } = options;
204
- if (items.length === 0) return [];
205
- const results = new Array(items.length);
206
- let nextIndex = 0;
207
- async function worker() {
208
- while (nextIndex < items.length) {
209
- const i = nextIndex++;
210
- results[i] = await fn(items[i], i);
211
- }
212
- }
213
- await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, () => worker()));
214
- return results;
215
- }
216
-
217
- //#endregion
218
- //#region src/utils/merge-hooks.ts
219
- function mergeHooks(...hookConfigs) {
220
- const merged = {};
221
- for (const config of hookConfigs) {
222
- if (!config || typeof config !== "object") continue;
223
- for (const [event, handlers] of Object.entries(config)) {
224
- if (!merged[event]) merged[event] = [];
225
- const handlerArray = Array.isArray(handlers) ? handlers : [handlers];
226
- merged[event].push(...handlerArray);
227
- }
228
- }
229
- return merged;
230
- }
231
-
232
- //#endregion
233
- export { isQuietHours as a, withRetry as c, MemoryIdempotencyStore as i, Emitter as l, pMap as n, calculateDelay as o, IDEMPOTENCY_DEFAULT_TTL as r, resolveRetryConfig as s, mergeHooks as t };
@@ -1,297 +0,0 @@
1
- //#region src/utils/idempotency.d.ts
2
- /**
3
- * Idempotency / deduplication utilities
4
- * @module @classytic/notifications/utils
5
- *
6
- * Prevents duplicate notification delivery using idempotency keys.
7
- * Ships with an in-memory store; implement IdempotencyStore for
8
- * Redis, database, or other distributed backends.
9
- */
10
- /**
11
- * Interface for idempotency stores.
12
- *
13
- * Methods may be sync or async to support both in-memory and
14
- * distributed backends (Redis, DB).
15
- */
16
- interface IdempotencyStore {
17
- /** Check if a key has been seen (within TTL) */
18
- has(key: string): boolean | Promise<boolean>;
19
- /** Record a key with TTL in milliseconds */
20
- set(key: string, ttlMs: number): void | Promise<void>;
21
- }
22
- /**
23
- * In-memory idempotency store with TTL-based expiry.
24
- *
25
- * Suitable for single-process apps. For distributed systems,
26
- * implement `IdempotencyStore` with Redis or your database.
27
- *
28
- * Expired entries are lazily cleaned up every `cleanupInterval` writes.
29
- */
30
- declare class MemoryIdempotencyStore implements IdempotencyStore {
31
- private store;
32
- private cleanupCounter;
33
- private readonly cleanupInterval;
34
- constructor(options?: {
35
- cleanupInterval?: number;
36
- });
37
- has(key: string): boolean;
38
- set(key: string, ttlMs: number): void;
39
- /** Number of entries (including possibly expired) */
40
- get size(): number;
41
- /** Remove all entries */
42
- clear(): void;
43
- private maybeCleanup;
44
- }
45
- /** Default TTL for idempotency keys (24 hours) */
46
- declare const IDEMPOTENCY_DEFAULT_TTL: number;
47
- //#endregion
48
- //#region src/types.d.ts
49
- /**
50
- * @classytic/notifications - Type Definitions
51
- *
52
- * Multi-channel notification system with pluggable providers
53
- *
54
- * @module @classytic/notifications
55
- */
56
- /** Notification recipient */
57
- interface Recipient {
58
- id?: string;
59
- email?: string;
60
- phone?: string;
61
- name?: string;
62
- deviceToken?: string;
63
- metadata?: Record<string, unknown>;
64
- }
65
- /** Notification payload sent through the service */
66
- interface NotificationPayload {
67
- /** Event name that triggered this notification */
68
- event: string;
69
- /** Recipient information */
70
- recipient: Recipient;
71
- /** Data for templates and channels */
72
- data: Record<string, unknown>;
73
- /** Template ID to resolve before sending */
74
- template?: string;
75
- /** Target specific channels by name (omit to send to all matching) */
76
- channels?: string[];
77
- /** Arbitrary metadata (passed through to results) */
78
- metadata?: Record<string, unknown>;
79
- /** Idempotency key — duplicate sends with the same key are skipped */
80
- idempotencyKey?: string;
81
- }
82
- /** Result from a single channel send */
83
- interface SendResult {
84
- status: 'sent' | 'skipped' | 'failed';
85
- channel: string;
86
- duration?: number;
87
- error?: string;
88
- metadata?: Record<string, unknown>;
89
- }
90
- /** Result from dispatching to all channels */
91
- interface DispatchResult {
92
- event: string;
93
- results: SendResult[];
94
- sent: number;
95
- failed: number;
96
- skipped: number;
97
- duration: number;
98
- }
99
- /** Base channel configuration */
100
- interface ChannelConfig {
101
- /** Channel name (defaults to class name) */
102
- name?: string;
103
- /** Enable/disable this channel */
104
- enabled?: boolean;
105
- /** Event whitelist (empty = handle all events) */
106
- events?: string[];
107
- /** Per-channel retry override */
108
- retry?: RetryConfig;
109
- }
110
- /** Channel interface - implement this for custom channels */
111
- interface Channel {
112
- readonly name: string;
113
- shouldHandle(event: string): boolean;
114
- send(payload: NotificationPayload): Promise<SendResult>;
115
- }
116
- /** SMTP / Nodemailer transport options */
117
- interface SmtpTransportOptions {
118
- host?: string;
119
- port?: number;
120
- secure?: boolean;
121
- auth?: {
122
- user: string;
123
- pass: string;
124
- };
125
- /** Nodemailer service shorthand (e.g. 'gmail', 'outlook') */
126
- service?: string;
127
- [key: string]: unknown;
128
- }
129
- /** Email attachment */
130
- interface EmailAttachment {
131
- filename: string;
132
- content?: string | Buffer;
133
- path?: string;
134
- contentType?: string;
135
- }
136
- /** EmailChannel configuration */
137
- interface EmailChannelConfig extends ChannelConfig {
138
- /** Sender address (e.g. 'App <noreply@app.com>') */
139
- from: string;
140
- /** SMTP transport options (creates a Nodemailer transporter) */
141
- transport?: SmtpTransportOptions;
142
- /** Pre-created Nodemailer transporter (for SES, custom transports) */
143
- transporter?: NodemailerTransporter;
144
- /** Default mail options merged into every send */
145
- defaults?: Record<string, unknown>;
146
- }
147
- /** Minimal Nodemailer transporter interface (avoids hard dep) */
148
- interface NodemailerTransporter {
149
- sendMail(options: Record<string, unknown>): Promise<{
150
- messageId: string;
151
- [key: string]: unknown;
152
- }>;
153
- verify?(): Promise<boolean>;
154
- close?(): void;
155
- }
156
- /** WebhookChannel configuration */
157
- interface WebhookChannelConfig extends ChannelConfig {
158
- /** Webhook URL */
159
- url: string;
160
- /** Custom headers */
161
- headers?: Record<string, string>;
162
- /** HMAC secret for signing payloads */
163
- secret?: string;
164
- /** HTTP method (default: POST) */
165
- method?: 'POST' | 'PUT';
166
- /** Request timeout in ms (default: 10000) */
167
- timeout?: number;
168
- }
169
- /** Resolved template content */
170
- interface TemplateResult {
171
- subject?: string;
172
- html?: string;
173
- text?: string;
174
- [key: string]: unknown;
175
- }
176
- /**
177
- * Template resolver function
178
- * Plug any template engine: React Email, MJML, Handlebars, etc.
179
- */
180
- type TemplateResolver = (templateId: string, data: Record<string, unknown>) => TemplateResult | Promise<TemplateResult>;
181
- /** Retry configuration */
182
- interface RetryConfig {
183
- /** Max send attempts (default: 1 = no retry) */
184
- maxAttempts?: number;
185
- /** Backoff strategy (default: 'exponential') */
186
- backoff?: 'fixed' | 'exponential' | 'linear';
187
- /** Initial delay in ms (default: 500) */
188
- initialDelay?: number;
189
- /** Maximum delay in ms (default: 30000) */
190
- maxDelay?: number;
191
- }
192
- /** Internal resolved retry config with defaults applied */
193
- interface ResolvedRetryConfig {
194
- maxAttempts: number;
195
- backoff: 'fixed' | 'exponential' | 'linear';
196
- initialDelay: number;
197
- maxDelay: number;
198
- }
199
- /** Per-user notification preferences */
200
- interface NotificationPreferences {
201
- /** Channel opt-in/out: { email: true, sms: false } */
202
- channels?: Record<string, boolean>;
203
- /** Event opt-in/out: { 'marketing.promo': false } */
204
- events?: Record<string, boolean>;
205
- /** Quiet hours */
206
- quiet?: {
207
- start?: string;
208
- end?: string;
209
- timezone?: string;
210
- };
211
- }
212
- /**
213
- * Preference resolver function
214
- * Load from DB, cache, or config
215
- */
216
- type PreferenceResolver = (recipientId: string, event: string) => NotificationPreferences | Promise<NotificationPreferences | null> | null;
217
- /** Pluggable logger interface (compatible with console, pino, winston) */
218
- interface Logger {
219
- info(message: string, ...args: unknown[]): void;
220
- warn(message: string, ...args: unknown[]): void;
221
- error(message: string, ...args: unknown[]): void;
222
- debug?(message: string, ...args: unknown[]): void;
223
- }
224
- /** NotificationService configuration */
225
- interface NotificationServiceConfig {
226
- /** Registered channels */
227
- channels?: Channel[];
228
- /** Template resolver (plug any engine) */
229
- templates?: TemplateResolver;
230
- /** Global retry config (channels can override) */
231
- retry?: RetryConfig;
232
- /** Preference resolver for per-user filtering */
233
- preferences?: PreferenceResolver;
234
- /** Logger (default: silent) */
235
- logger?: Logger;
236
- /** Idempotency / deduplication config */
237
- idempotency?: {
238
- /** Store implementation (default: MemoryIdempotencyStore) */store?: IdempotencyStore; /** TTL in milliseconds (default: 86400000 = 24h) */
239
- ttl?: number;
240
- };
241
- }
242
- /** Service lifecycle events */
243
- type ServiceEvent = 'before:send' | 'after:send' | 'send:success' | 'send:failed' | 'send:retry';
244
- /** Event handler function */
245
- type EventHandler<T = unknown> = (data: T) => void | Promise<void>;
246
- /** Hook config for creating event-specific handlers */
247
- interface NotificationHookConfig<T = unknown> {
248
- /** Event name */
249
- event: string;
250
- /** Target specific channels */
251
- channels?: string[];
252
- /** Extract recipient from event data */
253
- getRecipient: (eventData: T) => Recipient | Promise<Recipient | null> | null;
254
- /** Extract notification data from event data */
255
- getData: (eventData: T) => Record<string, unknown>;
256
- /** Template to resolve */
257
- template?: string;
258
- /** Enable/disable */
259
- enabled?: boolean;
260
- }
261
- /** Hook handler function */
262
- type HookHandler = (eventData: unknown) => Promise<DispatchResult | undefined>;
263
- /** Map of event name to hook handler arrays */
264
- type HookMap = Record<string, HookHandler[]>;
265
- /** Options for batch sending */
266
- interface BatchOptions {
267
- /** Max concurrent notification sends (default: 10) */
268
- concurrency?: number;
269
- /** Called after each notification completes */
270
- onProgress?: (progress: BatchProgress) => void;
271
- }
272
- /** Progress info emitted during batch sending */
273
- interface BatchProgress {
274
- /** Number of notifications completed so far */
275
- completed: number;
276
- /** Total number of notifications in the batch */
277
- total: number;
278
- /** Result of the just-completed notification */
279
- result: DispatchResult;
280
- }
281
- /** Aggregated result from sending a batch of notifications */
282
- interface BatchResult {
283
- /** Total notifications in the batch */
284
- total: number;
285
- /** Total successful channel sends across all notifications */
286
- sent: number;
287
- /** Total failed channel sends across all notifications */
288
- failed: number;
289
- /** Total skipped sends (quiet hours, dedup, preferences) */
290
- skipped: number;
291
- /** Total wall-clock duration in ms */
292
- duration: number;
293
- /** Per-notification dispatch results (same order as input) */
294
- results: DispatchResult[];
295
- }
296
- //#endregion
297
- export { MemoryIdempotencyStore as A, ServiceEvent as C, WebhookChannelConfig as D, TemplateResult as E, IDEMPOTENCY_DEFAULT_TTL as O, SendResult as S, TemplateResolver as T, NotificationServiceConfig as _, ChannelConfig as a, ResolvedRetryConfig as b, EmailChannelConfig as c, HookMap as d, Logger as f, NotificationPreferences as g, NotificationPayload as h, Channel as i, IdempotencyStore as k, EventHandler as l, NotificationHookConfig as m, BatchProgress as n, DispatchResult as o, NodemailerTransporter as p, BatchResult as r, EmailAttachment as s, BatchOptions as t, HookHandler as u, PreferenceResolver as v, SmtpTransportOptions as w, RetryConfig as x, Recipient as y };