@classytic/notifications 2.0.0 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +84 -0
- package/README.md +86 -0
- package/dist/channels/index.d.mts +1 -1
- package/dist/channels/index.mjs +1 -1
- package/dist/index.d.mts +4 -3
- package/dist/index.mjs +14 -2
- package/dist/providers/index.d.mts +136 -0
- package/dist/providers/index.mjs +280 -0
- package/dist/{push.channel-D1FdTPUi.mjs → push.channel-OkjPEVTN.mjs} +51 -0
- package/dist/{push.channel-4mRkzrEu.d.mts → push.channel-YtZrCCH1.d.mts} +19 -1
- package/dist/{status-webhook-BDaI1BMy.d.mts → status-webhook-Bb4UoinT.d.mts} +1 -1
- package/dist/{types-D94B3VNX.d.mts → types-BMs4UhKD.d.mts} +26 -0
- package/dist/utils/index.d.mts +2 -2
- package/package.json +20 -3
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,90 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to `@classytic/notifications` will be documented in this file.
|
|
4
4
|
|
|
5
|
+
## [2.1.0] - 2026-05-17
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- **Email provider abstraction** at the new `@classytic/notifications/providers`
|
|
10
|
+
subpath export — for multi-tenant hosts that need to store an SMTP
|
|
11
|
+
credential per organization and route sends through it:
|
|
12
|
+
- `EMAIL_PRESETS` / `EMAIL_PROVIDER_OPTIONS` — Resend, Gmail (App
|
|
13
|
+
Password), SendGrid, Mailgun, AWS SES (SMTP), and Custom SMTP. Every
|
|
14
|
+
preset is SMTP-based; the table captures host / port / secure /
|
|
15
|
+
userSource / passSource and leaves the secret bits to the
|
|
16
|
+
credential blob.
|
|
17
|
+
- `buildEmailTransport(data)` — turns an `EmailCredentialData` blob
|
|
18
|
+
into a `nodemailer.Transporter`. Dynamic `import('nodemailer')` so
|
|
19
|
+
the peer stays optional.
|
|
20
|
+
- `buildFromHeader(data)` — formats `"Brand" <hello@…>` (or bare
|
|
21
|
+
email).
|
|
22
|
+
- `getEmailCredentialSchema()` — union-of-fields form schema; the UI
|
|
23
|
+
hides irrelevant fields based on the selected provider.
|
|
24
|
+
- `testEmailCredential(data)` — opens an SMTP connection and runs
|
|
25
|
+
`verify()`. Returns `{ status: 'OK' | 'Error', message }` instead
|
|
26
|
+
of throwing.
|
|
27
|
+
- SES preset opts into `allowHostOverride` so callers can target a
|
|
28
|
+
non-default region by supplying
|
|
29
|
+
`host: 'email-smtp.<region>.amazonaws.com'`. Fixed-host presets
|
|
30
|
+
(Resend / Gmail / SendGrid / Mailgun) deliberately ignore host
|
|
31
|
+
overrides to prevent "changed host, kept the API key" footguns.
|
|
32
|
+
- **`Channel.canSend(payload)` pre-flight hook (optional).** Channels
|
|
33
|
+
can return a `SendResult` (typically `{ status: 'skipped' }`) before
|
|
34
|
+
the service consumes a rate-limit token. Built-in `EmailChannel`,
|
|
35
|
+
`SmsChannel`, and `PushChannel` implement it to skip when the
|
|
36
|
+
recipient field for that channel is missing — preventing a mixed-
|
|
37
|
+
channel batch from burning, say, email quota on a payload that was
|
|
38
|
+
never going to deliver email. Channels that omit `canSend` keep
|
|
39
|
+
working exactly as before.
|
|
40
|
+
- **`queueFailureMode` config knob** on `NotificationService`. Controls
|
|
41
|
+
how the queue processor signals failure to the queue adapter:
|
|
42
|
+
- `'throw-on-total-failure'` (new default) — when
|
|
43
|
+
`sent === 0 && failed > 0`, the processor throws so the queue
|
|
44
|
+
marks the job failed and its retry policy kicks in. Partial
|
|
45
|
+
successes resolve normally so a retry can't double-send the
|
|
46
|
+
channels that already delivered.
|
|
47
|
+
- `'always-complete'` — legacy behavior preserved for hosts whose
|
|
48
|
+
delivery log is the source of truth for failures.
|
|
49
|
+
|
|
50
|
+
### Changed
|
|
51
|
+
|
|
52
|
+
- **Queue jobs no longer silently complete on total dispatch failure.**
|
|
53
|
+
Previously, the queue processor swallowed `DispatchResult` and
|
|
54
|
+
resolved every job, so `MemoryQueue` (or a BullMQ adapter) would
|
|
55
|
+
mark a job completed even when every channel raised. The processor
|
|
56
|
+
now propagates total failure under the default `queueFailureMode`.
|
|
57
|
+
Opt back into the old behavior with
|
|
58
|
+
`queueFailureMode: 'always-complete'`.
|
|
59
|
+
- **Rate-limit tokens are no longer consumed for deterministic skips.**
|
|
60
|
+
`sendToChannel` calls `channel.canSend?.(payload)` before
|
|
61
|
+
`rateLimitStore.consume()`. This fixes a quota-exhaustion footgun
|
|
62
|
+
where a payload addressing an email recipient with no `phone` would
|
|
63
|
+
still decrement the SMS channel's quota.
|
|
64
|
+
- `package.json` adds a `typesVersions` map so node10-style resolvers
|
|
65
|
+
find subpath declarations (`./channels`, `./providers`, `./utils`).
|
|
66
|
+
|
|
67
|
+
### Test infrastructure
|
|
68
|
+
|
|
69
|
+
- Live network tests now live behind a dedicated
|
|
70
|
+
`vitest.live.config.ts` and the `npm run test:live` script. The
|
|
71
|
+
default `npm test` glob no longer includes `*.live.test.ts`, so a
|
|
72
|
+
fresh checkout — even with the workspace `.env.dev` mounted —
|
|
73
|
+
cannot accidentally trigger real SMTP sends.
|
|
74
|
+
- `prepublishOnly` and `release` now run `npm test` (unit suite) in
|
|
75
|
+
addition to the build + typecheck.
|
|
76
|
+
- New live "send" suite (`EMAIL_LIVE_SEND_TO=<inbox>`) actually invokes
|
|
77
|
+
`nodemailer.sendMail` for each provider with creds in the
|
|
78
|
+
environment, so deliverability can be smoke-tested before publish.
|
|
79
|
+
The send gate is intentionally NOT placed in shared env files —
|
|
80
|
+
export it per-shell.
|
|
81
|
+
- `tests/setup-env.ts` auto-loads workspace `../.env.dev` plus
|
|
82
|
+
package-local `.env` / `.env.test` / `.env.test.local`; shell vars
|
|
83
|
+
always win.
|
|
84
|
+
|
|
85
|
+
### Dependencies
|
|
86
|
+
|
|
87
|
+
- `nodemailer >=6` remains the only optional peer dependency.
|
|
88
|
+
|
|
5
89
|
## [2.0.0] - 2026-03-24
|
|
6
90
|
|
|
7
91
|
### Added
|
package/README.md
CHANGED
|
@@ -31,6 +31,23 @@ npm install @classytic/notifications
|
|
|
31
31
|
npm install nodemailer
|
|
32
32
|
```
|
|
33
33
|
|
|
34
|
+
### Module Format
|
|
35
|
+
|
|
36
|
+
This package is **ESM-only** (`"type": "module"`, Node 18+, no CJS build).
|
|
37
|
+
That means:
|
|
38
|
+
|
|
39
|
+
- ✅ ESM consumers — `import { ... } from '@classytic/notifications'` just works.
|
|
40
|
+
- ⚠️ CommonJS consumers — you must use a dynamic import:
|
|
41
|
+
```js
|
|
42
|
+
const { NotificationService } = await import('@classytic/notifications');
|
|
43
|
+
```
|
|
44
|
+
A top-level `require('@classytic/notifications')` will fail with
|
|
45
|
+
`ERR_REQUIRE_ESM`. If you're starting a new project, prefer ESM
|
|
46
|
+
(`"type": "module"` in your `package.json`) or use a bundler/runtime
|
|
47
|
+
that handles ESM natively (Vite, Next.js, Bun, modern Node).
|
|
48
|
+
- TypeScript declarations are emitted as `.d.mts`. `typesVersions` is
|
|
49
|
+
configured so node10-style resolvers still resolve subpaths.
|
|
50
|
+
|
|
34
51
|
## Quick Start
|
|
35
52
|
|
|
36
53
|
```typescript
|
|
@@ -112,6 +129,75 @@ const email = new EmailChannel({
|
|
|
112
129
|
});
|
|
113
130
|
```
|
|
114
131
|
|
|
132
|
+
### Email Providers (`/providers`)
|
|
133
|
+
|
|
134
|
+
For multi-tenant apps where each org brings its own email provider, use the
|
|
135
|
+
`/providers` surface to render a credential form, validate the connection,
|
|
136
|
+
and build a transporter from the stored blob — no per-provider branching
|
|
137
|
+
in your host code.
|
|
138
|
+
|
|
139
|
+
```typescript
|
|
140
|
+
import {
|
|
141
|
+
EMAIL_PRESETS,
|
|
142
|
+
EMAIL_PROVIDER_OPTIONS,
|
|
143
|
+
buildEmailTransport,
|
|
144
|
+
buildFromHeader,
|
|
145
|
+
getEmailCredentialSchema,
|
|
146
|
+
testEmailCredential,
|
|
147
|
+
type EmailCredentialData,
|
|
148
|
+
type EmailProviderName,
|
|
149
|
+
} from '@classytic/notifications/providers';
|
|
150
|
+
import { EmailChannel } from '@classytic/notifications/channels';
|
|
151
|
+
|
|
152
|
+
// 1. Render a dynamic form from the schema (provider select + the union
|
|
153
|
+
// of all provider-specific fields — UI hides what's not relevant).
|
|
154
|
+
const fields = getEmailCredentialSchema();
|
|
155
|
+
|
|
156
|
+
// 2. "Test Connection" — opens an SMTP connection and runs `verify()`.
|
|
157
|
+
// Returns `{ status: 'OK' | 'Error', message }` instead of throwing.
|
|
158
|
+
const result = await testEmailCredential({
|
|
159
|
+
provider: 'resend',
|
|
160
|
+
fromEmail: 'hello@yourdomain.com',
|
|
161
|
+
fromName: 'Your Brand',
|
|
162
|
+
apiKey: 're_xxx',
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
// 3. At send time, turn the encrypted DB blob into a transporter and
|
|
166
|
+
// plug it straight into EmailChannel.
|
|
167
|
+
const data: EmailCredentialData = /* decrypted from DB */;
|
|
168
|
+
const transporter = await buildEmailTransport(data);
|
|
169
|
+
const channel = new EmailChannel({
|
|
170
|
+
from: buildFromHeader(data), // '"Brand" <hello@…>' or bare email
|
|
171
|
+
transporter,
|
|
172
|
+
});
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
**Supported providers** — every one is SMTP under the hood:
|
|
176
|
+
|
|
177
|
+
| `provider` | Host | Auth fields | Notes |
|
|
178
|
+
|---|---|---|---|
|
|
179
|
+
| `resend` | `smtp.resend.com:465` | `apiKey` | User is the literal `resend` |
|
|
180
|
+
| `gmail` | `smtp.gmail.com:465` | `user`, `password` | App Password, NOT account password |
|
|
181
|
+
| `sendgrid` | `smtp.sendgrid.net:587` | `apiKey` | User is the literal `apikey` |
|
|
182
|
+
| `mailgun` | `smtp.mailgun.org:465` | `user`, `password` | Per-domain SMTP creds |
|
|
183
|
+
| `ses` | `email-smtp.us-east-1.amazonaws.com:465` | `user`, `password` | SES IAM SMTP creds. Override `host` for other regions |
|
|
184
|
+
| `smtp` | user-supplied | `host`, `port`, `secure`, `user`, `password` | Any auth-SMTP server |
|
|
185
|
+
|
|
186
|
+
Host override is allowed only for `smtp` and `ses` (regional). Other
|
|
187
|
+
presets pin the host to prevent footguns like "I changed the host but
|
|
188
|
+
kept the Resend API key".
|
|
189
|
+
|
|
190
|
+
```typescript
|
|
191
|
+
// SES in eu-west-1
|
|
192
|
+
await buildEmailTransport({
|
|
193
|
+
provider: 'ses',
|
|
194
|
+
fromEmail: 'support@yourdomain.com',
|
|
195
|
+
user: 'AKIAxxxx',
|
|
196
|
+
password: 'BFxxxx',
|
|
197
|
+
host: 'email-smtp.eu-west-1.amazonaws.com',
|
|
198
|
+
});
|
|
199
|
+
```
|
|
200
|
+
|
|
115
201
|
### SmsChannel (BYOP)
|
|
116
202
|
|
|
117
203
|
Zero dependencies — bring your own SMS SDK.
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "../push.channel-
|
|
1
|
+
import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "../push.channel-YtZrCCH1.mjs";
|
|
2
2
|
export { BaseChannel, ConsoleChannel, EmailChannel, PushChannel, SmsChannel, WebhookChannel };
|
package/dist/channels/index.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "../push.channel-
|
|
1
|
+
import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "../push.channel-OkjPEVTN.mjs";
|
|
2
2
|
|
|
3
3
|
export { BaseChannel, ConsoleChannel, EmailChannel, PushChannel, SmsChannel, WebhookChannel };
|
package/dist/index.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
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-
|
|
2
|
-
import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "./push.channel-
|
|
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-
|
|
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-BMs4UhKD.mjs";
|
|
2
|
+
import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "./push.channel-YtZrCCH1.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-Bb4UoinT.mjs";
|
|
4
4
|
|
|
5
5
|
//#region src/NotificationService.d.ts
|
|
6
6
|
declare class NotificationService {
|
|
@@ -15,6 +15,7 @@ declare class NotificationService {
|
|
|
15
15
|
private deliveryLog?;
|
|
16
16
|
private rateLimitStore?;
|
|
17
17
|
private queueAdapter?;
|
|
18
|
+
private queueFailureMode;
|
|
18
19
|
constructor(config?: NotificationServiceConfig);
|
|
19
20
|
/** Add a channel at runtime */
|
|
20
21
|
addChannel(channel: Channel): this;
|
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
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
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-
|
|
3
|
+
import { a as EmailChannel, i as WebhookChannel, n as SmsChannel, o as BaseChannel, r as ConsoleChannel, t as PushChannel } from "./push.channel-OkjPEVTN.mjs";
|
|
4
4
|
|
|
5
5
|
//#region src/NotificationService.ts
|
|
6
6
|
/**
|
|
@@ -69,6 +69,7 @@ var NotificationService = class {
|
|
|
69
69
|
deliveryLog;
|
|
70
70
|
rateLimitStore;
|
|
71
71
|
queueAdapter;
|
|
72
|
+
queueFailureMode;
|
|
72
73
|
constructor(config = {}) {
|
|
73
74
|
this.channels = config.channels ?? [];
|
|
74
75
|
this.templateResolver = config.templates;
|
|
@@ -82,10 +83,15 @@ var NotificationService = class {
|
|
|
82
83
|
this.deliveryLog = config.deliveryLog;
|
|
83
84
|
if (config.rateLimitStore) this.rateLimitStore = config.rateLimitStore;
|
|
84
85
|
else if (this.channels.some((ch) => this.getChannelRateLimit(ch))) this.rateLimitStore = new MemoryRateLimitStore();
|
|
86
|
+
this.queueFailureMode = config.queueFailureMode ?? "throw-on-total-failure";
|
|
85
87
|
if (config.queue) {
|
|
86
88
|
this.queueAdapter = config.queue;
|
|
87
89
|
this.queueAdapter.process(async (payload) => {
|
|
88
|
-
await this.sendDirect(payload);
|
|
90
|
+
const dispatch = await this.sendDirect(payload);
|
|
91
|
+
if (this.queueFailureMode === "throw-on-total-failure" && dispatch.sent === 0 && dispatch.failed > 0) {
|
|
92
|
+
const summary = dispatch.results.filter((r) => r.status === "failed").map((r) => `${r.channel}: ${r.error ?? "unknown error"}`).join("; ");
|
|
93
|
+
throw new NotificationError(`Queued dispatch for "${dispatch.event}" failed on every channel: ${summary || "no detail"}`, { code: "QUEUE_DISPATCH_FAILED" });
|
|
94
|
+
}
|
|
89
95
|
});
|
|
90
96
|
}
|
|
91
97
|
}
|
|
@@ -268,6 +274,12 @@ var NotificationService = class {
|
|
|
268
274
|
}
|
|
269
275
|
/** Send to a single channel with rate limiting and retry */
|
|
270
276
|
async sendToChannel(channel, payload) {
|
|
277
|
+
if (typeof channel.canSend === "function") try {
|
|
278
|
+
const preflight = channel.canSend(payload);
|
|
279
|
+
if (preflight) return preflight;
|
|
280
|
+
} catch (err) {
|
|
281
|
+
this.logger.warn(`[${channel.name}] canSend() threw, falling through to send(): ${err instanceof Error ? err.message : err}`);
|
|
282
|
+
}
|
|
271
283
|
const rateLimit = this.getChannelRateLimit(channel);
|
|
272
284
|
if (rateLimit && this.rateLimitStore) {
|
|
273
285
|
if (!await this.rateLimitStore.consume(channel.name, rateLimit)) {
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { Transporter } from "nodemailer";
|
|
2
|
+
|
|
3
|
+
//#region src/providers/email/presets.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Email provider presets — Resend, Gmail, SendGrid, Mailgun, custom SMTP.
|
|
6
|
+
*
|
|
7
|
+
* Every provider that ships today exposes an SMTP gateway, so the table
|
|
8
|
+
* here captures the constants (host / port / secure / user-source /
|
|
9
|
+
* pass-source) and leaves the variable bits (api key, app password) to
|
|
10
|
+
* the credential's `data` blob. `buildEmailTransport` reads the preset,
|
|
11
|
+
* fills in the auth tuple, and builds a `nodemailer` transport.
|
|
12
|
+
*
|
|
13
|
+
* Adding a new SMTP-based provider is one entry below. Non-SMTP API
|
|
14
|
+
* providers (Postmark API, SES API) would branch in `buildEmailTransport`
|
|
15
|
+
* BEFORE the SMTP fallback — none are shipped yet.
|
|
16
|
+
*/
|
|
17
|
+
type EmailProviderName = 'resend' | 'gmail' | 'sendgrid' | 'mailgun' | 'ses' | 'smtp';
|
|
18
|
+
interface EmailPreset {
|
|
19
|
+
/** Display label for the credential card / dropdown. */
|
|
20
|
+
displayName: string;
|
|
21
|
+
/** One-line description shown next to the option. */
|
|
22
|
+
description: string;
|
|
23
|
+
/** SMTP host. `null` ⇒ user-supplied (custom SMTP). */
|
|
24
|
+
host: string | null;
|
|
25
|
+
/** SMTP port. */
|
|
26
|
+
port: number;
|
|
27
|
+
/** TLS — `true` = implicit TLS, `false` = STARTTLS. */
|
|
28
|
+
secure: boolean;
|
|
29
|
+
/**
|
|
30
|
+
* Where the SMTP `user` comes from:
|
|
31
|
+
* - `literal:<value>` — fixed for this provider (Resend → `resend`, SendGrid → `apikey`)
|
|
32
|
+
* - `user` — read `credential.data.user` (Gmail, Mailgun, custom SMTP)
|
|
33
|
+
*/
|
|
34
|
+
userSource: string;
|
|
35
|
+
/**
|
|
36
|
+
* Where the SMTP `pass` comes from:
|
|
37
|
+
* - `apiKey` — read `credential.data.apiKey` (Resend, SendGrid)
|
|
38
|
+
* - `password` — read `credential.data.password` (Gmail, Mailgun, SMTP)
|
|
39
|
+
*/
|
|
40
|
+
passSource: 'apiKey' | 'password';
|
|
41
|
+
/**
|
|
42
|
+
* Allow user-supplied `data.host` / `data.port` / `data.secure` to
|
|
43
|
+
* override the preset defaults. `true` for providers like SES where
|
|
44
|
+
* the region picks the host (`email-smtp.{region}.amazonaws.com`).
|
|
45
|
+
* `false` for fixed-host providers (Resend, Gmail, SendGrid, Mailgun)
|
|
46
|
+
* — prevents "changed host, kept the Resend key" footguns.
|
|
47
|
+
*/
|
|
48
|
+
allowHostOverride?: boolean;
|
|
49
|
+
/** Setup instructions surfaced in the Integrations UI. */
|
|
50
|
+
setupHint: string;
|
|
51
|
+
}
|
|
52
|
+
declare const EMAIL_PRESETS: Record<EmailProviderName, EmailPreset>;
|
|
53
|
+
/** Convenience dropdown options for the credential UI. */
|
|
54
|
+
declare const EMAIL_PROVIDER_OPTIONS: {
|
|
55
|
+
value: EmailProviderName;
|
|
56
|
+
label: string;
|
|
57
|
+
}[];
|
|
58
|
+
//#endregion
|
|
59
|
+
//#region src/providers/email/transport.d.ts
|
|
60
|
+
/**
|
|
61
|
+
* Per-org credential blob — what the host stores (encrypted) and passes
|
|
62
|
+
* back into `buildEmailTransport()` at send time.
|
|
63
|
+
*
|
|
64
|
+
* Only the fields matching `provider` are read; the rest are ignored so
|
|
65
|
+
* a host can store the union shape (a single form with conditionally
|
|
66
|
+
* relevant fields) without leaking unused values into the auth tuple.
|
|
67
|
+
*/
|
|
68
|
+
interface EmailCredentialData {
|
|
69
|
+
provider: EmailProviderName;
|
|
70
|
+
fromEmail: string;
|
|
71
|
+
fromName?: string;
|
|
72
|
+
apiKey?: string;
|
|
73
|
+
user?: string;
|
|
74
|
+
password?: string;
|
|
75
|
+
host?: string;
|
|
76
|
+
port?: string | number;
|
|
77
|
+
secure?: string | boolean;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Build a `nodemailer` `Transporter` from the credential blob.
|
|
81
|
+
*
|
|
82
|
+
* @throws `Error` when required fields are missing for the chosen provider.
|
|
83
|
+
* @throws `Error` when `nodemailer` is not installed (optional peer).
|
|
84
|
+
*/
|
|
85
|
+
declare function buildEmailTransport(data: EmailCredentialData): Promise<Transporter>;
|
|
86
|
+
/**
|
|
87
|
+
* Compose the RFC-5322 `From` header value from the credential blob.
|
|
88
|
+
* Returns `"Display Name" <email@example.com>` when `fromName` is set,
|
|
89
|
+
* otherwise just `email@example.com`.
|
|
90
|
+
*/
|
|
91
|
+
declare function buildFromHeader(data: EmailCredentialData): string;
|
|
92
|
+
//#endregion
|
|
93
|
+
//#region src/providers/email/schema.d.ts
|
|
94
|
+
/**
|
|
95
|
+
* Credential field schema for the email provider.
|
|
96
|
+
*
|
|
97
|
+
* Hosts that ship a dynamic credential form (driven by a provider's
|
|
98
|
+
* `getCredentialSchema()`-style method) read this to render the right
|
|
99
|
+
* fields. Returning the UNION of all provider-specific fields keeps the
|
|
100
|
+
* form generic — the UI hides irrelevant fields based on the chosen
|
|
101
|
+
* `provider`. Only relevant fields get saved into the encrypted blob.
|
|
102
|
+
*
|
|
103
|
+
* Shape is host-agnostic (no `@classytic/social` import). Hosts that
|
|
104
|
+
* use the social registry's `CredentialField` type can structurally cast.
|
|
105
|
+
*/
|
|
106
|
+
type EmailCredentialFieldType = 'text' | 'password' | 'url' | 'select' | 'textarea';
|
|
107
|
+
interface EmailCredentialField {
|
|
108
|
+
name: string;
|
|
109
|
+
displayName: string;
|
|
110
|
+
type: EmailCredentialFieldType;
|
|
111
|
+
required: boolean;
|
|
112
|
+
placeholder?: string;
|
|
113
|
+
description?: string;
|
|
114
|
+
options?: {
|
|
115
|
+
label: string;
|
|
116
|
+
value: string;
|
|
117
|
+
}[];
|
|
118
|
+
}
|
|
119
|
+
/** Union-of-fields schema — every field appears; the UI hides what's
|
|
120
|
+
* not relevant for the chosen `provider`. */
|
|
121
|
+
declare function getEmailCredentialSchema(): EmailCredentialField[];
|
|
122
|
+
//#endregion
|
|
123
|
+
//#region src/providers/email/test.d.ts
|
|
124
|
+
type EmailTestStatus = 'OK' | 'Error';
|
|
125
|
+
interface EmailTestResult {
|
|
126
|
+
status: EmailTestStatus;
|
|
127
|
+
message: string;
|
|
128
|
+
/** Set when status === 'OK'. */
|
|
129
|
+
data?: {
|
|
130
|
+
provider: EmailCredentialData['provider'];
|
|
131
|
+
fromEmail: string;
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
declare function testEmailCredential(data: EmailCredentialData): Promise<EmailTestResult>;
|
|
135
|
+
//#endregion
|
|
136
|
+
export { EMAIL_PRESETS, EMAIL_PROVIDER_OPTIONS, type EmailCredentialData, type EmailCredentialField, type EmailCredentialFieldType, type EmailPreset, type EmailProviderName, type EmailTestResult, type EmailTestStatus, buildEmailTransport, buildFromHeader, getEmailCredentialSchema, testEmailCredential };
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
//#region src/providers/email/presets.ts
|
|
2
|
+
const EMAIL_PRESETS = {
|
|
3
|
+
resend: {
|
|
4
|
+
displayName: "Resend",
|
|
5
|
+
description: "Transactional + broadcast email via Resend SMTP relay.",
|
|
6
|
+
host: "smtp.resend.com",
|
|
7
|
+
port: 465,
|
|
8
|
+
secure: true,
|
|
9
|
+
userSource: "literal:resend",
|
|
10
|
+
passSource: "apiKey",
|
|
11
|
+
setupHint: "Verify your sending domain in resend.com → Domains. Create an API key (full access) and paste it below."
|
|
12
|
+
},
|
|
13
|
+
gmail: {
|
|
14
|
+
displayName: "Gmail (App Password)",
|
|
15
|
+
description: "Send via a personal Gmail account using a 16-character app password.",
|
|
16
|
+
host: "smtp.gmail.com",
|
|
17
|
+
port: 465,
|
|
18
|
+
secure: true,
|
|
19
|
+
userSource: "user",
|
|
20
|
+
passSource: "password",
|
|
21
|
+
setupHint: "Enable 2-Step Verification, then generate an App Password at myaccount.google.com/apppasswords. The from-address must match the Gmail account."
|
|
22
|
+
},
|
|
23
|
+
sendgrid: {
|
|
24
|
+
displayName: "SendGrid",
|
|
25
|
+
description: "SendGrid SMTP relay (username is literally \"apikey\").",
|
|
26
|
+
host: "smtp.sendgrid.net",
|
|
27
|
+
port: 587,
|
|
28
|
+
secure: false,
|
|
29
|
+
userSource: "literal:apikey",
|
|
30
|
+
passSource: "apiKey",
|
|
31
|
+
setupHint: "Verify your sending domain in app.sendgrid.com → Sender Authentication. Create an API key with Mail Send permission."
|
|
32
|
+
},
|
|
33
|
+
mailgun: {
|
|
34
|
+
displayName: "Mailgun",
|
|
35
|
+
description: "Mailgun SMTP relay using per-domain SMTP credentials.",
|
|
36
|
+
host: "smtp.mailgun.org",
|
|
37
|
+
port: 465,
|
|
38
|
+
secure: true,
|
|
39
|
+
userSource: "user",
|
|
40
|
+
passSource: "password",
|
|
41
|
+
setupHint: "Verify your sending domain in app.mailgun.com. The SMTP credentials shown on the domain page (user + password) go below — these are NOT your account password."
|
|
42
|
+
},
|
|
43
|
+
ses: {
|
|
44
|
+
displayName: "AWS SES (SMTP)",
|
|
45
|
+
description: "Amazon SES via SMTP. Host defaults to us-east-1; override for other regions.",
|
|
46
|
+
host: "email-smtp.us-east-1.amazonaws.com",
|
|
47
|
+
port: 465,
|
|
48
|
+
secure: true,
|
|
49
|
+
userSource: "user",
|
|
50
|
+
passSource: "password",
|
|
51
|
+
allowHostOverride: true,
|
|
52
|
+
setupHint: "In the SES console (your region), Account dashboard → SMTP settings → Create SMTP credentials. The IAM user gets an SMTP username and password — those go below (NOT your AWS access key). To use a non-default region, set host to email-smtp.<region>.amazonaws.com."
|
|
53
|
+
},
|
|
54
|
+
smtp: {
|
|
55
|
+
displayName: "Custom SMTP",
|
|
56
|
+
description: "Any SMTP relay — supply host, port, user, and password manually.",
|
|
57
|
+
host: null,
|
|
58
|
+
port: 587,
|
|
59
|
+
secure: false,
|
|
60
|
+
userSource: "user",
|
|
61
|
+
passSource: "password",
|
|
62
|
+
setupHint: "Use for SMTP servers without a preset. Standard auth-SMTP only — no OAuth-XOAUTH2."
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
/** Convenience dropdown options for the credential UI. */
|
|
66
|
+
const EMAIL_PROVIDER_OPTIONS = Object.keys(EMAIL_PRESETS).map((name) => ({
|
|
67
|
+
value: name,
|
|
68
|
+
label: EMAIL_PRESETS[name].displayName
|
|
69
|
+
}));
|
|
70
|
+
|
|
71
|
+
//#endregion
|
|
72
|
+
//#region src/providers/email/transport.ts
|
|
73
|
+
function resolveUser(data, userSource) {
|
|
74
|
+
if (userSource.startsWith("literal:")) return userSource.slice(8);
|
|
75
|
+
if (userSource === "user") {
|
|
76
|
+
if (!data.user) throw new Error("SMTP user is required for this provider");
|
|
77
|
+
return data.user;
|
|
78
|
+
}
|
|
79
|
+
throw new Error(`Unknown userSource: ${userSource}`);
|
|
80
|
+
}
|
|
81
|
+
function resolvePass(data, passSource) {
|
|
82
|
+
const value = passSource === "apiKey" ? data.apiKey : data.password;
|
|
83
|
+
if (!value) throw new Error(passSource === "apiKey" ? "API key is required for this provider" : "Password is required for this provider");
|
|
84
|
+
return value;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Build a `nodemailer` `Transporter` from the credential blob.
|
|
88
|
+
*
|
|
89
|
+
* @throws `Error` when required fields are missing for the chosen provider.
|
|
90
|
+
* @throws `Error` when `nodemailer` is not installed (optional peer).
|
|
91
|
+
*/
|
|
92
|
+
async function buildEmailTransport(data) {
|
|
93
|
+
const preset = EMAIL_PRESETS[data.provider];
|
|
94
|
+
if (!preset) throw new Error(`Unknown email provider: ${data.provider}`);
|
|
95
|
+
const allowOverride = preset.host === null || preset.allowHostOverride === true;
|
|
96
|
+
const overrideHost = data.host?.trim();
|
|
97
|
+
const host = allowOverride && overrideHost ? overrideHost : preset.host;
|
|
98
|
+
if (!host) throw new Error("SMTP host is required");
|
|
99
|
+
const port = allowOverride && data.port !== void 0 && data.port !== "" ? typeof data.port === "number" ? data.port : parseInt(String(data.port), 10) : preset.port;
|
|
100
|
+
let secure = preset.secure;
|
|
101
|
+
if (allowOverride && data.secure !== void 0 && data.secure !== "") {
|
|
102
|
+
if (typeof data.secure === "boolean") secure = data.secure;
|
|
103
|
+
else if (typeof data.secure === "string") secure = data.secure === "true";
|
|
104
|
+
}
|
|
105
|
+
let nodemailer;
|
|
106
|
+
try {
|
|
107
|
+
nodemailer = await import("nodemailer");
|
|
108
|
+
} catch {
|
|
109
|
+
throw new Error("nodemailer is required to build an email transport — install it: `npm install nodemailer`");
|
|
110
|
+
}
|
|
111
|
+
return (nodemailer.default ?? nodemailer).createTransport({
|
|
112
|
+
host,
|
|
113
|
+
port,
|
|
114
|
+
secure,
|
|
115
|
+
auth: {
|
|
116
|
+
user: resolveUser(data, preset.userSource),
|
|
117
|
+
pass: resolvePass(data, preset.passSource)
|
|
118
|
+
}
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Compose the RFC-5322 `From` header value from the credential blob.
|
|
123
|
+
* Returns `"Display Name" <email@example.com>` when `fromName` is set,
|
|
124
|
+
* otherwise just `email@example.com`.
|
|
125
|
+
*/
|
|
126
|
+
function buildFromHeader(data) {
|
|
127
|
+
const name = data.fromName?.trim();
|
|
128
|
+
return name ? `"${name}" <${data.fromEmail}>` : data.fromEmail;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
//#endregion
|
|
132
|
+
//#region src/providers/email/schema.ts
|
|
133
|
+
/**
|
|
134
|
+
* Credential field schema for the email provider.
|
|
135
|
+
*
|
|
136
|
+
* Hosts that ship a dynamic credential form (driven by a provider's
|
|
137
|
+
* `getCredentialSchema()`-style method) read this to render the right
|
|
138
|
+
* fields. Returning the UNION of all provider-specific fields keeps the
|
|
139
|
+
* form generic — the UI hides irrelevant fields based on the chosen
|
|
140
|
+
* `provider`. Only relevant fields get saved into the encrypted blob.
|
|
141
|
+
*
|
|
142
|
+
* Shape is host-agnostic (no `@classytic/social` import). Hosts that
|
|
143
|
+
* use the social registry's `CredentialField` type can structurally cast.
|
|
144
|
+
*/
|
|
145
|
+
/** Union-of-fields schema — every field appears; the UI hides what's
|
|
146
|
+
* not relevant for the chosen `provider`. */
|
|
147
|
+
function getEmailCredentialSchema() {
|
|
148
|
+
return [
|
|
149
|
+
{
|
|
150
|
+
name: "provider",
|
|
151
|
+
displayName: "Provider",
|
|
152
|
+
type: "select",
|
|
153
|
+
required: true,
|
|
154
|
+
options: EMAIL_PROVIDER_OPTIONS,
|
|
155
|
+
description: "Which SMTP relay handles your sends."
|
|
156
|
+
},
|
|
157
|
+
{
|
|
158
|
+
name: "fromEmail",
|
|
159
|
+
displayName: "From Email",
|
|
160
|
+
type: "text",
|
|
161
|
+
required: true,
|
|
162
|
+
placeholder: "hello@yourdomain.com",
|
|
163
|
+
description: "Must be verified with your provider — sends from unverified addresses are rejected."
|
|
164
|
+
},
|
|
165
|
+
{
|
|
166
|
+
name: "fromName",
|
|
167
|
+
displayName: "From Name",
|
|
168
|
+
type: "text",
|
|
169
|
+
required: false,
|
|
170
|
+
placeholder: "Your Brand",
|
|
171
|
+
description: "Optional. Shown as the sender name in inboxes."
|
|
172
|
+
},
|
|
173
|
+
{
|
|
174
|
+
name: "apiKey",
|
|
175
|
+
displayName: "API Key",
|
|
176
|
+
type: "password",
|
|
177
|
+
required: false,
|
|
178
|
+
description: "Resend or SendGrid only."
|
|
179
|
+
},
|
|
180
|
+
{
|
|
181
|
+
name: "user",
|
|
182
|
+
displayName: "SMTP Username",
|
|
183
|
+
type: "text",
|
|
184
|
+
required: false,
|
|
185
|
+
description: "Gmail address, Mailgun SMTP user, or custom SMTP user."
|
|
186
|
+
},
|
|
187
|
+
{
|
|
188
|
+
name: "password",
|
|
189
|
+
displayName: "SMTP Password",
|
|
190
|
+
type: "password",
|
|
191
|
+
required: false,
|
|
192
|
+
description: "Gmail app password, Mailgun SMTP password, or custom SMTP password."
|
|
193
|
+
},
|
|
194
|
+
{
|
|
195
|
+
name: "host",
|
|
196
|
+
displayName: "SMTP Host",
|
|
197
|
+
type: "text",
|
|
198
|
+
required: false,
|
|
199
|
+
placeholder: "smtp.example.com",
|
|
200
|
+
description: "Custom SMTP only — preset hosts are filled automatically."
|
|
201
|
+
},
|
|
202
|
+
{
|
|
203
|
+
name: "port",
|
|
204
|
+
displayName: "SMTP Port",
|
|
205
|
+
type: "text",
|
|
206
|
+
required: false,
|
|
207
|
+
placeholder: "587",
|
|
208
|
+
description: "Custom SMTP only."
|
|
209
|
+
},
|
|
210
|
+
{
|
|
211
|
+
name: "secure",
|
|
212
|
+
displayName: "Secure (implicit TLS)",
|
|
213
|
+
type: "select",
|
|
214
|
+
required: false,
|
|
215
|
+
options: [{
|
|
216
|
+
value: "true",
|
|
217
|
+
label: "true (port 465 / implicit TLS)"
|
|
218
|
+
}, {
|
|
219
|
+
value: "false",
|
|
220
|
+
label: "false (port 587 / STARTTLS)"
|
|
221
|
+
}],
|
|
222
|
+
description: "Custom SMTP only."
|
|
223
|
+
}
|
|
224
|
+
];
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
//#endregion
|
|
228
|
+
//#region src/providers/email/test.ts
|
|
229
|
+
/**
|
|
230
|
+
* Validate an email credential by building its transport and asking the
|
|
231
|
+
* underlying SMTP server to verify the auth tuple. Used by hosts during
|
|
232
|
+
* "Test Connection" flows.
|
|
233
|
+
*
|
|
234
|
+
* Returns a typed result rather than throwing — UI consumers usually
|
|
235
|
+
* want to surface the message + status pair regardless of outcome.
|
|
236
|
+
*/
|
|
237
|
+
async function testEmailCredential(data) {
|
|
238
|
+
if (!data.provider) return {
|
|
239
|
+
status: "Error",
|
|
240
|
+
message: "Provider is required"
|
|
241
|
+
};
|
|
242
|
+
if (!data.fromEmail) return {
|
|
243
|
+
status: "Error",
|
|
244
|
+
message: "From email is required"
|
|
245
|
+
};
|
|
246
|
+
if (!Object.keys(EMAIL_PRESETS).includes(data.provider)) return {
|
|
247
|
+
status: "Error",
|
|
248
|
+
message: `Unknown provider: ${data.provider}`
|
|
249
|
+
};
|
|
250
|
+
let transport;
|
|
251
|
+
try {
|
|
252
|
+
transport = await buildEmailTransport(data);
|
|
253
|
+
} catch (err) {
|
|
254
|
+
return {
|
|
255
|
+
status: "Error",
|
|
256
|
+
message: err?.message ?? "Failed to build SMTP transport"
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
try {
|
|
260
|
+
if (typeof transport.verify === "function") await transport.verify();
|
|
261
|
+
return {
|
|
262
|
+
status: "OK",
|
|
263
|
+
message: `SMTP connection verified for ${data.fromEmail}`,
|
|
264
|
+
data: {
|
|
265
|
+
provider: data.provider,
|
|
266
|
+
fromEmail: data.fromEmail
|
|
267
|
+
}
|
|
268
|
+
};
|
|
269
|
+
} catch (err) {
|
|
270
|
+
return {
|
|
271
|
+
status: "Error",
|
|
272
|
+
message: err?.message ?? "SMTP verification failed"
|
|
273
|
+
};
|
|
274
|
+
} finally {
|
|
275
|
+
if (typeof transport.close === "function") transport.close();
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
//#endregion
|
|
280
|
+
export { EMAIL_PRESETS, EMAIL_PROVIDER_OPTIONS, buildEmailTransport, buildFromHeader, getEmailCredentialSchema, testEmailCredential };
|
|
@@ -101,6 +101,20 @@ var EmailChannel = class EmailChannel extends BaseChannel {
|
|
|
101
101
|
"replyTo",
|
|
102
102
|
"attachments"
|
|
103
103
|
]);
|
|
104
|
+
/**
|
|
105
|
+
* Pre-flight check called by the service before consuming a rate-limit
|
|
106
|
+
* token. Returning a skip result here avoids burning quota on payloads
|
|
107
|
+
* that obviously can't deliver (e.g., a mixed-channel batch where the
|
|
108
|
+
* recipient has a phone but no email).
|
|
109
|
+
*/
|
|
110
|
+
canSend(payload) {
|
|
111
|
+
if (!payload.recipient.email) return {
|
|
112
|
+
status: "skipped",
|
|
113
|
+
channel: this.name,
|
|
114
|
+
error: "No recipient email"
|
|
115
|
+
};
|
|
116
|
+
return null;
|
|
117
|
+
}
|
|
104
118
|
async send(payload) {
|
|
105
119
|
const { recipient, data } = payload;
|
|
106
120
|
if (!recipient.email) return {
|
|
@@ -328,6 +342,24 @@ var SmsChannel = class extends BaseChannel {
|
|
|
328
342
|
});
|
|
329
343
|
this.provider = config.provider;
|
|
330
344
|
}
|
|
345
|
+
/**
|
|
346
|
+
* Pre-flight check called by the service before consuming a rate-limit
|
|
347
|
+
* token. Skip if the payload lacks a recipient phone OR a body — these
|
|
348
|
+
* skips are deterministic and shouldn't burn SMS quota.
|
|
349
|
+
*/
|
|
350
|
+
canSend(payload) {
|
|
351
|
+
if (!payload.recipient.phone) return {
|
|
352
|
+
status: "skipped",
|
|
353
|
+
channel: this.name,
|
|
354
|
+
error: "No recipient phone number"
|
|
355
|
+
};
|
|
356
|
+
if (!(payload.data.text ?? payload.data.message ?? payload.data.subject ?? "")) return {
|
|
357
|
+
status: "skipped",
|
|
358
|
+
channel: this.name,
|
|
359
|
+
error: "No message body (data.text, data.message, or data.subject)"
|
|
360
|
+
};
|
|
361
|
+
return null;
|
|
362
|
+
}
|
|
331
363
|
async send(payload) {
|
|
332
364
|
const { recipient, data } = payload;
|
|
333
365
|
if (!recipient.phone) return {
|
|
@@ -430,6 +462,25 @@ var PushChannel = class extends BaseChannel {
|
|
|
430
462
|
});
|
|
431
463
|
this.provider = config.provider;
|
|
432
464
|
}
|
|
465
|
+
/**
|
|
466
|
+
* Pre-flight check called by the service before consuming a rate-limit
|
|
467
|
+
* token. Skip when there's no device token or no displayable content.
|
|
468
|
+
*/
|
|
469
|
+
canSend(payload) {
|
|
470
|
+
if (!payload.recipient.deviceToken) return {
|
|
471
|
+
status: "skipped",
|
|
472
|
+
channel: this.name,
|
|
473
|
+
error: "No recipient deviceToken"
|
|
474
|
+
};
|
|
475
|
+
const title = payload.data.title ?? payload.data.subject ?? "";
|
|
476
|
+
const body = payload.data.body ?? payload.data.text ?? payload.data.message ?? "";
|
|
477
|
+
if (!title && !body) return {
|
|
478
|
+
status: "skipped",
|
|
479
|
+
channel: this.name,
|
|
480
|
+
error: "No title or body (data.title, data.body)"
|
|
481
|
+
};
|
|
482
|
+
return null;
|
|
483
|
+
}
|
|
433
484
|
async send(payload) {
|
|
434
485
|
const { recipient, data } = payload;
|
|
435
486
|
if (!recipient.deviceToken) return {
|
|
@@ -1,4 +1,4 @@
|
|
|
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-
|
|
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-BMs4UhKD.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/channels/BaseChannel.d.ts
|
|
4
4
|
declare abstract class BaseChannel<TConfig extends ChannelConfig = ChannelConfig> implements Channel {
|
|
@@ -19,6 +19,13 @@ declare class EmailChannel extends BaseChannel<EmailChannelConfig> {
|
|
|
19
19
|
private getTransporter;
|
|
20
20
|
/** Fields that defaults must never override */
|
|
21
21
|
private static readonly PROTECTED_FIELDS;
|
|
22
|
+
/**
|
|
23
|
+
* Pre-flight check called by the service before consuming a rate-limit
|
|
24
|
+
* token. Returning a skip result here avoids burning quota on payloads
|
|
25
|
+
* that obviously can't deliver (e.g., a mixed-channel batch where the
|
|
26
|
+
* recipient has a phone but no email).
|
|
27
|
+
*/
|
|
28
|
+
canSend(payload: NotificationPayload): SendResult | null;
|
|
22
29
|
send(payload: NotificationPayload): Promise<SendResult>;
|
|
23
30
|
/** Verify the SMTP connection (useful for health checks) */
|
|
24
31
|
verify(): Promise<boolean>;
|
|
@@ -42,6 +49,12 @@ declare class ConsoleChannel extends BaseChannel<ChannelConfig> {
|
|
|
42
49
|
declare class SmsChannel extends BaseChannel<SmsChannelConfig> {
|
|
43
50
|
private provider;
|
|
44
51
|
constructor(config: SmsChannelConfig);
|
|
52
|
+
/**
|
|
53
|
+
* Pre-flight check called by the service before consuming a rate-limit
|
|
54
|
+
* token. Skip if the payload lacks a recipient phone OR a body — these
|
|
55
|
+
* skips are deterministic and shouldn't burn SMS quota.
|
|
56
|
+
*/
|
|
57
|
+
canSend(payload: NotificationPayload): SendResult | null;
|
|
45
58
|
send(payload: NotificationPayload): Promise<SendResult>;
|
|
46
59
|
}
|
|
47
60
|
//#endregion
|
|
@@ -49,6 +62,11 @@ declare class SmsChannel extends BaseChannel<SmsChannelConfig> {
|
|
|
49
62
|
declare class PushChannel extends BaseChannel<PushChannelConfig> {
|
|
50
63
|
private provider;
|
|
51
64
|
constructor(config: PushChannelConfig);
|
|
65
|
+
/**
|
|
66
|
+
* Pre-flight check called by the service before consuming a rate-limit
|
|
67
|
+
* token. Skip when there's no device token or no displayable content.
|
|
68
|
+
*/
|
|
69
|
+
canSend(payload: NotificationPayload): SendResult | null;
|
|
52
70
|
send(payload: NotificationPayload): Promise<SendResult>;
|
|
53
71
|
}
|
|
54
72
|
//#endregion
|
|
@@ -1,4 +1,4 @@
|
|
|
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-
|
|
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-BMs4UhKD.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/utils/merge-hooks.d.ts
|
|
4
4
|
type HookInput = Record<string, HookHandler | HookHandler[]>;
|
|
@@ -321,6 +321,18 @@ interface Channel {
|
|
|
321
321
|
readonly name: string;
|
|
322
322
|
shouldHandle(event: string): boolean;
|
|
323
323
|
send(payload: NotificationPayload): Promise<SendResult>;
|
|
324
|
+
/**
|
|
325
|
+
* Optional pre-flight check. Return a `SendResult` (typically with
|
|
326
|
+
* `status: 'skipped'`) to short-circuit before the service consumes a
|
|
327
|
+
* rate-limit token or starts the retry loop. Return `null` to proceed.
|
|
328
|
+
*
|
|
329
|
+
* Built-in channels use this to skip when the payload obviously can't
|
|
330
|
+
* be delivered (no `recipient.email` for `EmailChannel`, no
|
|
331
|
+
* `recipient.phone` for `SmsChannel`, etc.) so a mixed-channel batch
|
|
332
|
+
* doesn't burn the quota of one channel because another channel's
|
|
333
|
+
* recipient field is missing.
|
|
334
|
+
*/
|
|
335
|
+
canSend?(payload: NotificationPayload): SendResult | null;
|
|
324
336
|
}
|
|
325
337
|
/** SMTP / Nodemailer transport options */
|
|
326
338
|
interface SmtpTransportOptions {
|
|
@@ -487,6 +499,20 @@ interface NotificationServiceConfig {
|
|
|
487
499
|
rateLimitStore?: RateLimitStore;
|
|
488
500
|
/** Queue adapter for crash-resilient delivery. Service owns the queue. */
|
|
489
501
|
queue?: QueueAdapter;
|
|
502
|
+
/**
|
|
503
|
+
* How the queue processor signals failure back to the queue adapter.
|
|
504
|
+
*
|
|
505
|
+
* - `'throw-on-total-failure'` (default) — the processor throws
|
|
506
|
+
* when a dispatch had `sent === 0 && failed > 0`, so the queue
|
|
507
|
+
* marks the job failed (and retries up to `maxAttempts`). Partial
|
|
508
|
+
* successes (some channels sent) resolve normally to avoid
|
|
509
|
+
* double-sending the channels that already succeeded.
|
|
510
|
+
* - `'always-complete'` — legacy behavior. The processor never
|
|
511
|
+
* throws; queued jobs always resolve as completed, regardless of
|
|
512
|
+
* channel outcome. Keep this if your delivery log is the source
|
|
513
|
+
* of truth for failures and you don't want queue-level retries.
|
|
514
|
+
*/
|
|
515
|
+
queueFailureMode?: 'throw-on-total-failure' | 'always-complete';
|
|
490
516
|
}
|
|
491
517
|
/** Service lifecycle events */
|
|
492
518
|
type ServiceEvent = 'before:send' | 'after:send' | 'send:success' | 'send:failed' | 'send:retry' | 'send:rate_limited' | 'send:queued';
|
package/dist/utils/index.d.mts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { B as DeliveryLogQuery, 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, P as QueueEnqueueOptions, R as DeliveryLog, U as IdempotencyStore, V as MemoryDeliveryLog, W as MemoryIdempotencyStore, q as RateLimitStore, z as DeliveryLogEntry } from "../types-
|
|
2
|
-
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-
|
|
1
|
+
import { B as DeliveryLogQuery, 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, P as QueueEnqueueOptions, R as DeliveryLog, U as IdempotencyStore, V as MemoryDeliveryLog, W as MemoryIdempotencyStore, q as RateLimitStore, z as DeliveryLogEntry } from "../types-BMs4UhKD.mjs";
|
|
2
|
+
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-Bb4UoinT.mjs";
|
|
3
3
|
export { ChannelError, type DeliveryLog, type DeliveryLogEntry, type DeliveryLogQuery, type DeliveryStatus, Emitter, type FallbackOptions, IDEMPOTENCY_DEFAULT_TTL, type IdempotencyStore, MemoryDeliveryLog, MemoryIdempotencyStore, MemoryQueue, MemoryRateLimitStore, NotificationError, type PMapOptions, ProviderNotInstalledError, type QueueAdapter, type QueueEnqueueOptions, type QueueJob, type QueueJobStatus, type QueueProcessor, type QuietHoursConfig, type RateLimitConfig, type RateLimitStore, type StatusHandler, type StatusHandlerConfig, type StatusUpdate, type TemplateDefinition, type TemplateMap, calculateDelay, createSimpleResolver, createStatusHandler, isQuietHours, mergeHooks, pMap, resolveRetryConfig, withFallback, withRetry };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@classytic/notifications",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.1.0",
|
|
4
4
|
"description": "Multi-channel notifications (Email, SMS, Push, Webhook) with rate limiting, delivery tracking, queue adapters, channel fallback, templates, retry — zero required dependencies",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -16,11 +16,22 @@
|
|
|
16
16
|
"types": "./dist/channels/index.d.mts",
|
|
17
17
|
"default": "./dist/channels/index.mjs"
|
|
18
18
|
},
|
|
19
|
+
"./providers": {
|
|
20
|
+
"types": "./dist/providers/index.d.mts",
|
|
21
|
+
"default": "./dist/providers/index.mjs"
|
|
22
|
+
},
|
|
19
23
|
"./utils": {
|
|
20
24
|
"types": "./dist/utils/index.d.mts",
|
|
21
25
|
"default": "./dist/utils/index.mjs"
|
|
22
26
|
}
|
|
23
27
|
},
|
|
28
|
+
"typesVersions": {
|
|
29
|
+
"*": {
|
|
30
|
+
"channels": ["./dist/channels/index.d.mts"],
|
|
31
|
+
"providers": ["./dist/providers/index.d.mts"],
|
|
32
|
+
"utils": ["./dist/utils/index.d.mts"]
|
|
33
|
+
}
|
|
34
|
+
},
|
|
24
35
|
"files": [
|
|
25
36
|
"dist",
|
|
26
37
|
"README.md",
|
|
@@ -54,6 +65,9 @@
|
|
|
54
65
|
"Sadman Chowdhury (https://github.com/siam923)"
|
|
55
66
|
],
|
|
56
67
|
"license": "MIT",
|
|
68
|
+
"publishConfig": {
|
|
69
|
+
"access": "public"
|
|
70
|
+
},
|
|
57
71
|
"repository": {
|
|
58
72
|
"type": "git",
|
|
59
73
|
"url": "git+https://github.com/classytic/notifications.git"
|
|
@@ -79,16 +93,19 @@
|
|
|
79
93
|
"test": "vitest run",
|
|
80
94
|
"test:watch": "vitest",
|
|
81
95
|
"test:coverage": "vitest run --coverage",
|
|
96
|
+
"test:live": "vitest run --config vitest.live.config.ts",
|
|
82
97
|
"typecheck": "tsc --noEmit",
|
|
83
|
-
"prepublishOnly": "npm run build && npm run typecheck",
|
|
98
|
+
"prepublishOnly": "npm run build && npm run typecheck && npm test",
|
|
99
|
+
"push": "classytic-push",
|
|
84
100
|
"publish:dry": "npm publish --dry-run --access public",
|
|
85
101
|
"publish:npm": "npm publish --access public",
|
|
86
|
-
"release": "npm run build && npm run typecheck && npm publish --access public",
|
|
102
|
+
"release": "npm run build && npm run typecheck && npm test && npm publish --access public",
|
|
87
103
|
"release:patch": "npm version patch && npm run release",
|
|
88
104
|
"release:minor": "npm version minor && npm run release",
|
|
89
105
|
"release:major": "npm version major && npm run release"
|
|
90
106
|
},
|
|
91
107
|
"devDependencies": {
|
|
108
|
+
"@classytic/dev-tools": "^0.2.0",
|
|
92
109
|
"@types/node": "^22.0.0",
|
|
93
110
|
"@types/nodemailer": "^6.4.17",
|
|
94
111
|
"@vitest/coverage-v8": "3.2.4",
|