@miguelmorales13/nestkit 0.18.0 → 0.19.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/README.md +67 -40
- package/dist/auth/index.cjs +4 -4
- package/dist/auth/index.js +2 -2
- package/dist/auth/oauth/index.cjs +6 -6
- package/dist/auth/oauth/index.js +2 -2
- package/dist/email/adapters/brevo.email.d.ts +22 -0
- package/dist/email/adapters/memory.email.d.ts +14 -0
- package/dist/email/adapters/message.d.ts +13 -0
- package/dist/email/adapters/resend.email.d.ts +28 -0
- package/dist/email/adapters/smtp.email.d.ts +22 -0
- package/dist/email/address.d.ts +15 -0
- package/dist/email/email.module.d.ts +37 -0
- package/dist/email/email.options.d.ts +39 -0
- package/dist/email/email.port.d.ts +62 -0
- package/dist/email/index.cjs +314 -0
- package/dist/email/index.d.ts +12 -0
- package/dist/email/index.js +314 -0
- package/dist/errors/index.cjs +5 -5
- package/dist/errors/index.js +6 -6
- package/dist/index.cjs +14 -14
- package/dist/index.js +18 -18
- package/package.json +6 -1
- package/dist/{chunk-4HHZFOVC.cjs → chunk-FH5UNWWW.cjs} +2 -2
- package/dist/{chunk-IKXSVEJ7.js → chunk-TUNDBBQF.js} +3 -3
package/README.md
CHANGED
|
@@ -12,8 +12,8 @@ está listo, la implementación no.
|
|
|
12
12
|
**Las integraciones**, cada una en su subpath y sin arrastrar dependencias a quien no la use: acceso
|
|
13
13
|
con Google, Facebook o enlace mágico por correo (`auth/oauth`) o con email y contraseña (`auth`), Stripe, cobro presencial en
|
|
14
14
|
terminal Mercado Pago Point o Clip (`payments`), facturación CFDI 4.0 (`invoicing`), Telegram,
|
|
15
|
-
WhatsApp, Instagram y Facebook Pages (`meta`), subida de archivos (`storage`),
|
|
16
|
-
|
|
15
|
+
WhatsApp, Instagram y Facebook Pages (`meta`), subida de archivos (`storage`), correo transaccional con Resend,
|
|
16
|
+
Brevo o SMTP tras un puerto (`email`) y lectura de analítica (`umami`).
|
|
17
17
|
|
|
18
18
|
## ¿Para qué proyectos es esto?
|
|
19
19
|
|
|
@@ -1413,19 +1413,20 @@ por email, así que quien entró ayer con Google y hoy pide un enlace sigue sien
|
|
|
1413
1413
|
igual que Google↔Facebook. No se crea ninguna fila de cuenta (`OAuthAccount`): el email ya es la
|
|
1414
1414
|
identidad.
|
|
1415
1415
|
|
|
1416
|
-
Se enciende atando dos puertos más. nestkit no
|
|
1417
|
-
proyecto pone
|
|
1416
|
+
Se enciende atando dos puertos más. nestkit no decide el correo: `MagicLinkSenderPort` es donde el
|
|
1417
|
+
proyecto pone la plantilla y el idioma, normalmente sobre el `EmailPort` de [`email`](#email--correo-transaccional-con-el-proveedor-como-configuración).
|
|
1418
1418
|
|
|
1419
1419
|
```ts
|
|
1420
1420
|
import {
|
|
1421
1421
|
MAGIC_LINK_STORE, MAGIC_LINK_SENDER, type MagicLinkSenderPort, type MagicLinkDelivery,
|
|
1422
1422
|
} from '@miguelmorales13/nestkit/auth/oauth';
|
|
1423
|
+
import { EMAIL, type EmailPort } from '@miguelmorales13/nestkit/email';
|
|
1423
1424
|
|
|
1424
1425
|
@Injectable()
|
|
1425
1426
|
class MagicLinkMailer implements MagicLinkSenderPort {
|
|
1426
|
-
constructor(@Inject(
|
|
1427
|
-
async send({ email, url
|
|
1428
|
-
await this.
|
|
1427
|
+
constructor(@Inject(EMAIL) private readonly email: EmailPort) {} // Resend, Brevo o SMTP: da igual
|
|
1428
|
+
async send({ email, url }: MagicLinkDelivery) {
|
|
1429
|
+
await this.email.send({ to: email, subject: 'Tu enlace de acceso', html: `<a href="${url}">Entrar</a>` });
|
|
1429
1430
|
}
|
|
1430
1431
|
}
|
|
1431
1432
|
|
|
@@ -1472,62 +1473,87 @@ correo y obtiene el mismo `ok`. Lo que sí es del proyecto: **limitar la frecuen
|
|
|
1472
1473
|
manda tantos correos como se le pidan— y decidir si el store invalida los enlaces anteriores de la
|
|
1473
1474
|
misma dirección al crear uno nuevo.
|
|
1474
1475
|
|
|
1475
|
-
### `email
|
|
1476
|
+
### `email` — correo transaccional con el proveedor como configuración
|
|
1476
1477
|
|
|
1477
|
-
|
|
1478
|
-
|
|
1478
|
+
Un puerto, `EmailPort`, y el proveedor detrás se elige en una línea: **Resend**, **Brevo** (antes
|
|
1479
|
+
Sendinblue) o **cualquier servidor SMTP** vía Nodemailer. Mismo patrón que `storage`: nada en la
|
|
1480
|
+
app depende de un cliente concreto, así que cambiar de proveedor no toca ninguna llamada.
|
|
1479
1481
|
|
|
1480
1482
|
```ts
|
|
1481
|
-
import {
|
|
1482
|
-
import { ResendModule } from '@miguelmorales13/nestkit/email/resend';
|
|
1483
|
+
import { EmailModule } from '@miguelmorales13/nestkit/email';
|
|
1483
1484
|
|
|
1484
|
-
@Module({
|
|
1485
|
+
@Module({
|
|
1486
|
+
imports: [
|
|
1487
|
+
EmailModule.forRoot({ provider: 'brevo' }), // lee BREVO_API_KEY y EMAIL_FROM
|
|
1488
|
+
// EmailModule.forRoot({ provider: 'resend', from: 'Mi App <hola@miapp.mx>' }),
|
|
1489
|
+
// EmailModule.forRoot({ provider: 'smtp', smtp: { host, port: 587, user, password } }),
|
|
1490
|
+
// EmailModule.forRoot({ provider: 'memory' }), // pruebas y desarrollo: nadie recibe nada
|
|
1491
|
+
],
|
|
1492
|
+
})
|
|
1485
1493
|
export class AppModule {}
|
|
1486
1494
|
```
|
|
1487
1495
|
|
|
1488
1496
|
```ts
|
|
1489
|
-
import {
|
|
1490
|
-
import { RESEND_CLIENT } from '@miguelmorales13/nestkit/email/resend';
|
|
1491
|
-
import type { Resend } from 'resend';
|
|
1497
|
+
import { EMAIL, type EmailPort } from '@miguelmorales13/nestkit/email';
|
|
1492
1498
|
|
|
1493
1499
|
@Injectable()
|
|
1494
1500
|
export class NotificationsService {
|
|
1495
|
-
constructor(@Inject(
|
|
1496
|
-
|
|
1497
|
-
async
|
|
1498
|
-
await this.
|
|
1501
|
+
constructor(@Inject(EMAIL) private readonly email: EmailPort) {}
|
|
1502
|
+
|
|
1503
|
+
async welcome(to: string, name: string) {
|
|
1504
|
+
const { id } = await this.email.send({
|
|
1505
|
+
to: { email: to, name }, // o 'Ana <ana@example.com>'
|
|
1506
|
+
subject: 'Bienvenida',
|
|
1507
|
+
text: `Hola ${name}`,
|
|
1508
|
+
html: `<p>Hola ${name}</p>`,
|
|
1509
|
+
tags: { category: 'welcome' },
|
|
1510
|
+
attachments: [{ filename: 'guia.pdf', content: pdfBuffer, contentType: 'application/pdf' }],
|
|
1511
|
+
});
|
|
1499
1512
|
}
|
|
1500
1513
|
}
|
|
1501
1514
|
```
|
|
1502
1515
|
|
|
1503
|
-
|
|
1516
|
+
Lo que no pases en código sale del entorno: `EMAIL_PROVIDER`, `EMAIL_FROM`, `EMAIL_REPLY_TO`;
|
|
1517
|
+
`RESEND_API_KEY`; `SMTP_HOST`, `SMTP_PORT`, `SMTP_SECURE`, `SMTP_USER`, `SMTP_PASSWORD`;
|
|
1518
|
+
`BREVO_API_KEY`. **No hay proveedor por defecto**: sin `provider` ni `EMAIL_PROVIDER` el módulo
|
|
1519
|
+
falla al cablear, no en el primer envío. Lo mismo si el proveedor elegido no tiene credenciales.
|
|
1504
1520
|
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1521
|
+
El mensaje es el mismo para los tres —`from`, `to`/`cc`/`bcc`, `replyTo`, `subject`, `text`/`html`,
|
|
1522
|
+
`headers`, `tags`, `attachments`— y cada adaptador lo traduce a lo suyo: las direcciones con nombre
|
|
1523
|
+
van como `"Ana <ana@…>"` a Resend y SMTP y como `{ name, email }` a Brevo; los `tags` son pares
|
|
1524
|
+
nombre/valor en Resend, `nombre:valor` en Brevo y cabeceras `X-Tag-<nombre>` por SMTP. Un fallo del
|
|
1525
|
+
proveedor es una `EmailProviderException` (502, código `EMAIL_PROVIDER_ERROR`) con el estado y el
|
|
1526
|
+
cuerpo originales en `details` — también en Resend, cuyo SDK no lanza sino que devuelve `{ error }`.
|
|
1508
1527
|
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1528
|
+
**Brevo** va por su API REST v3 con `fetch`, sin SDK. Cosas a saber: los adjuntos viajan en base64
|
|
1529
|
+
dentro del JSON y la petición completa no puede pasar de 10 MB; y Brevo **rechaza extensiones fuera
|
|
1530
|
+
de su lista** (pdf, docx, xlsx, csv, png, jpg, zip… — un `.exe` o un `.json` no entra). Su relay
|
|
1531
|
+
SMTP (`smtp-relay.brevo.com:587`, login + clave SMTP) también funciona con `provider: 'smtp'`, por
|
|
1532
|
+
si se prefiere.
|
|
1512
1533
|
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
import type { Transporter } from 'nodemailer';
|
|
1534
|
+
Los SDKs de Resend y Nodemailer se cargan **perezosamente en el primer envío**: una app en Brevo no
|
|
1535
|
+
instala ninguno de los dos. `memory` guarda cada mensaje en `MemoryEmail.sent` — el buzón de salida
|
|
1536
|
+
de las pruebas.
|
|
1517
1537
|
|
|
1518
|
-
|
|
1519
|
-
export class NotificationsService {
|
|
1520
|
-
constructor(@Inject(NODEMAILER_TRANSPORT) private readonly mailer: Transporter) {}
|
|
1538
|
+
Es el sitio natural para el `MagicLinkSenderPort` de `auth/oauth`:
|
|
1521
1539
|
|
|
1522
|
-
|
|
1523
|
-
|
|
1540
|
+
```ts
|
|
1541
|
+
@Injectable()
|
|
1542
|
+
class MagicLinkMailer implements MagicLinkSenderPort {
|
|
1543
|
+
constructor(@Inject(EMAIL) private readonly email: EmailPort) {}
|
|
1544
|
+
send({ email, url }: MagicLinkDelivery) {
|
|
1545
|
+
return this.email.send({ to: email, subject: 'Tu enlace de acceso', html: `<a href="${url}">Entrar</a>` });
|
|
1524
1546
|
}
|
|
1525
1547
|
}
|
|
1526
1548
|
```
|
|
1527
1549
|
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1550
|
+
#### `email/resend` y `email/nodemailer` — los clientes crudos
|
|
1551
|
+
|
|
1552
|
+
Siguen existiendo para quien necesite algo que el puerto no expresa (plantillas de Resend, opciones
|
|
1553
|
+
de transporte de Nodemailer): `ResendModule` exporta `RESEND_CLIENT` (un `Resend`, requiere
|
|
1554
|
+
`RESEND_API_KEY`) y `NodemailerModule` exporta `NODEMAILER_TRANSPORT` (un `Transporter`, requiere
|
|
1555
|
+
`SMTP_HOST`, `SMTP_PORT`, `SMTP_USER`, `SMTP_PASSWORD`; `SMTP_SECURE` opcional). Usar el puerto
|
|
1556
|
+
por defecto y bajar al cliente solo cuando haga falta.
|
|
1531
1557
|
|
|
1532
1558
|
### `storage` — subida de archivos agnóstica del proveedor
|
|
1533
1559
|
|
|
@@ -1697,6 +1723,7 @@ trae los datos.
|
|
|
1697
1723
|
| `@miguelmorales13/nestkit/invoicing` | `InvoicingModule`, `INVOICING`, `InvoicingPort`, adaptadores `FacturapiInvoicing`/`FacturamaInvoicing` — CFDI 4.0 |
|
|
1698
1724
|
| `@miguelmorales13/nestkit/payments` | `PaymentsModule`, `TERMINAL_PAYMENTS`, `TerminalPaymentsPort`, adaptadores `MercadoPagoTerminalPayments`/`ClipTerminalPayments`, `createTerminalPaymentsWebhookController` |
|
|
1699
1725
|
| `@miguelmorales13/nestkit/storage` | `StorageModule`, `STORAGE`, `StoragePort`, adaptadores `LocalStorage`/`S3Storage`/`BunnyStorage` |
|
|
1726
|
+
| `@miguelmorales13/nestkit/email` | `EmailModule`, `EMAIL`, `EmailPort`, adaptadores `ResendEmail`/`SmtpEmail`/`BrevoEmail`/`MemoryEmail` |
|
|
1700
1727
|
| `@miguelmorales13/nestkit/email/resend` | `ResendModule`, `RESEND_CLIENT` |
|
|
1701
1728
|
| `@miguelmorales13/nestkit/email/nodemailer` | `NodemailerModule`, `NODEMAILER_TRANSPORT` |
|
|
1702
1729
|
| `@miguelmorales13/nestkit/i18n` | `I18nModule`, `t`, `translate`, `currentLanguage`, `I18nInterceptor`, `TranslatorPort`, `NestI18nTranslator`, `translateOr` |
|
|
@@ -1708,7 +1735,7 @@ Qué se añadió en cada versión y por qué está hecho así: [CAMBIOS.md](./CA
|
|
|
1708
1735
|
|
|
1709
1736
|
## Estado del paquete
|
|
1710
1737
|
|
|
1711
|
-
`0.
|
|
1738
|
+
`0.19.0`. Sin adaptador Mongo real. Con 251 pruebas propias (`bun test`): las de
|
|
1712
1739
|
`verifyState`, que existen porque las pruebas end-to-end de la app consumidora
|
|
1713
1740
|
**no podían ver ese fallo** — desactivada la verificación seguían pasando,
|
|
1714
1741
|
porque el callback pasaba a canjear el código y fallaba redirigiendo al mismo
|
package/dist/auth/index.cjs
CHANGED
|
@@ -2,13 +2,13 @@
|
|
|
2
2
|
|
|
3
3
|
|
|
4
4
|
|
|
5
|
-
var
|
|
6
|
-
require('../chunk-SDWHKPXI.cjs');
|
|
5
|
+
var _chunkFH5UNWWWcjs = require('../chunk-FH5UNWWW.cjs');
|
|
7
6
|
|
|
8
7
|
|
|
9
8
|
|
|
10
9
|
|
|
11
10
|
var _chunkHDFPSA2Vcjs = require('../chunk-HDFPSA2V.cjs');
|
|
11
|
+
require('../chunk-SDWHKPXI.cjs');
|
|
12
12
|
require('../chunk-Q5Y33L7B.cjs');
|
|
13
13
|
require('../chunk-PNK5WMPP.cjs');
|
|
14
14
|
|
|
@@ -108,7 +108,7 @@ _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
|
|
|
108
108
|
|
|
109
109
|
// src/auth/auth.service.ts
|
|
110
110
|
var BaseAuthService = class {
|
|
111
|
-
constructor(users, tokens = new (0,
|
|
111
|
+
constructor(users, tokens = new (0, _chunkFH5UNWWWcjs.TokenService)()) {
|
|
112
112
|
this.users = users;
|
|
113
113
|
this.tokens = tokens;
|
|
114
114
|
}
|
|
@@ -206,4 +206,4 @@ function createAuthController(serviceToken, options = {}) {
|
|
|
206
206
|
|
|
207
207
|
|
|
208
208
|
|
|
209
|
-
exports.BaseAuthService = BaseAuthService; exports.CurrentTenant = CurrentTenant; exports.CurrentUser =
|
|
209
|
+
exports.BaseAuthService = BaseAuthService; exports.CurrentTenant = CurrentTenant; exports.CurrentUser = _chunkFH5UNWWWcjs.CurrentUser; exports.JwtAuthGuard = _chunkFH5UNWWWcjs.JwtAuthGuard; exports.LoginDto = LoginDto; exports.ROLES_KEY = ROLES_KEY; exports.RefreshDto = RefreshDto; exports.RegisterDto = RegisterDto; exports.RequireTenantGuard = RequireTenantGuard; exports.Roles = Roles; exports.RolesGuard = RolesGuard; exports.TokenService = _chunkFH5UNWWWcjs.TokenService; exports.createAuthController = createAuthController; exports.hashPassword = hashPassword; exports.verifyPassword = verifyPassword;
|
package/dist/auth/index.js
CHANGED
|
@@ -2,13 +2,13 @@ import {
|
|
|
2
2
|
CurrentUser,
|
|
3
3
|
JwtAuthGuard,
|
|
4
4
|
TokenService
|
|
5
|
-
} from "../chunk-
|
|
6
|
-
import "../chunk-ETRUVZTJ.js";
|
|
5
|
+
} from "../chunk-TUNDBBQF.js";
|
|
7
6
|
import {
|
|
8
7
|
ConflictAppException,
|
|
9
8
|
ForbiddenAppException,
|
|
10
9
|
UnauthorizedAppException
|
|
11
10
|
} from "../chunk-ZFIDAX7K.js";
|
|
11
|
+
import "../chunk-ETRUVZTJ.js";
|
|
12
12
|
import "../chunk-M3GQDRWR.js";
|
|
13
13
|
import "../chunk-VVMRZEIW.js";
|
|
14
14
|
import {
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
|
|
2
2
|
|
|
3
3
|
|
|
4
|
-
var
|
|
5
|
-
require('../../chunk-SDWHKPXI.cjs');
|
|
4
|
+
var _chunkFH5UNWWWcjs = require('../../chunk-FH5UNWWW.cjs');
|
|
6
5
|
|
|
7
6
|
|
|
8
7
|
|
|
9
8
|
var _chunkHDFPSA2Vcjs = require('../../chunk-HDFPSA2V.cjs');
|
|
9
|
+
require('../../chunk-SDWHKPXI.cjs');
|
|
10
10
|
require('../../chunk-Q5Y33L7B.cjs');
|
|
11
11
|
require('../../chunk-PNK5WMPP.cjs');
|
|
12
12
|
|
|
@@ -630,7 +630,7 @@ OAuthCallbackFilter = exports.OAuthCallbackFilter = _chunk2REOCMUDcjs.__decorate
|
|
|
630
630
|
|
|
631
631
|
|
|
632
632
|
function createOAuthController(options = {}) {
|
|
633
|
-
const Guard = _nullishCoalesce(options.guard, () => (
|
|
633
|
+
const Guard = _nullishCoalesce(options.guard, () => ( _chunkFH5UNWWWcjs.JwtAuthGuard));
|
|
634
634
|
const userId = _nullishCoalesce(options.userId, () => ( ((user) => user.sub)));
|
|
635
635
|
let OAuthControllerHost = class {
|
|
636
636
|
// Explicit token: the build emits no `design:paramtypes`, so a subclass
|
|
@@ -743,17 +743,17 @@ function createOAuthController(options = {}) {
|
|
|
743
743
|
_chunk2REOCMUDcjs.__decorateClass.call(void 0, [
|
|
744
744
|
_common.UseGuards.call(void 0, Guard),
|
|
745
745
|
_common.Get.call(void 0, "me"),
|
|
746
|
-
_chunk2REOCMUDcjs.__decorateParam.call(void 0, 0,
|
|
746
|
+
_chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _chunkFH5UNWWWcjs.CurrentUser.call(void 0, ))
|
|
747
747
|
], OAuthControllerHost.prototype, "me", 1);
|
|
748
748
|
_chunk2REOCMUDcjs.__decorateClass.call(void 0, [
|
|
749
749
|
_common.UseGuards.call(void 0, Guard),
|
|
750
750
|
_common.Get.call(void 0, "linked-accounts"),
|
|
751
|
-
_chunk2REOCMUDcjs.__decorateParam.call(void 0, 0,
|
|
751
|
+
_chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _chunkFH5UNWWWcjs.CurrentUser.call(void 0, ))
|
|
752
752
|
], OAuthControllerHost.prototype, "linkedAccounts", 1);
|
|
753
753
|
_chunk2REOCMUDcjs.__decorateClass.call(void 0, [
|
|
754
754
|
_common.UseGuards.call(void 0, Guard),
|
|
755
755
|
_common.Post.call(void 0, "link-intent"),
|
|
756
|
-
_chunk2REOCMUDcjs.__decorateParam.call(void 0, 0,
|
|
756
|
+
_chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _chunkFH5UNWWWcjs.CurrentUser.call(void 0, )),
|
|
757
757
|
_chunk2REOCMUDcjs.__decorateParam.call(void 0, 1, _common.Res.call(void 0, { passthrough: true }))
|
|
758
758
|
], OAuthControllerHost.prototype, "linkIntent", 1);
|
|
759
759
|
_chunk2REOCMUDcjs.__decorateClass.call(void 0, [
|
package/dist/auth/oauth/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import {
|
|
2
2
|
CurrentUser,
|
|
3
3
|
JwtAuthGuard
|
|
4
|
-
} from "../../chunk-
|
|
5
|
-
import "../../chunk-ETRUVZTJ.js";
|
|
4
|
+
} from "../../chunk-TUNDBBQF.js";
|
|
6
5
|
import {
|
|
7
6
|
UnauthorizedAppException,
|
|
8
7
|
ValidationAppException
|
|
9
8
|
} from "../../chunk-ZFIDAX7K.js";
|
|
9
|
+
import "../../chunk-ETRUVZTJ.js";
|
|
10
10
|
import "../../chunk-M3GQDRWR.js";
|
|
11
11
|
import "../../chunk-VVMRZEIW.js";
|
|
12
12
|
import {
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { BrevoEmailOptions } from '../email.options.js';
|
|
2
|
+
import { type EmailMessage, type EmailPort, type SentEmail } from '../email.port.js';
|
|
3
|
+
/**
|
|
4
|
+
* Brevo (formerly Sendinblue) over its v3 REST API — one `POST /smtp/email`
|
|
5
|
+
* with the key in an `api-key` header. No SDK: the call is a dozen lines of
|
|
6
|
+
* `fetch`, and every field it sends is visible here, which is the same
|
|
7
|
+
* reasoning as `payments` and `auth/oauth`.
|
|
8
|
+
*
|
|
9
|
+
* Attachments travel base64-encoded inside the JSON; Brevo caps the whole
|
|
10
|
+
* request at 10 MB, so anything bigger belongs in `storage` with a link.
|
|
11
|
+
*/
|
|
12
|
+
export declare class BrevoEmail implements EmailPort {
|
|
13
|
+
private readonly options;
|
|
14
|
+
private readonly defaults;
|
|
15
|
+
private readonly baseUrl;
|
|
16
|
+
private readonly fetchImpl;
|
|
17
|
+
constructor(options: BrevoEmailOptions, defaults?: {
|
|
18
|
+
from?: string;
|
|
19
|
+
replyTo?: string;
|
|
20
|
+
});
|
|
21
|
+
send(input: EmailMessage): Promise<SentEmail>;
|
|
22
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { EmailMessage, EmailPort, SentEmail } from '../email.port.js';
|
|
2
|
+
/**
|
|
3
|
+
* Keeps every message in memory instead of sending it. For tests, and for a
|
|
4
|
+
* development environment that must not email anyone. `sent` is the outbox.
|
|
5
|
+
*/
|
|
6
|
+
export declare class MemoryEmail implements EmailPort {
|
|
7
|
+
private readonly defaults;
|
|
8
|
+
readonly sent: EmailMessage[];
|
|
9
|
+
constructor(defaults?: {
|
|
10
|
+
from?: string;
|
|
11
|
+
replyTo?: string;
|
|
12
|
+
});
|
|
13
|
+
send(message: EmailMessage): Promise<SentEmail>;
|
|
14
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { EmailAddress, EmailMessage } from '../email.port.js';
|
|
2
|
+
/**
|
|
3
|
+
* Fills the defaults in and refuses what no provider would accept, so each
|
|
4
|
+
* adapter can assume a complete message and the error reads the same
|
|
5
|
+
* whichever one is configured.
|
|
6
|
+
*/
|
|
7
|
+
export declare function completeMessage(message: EmailMessage, defaults: {
|
|
8
|
+
from?: string;
|
|
9
|
+
replyTo?: string;
|
|
10
|
+
}): EmailMessage & {
|
|
11
|
+
from: EmailAddress;
|
|
12
|
+
};
|
|
13
|
+
export declare function attachmentBuffer(content: Buffer | string): Buffer;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { Resend } from 'resend';
|
|
2
|
+
import type { ResendEmailOptions } from '../email.options.js';
|
|
3
|
+
import { type EmailMessage, type EmailPort, type SentEmail } from '../email.port.js';
|
|
4
|
+
/** The one method of the SDK this adapter uses — what a test hands in instead of the real thing. */
|
|
5
|
+
export type ResendLike = {
|
|
6
|
+
emails: {
|
|
7
|
+
send: Resend['emails']['send'];
|
|
8
|
+
};
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* Resend through its SDK, loaded lazily on the first send so an app on Brevo
|
|
12
|
+
* or SMTP never loads it — the same rule as `storage`'s S3 adapter.
|
|
13
|
+
*
|
|
14
|
+
* The SDK does not throw: it answers `{ data, error }`. The adapter turns the
|
|
15
|
+
* error half into {@link EmailProviderException} so a failed send is an
|
|
16
|
+
* exception here like everywhere else, and never a silently ignored result.
|
|
17
|
+
*/
|
|
18
|
+
export declare class ResendEmail implements EmailPort {
|
|
19
|
+
private readonly options;
|
|
20
|
+
private readonly defaults;
|
|
21
|
+
private clientPromise?;
|
|
22
|
+
constructor(options: ResendEmailOptions, defaults?: {
|
|
23
|
+
from?: string;
|
|
24
|
+
replyTo?: string;
|
|
25
|
+
}, client?: ResendLike);
|
|
26
|
+
private client;
|
|
27
|
+
send(input: EmailMessage): Promise<SentEmail>;
|
|
28
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { Transporter } from 'nodemailer';
|
|
2
|
+
import type { SmtpEmailOptions } from '../email.options.js';
|
|
3
|
+
import { type EmailMessage, type EmailPort, type SentEmail } from '../email.port.js';
|
|
4
|
+
/** The one method this adapter needs from a transport. */
|
|
5
|
+
export type TransporterLike = Pick<Transporter, 'sendMail'>;
|
|
6
|
+
/**
|
|
7
|
+
* Any SMTP server through Nodemailer, loaded lazily on the first send.
|
|
8
|
+
*
|
|
9
|
+
* Tags have no place in SMTP; they go out as `X-Tag-<name>` headers, which
|
|
10
|
+
* most providers' relays surface in their dashboards and nobody else minds.
|
|
11
|
+
*/
|
|
12
|
+
export declare class SmtpEmail implements EmailPort {
|
|
13
|
+
private readonly options;
|
|
14
|
+
private readonly defaults;
|
|
15
|
+
private transportPromise?;
|
|
16
|
+
constructor(options: SmtpEmailOptions, defaults?: {
|
|
17
|
+
from?: string;
|
|
18
|
+
replyTo?: string;
|
|
19
|
+
}, transport?: TransporterLike);
|
|
20
|
+
private transport;
|
|
21
|
+
send(input: EmailMessage): Promise<SentEmail>;
|
|
22
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { EmailAddress } from './email.port.js';
|
|
2
|
+
export interface ParsedAddress {
|
|
3
|
+
email: string;
|
|
4
|
+
name?: string;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Normalises the two spellings the port accepts into one shape. Providers
|
|
8
|
+
* disagree — Resend and Nodemailer take `"Name <email>"`, Brevo wants
|
|
9
|
+
* `{ name, email }` — so every adapter goes through here and the caller
|
|
10
|
+
* never has to know which one is behind the port.
|
|
11
|
+
*/
|
|
12
|
+
export declare function parseAddress(address: EmailAddress): ParsedAddress;
|
|
13
|
+
/** `Name <email>` when there is a name, the bare address otherwise. */
|
|
14
|
+
export declare function formatAddress(address: EmailAddress): string;
|
|
15
|
+
export declare function toList(value: EmailAddress | EmailAddress[] | undefined): EmailAddress[];
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { type DynamicModule } from '@nestjs/common';
|
|
2
|
+
import { type EmailOptions } from './email.options.js';
|
|
3
|
+
import { type EmailPort } from './email.port.js';
|
|
4
|
+
/**
|
|
5
|
+
* Merges explicit options with the environment; anything not passed in code
|
|
6
|
+
* falls back to the env, so `EmailModule.forRoot()` with no arguments works
|
|
7
|
+
* when the environment is configured.
|
|
8
|
+
*
|
|
9
|
+
* Recognised vars: `EMAIL_PROVIDER`, `EMAIL_FROM`, `EMAIL_REPLY_TO`; resend
|
|
10
|
+
* `RESEND_API_KEY`; smtp `SMTP_HOST`, `SMTP_PORT`, `SMTP_SECURE`, `SMTP_USER`,
|
|
11
|
+
* `SMTP_PASSWORD`; brevo `BREVO_API_KEY`, `BREVO_BASE_URL`.
|
|
12
|
+
*/
|
|
13
|
+
export declare function resolveEmailOptions(options?: EmailOptions): EmailOptions;
|
|
14
|
+
/** Constructs the adapter the options select, failing loudly on missing config. */
|
|
15
|
+
export declare function createEmailAdapter(options?: EmailOptions): EmailPort;
|
|
16
|
+
/**
|
|
17
|
+
* Provider-agnostic transactional email. Register once in the root module
|
|
18
|
+
* and inject the port anywhere with `@Inject(EMAIL) email: EmailPort`.
|
|
19
|
+
*
|
|
20
|
+
* ```ts
|
|
21
|
+
* EmailModule.forRoot({ provider: 'brevo' }) // reads BREVO_API_KEY, EMAIL_FROM
|
|
22
|
+
* EmailModule.forRoot({ provider: 'resend', from: 'Mi App <hola@miapp.mx>' })
|
|
23
|
+
* EmailModule.forRoot({ provider: 'smtp', smtp: { host, port: 587, user, password } })
|
|
24
|
+
* EmailModule.forRootAsync({ inject: [Config], useFactory: (c) => ({ provider: c.emailProvider }) })
|
|
25
|
+
* ```
|
|
26
|
+
*
|
|
27
|
+
* Switching providers is this one line — no call site changes, because
|
|
28
|
+
* everything depends on `EmailPort`, never on a concrete client.
|
|
29
|
+
*/
|
|
30
|
+
export declare class EmailModule {
|
|
31
|
+
static forRoot(options?: EmailOptions): DynamicModule;
|
|
32
|
+
static forRootAsync(config: {
|
|
33
|
+
imports?: any[];
|
|
34
|
+
inject?: any[];
|
|
35
|
+
useFactory: (...args: any[]) => EmailOptions | Promise<EmailOptions>;
|
|
36
|
+
}): DynamicModule;
|
|
37
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/** DI token carrying the resolved {@link EmailOptions}. */
|
|
2
|
+
export declare const EMAIL_OPTIONS: unique symbol;
|
|
3
|
+
/** Which adapter backs the {@link EmailPort}. */
|
|
4
|
+
export type EmailProvider = 'resend' | 'smtp' | 'brevo' | 'memory';
|
|
5
|
+
export interface ResendEmailOptions {
|
|
6
|
+
apiKey: string;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Any SMTP server, through Nodemailer. Brevo's own relay works here too
|
|
10
|
+
* (`smtp-relay.brevo.com:587`, login + SMTP key) for an app that would rather
|
|
11
|
+
* not depend on the HTTP API — but the `brevo` adapter is the lighter choice.
|
|
12
|
+
*/
|
|
13
|
+
export interface SmtpEmailOptions {
|
|
14
|
+
host: string;
|
|
15
|
+
port: number;
|
|
16
|
+
/** TLS from the first byte (port 465). Off for STARTTLS on 587. */
|
|
17
|
+
secure?: boolean;
|
|
18
|
+
/** Both omitted for a relay that needs no authentication (a local MailHog, say). */
|
|
19
|
+
user?: string;
|
|
20
|
+
password?: string;
|
|
21
|
+
}
|
|
22
|
+
export interface BrevoEmailOptions {
|
|
23
|
+
apiKey: string;
|
|
24
|
+
/** Defaults to `https://api.brevo.com/v3`. */
|
|
25
|
+
baseUrl?: string;
|
|
26
|
+
/** For tests. Defaults to the global `fetch`. */
|
|
27
|
+
fetchImpl?: typeof fetch;
|
|
28
|
+
}
|
|
29
|
+
export interface EmailOptions {
|
|
30
|
+
/** Read from `EMAIL_PROVIDER` when omitted. There is no default: a misconfigured app must not send nowhere in silence. */
|
|
31
|
+
provider?: EmailProvider;
|
|
32
|
+
/** Default sender, `"Name <email>"` or bare. `EMAIL_FROM` when omitted. A message may override it. */
|
|
33
|
+
from?: string;
|
|
34
|
+
/** Default reply-to. `EMAIL_REPLY_TO` when omitted. */
|
|
35
|
+
replyTo?: string;
|
|
36
|
+
resend?: ResendEmailOptions;
|
|
37
|
+
smtp?: SmtpEmailOptions;
|
|
38
|
+
brevo?: BrevoEmailOptions;
|
|
39
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { AppException } from '../errors/app.exception.js';
|
|
2
|
+
/** DI token for the {@link EmailPort}. Inject with `@Inject(EMAIL)`. */
|
|
3
|
+
export declare const EMAIL: unique symbol;
|
|
4
|
+
/** `"Ana <ana@example.com>"`, `"ana@example.com"`, or the same as an object. */
|
|
5
|
+
export type EmailAddress = string | {
|
|
6
|
+
email: string;
|
|
7
|
+
name?: string;
|
|
8
|
+
};
|
|
9
|
+
export interface EmailAttachment {
|
|
10
|
+
filename: string;
|
|
11
|
+
/** A string is taken as UTF-8 text. */
|
|
12
|
+
content: Buffer | string;
|
|
13
|
+
contentType?: string;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* One transactional message, the way every provider understands it. Nothing
|
|
17
|
+
* provider-specific lives here: templates, tracking settings and the like are
|
|
18
|
+
* what the raw clients in `email/resend` and `email/nodemailer` are for.
|
|
19
|
+
*/
|
|
20
|
+
export interface EmailMessage {
|
|
21
|
+
/** Overrides the module's default `from`. One of the two must exist. */
|
|
22
|
+
from?: EmailAddress;
|
|
23
|
+
to: EmailAddress | EmailAddress[];
|
|
24
|
+
cc?: EmailAddress | EmailAddress[];
|
|
25
|
+
bcc?: EmailAddress | EmailAddress[];
|
|
26
|
+
replyTo?: EmailAddress;
|
|
27
|
+
subject: string;
|
|
28
|
+
/** At least one of `text` / `html`. Sending both is the well-behaved default. */
|
|
29
|
+
text?: string;
|
|
30
|
+
html?: string;
|
|
31
|
+
attachments?: EmailAttachment[];
|
|
32
|
+
headers?: Record<string, string>;
|
|
33
|
+
/**
|
|
34
|
+
* Free-form labels for the provider's dashboard. Resend keeps them as
|
|
35
|
+
* name/value pairs, Brevo as `name:value` strings, SMTP as `X-Tag-<name>`
|
|
36
|
+
* headers.
|
|
37
|
+
*/
|
|
38
|
+
tags?: Record<string, string>;
|
|
39
|
+
}
|
|
40
|
+
export interface SentEmail {
|
|
41
|
+
/** The provider's id for the message, when it gives one. */
|
|
42
|
+
id: string | null;
|
|
43
|
+
provider: string;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* What the rest of an app needs from email: send one message, get back an
|
|
47
|
+
* id. Switching Resend for Brevo or an SMTP relay is configuration; no call
|
|
48
|
+
* site changes, because everything depends on this and never on a client.
|
|
49
|
+
*/
|
|
50
|
+
export interface EmailPort {
|
|
51
|
+
send(message: EmailMessage): Promise<SentEmail>;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* The provider said no, or said nothing.
|
|
55
|
+
*
|
|
56
|
+
* 502 rather than the provider's own status, on the same reasoning as
|
|
57
|
+
* `payments`: the caller's request was fine, the dependency failed. `details`
|
|
58
|
+
* keeps the original status and body so the real cause is one log line away.
|
|
59
|
+
*/
|
|
60
|
+
export declare class EmailProviderException extends AppException {
|
|
61
|
+
constructor(provider: string, status: number, body: unknown, message?: string);
|
|
62
|
+
}
|