@visulima/email 1.0.0-alpha.43 → 1.0.0-alpha.44

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.
Files changed (94) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/README.md +10 -191
  3. package/dist/index.js +1 -1
  4. package/dist/packem_shared/DraftMailMessage-BxqGSLMN.js +1 -0
  5. package/dist/packem_shared/Mail-BEuzrB00.js +1 -0
  6. package/dist/packem_shared/MailMessage-D9k5gYrd.js +1 -0
  7. package/dist/packem_shared/ahaSendProvider-D81_wUA1.js +1 -0
  8. package/dist/packem_shared/{attachment-processor-BjTNoMyb.js → attachment-processor-CMp7qqMI.js} +1 -1
  9. package/dist/packem_shared/{azureProvider-DlM6UWUv.js → azureProvider-CmcK4bsf.js} +1 -1
  10. package/dist/packem_shared/brevoProvider-C1BDXr41.js +1 -0
  11. package/dist/packem_shared/{build-mime-message-Be6TOi1T.js → build-mime-message-B6927SQy.js} +2 -2
  12. package/dist/packem_shared/{cloudflareEmailProvider-D4adkOjA.js → cloudflareEmailProvider-Bv-ty-74.js} +1 -1
  13. package/dist/packem_shared/{createTestEmail-BM3iNznm.js → createTestEmail-CF_RUjqo.js} +1 -1
  14. package/dist/packem_shared/infobipProvider-lHyGrXgZ.js +1 -0
  15. package/dist/packem_shared/{loopsProvider-BXr0KSjB.js → loopsProvider-DyloxzNC.js} +1 -1
  16. package/dist/packem_shared/{mailCrabProvider-C7Ao5H9p.js → mailCrabProvider-CPtBT6Th.js} +1 -1
  17. package/dist/packem_shared/{mailPaceProvider-DklGeGEM.js → mailPaceProvider-CJEvOFBh.js} +1 -1
  18. package/dist/packem_shared/{mailchannelsProvider-DPfQVzUd.js → mailchannelsProvider-osRkW_tz.js} +1 -1
  19. package/dist/packem_shared/mailerSendProvider-C_6LzARK.js +1 -0
  20. package/dist/packem_shared/{mailgunProvider-Ctyrs9d0.js → mailgunProvider-DkISvMPe.js} +1 -1
  21. package/dist/packem_shared/mailjetProvider-CV0i4Xzh.js +1 -0
  22. package/dist/packem_shared/mailomatProvider-B5YFonEO.js +1 -0
  23. package/dist/packem_shared/mailtrapProvider-C4ZquIPz.js +1 -0
  24. package/dist/packem_shared/mandrillProvider-DWPFh_Sj.js +1 -0
  25. package/dist/packem_shared/{netcoreProvider-XMWO_Aoa.js → netcoreProvider-C5TEciaN.js} +1 -1
  26. package/dist/packem_shared/{outlook365Provider-BoNtxqIx.js → outlook365Provider-63ggDpqV.js} +1 -1
  27. package/dist/packem_shared/plunkProvider-yTlrJVEp.js +1 -0
  28. package/dist/packem_shared/postalProvider-CRX_bMYD.js +1 -0
  29. package/dist/packem_shared/{postmarkProvider-DWQJv5_M.js → postmarkProvider-CDx85Yge.js} +1 -1
  30. package/dist/packem_shared/{provider-base-gIoUu9so.js → provider-base-C7PuopYK.js} +1 -1
  31. package/dist/packem_shared/resendProvider-CiclWxzr.js +1 -0
  32. package/dist/packem_shared/scalewayProvider-BcND48qO.js +1 -0
  33. package/dist/packem_shared/{sendGridProvider-CChhLr7s.js → sendGridProvider-D8ZLgY62.js} +1 -1
  34. package/dist/packem_shared/{smtpProvider-x4WBN-3W.js → smtpProvider-Bm0yP97W.js} +1 -1
  35. package/dist/packem_shared/{sparkpostProvider-BytvwqjP.js → sparkpostProvider-CTYfSRaV.js} +1 -1
  36. package/dist/packem_shared/sweegoProvider-DOoin_vi.js +1 -0
  37. package/dist/packem_shared/{zeptomailProvider-D3nQKXRf.js → zeptomailProvider-DKBPSHPj.js} +1 -1
  38. package/dist/providers/ahasend/index.js +1 -1
  39. package/dist/providers/azure/index.js +1 -1
  40. package/dist/providers/brevo/index.js +1 -1
  41. package/dist/providers/cloudflare-email/index.js +1 -1
  42. package/dist/providers/infobip/index.js +1 -1
  43. package/dist/providers/loops/index.js +1 -1
  44. package/dist/providers/mailchannels/index.js +1 -1
  45. package/dist/providers/mailcrab/index.js +1 -1
  46. package/dist/providers/mailersend/index.js +1 -1
  47. package/dist/providers/mailgun/index.js +1 -1
  48. package/dist/providers/mailjet/index.js +1 -1
  49. package/dist/providers/mailomat/index.js +1 -1
  50. package/dist/providers/mailpace/index.js +1 -1
  51. package/dist/providers/mailtrap/index.js +1 -1
  52. package/dist/providers/mandrill/index.js +1 -1
  53. package/dist/providers/netcore/index.js +1 -1
  54. package/dist/providers/outlook365/index.js +1 -1
  55. package/dist/providers/plunk/index.js +1 -1
  56. package/dist/providers/postal/index.js +1 -1
  57. package/dist/providers/postmark/index.js +1 -1
  58. package/dist/providers/resend/index.js +1 -1
  59. package/dist/providers/scaleway/index.js +1 -1
  60. package/dist/providers/sendgrid/index.js +1 -1
  61. package/dist/providers/smtp/index.js +1 -1
  62. package/dist/providers/sparkpost/index.js +1 -1
  63. package/dist/providers/sweego/index.js +1 -1
  64. package/dist/providers/zeptomail/index.js +1 -1
  65. package/dist/test/index.d.ts +0 -4
  66. package/dist/test/index.js +1 -1
  67. package/dist/utils/parse-eml.js +2 -2
  68. package/package.json +1 -24
  69. package/dist/packem_shared/DraftMailMessage-C9tevR8K.js +0 -1
  70. package/dist/packem_shared/Mail-DpjH0Exh.js +0 -1
  71. package/dist/packem_shared/MailMessage-L-Q9yc5v.js +0 -1
  72. package/dist/packem_shared/ahaSendProvider-Dq5mElHZ.js +0 -1
  73. package/dist/packem_shared/brevoProvider-D_Hhc0Z-.js +0 -1
  74. package/dist/packem_shared/infobipProvider-oOL-ThpP.js +0 -1
  75. package/dist/packem_shared/mailerSendProvider-B8iT5Uhb.js +0 -1
  76. package/dist/packem_shared/mailjetProvider-v55nFDsr.js +0 -1
  77. package/dist/packem_shared/mailomatProvider-BCyB4Q4B.js +0 -1
  78. package/dist/packem_shared/mailtrapProvider-DcVw3sxR.js +0 -1
  79. package/dist/packem_shared/mandrillProvider-gqMFMwgs.js +0 -1
  80. package/dist/packem_shared/plunkProvider-C0LO-1E3.js +0 -1
  81. package/dist/packem_shared/postalProvider-B26IqgxE.js +0 -1
  82. package/dist/packem_shared/resendProvider-DhvKVyCD.js +0 -1
  83. package/dist/packem_shared/scalewayProvider-D8dmHuwZ.js +0 -1
  84. package/dist/packem_shared/sweegoProvider-7xhOvagC.js +0 -1
  85. package/dist/utils/validation/check-mx-records.d.ts +0 -43
  86. package/dist/utils/validation/check-mx-records.js +0 -1
  87. package/dist/utils/validation/disposable-email-domains.d.ts +0 -1
  88. package/dist/utils/validation/disposable-email-domains.js +0 -1
  89. package/dist/utils/validation/role-accounts.d.ts +0 -21
  90. package/dist/utils/validation/role-accounts.js +0 -1
  91. package/dist/utils/validation/verify-email.d.ts +0 -50
  92. package/dist/utils/validation/verify-email.js +0 -1
  93. package/dist/utils/validation/verify-smtp.d.ts +0 -40
  94. package/dist/utils/validation/verify-smtp.js +0 -4
package/CHANGELOG.md CHANGED
@@ -1,3 +1,43 @@
1
+ ## @visulima/email [1.0.0-alpha.44](https://github.com/visulima/visulima/compare/@visulima/email@1.0.0-alpha.43...@visulima/email@1.0.0-alpha.44) (2026-06-30)
2
+
3
+ ### Features
4
+
5
+ * **email:** emailable-parity verification & enrichment packages ([#718](https://github.com/visulima/visulima/issues/718)) ([e2d8c1e](https://github.com/visulima/visulima/commit/e2d8c1e78e3e0c2548ece87b20d730dab60f677a))
6
+
7
+ ### Bug Fixes
8
+
9
+ * **email:** fixed missing eslint deps ([5bab056](https://github.com/visulima/visulima/commit/5bab056decffc16cdcbcd81d9ec5edb569019255))
10
+ * **mail:** fixed build ([9c677c6](https://github.com/visulima/visulima/commit/9c677c60c370f59c7def564df25977cf2d97e08c))
11
+
12
+ ### Styles
13
+
14
+ * cs fixes ([2a960bb](https://github.com/visulima/visulima/commit/2a960bb1772c9dc70080e2d75d3a0d827034e294))
15
+
16
+ ### Miscellaneous Chores
17
+
18
+ * add fallow code-intelligence across all packages ([a3b4821](https://github.com/visulima/visulima/commit/a3b48215002e86fed20f2973038b5d4a0aa1ce04))
19
+ * **fallow:** resolve dead-code findings ([c4125d5](https://github.com/visulima/visulima/commit/c4125d53e03ac9d90115399634535991927a96cc))
20
+
21
+ ### Code Refactoring
22
+
23
+ * **email:** use shared processAttachmentContent in 13 providers ([12b3512](https://github.com/visulima/visulima/commit/12b3512c31641d41d2a05a0caf155df85f0af6c8))
24
+ * resolve fallow dead-code across 13 packages ([8c458d2](https://github.com/visulima/visulima/commit/8c458d2eb17225ed48fc4bee4569e522912e8c3d))
25
+
26
+ ### Tests
27
+
28
+ * fix failing and flaky package tests ([3f2894e](https://github.com/visulima/visulima/commit/3f2894e816e99f465abb0d3b7d5161af69bbb4ec))
29
+
30
+ ### Continuous Integration
31
+
32
+ * **fallow:** make fallow:health advisory (--report-only) ([d57148e](https://github.com/visulima/visulima/commit/d57148ea0e3556b4c24d8d336b9fa14987f5dc7d))
33
+ * **lint:** raise eslint job timeout and cache slow per-package eslint runs ([#717](https://github.com/visulima/visulima/issues/717)) ([c93878d](https://github.com/visulima/visulima/commit/c93878dbfa1888cc834704448ae6eefd3098597e)), closes [#713](https://github.com/visulima/visulima/issues/713)
34
+
35
+
36
+ ### Dependencies
37
+
38
+ * **@visulima/error:** upgraded to 6.0.0-alpha.35
39
+ * **@visulima/fs:** upgraded to 5.0.0-alpha.33
40
+
1
41
  ## @visulima/email [1.0.0-alpha.43](https://github.com/visulima/visulima/compare/@visulima/email@1.0.0-alpha.42...@visulima/email@1.0.0-alpha.43) (2026-06-23)
2
42
 
3
43
  ## @visulima/email [1.0.0-alpha.42](https://github.com/visulima/visulima/compare/@visulima/email@1.0.0-alpha.41...@visulima/email@1.0.0-alpha.42) (2026-06-23)
package/README.md CHANGED
@@ -1229,203 +1229,22 @@ Template engines are optional peer dependencies and work where their underlying
1229
1229
 
1230
1230
  \* Runtime support depends on the wrapped providers. Works if all wrapped providers support the runtime.
1231
1231
 
1232
- ## Disposable Email Detection
1232
+ ## Email Verification & Enrichment
1233
1233
 
1234
- The package includes support for detecting disposable email addresses using the `@visulima/disposable-email-domains` package, which is included as a dependency.
1235
-
1236
- ### Usage
1237
-
1238
- ```typescript
1239
- import { isDisposableEmail } from "@visulima/email/validation/disposable-email-domains";
1240
-
1241
- // Check if an email is disposable
1242
- if (isDisposableEmail("user@mailinator.com")) {
1243
- console.log("Disposable email detected!");
1244
- }
1245
-
1246
- // With custom domains
1247
- const customDomains = new Set(["my-disposable.com"]);
1248
- if (isDisposableEmail("user@my-disposable.com", customDomains)) {
1249
- console.log("Custom disposable email detected!");
1250
- }
1251
- ```
1252
-
1253
- **Note:** The `@visulima/disposable-email-domains` package is included as a dependency, so no additional installation is required.
1254
-
1255
- ## Email Verification
1256
-
1257
- The package provides comprehensive email verification utilities including MX record checking, SMTP verification, and role account detection.
1258
-
1259
- ### MX Record Checking
1260
-
1261
- Check if a domain has valid MX (Mail Exchange) records:
1262
-
1263
- ```typescript
1264
- import { checkMxRecords } from "@visulima/email/validation/check-mx-records";
1265
-
1266
- const result = await checkMxRecords("example.com");
1267
-
1268
- if (result.valid) {
1269
- console.log("MX records:", result.records);
1270
- // Records are sorted by priority (lowest first)
1271
- } else {
1272
- console.error("No MX records found:", result.error);
1273
- }
1274
- ```
1275
-
1276
- #### Caching MX Records
1277
-
1278
- Use caching to improve performance and reduce DNS lookups:
1279
-
1280
- ```typescript
1281
- import { checkMxRecords } from "@visulima/email/validation/check-mx-records";
1282
- import { InMemoryCache } from "@visulima/email/utils/cache";
1283
-
1284
- // Create a cache instance
1285
- const cache = new InMemoryCache();
1286
-
1287
- // Use cache with default TTL (1 hour)
1288
- const result1 = await checkMxRecords("example.com", { cache });
1289
-
1290
- // Use cache with custom TTL (5 minutes)
1291
- const result2 = await checkMxRecords("example.com", {
1292
- cache,
1293
- ttl: 5 * 60 * 1000, // 5 minutes in milliseconds
1294
- });
1295
-
1296
- // Clear cache when needed
1297
- await cache.clear();
1298
- ```
1299
-
1300
- #### Custom Cache Implementation
1301
-
1302
- You can implement your own cache using the `Cache` interface (e.g., for Redis, LRU cache, etc.):
1303
-
1304
- ```typescript
1305
- import type { Cache, MxCheckResult } from "@visulima/email/utils/cache";
1306
- import { checkMxRecords } from "@visulima/email/validation/check-mx-records";
1307
-
1308
- // Example: Custom Redis cache implementation
1309
- const redisCache: Cache<MxCheckResult> = {
1310
- get: async (key: string) => {
1311
- const cached = await redis.get(`mx:${key}`);
1312
- return cached ? JSON.parse(cached) : undefined;
1313
- },
1314
- set: async (key: string, value: MxCheckResult, ttl: number) => {
1315
- await redis.setex(`mx:${key}`, Math.floor(ttl / 1000), JSON.stringify(value));
1316
- },
1317
- delete: async (key: string) => {
1318
- await redis.del(`mx:${key}`);
1319
- },
1320
- clear: async () => {
1321
- // Clear all MX cache keys
1322
- const keys = await redis.keys("mx:*");
1323
- if (keys.length > 0) {
1324
- await redis.del(...keys);
1325
- }
1326
- },
1327
- };
1328
-
1329
- // Use custom cache
1330
- const result = await checkMxRecords("example.com", {
1331
- cache: redisCache,
1332
- ttl: 10 * 60 * 1000, // 10 minutes
1333
- });
1334
- ```
1335
-
1336
- ### Role Account Detection
1337
-
1338
- Detect if an email address is a role account (non-personal email like `noreply@`, `support@`, etc.):
1339
-
1340
- ```typescript
1341
- import { isRoleAccount } from "@visulima/email/validation/role-accounts";
1342
-
1343
- if (isRoleAccount("noreply@example.com")) {
1344
- console.log("This is a role account");
1345
- }
1346
-
1347
- // With custom role prefixes
1348
- const customPrefixes = new Set(["custom-role", "my-role"]);
1349
- if (isRoleAccount("custom-role@example.com", customPrefixes)) {
1350
- console.log("Custom role account detected");
1351
- }
1352
- ```
1353
-
1354
- ### SMTP Verification
1355
-
1356
- Verify if an email address exists by connecting to the mail server:
1357
-
1358
- ```typescript
1359
- import { verifySmtp } from "@visulima/email/validation/verify-smtp";
1360
- import { InMemoryCache } from "@visulima/email/utils/cache";
1361
- import type { MxCheckResult, SmtpVerificationResult } from "@visulima/email/validation/check-mx-records";
1362
-
1363
- // Create separate caches for MX records and SMTP results
1364
- const mxCache = new InMemoryCache<MxCheckResult>();
1365
- const smtpCache = new InMemoryCache<SmtpVerificationResult>();
1366
-
1367
- const result = await verifySmtp("user@example.com", {
1368
- timeout: 5000,
1369
- fromEmail: "test@example.com",
1370
- port: 25,
1371
- cache: mxCache, // Optional: cache MX records
1372
- smtpCache, // Optional: cache SMTP verification results
1373
- ttl: 5 * 60 * 1000, // Cache for 5 minutes
1374
- });
1375
-
1376
- if (result.valid) {
1377
- console.log("Email address exists");
1378
- } else {
1379
- console.error("Verification failed:", result.error);
1380
- }
1381
- ```
1382
-
1383
- **Note:** Many mail servers block SMTP verification to prevent email harvesting. This method may not work for all domains.
1384
-
1385
- ### Comprehensive Email Verification
1386
-
1387
- Combine all verification checks in a single function:
1234
+ Address verification and enrichment MX/SMTP probing, disposable/free/role detection, catch-all & mailbox-full detection, SMTP-provider and secure-email-gateway classification, misspelled-domain suggestions, and a 0–100 quality score — now live in the standalone, mailer-free [`@visulima/email-verifier`](https://visulima.com/packages/email-verifier) package, so a validation-only consumer doesn't pull in the provider adapters.
1388
1235
 
1389
1236
  ```typescript
1390
- import { verifyEmail } from "@visulima/email/validation/verify-email";
1391
- import { InMemoryCache } from "@visulima/email/utils/cache";
1392
- import type { MxCheckResult, SmtpVerificationResult } from "@visulima/email/validation/check-mx-records";
1393
-
1394
- // Create separate caches for MX records and SMTP results
1395
- const mxCache = new InMemoryCache<MxCheckResult>();
1396
- const smtpCache = new InMemoryCache<SmtpVerificationResult>();
1397
-
1398
- const result = await verifyEmail("user@example.com", {
1399
- checkDisposable: true,
1400
- checkRoleAccount: true,
1401
- checkMx: true,
1402
- checkSmtp: false, // Optional, many servers block this
1403
- cache: mxCache, // Optional: cache MX records
1404
- smtpCache, // Optional: cache SMTP verification results
1405
- customDisposableDomains: new Set(["custom-disposable.com"]),
1406
- customRolePrefixes: new Set(["custom-role"]),
1407
- });
1408
-
1409
- if (result.valid) {
1410
- console.log("Email is valid!");
1411
- } else {
1412
- console.error("Errors:", result.errors);
1413
- console.warn("Warnings:", result.warnings);
1414
- }
1237
+ import { verifyEmail } from "@visulima/email-verifier";
1415
1238
 
1416
- // Access individual check results
1417
- console.log("Format valid:", result.formatValid);
1418
- console.log("Is disposable:", result.disposable);
1419
- console.log("Is role account:", result.roleAccount);
1420
- console.log("MX valid:", result.mxValid);
1421
- console.log("SMTP valid:", result.smtpValid);
1239
+ const report = await verifyEmail("user@example.com");
1240
+ // { state: "deliverable" | "risky" | "undeliverable" | "unknown", score, disposable, free, role, acceptAll, provider, ... }
1422
1241
  ```
1423
1242
 
1424
- ### Email Utilities
1243
+ ## Email Utilities
1425
1244
 
1426
1245
  The package also exports standalone utility functions that can be used independently:
1427
1246
 
1428
- #### Email Validation
1247
+ ### Email Validation
1429
1248
 
1430
1249
  ```typescript
1431
1250
  import { validateEmail } from "@visulima/email/validation/validate-email";
@@ -1435,7 +1254,7 @@ if (validateEmail("user@example.com")) {
1435
1254
  }
1436
1255
  ```
1437
1256
 
1438
- #### Parse Email Address
1257
+ ### Parse Email Address
1439
1258
 
1440
1259
  ```typescript
1441
1260
  import { parseAddress } from "@visulima/email/utils/parse-address";
@@ -1449,7 +1268,7 @@ const simple = parseAddress("jane@example.com");
1449
1268
  // { email: "jane@example.com" }
1450
1269
  ```
1451
1270
 
1452
- #### Format Email Address
1271
+ ### Format Email Address
1453
1272
 
1454
1273
  ```typescript
1455
1274
  import { formatEmailAddress } from "@visulima/email/utils/format-email-address";
@@ -1464,7 +1283,7 @@ const simple = formatEmailAddress({ email: "user@example.com" });
1464
1283
  // "user@example.com"
1465
1284
  ```
1466
1285
 
1467
- #### Normalize Email Aliases
1286
+ ### Normalize Email Aliases
1468
1287
 
1469
1288
  Normalize email aliases for supported providers (Gmail, Yahoo, Outlook, etc.):
1470
1289
 
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{detectMimeType as o,generateContentId as t,readFileAsBuffer as a}from"./packem_shared/detectMimeType-Dxv4MjZ7.js";import{DraftMailMessage as p}from"./packem_shared/DraftMailMessage-C9tevR8K.js";import{default as i}from"./packem_shared/EmailError-B-sEf3bp.js";import{default as l}from"./packem_shared/RequiredOptionError-DuNNY_a5.js";import{Mail as u,createMail as x}from"./packem_shared/Mail-DpjH0Exh.js";import{MailMessage as M}from"./packem_shared/MailMessage-L-Q9yc5v.js";import{defineProvider as E}from"./packem_shared/defineProvider-C9q-7iwt.js";import{default as g}from"./utils/parse-eml.js";import{isErr as y,isOk as w,mapOk as A,tryAsync as F,unwrap as h,unwrapOr as q}from"./utils/result.js";import{default as B}from"./utils/validation/check-feature-support.js";export{p as DraftMailMessage,i as EmailError,u as Mail,M as MailMessage,l as RequiredOptionError,B as checkFeatureSupport,x as createMail,E as defineProvider,o as detectMimeType,t as generateContentId,y as isErr,w as isOk,A as mapOk,g as parseEml,a as readFileAsBuffer,F as tryAsync,h as unwrap,q as unwrapOr};
1
+ import{detectMimeType as a,generateContentId as t,readFileAsBuffer as o}from"./packem_shared/detectMimeType-Dxv4MjZ7.js";import{default as p}from"./packem_shared/DraftMailMessage-BxqGSLMN.js";import{default as m}from"./packem_shared/EmailError-B-sEf3bp.js";import{default as l}from"./packem_shared/RequiredOptionError-DuNNY_a5.js";import{Mail as u,createMail as x}from"./packem_shared/Mail-BEuzrB00.js";import{default as M}from"./packem_shared/MailMessage-D9k5gYrd.js";import{defineProvider as E}from"./packem_shared/defineProvider-C9q-7iwt.js";import{default as g}from"./utils/parse-eml.js";import{isErr as y,isOk as w,mapOk as A,tryAsync as F,unwrap as h,unwrapOr as q}from"./utils/result.js";import{default as B}from"./utils/validation/check-feature-support.js";export{p as DraftMailMessage,m as EmailError,u as Mail,M as MailMessage,l as RequiredOptionError,B as checkFeatureSupport,x as createMail,E as defineProvider,a as detectMimeType,t as generateContentId,y as isErr,w as isOk,A as mapOk,g as parseEml,o as readFileAsBuffer,F as tryAsync,h as unwrap,q as unwrapOr};
@@ -0,0 +1 @@
1
+ import s from"./MailMessage-D9k5gYrd.js";class r extends s{constructor(){super(),this.header("X-Unsent","1")}}export{r as default};
@@ -0,0 +1 @@
1
+ import h from"./DraftMailMessage-BxqGSLMN.js";import v from"./EmailError-B-sEf3bp.js";import f from"./MailMessage-D9k5gYrd.js";import{composeMiddleware as C}from"./composeMiddleware-BHwLLEzK.js";import{F as w}from"./build-mime-message-B6927SQy.js";import{c as M}from"./create-logger-BQTS3f-I.js";import{s as l}from"./headers-to-record-De1Eg951.js";import T from"../utils/validation/check-feature-support.js";const S=(i,e,r)=>{e.success&&e.data?i&&i.info("Email sent successfully",{messageId:e.data.messageId,provider:e.data.provider}):i&&i.error("Email send failed",{error:e.error,provider:r})},j=async(i,e,r)=>{const s={...i,to:e.to};return e.cc&&(s.cc=e.cc),e.bcc&&(s.bcc=e.bcc),e.replyTo&&(s.replyTo=e.replyTo),e.headers&&(s.headers={...l(i.headers??{}),...l(e.headers)}),s.subject=e.subject??i.subject,r&&e.data&&(s.subject=await r(s.subject,e.data),i.html!==void 0&&(s.html=await r(i.html,e.data)),i.text!==void 0&&(s.text=await r(i.text,e.data))),s};class u{static extractErrorMessages(e){return e instanceof Error?[e.message]:[String(e??"Unknown error")]}provider;logger;loggerInstance;globalConfig;featureCheck;middlewares=[];composedSend;mountedProviders=new Map;constructor(e,r){this.provider=e,this.featureCheck=r?.featureCheck??"error"}setLogger(e){return this.loggerInstance=e,this.logger=M("Mail",e),this}use(e){return this.middlewares.push(e),this.composedSend=void 0,this}mount(e,r){return this.mountedProviders.set(e,r),this}setFrom(e){return this.globalConfig??={},this.globalConfig.from=e,this.logger&&this.logger.debug("Default from address updated",{from:e.email}),this}setReplyTo(e){return this.globalConfig??={},this.globalConfig.replyTo=e,this.logger&&this.logger.debug("Default reply-to address updated",{replyTo:e.email}),this}setHeaders(e){if(this.globalConfig??={},this.globalConfig.headers=e,this.logger){const r=l(e);this.logger.debug("Default headers updated",{count:Object.keys(r).length,headers:Object.keys(r)})}return this}async draft(e){let r=e instanceof f||e instanceof h?await this.buildDraftFromMessage(e):await this.buildDraftFromOptions(e);r=this.applyGlobalConfig(r);const s=r.headers?l(r.headers):{};r.headers={...s,"X-Unsent":"1"};const t=await w(r,{includeBcc:!0});return this.logger&&this.logger.debug("Draft created successfully in EML format",{from:r.from.email,size:t.length,subject:r.subject,to:Array.isArray(r.to)?r.to.length:1}),t}async send(e){if(e instanceof h)throw new TypeError("Cannot send draft messages. Convert to MailMessage first or remove X-Unsent header.");let r;if(e instanceof f)this.logger&&this.logger.debug("Sending MailMessage instance"),this.loggerInstance&&e.setLogger(this.loggerInstance),r=await e.build();else{const o=e;this.logger&&this.logger.debug("Sending email with options",{subject:o.subject,to:Array.isArray(o.to)?o.to.length:1}),r=o}r=this.applyGlobalConfig(r);const s=this.assertFeatureSupport(r);if(s)return{error:s,success:!1};const t=await this.dispatch(r);return S(this.logger,t,this.provider.name??"unknown"),t}sendMany(e,r){const s=Math.max(1,Math.floor(r?.concurrency??1));return s===1?this.sendManySerial(e,r?.signal):this.sendManyConcurrent(e,s,r?.signal)}sendBatch(e,r,s){const t=async function*(){const o=e instanceof f?await e.build():e;for(const a of r)yield await j(o,a,s?.render)};return this.sendMany(t(),{concurrency:s?.concurrency,signal:s?.signal})}async sendOneToReceipt(e){const r=this.provider.name;try{const s=await this.send(e);return s.success&&s.data?{messageId:s.data.messageId,provider:s.data.provider??r,response:s.data.response,successful:!0,timestamp:s.data.timestamp}:{errorMessages:u.extractErrorMessages(s.error),provider:r,successful:!1}}catch(s){return{errorMessages:u.extractErrorMessages(s),provider:r,successful:!1}}}async*sendManySerial(e,r){const s=this.provider.name;let t=0,o=0,a=0;this.logger&&this.logger.debug("Starting batch email send",{provider:s});for await(const n of e){if(n instanceof h)throw new TypeError("Cannot send draft messages. Convert to MailMessage first or remove X-Unsent header.");if(r?.aborted){this.logger&&this.logger.warn("Batch send operation was aborted",{failed:a,processed:t,successful:o}),yield{errorMessages:["Send operation was aborted"],provider:s,successful:!1};return}t+=1;const g=await this.sendOneToReceipt(n);g.successful?o+=1:a+=1,yield g}this.logger&&this.logger.debug("Batch email send completed",{failureCount:a,processedCount:t,provider:s,successCount:o})}async*sendManyConcurrent(e,r,s){const t=this.provider.name;this.logger&&this.logger.debug("Starting concurrent batch email send",{concurrency:r,provider:t});const o=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator](),a=new Map;let n=0,g=!1,p=!1;const m=async()=>{for(;!g&&!p&&a.size<r;){const d=await o.next();if(d.done){g=!0;break}const c=d.value;if(c instanceof h)throw new TypeError("Cannot send draft messages. Convert to MailMessage first or remove X-Unsent header.");const b=n;n+=1,a.set(b,this.sendOneToReceipt(c).then(y=>({id:b,receipt:y})))}};for(await m();a.size>0;){if(s?.aborted){p=!0,yield{errorMessages:["Send operation was aborted"],provider:t,successful:!1};return}const{id:d,receipt:c}=await Promise.race(a.values());a.delete(d),yield c,await m()}this.logger&&this.logger.debug("Concurrent batch email send completed",{processedCount:n,provider:t})}async dispatch(e){return this.middlewares.length===0?await this.resolveProvider(e).sendEmail(e):(this.composedSend??=C(this.middlewares,r=>Promise.resolve(this.resolveProvider(r).sendEmail(r))),await this.composedSend(e))}resolveProvider(e){return e.stream!==void 0?this.mountedProviders.get(e.stream)??this.provider:this.provider}assertFeatureSupport(e){if(this.featureCheck==="off")return;const{supported:r,violations:s}=T(e,this.provider.features);if(r)return;const t=this.provider.name??"unknown",o=s.map(n=>n.field),a=s.map(n=>n.message);if(this.featureCheck==="warn"){this.logger&&this.logger.warn("Message uses capabilities the provider does not support",{fields:o,provider:t});return}return this.logger&&this.logger.error("Message rejected by capability guard",{fields:o,provider:t}),new v(t,`Provider does not support the following message fields: ${o.join(", ")}`,{code:"UNSUPPORTED_FEATURES",hint:a})}async buildDraftFromMessage(e){return this.logger&&this.logger.debug("Creating draft from MailMessage instance"),this.loggerInstance&&e.setLogger(this.loggerInstance),this.applyGlobalConfigToMessage(e),await e.build()}async buildDraftFromOptions(e){return this.logger&&this.logger.debug("Creating draft from email options",{subject:e.subject,to:Array.isArray(e.to)?e.to.length:1}),e}applyGlobalConfigToMessage(e){const r=this.globalConfig?.from;r&&!e.getFrom()&&e.from(r);const s=this.globalConfig?.replyTo;if(s&&!e.getReplyTo()&&e.replyTo(s),this.globalConfig?.headers){const t=l(this.globalConfig.headers);Object.entries(t).forEach(([o,a])=>{e.header(o,a)})}}applyGlobalConfig(e){if(!this.globalConfig)return e;const r={...e};if(!r.from&&this.globalConfig.from&&(r.from=this.globalConfig.from,this.logger&&this.logger.debug("Applied global from address",{from:this.globalConfig.from.email})),!r.replyTo&&this.globalConfig.replyTo&&(r.replyTo=this.globalConfig.replyTo,this.logger&&this.logger.debug("Applied global reply-to address",{replyTo:this.globalConfig.replyTo.email})),this.globalConfig.headers){const s=l(this.globalConfig.headers),t=r.headers?l(r.headers):{};r.headers={...s,...t},this.logger&&this.logger.debug("Merged global headers",{globalCount:Object.keys(s).length,messageCount:Object.keys(t).length})}return r}}const D=(i,e)=>new u(i,e);export{u as Mail,D as createMail};
@@ -0,0 +1 @@
1
+ import{createRequire as f}from"node:module";import{readFileAsBuffer as c,detectMimeType as d,generateContentId as u}from"./detectMimeType-Dxv4MjZ7.js";import{c as b}from"./create-logger-BQTS3f-I.js";import{s as l}from"./headers-to-record-De1Eg951.js";const y=f(import.meta.url),o=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,p=n=>{if(typeof o<"u"&&o.versions&&o.versions.node){const[t,e]=o.versions.node.split(".").map(Number);if(t>22||t===22&&e>=3||t===20&&e>=16)return o.getBuiltinModule(n)}return y(n)},{basename:g}=p("node:path"),{fileURLToPath:A}=p("node:url"),m=async()=>(await import("../template-engines/html-to-text.js")).default,T=async()=>(await import("ical-generator")).default,a=n=>Array.isArray(n)?n.map(t=>typeof t=="string"?{email:t}:t):typeof n=="string"?[{email:n}]:[n];class v{fromAddress;toAddresses=[];ccAddresses=[];bccAddresses=[];subjectText="";textContent;textCharset="utf8";autoTextEnabled=!0;htmlContent;htmlCharset="utf8";dateValue;returnPathAddress;senderAddress;headers={};attachments=[];replyToAddress;priorityValue;tagsValue=[];signer;encrypter;logger;icalEventData;icalEventBuilder;from(t){return this.fromAddress=typeof t=="string"?{email:t}:t,this}to(t){return this.toAddresses.length=0,this.toAddresses.push(...a(t)),this}cc(t){return this.ccAddresses.length=0,this.ccAddresses.push(...a(t)),this}bcc(t){return this.bccAddresses.length=0,this.bccAddresses.push(...a(t)),this}subject(t){return this.subjectText=t,this}text(t,e="utf8"){return this.textContent=t,this.textCharset=e,this}html(t,e="utf8"){return this.htmlContent=t,this.htmlCharset=e,this}header(t,e){return this.headers[t]=e,this}setHeaders(t){const e=l(t);return Object.assign(this.headers,e),this}async attachFromPath(t,e){try{const s=await c(t),i=e?.filename??(g(t)||"attachment"),r=e?.contentType??d(i);this.attachments.push({cid:e?.cid,content:s,contentDisposition:e?.contentDisposition??"attachment",contentType:r,encoding:e?.encoding,filename:i,headers:e?.headers}),this.logger&&this.logger.debug(`Attachment added from path: ${t}`,{contentType:r,filename:i})}catch(s){throw this.logger&&this.logger.error(`Failed to attach file from path: ${t}`,s),s}return this}attachData(t,e){const s=e.contentType??d(e.filename);return this.attachments.push({cid:e.cid,content:t,contentDisposition:e.contentDisposition??"attachment",contentType:s,encoding:e.encoding,filename:e.filename,headers:e.headers}),this.logger&&this.logger.debug("Attachment added from data",{contentType:s,filename:e.filename}),this}async embedFromPath(t,e){try{const s=await c(t),i=e?.filename??(g(t)||"inline"),r=e?.contentType??d(i),h=u(i);return this.attachments.push({cid:h,content:s,contentDisposition:"inline",contentType:r,filename:i}),this.logger&&this.logger.debug(`Inline attachment embedded from path: ${t}`,{cid:h,contentType:r,filename:i}),h}catch(s){throw this.logger&&this.logger.error(`Failed to embed file from path: ${t}`,s),s}}embedData(t,e,s){const i=s?.contentType??d(e),r=u(e);return this.attachments.push({cid:r,content:t,contentDisposition:"inline",contentType:i,filename:e}),this.logger&&this.logger.debug("Inline attachment embedded from data",{cid:r,contentType:i,filename:e}),r}replyTo(t){return this.replyToAddress=typeof t=="string"?{email:t}:t,this}date(t){return this.dateValue=typeof t=="string"?new Date(t):t,this.logger&&this.logger.debug("Date header set",{date:this.dateValue.toISOString()}),this}returnPath(t){return this.returnPathAddress=typeof t=="string"?{email:t}:t,this.logger&&this.logger.debug("Return-path address set",{returnPath:this.returnPathAddress.email}),this}sender(t){return this.senderAddress=typeof t=="string"?{email:t}:t,this.logger&&this.logger.debug("Sender address set",{sender:this.senderAddress.email}),this}addTo(t){return this.toAddresses.push(...a(t)),this}addCc(t){return this.ccAddresses.push(...a(t)),this}addBcc(t){return this.bccAddresses.push(...a(t)),this}addReplyTo(t){const e=Array.isArray(t)?t:[t];if(e.length>0){const s=e[0];this.replyToAddress=typeof s=="string"?{email:s}:s}return this}addFrom(t){const e=Array.isArray(t)?t:[t];if(e.length>0){const s=e[0];this.fromAddress=typeof s=="string"?{email:s}:s}return this}priority(t){return this.priorityValue=t,this}tags(t){return this.tagsValue=Array.isArray(t)?t:[t],this}sign(t){return this.signer=t,this.logger&&this.logger.debug("Email signer configured"),this}encrypt(t){return this.encrypter=t,this.logger&&this.logger.debug("Email encrypter configured"),this}setLogger(t){return this.logger=b("MailMessage",t),this}icalEvent(t,e){return typeof t=="function"?(this.icalEventBuilder={build:t,options:e},this.icalEventData=void 0):(this.icalEventBuilder=void 0,this.icalEventData={content:t,...e}),this.logger&&this.logger.debug("Calendar event attached",{method:e?.method}),this}icalEventFromFile(t,e){const s=typeof t=="string"?t:A(t);return this.icalEventData={path:s,...e},this.logger&&this.logger.debug(`Calendar event attached from file: ${s}`,{method:e?.method}),this}icalEventFromUrl(t,e){return this.icalEventData={href:t,...e},this.logger&&this.logger.debug(`Calendar event attached from URL: ${t}`,{method:e?.method}),this}async view(t,e,s,i){try{const r=i?.autoText!==!1;this.autoTextEnabled=r,this.logger&&this.logger.debug("Rendering template",{autoText:r});const h=await t(e,s,i);this.html(h),r&&h&&await this.tryAutoGenerateText(h),this.logger&&this.logger.debug("Template rendered successfully")}catch(r){throw this.logger&&this.logger.error("Failed to render template",r),new Error(`Failed to render template: ${r.message}`)}return this}async viewText(t,e,s,i){try{this.logger&&this.logger.debug("Rendering text template");const r=await t(e,s,i);if(typeof r=="string")this.text(r),this.logger&&this.logger.debug("Text template rendered successfully");else throw new TypeError("Text renderer must return a string")}catch(r){throw this.logger&&this.logger.error("Failed to render text template",r),new Error(`Failed to render text template: ${r.message}`)}return this}async build(){if(this.logger&&this.logger.debug("Building email message"),this.fromAddress||this.throwAndLogError("From address is required","Build failed: from address is required"),this.toAddresses.length===0&&this.throwAndLogError("At least one recipient is required","Build failed: at least one recipient is required"),this.subjectText||this.throwAndLogError("Subject is required","Build failed: subject is required"),this.htmlContent&&!this.textContent&&this.autoTextEnabled)try{const e=await m();this.textContent=e(this.htmlContent),this.logger&&this.logger.debug("Auto-generated text content from HTML")}catch{this.logger&&this.logger.debug("Failed to convert HTML to text; proceeding without text content.")}!this.textContent&&!this.htmlContent&&this.throwAndLogError("Either text or html content is required","Build failed: either text or html content is required");let t={from:this.fromAddress,html:this.htmlContent,subject:this.subjectText,text:this.textContent,to:this.toAddresses.length===1?this.toAddresses[0]:this.toAddresses};if(this.ccAddresses.length>0&&(t.cc=this.ccAddresses.length===1?this.ccAddresses[0]:this.ccAddresses),this.bccAddresses.length>0&&(t.bcc=this.bccAddresses.length===1?this.bccAddresses[0]:this.bccAddresses),Object.keys(this.headers).length>0&&(t.headers=this.headers),this.attachments.length>0&&(t.attachments=this.attachments,this.logger&&this.logger.debug(`Email includes ${this.attachments.length} attachment(s)`)),this.replyToAddress&&(t.replyTo=this.replyToAddress),this.priorityValue&&(t.priority=this.priorityValue),this.tagsValue.length>0&&(t.tags=this.tagsValue),this.icalEventBuilder){const e=(await T())();this.icalEventBuilder.build(e),this.icalEventData={content:e.toString(),...this.icalEventBuilder.options}}return this.icalEventData&&(t.icalEvent=this.icalEventData,this.logger&&this.logger.debug("Email includes calendar event")),this.dateValue&&(t.headers={...l(t.headers??{}),Date:this.dateValue.toUTCString()}),this.returnPathAddress&&(t.headers={...l(t.headers??{}),"Return-Path":this.returnPathAddress.email}),this.senderAddress&&(t.headers={...l(t.headers??{}),Sender:this.senderAddress.email}),this.signer&&(this.logger&&this.logger.debug("Signing email message"),t=await this.signer.sign(t),this.logger&&this.logger.debug("Email message signed successfully")),this.encrypter&&(this.logger&&this.logger.debug("Encrypting email message"),t=await this.encrypter.encrypt(t),this.logger&&this.logger.debug("Email message encrypted successfully")),this.logger&&this.logger.debug("Email message built successfully",{bcc:this.bccAddresses.length,cc:this.ccAddresses.length,hasHtml:!!this.htmlContent,hasText:!!this.textContent,to:this.toAddresses.length}),t}getSubject(){return this.subjectText}getFrom(){return this.fromAddress}getTo(){return[...this.toAddresses]}getCc(){return[...this.ccAddresses]}getBcc(){return[...this.bccAddresses]}getReplyTo(){return this.replyToAddress}getSender(){return this.senderAddress}getReturnPath(){return this.returnPathAddress}getDate(){return this.dateValue}getPriority(){return this.priorityValue}getTextBody(){return this.textContent}getTextCharset(){return this.textCharset}getHtmlBody(){return this.htmlContent}getHtmlCharset(){return this.htmlCharset}getAttachments(){return[...this.attachments]}async tryAutoGenerateText(t){try{const e=(await m())(t);e&&!this.textContent&&this.text(e),this.logger&&this.logger.debug("Auto-generated text content from HTML template")}catch(e){this.logger&&this.logger.warn("Failed to auto-generate text from HTML template",e)}}throwAndLogError(t,e){const s=new Error(t);throw this.logger&&this.logger.error(e??t),s}}export{v as default};
@@ -0,0 +1 @@
1
+ import l from"./EmailError-B-sEf3bp.js";import b from"./RequiredOptionError-DuNNY_a5.js";import{e as v}from"./generate-message-id-gXAuMz4g.js";import{s as w}from"./headers-to-record-De1Eg951.js";import{m}from"./make-request-BlK_B72c.js";import{u as g}from"./retry-3pnxTuNs.js";import{f as A}from"./validate-email-options-mCM9dVug.js";import{defineProvider as I}from"./defineProvider-C9q-7iwt.js";import{f as d,a as P}from"./address-formatter-BWR2Dddx.js";import{p as T}from"./attachment-processor-CMp7qqMI.js";import{h,P as E,c as S}from"./provider-base-C7PuopYK.js";const a="ahasend",j="https://api.ahasend.com",z=3e4,k=3,H=I((s={})=>{if(!s.apiKey)throw new b(a,"apiKey");const r={apiKey:s.apiKey,debug:s.debug??!1,endpoint:s.endpoint??j,retries:s.retries??k,timeout:s.timeout??z,...s.logger&&{logger:s.logger}},f=new E,i=S(a,s.logger);return{features:{attachments:!0,batchSending:!0,customHeaders:!0,html:!0,replyTo:!0,scheduling:!1,tagging:!0,templates:!0,tracking:!0},async getEmail(e){try{if(!e)return{error:new l(a,"Email ID is required to retrieve email details"),success:!1};await this.initialize();const n={Authorization:`Bearer ${r.apiKey}`,"Content-Type":"application/json"};i.debug("Retrieving email details",{id:e});const t=await g(async()=>m(`${r.endpoint}/emails/${e}`,{headers:n,method:"GET",timeout:r.timeout}),r.retries);return t.success?(i.debug("Email details retrieved successfully"),{data:t.data?.body,success:!0}):(i.debug("API request failed when retrieving email",t.error),{error:new l(a,`Failed to retrieve email: ${t.error instanceof Error?t.error.message:"Unknown error"}`,{cause:t.error}),success:!1})}catch(n){return{error:h(a,"retrieve email",n,i),success:!1}}},async initialize(){await f.ensureInitialized(async()=>{if(!await this.isAvailable())throw new l(a,"AhaSend API not available or invalid API key");i.debug("Provider initialized successfully")},a)},async isAvailable(){try{return i.debug("Checking AhaSend API availability"),!!(await m(`${r.endpoint}/v2/ping`,{headers:{Authorization:`Bearer ${r.apiKey}`,"Content-Type":"application/json"},method:"GET",timeout:r.timeout})).success}catch(e){return i.debug("Error checking availability:",e),!1}},name:a,options:r,async sendEmail(e){try{const n=A(e);if(n.length>0)return{error:new l(a,`Invalid email options: ${n.join(", ")}`),success:!1};await this.initialize();const t={from:{email:e.from.email,name:e.from.name},subject:e.subject,to:d(e.to)};if(e.html&&(t.html=e.html),e.text&&(t.text=e.text),e.cc&&(t.cc=d(e.cc)),e.bcc&&(t.bcc=d(e.bcc)),e.replyTo&&(t.replyTo=P(e.replyTo)),e.templateId&&(t.templateId=e.templateId,e.templateVariables&&(t.templateVariables=e.templateVariables)),e.tags&&e.tags.length>0&&(t.tags=e.tags),e.headers){const o=w(e.headers);t.headers=o}e.attachments&&e.attachments.length>0&&(t.attachments=await Promise.all(e.attachments.map(async o=>({content:await T(o,a),contentType:o.contentType??"application/octet-stream",filename:o.filename,...o.cid&&{cid:o.cid}})))),i.debug("Sending email via AhaSend API",{subject:t.subject,to:t.to});const y={Authorization:`Bearer ${r.apiKey}`,"Content-Type":"application/json"},c=await g(async()=>m(`${r.endpoint}/send`,{headers:y,method:"POST",timeout:r.timeout},JSON.stringify(t)),r.retries);if(!c.success)return i.debug("API request failed when sending email",c.error),{error:c.error??new l(a,"Failed to send email"),success:!1};const u=c.data?.body,p=u?.messageId??u?.id??v();return i.debug("Email sent successfully",{messageId:p}),{data:{messageId:p,provider:a,response:c.data,sent:!0,timestamp:new Date},success:!0}}catch(n){return{error:h(a,"send email",n,i),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{H as default};
@@ -1 +1 @@
1
- import{createRequire as c}from"node:module";import p from"./EmailError-B-sEf3bp.js";const s=c(import.meta.url),o=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,r=e=>{if(typeof o<"u"&&o.versions&&o.versions.node){const[t,n]=o.versions.node.split(".").map(Number);if(t>22||t===22&&n>=3||t===20&&n>=16)return o.getBuiltinModule(e)}return s(e)},{Buffer:m}=r("node:buffer"),a=async(e,t)=>{let n;if(e.content)if(typeof e.content=="string")n=e.content;else if(e.content instanceof Promise){const i=await e.content;n=m.from(i).toString("base64")}else n=e.content.toString("base64");else if(e.raw)n=typeof e.raw=="string"?e.raw:e.raw.toString("base64");else throw new p(t,`Attachment ${e.filename} has no content`);return n},d=async(e,t)=>({content:await a(e,t),contentType:e.contentType??"application/octet-stream",disposition:e.contentDisposition??"attachment",filename:e.filename,...e.cid&&{contentId:e.cid}}),u=async(e,t)=>({content:await a(e,t),disposition:e.contentDisposition??"attachment",filename:e.filename,type:e.contentType??"application/octet-stream",...e.cid&&{content_id:e.cid}}),y=async(e,t)=>({Content:await a(e,t),ContentType:e.contentType??"application/octet-stream",Name:e.filename,...e.cid&&{ContentID:e.cid}}),h=async(e,t,n)=>({content:await a(e,t),key:`attachment[${n}]`});export{h as a,y as b,d as c,u as d};
1
+ import{createRequire as c}from"node:module";import m from"./EmailError-B-sEf3bp.js";const s=c(import.meta.url),o=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,r=e=>{if(typeof o<"u"&&o.versions&&o.versions.node){const[t,n]=o.versions.node.split(".").map(Number);if(t>22||t===22&&n>=3||t===20&&n>=16)return o.getBuiltinModule(e)}return s(e)},{Buffer:p}=r("node:buffer"),a=async(e,t)=>{let n;if(e.content)if(typeof e.content=="string")n=e.content;else if(e.content instanceof Promise){const i=await e.content;n=p.from(i).toString("base64")}else n=e.content.toString("base64");else if(e.raw)n=typeof e.raw=="string"?e.raw:e.raw.toString("base64");else throw new m(t,`Attachment ${e.filename} has no content`);return n},d=async(e,t)=>({content:await a(e,t),contentType:e.contentType??"application/octet-stream",disposition:e.contentDisposition??"attachment",filename:e.filename,...e.cid&&{contentId:e.cid}}),u=async(e,t)=>({content:await a(e,t),disposition:e.contentDisposition??"attachment",filename:e.filename,type:e.contentType??"application/octet-stream",...e.cid&&{content_id:e.cid}}),y=async(e,t)=>({Content:await a(e,t),ContentType:e.contentType??"application/octet-stream",Name:e.filename,...e.cid&&{ContentID:e.cid}}),h=async(e,t,n)=>({content:await a(e,t),key:`attachment[${n}]`});export{h as a,y as b,d as c,u as d,a as p};
@@ -1 +1 @@
1
- import{createRequire as A}from"node:module";import l from"./EmailError-B-sEf3bp.js";import w from"./RequiredOptionError-DuNNY_a5.js";import{e as I}from"./generate-message-id-gXAuMz4g.js";import{s as P}from"./headers-to-record-De1Eg951.js";import{m as h}from"./make-request-BlK_B72c.js";import{u as v}from"./retry-3pnxTuNs.js";import{f as j}from"./validate-email-options-mCM9dVug.js";import{defineProvider as _}from"./defineProvider-C9q-7iwt.js";import{P as B,h as T,c as C}from"./provider-base-gIoUu9so.js";import{b as y,c as E}from"./address-formatter-BWR2Dddx.js";const z=A(import.meta.url),f=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,k=n=>{if(typeof f<"u"&&f.versions&&f.versions.node){const[u,t]=f.versions.node.split(".").map(Number);if(u>22||u===22&&t>=3||u===20&&t>=16)return f.getBuiltinModule(n)}return z(n)},{Buffer:p}=k("node:buffer"),i="azure",q=3e4,R=3,K=_((n={})=>{if(!n.region)throw new w(i,"region");if(!n.connectionString&&!n.accessToken)throw new w(i,"connectionString or accessToken");const u=n.endpoint??`https://${n.region}.communication.azure.com`,t={debug:n.debug??!1,endpoint:u,region:n.region,retries:n.retries??R,timeout:n.timeout??q,...n.connectionString&&{connectionString:n.connectionString},...n.accessToken&&{accessToken:n.accessToken},...n.logger&&{logger:n.logger}},g=new B,a=C(i,n.logger);return{features:{attachments:!0,batchSending:!1,customHeaders:!0,html:!0,replyTo:!0,scheduling:!1,tagging:!1,templates:!0,tracking:!1},async getEmail(e){try{if(!e)return{error:new l(i,"Email ID is required to retrieve email details"),success:!1};await g.ensureInitialized(()=>this.initialize(),i);const o={"Content-Type":"application/json"};if(t.accessToken)o.Authorization=`Bearer ${t.accessToken}`;else if(t.connectionString){const c=t.connectionString.match(/endpoint=([^;]+);accesskey=([^;]+)/);c&&(o.Authorization=`Bearer ${c[2]}`)}a.debug("Retrieving email details",{id:e});const r=await v(async()=>h(`${t.endpoint}/emails/${e}`,{headers:o,method:"GET",timeout:t.timeout}),t.retries);return r.success?(a.debug("Email details retrieved successfully"),{data:r.data?.body,success:!0}):(a.debug("API request failed when retrieving email",r.error),{error:new l(i,`Failed to retrieve email: ${r.error instanceof Error?r.error.message:"Unknown error"}`,{cause:r.error}),success:!1})}catch(o){return{error:T(i,"retrieve email",o,a),success:!1}}},async initialize(){await g.ensureInitialized(async()=>{if(!await this.isAvailable())throw new l(i,"Azure Communication Services API not available or invalid credentials");a.debug("Provider initialized successfully")},i)},async isAvailable(){try{const e={"Content-Type":"application/json"};if(t.accessToken)e.Authorization=`Bearer ${t.accessToken}`;else if(t.connectionString){const c=t.connectionString.match(/endpoint=([^;]+);accesskey=([^;]+)/);if(c)e.Authorization=`Bearer ${c[2]}`;else return!1}else return!1;a.debug("Checking Azure Communication Services API availability");const o=await h(`${t.endpoint}/emails:send`,{headers:e,method:"POST",timeout:t.timeout},JSON.stringify({}));if(o.success)return!0;const r=o.data?.statusCode;return r===401||r===403?!1:r===400}catch(e){if(a.debug("Error checking availability:",e),e instanceof Error){const o=e.message;if(o.includes("401")||o.includes("403"))return!1}return!1}},name:i,options:t,async sendEmail(e){try{const o=j(e);if(o.length>0)return{error:new l(i,`Invalid email options: ${o.join(", ")}`),success:!1};await g.ensureInitialized(()=>this.initialize(),i);const r={content:{subject:e.subject},recipients:{to:y(e.to)},senderAddress:e.from.email};if(e.html&&(r.content.html=e.html),e.text&&(r.content.plainText=e.text),e.cc&&(r.recipients.cc=y(e.cc)),e.bcc&&(r.recipients.bcc=y(e.bcc)),e.replyTo&&(r.replyTo=E(e.replyTo).email),e.importance&&(r.importance=e.importance),e.headers){const s=P(e.headers);r.headers=s}e.attachments&&e.attachments.length>0&&(r.attachments=await Promise.all(e.attachments.map(async s=>{let d;if(s.content)if(typeof s.content=="string")d=p.from(s.content,"utf8").toString("base64");else if(s.content&&typeof s.content.then=="function"){const S=await s.content;d=p.from(S).toString("base64")}else d=s.content.toString("base64");else if(s.raw)d=typeof s.raw=="string"?p.from(s.raw,"utf8").toString("base64"):s.raw.toString("base64");else throw new l(i,`Attachment ${s.filename} has no content`);return{contentInBase64:d,contentType:s.contentType??"application/octet-stream",name:s.filename}}))),a.debug("Sending email via Azure Communication Services API",{subject:r.content.subject,to:r.recipients.to});const c={"Content-Type":"application/json"};if(t.accessToken)c.Authorization=`Bearer ${t.accessToken}`;else if(t.connectionString){const s=t.connectionString.match(/endpoint=([^;]+);accesskey=([^;]+)/);if(s)c.Authorization=`Bearer ${s[2]}`;else return{error:new l(i,"Invalid connection string format"),success:!1}}const m=await v(async()=>h(`${t.endpoint}/emails:send`,{headers:c,method:"POST",timeout:t.timeout},JSON.stringify(r)),t.retries);if(!m.success)return a.debug("API request failed when sending email",m.error),{error:m.error??new l(i,"Failed to send email"),success:!1};const b=m.data?.body?.messageId??I();return a.debug("Email sent successfully",{messageId:b}),{data:{messageId:b,provider:i,response:m.data,sent:!0,timestamp:new Date},success:!0}}catch(o){return{error:T(i,"send email",o,a),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{K as default};
1
+ import{createRequire as A}from"node:module";import l from"./EmailError-B-sEf3bp.js";import w from"./RequiredOptionError-DuNNY_a5.js";import{e as I}from"./generate-message-id-gXAuMz4g.js";import{s as P}from"./headers-to-record-De1Eg951.js";import{m as h}from"./make-request-BlK_B72c.js";import{u as v}from"./retry-3pnxTuNs.js";import{f as j}from"./validate-email-options-mCM9dVug.js";import{defineProvider as _}from"./defineProvider-C9q-7iwt.js";import{P as B,h as T,c as C}from"./provider-base-C7PuopYK.js";import{b as y,c as E}from"./address-formatter-BWR2Dddx.js";const z=A(import.meta.url),f=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,k=n=>{if(typeof f<"u"&&f.versions&&f.versions.node){const[u,t]=f.versions.node.split(".").map(Number);if(u>22||u===22&&t>=3||u===20&&t>=16)return f.getBuiltinModule(n)}return z(n)},{Buffer:p}=k("node:buffer"),i="azure",q=3e4,R=3,K=_((n={})=>{if(!n.region)throw new w(i,"region");if(!n.connectionString&&!n.accessToken)throw new w(i,"connectionString or accessToken");const u=n.endpoint??`https://${n.region}.communication.azure.com`,t={debug:n.debug??!1,endpoint:u,region:n.region,retries:n.retries??R,timeout:n.timeout??q,...n.connectionString&&{connectionString:n.connectionString},...n.accessToken&&{accessToken:n.accessToken},...n.logger&&{logger:n.logger}},g=new B,a=C(i,n.logger);return{features:{attachments:!0,batchSending:!1,customHeaders:!0,html:!0,replyTo:!0,scheduling:!1,tagging:!1,templates:!0,tracking:!1},async getEmail(e){try{if(!e)return{error:new l(i,"Email ID is required to retrieve email details"),success:!1};await g.ensureInitialized(()=>this.initialize(),i);const o={"Content-Type":"application/json"};if(t.accessToken)o.Authorization=`Bearer ${t.accessToken}`;else if(t.connectionString){const c=t.connectionString.match(/endpoint=([^;]+);accesskey=([^;]+)/);c&&(o.Authorization=`Bearer ${c[2]}`)}a.debug("Retrieving email details",{id:e});const r=await v(async()=>h(`${t.endpoint}/emails/${e}`,{headers:o,method:"GET",timeout:t.timeout}),t.retries);return r.success?(a.debug("Email details retrieved successfully"),{data:r.data?.body,success:!0}):(a.debug("API request failed when retrieving email",r.error),{error:new l(i,`Failed to retrieve email: ${r.error instanceof Error?r.error.message:"Unknown error"}`,{cause:r.error}),success:!1})}catch(o){return{error:T(i,"retrieve email",o,a),success:!1}}},async initialize(){await g.ensureInitialized(async()=>{if(!await this.isAvailable())throw new l(i,"Azure Communication Services API not available or invalid credentials");a.debug("Provider initialized successfully")},i)},async isAvailable(){try{const e={"Content-Type":"application/json"};if(t.accessToken)e.Authorization=`Bearer ${t.accessToken}`;else if(t.connectionString){const c=t.connectionString.match(/endpoint=([^;]+);accesskey=([^;]+)/);if(c)e.Authorization=`Bearer ${c[2]}`;else return!1}else return!1;a.debug("Checking Azure Communication Services API availability");const o=await h(`${t.endpoint}/emails:send`,{headers:e,method:"POST",timeout:t.timeout},JSON.stringify({}));if(o.success)return!0;const r=o.data?.statusCode;return r===401||r===403?!1:r===400}catch(e){if(a.debug("Error checking availability:",e),e instanceof Error){const o=e.message;if(o.includes("401")||o.includes("403"))return!1}return!1}},name:i,options:t,async sendEmail(e){try{const o=j(e);if(o.length>0)return{error:new l(i,`Invalid email options: ${o.join(", ")}`),success:!1};await g.ensureInitialized(()=>this.initialize(),i);const r={content:{subject:e.subject},recipients:{to:y(e.to)},senderAddress:e.from.email};if(e.html&&(r.content.html=e.html),e.text&&(r.content.plainText=e.text),e.cc&&(r.recipients.cc=y(e.cc)),e.bcc&&(r.recipients.bcc=y(e.bcc)),e.replyTo&&(r.replyTo=E(e.replyTo).email),e.importance&&(r.importance=e.importance),e.headers){const s=P(e.headers);r.headers=s}e.attachments&&e.attachments.length>0&&(r.attachments=await Promise.all(e.attachments.map(async s=>{let d;if(s.content)if(typeof s.content=="string")d=p.from(s.content,"utf8").toString("base64");else if(s.content&&typeof s.content.then=="function"){const S=await s.content;d=p.from(S).toString("base64")}else d=s.content.toString("base64");else if(s.raw)d=typeof s.raw=="string"?p.from(s.raw,"utf8").toString("base64"):s.raw.toString("base64");else throw new l(i,`Attachment ${s.filename} has no content`);return{contentInBase64:d,contentType:s.contentType??"application/octet-stream",name:s.filename}}))),a.debug("Sending email via Azure Communication Services API",{subject:r.content.subject,to:r.recipients.to});const c={"Content-Type":"application/json"};if(t.accessToken)c.Authorization=`Bearer ${t.accessToken}`;else if(t.connectionString){const s=t.connectionString.match(/endpoint=([^;]+);accesskey=([^;]+)/);if(s)c.Authorization=`Bearer ${s[2]}`;else return{error:new l(i,"Invalid connection string format"),success:!1}}const m=await v(async()=>h(`${t.endpoint}/emails:send`,{headers:c,method:"POST",timeout:t.timeout},JSON.stringify(r)),t.retries);if(!m.success)return a.debug("API request failed when sending email",m.error),{error:m.error??new l(i,"Failed to send email"),success:!1};const b=m.data?.body?.messageId??I();return a.debug("Email sent successfully",{messageId:b}),{data:{messageId:b,provider:i,response:m.data,sent:!0,timestamp:new Date},success:!0}}catch(o){return{error:T(i,"send email",o,a),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{K as default};
@@ -0,0 +1 @@
1
+ import d from"./EmailError-B-sEf3bp.js";import T from"./RequiredOptionError-DuNNY_a5.js";import{e as A}from"./generate-message-id-gXAuMz4g.js";import{s as I}from"./headers-to-record-De1Eg951.js";import{m}from"./make-request-BlK_B72c.js";import{u as g}from"./retry-3pnxTuNs.js";import{f as P}from"./validate-email-options-mCM9dVug.js";import{defineProvider as C}from"./defineProvider-C9q-7iwt.js";import{P as k,h as b,c as E}from"./provider-base-C7PuopYK.js";import{f as p,a as y}from"./address-formatter-BWR2Dddx.js";import{p as j}from"./attachment-processor-CMp7qqMI.js";const r="brevo",S="https://api.brevo.com/v3",z=3e4,K=3,L=C((n={})=>{if(!n.apiKey)throw new T(r,"apiKey");const v=n.endpoint??S,s={apiKey:n.apiKey,debug:n.debug??!1,endpoint:v,hardValidation:n.hardValidation??!1,retries:n.retries??K,timeout:n.timeout??z,...n.logger&&{logger:n.logger}},u=new k,i=E(r,n.logger);return{endpoint:s.endpoint,features:{attachments:!0,batchSending:!0,customHeaders:!0,html:!0,replyTo:!0,scheduling:!0,tagging:!0,templates:!0,tracking:!0},async getEmail(e){try{if(!e)return{error:new d(r,"Email ID is required to retrieve email details"),success:!1};await u.ensureInitialized(()=>this.initialize(),r);const t={"api-key":s.apiKey,"Content-Type":"application/json"};i.debug("Retrieving email details",{id:e});const l=await g(async()=>m(`${s.endpoint}/smtp/emails/${e}`,{headers:t,method:"GET",timeout:s.timeout}),s.retries);return l.success?(i.debug("Email details retrieved successfully"),{data:l.data?.body,success:!0}):(i.debug("API request failed when retrieving email",l.error),{error:new d(r,`Failed to retrieve email: ${l.error instanceof Error?l.error.message:"Unknown error"}`,{cause:l.error}),success:!1})}catch(t){return{error:b(r,"retrieve email",t,i),success:!1}}},async initialize(){await u.ensureInitialized(async()=>{if(!await this.isAvailable())throw new d(r,"Brevo API not available or invalid API key");i.debug("Provider initialized successfully")},r)},async isAvailable(){try{const e={"api-key":s.apiKey,"Content-Type":"application/json"};i.debug("Checking Brevo API availability");const t=await m(`${s.endpoint}/account`,{headers:e,method:"GET",timeout:s.timeout});return i.debug("Brevo API availability check response:",{error:t.error instanceof Error?t.error.message:void 0,statusCode:t.data?.statusCode,success:t.success}),!!(t.success&&t.data&&typeof t.data=="object"&&"statusCode"in t.data&&typeof t.data.statusCode=="number"&&t.data.statusCode>=200&&t.data.statusCode<300)}catch(e){return i.debug("Error checking availability:",e),!1}},name:r,options:s,async sendEmail(e){try{let t;Array.isArray(e.replyTo)?t=e.replyTo.length>0?e.replyTo[0]:void 0:t=e.replyTo;const l={...e,replyTo:t},f=P(l);if(f.length>0)return{error:new d(r,`Invalid email options: ${f.join(", ")}`),success:!1};await u.ensureInitialized(()=>this.initialize(),r);const a={sender:y(e.from),subject:e.subject,to:p(e.to)};if(e.html&&(a.htmlContent=e.html),e.text&&(a.textContent=e.text),e.cc&&(a.cc=p(e.cc)),e.bcc&&(a.bcc=p(e.bcc)),e.replyTo)if(Array.isArray(e.replyTo)){if(s.hardValidation)return{error:new d(r,"Only one replyTo address is allowed"),success:!1};if(e.replyTo.length===0)return{error:new d(r,"replyTo array cannot be empty"),success:!1};const o=e.replyTo[0];if(!o)return{error:new d(r,"replyTo array cannot be empty"),success:!1};a.replyTo=y(o)}else a.replyTo=y(e.replyTo);if(e.templateId&&(a.templateId=e.templateId,e.templateParams&&(a.params=e.templateParams)),e.tags&&e.tags.length>0&&(a.tags=e.tags),e.scheduledAt){const o=typeof e.scheduledAt=="number"?new Date(e.scheduledAt*1e3).toISOString():e.scheduledAt;a.scheduledAt=o}if(e.batchId&&(a.batchId=e.batchId),e.headers){const o=I(e.headers);a.headers=o}e.attachments&&e.attachments.length>0&&(a.attachment=await Promise.all(e.attachments.map(async o=>({content:await j(o,r),name:o.filename,...o.contentType&&{type:o.contentType}})))),i.debug("Sending email via Brevo API",{subject:a.subject,to:a.to});const w={"api-key":s.apiKey,"Content-Type":"application/json"},c=await g(async()=>m(`${s.endpoint}/smtp/email`,{headers:w,method:"POST",timeout:s.timeout},JSON.stringify(a)),s.retries);if(!c.success)return i.debug("API request failed when sending email",c.error),{error:c.error??new d(r,"Failed to send email"),success:!1};const h=c.data?.body?.messageId??A();return i.debug("Email sent successfully",{messageId:h}),{data:{messageId:h,provider:r,response:c.data,sent:!0,timestamp:new Date},success:!0}}catch(t){return{error:b(r,"send email",t,i),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{L as default};
@@ -1,3 +1,3 @@
1
- import v from"./EmailError-B-sEf3bp.js";import l from"../utils/format-email-address.js";import{r as F}from"./generate-boundary-DQbzDiOI.js";import{s as M}from"./headers-to-record-De1Eg951.js";import{f as $}from"./quoted-printable-nSGDA1tA.js";import{a as T,s as f}from"./sanitize-header-DJhgZl3y.js";const d=globalThis.Buffer!==void 0,g=t=>{if(typeof t=="string"){if(d)return Buffer.from(t,"utf8").toString("base64");const e=new TextEncoder().encode(t);let r="";const n=8192;for(let s=0;s<e.length;s+=n){const i=e.subarray(s,Math.min(s+n,e.length));r+=String.fromCharCode(...i)}return btoa(r)}if(d&&t instanceof Buffer)return t.toString("base64");const a=t instanceof Uint8Array?t:new Uint8Array(t);if(d)return Buffer.from(a).toString("base64");let h="";const o=8192;for(let e=0;e<a.length;e+=o){const r=a.subarray(e,Math.min(e+o,a.length));h+=String.fromCharCode(...r)}return btoa(h)},j=globalThis.Buffer!==void 0,A=/[^\u0000-\u007F]/,S=t=>!A.test(t),U=t=>{if(S(t))return t;const a=45,h=new TextDecoder,o=j?Buffer.from(t,"utf8"):new TextEncoder().encode(t),e=[];let r=0;for(;r<o.length;){let n=Math.min(r+a,o.length);if(n<o.length)for(;n>r&&(o[n]&192)===128;)n-=1;const s=o.subarray(r,n),i=h.decode(s);e.push(`=?UTF-8?B?${g(i)}?=`),r=n}return e.join(" ")},b=t=>Array.isArray(t)?t.map(a=>l(a)).join(", "):l(t),y=/[^ -]/,C=t=>U(f(t)),D=globalThis.Buffer!==void 0,x=t=>t.replaceAll(/.{1,76}/g,`$&\r
2
- `).trimEnd(),P=async(t,a={})=>{const{includeBcc:h=!1}=a,o=F(),e=[`From: ${l(t.from)}`,`To: ${b(t.to)}`];if(t.cc&&e.push(`Cc: ${b(t.cc)}`),h&&t.bcc&&e.push(`Bcc: ${b(t.bcc)}`),t.replyTo&&e.push(`Reply-To: ${l(t.replyTo)}`),e.push(`Subject: ${C(t.subject)}`,"MIME-Version: 1.0"),t.headers){const r=M(t.headers);Object.entries(r).forEach(([n,s])=>{const i=T(n),p=f(s);e.push(`${i}: ${p}`)})}if(e.push(`Content-Type: multipart/mixed; boundary="${o}"`,""),t.text&&(y.test(t.text)?e.push(`--${o}`,"Content-Type: text/plain; charset=UTF-8","Content-Transfer-Encoding: quoted-printable","",$(t.text),""):e.push(`--${o}`,"Content-Type: text/plain; charset=UTF-8","Content-Transfer-Encoding: 7bit","",t.text,"")),t.html&&(y.test(t.html)?e.push(`--${o}`,"Content-Type: text/html; charset=UTF-8","Content-Transfer-Encoding: quoted-printable","",$(t.html),""):e.push(`--${o}`,"Content-Type: text/html; charset=UTF-8","Content-Transfer-Encoding: 7bit","",t.html,"")),t.attachments&&t.attachments.length>0){const r=await Promise.all(t.attachments.map(async n=>{let s;if(n.raw!==void 0)s=n.raw;else{if(n.content===void 0)throw new v("attachment",`Attachment '${n.filename}' must have content, raw, or be resolved from path/href before building MIME message`);s=n.content instanceof Promise?await n.content:n.content}return{...n,resolvedContent:s}}));for(const n of r){e.push(`--${o}`);const s=f(n.contentType??"application/octet-stream"),i=C(n.filename);e.push(`Content-Type: ${s}; name="${i}"`);const p=f(n.contentDisposition??"attachment");e.push(`Content-Disposition: ${p}; filename="${i}"`),n.cid&&e.push(`Content-ID: <${f(n.cid)}>`),n.headers&&Object.entries(n.headers).forEach(([m,w])=>{const B=T(m),E=f(w);e.push(`${B}: ${E}`)});const u=f(n.encoding??"base64");e.push(`Content-Transfer-Encoding: ${u}`,"");const c=n.resolvedContent;if(u==="base64")e.push(x(g(c)));else if(u==="7bit"||u==="8bit")if(typeof c=="string")e.push(c);else if(D&&c instanceof Buffer)e.push(c.toString("utf8"));else{const m=new TextDecoder;e.push(m.decode(c))}else e.push(x(g(c)));e.push("")}}return e.push(`--${o}--`),e.join(`\r
1
+ import v from"./EmailError-B-sEf3bp.js";import l from"../utils/format-email-address.js";import{r as F}from"./generate-boundary-DQbzDiOI.js";import{s as M}from"./headers-to-record-De1Eg951.js";import{f as g}from"./quoted-printable-nSGDA1tA.js";import{a as T,s as f}from"./sanitize-header-DJhgZl3y.js";const d=globalThis.Buffer!==void 0,$=t=>{if(typeof t=="string"){if(d)return Buffer.from(t,"utf8").toString("base64");const e=new TextEncoder().encode(t);let r="";const n=8192;for(let s=0;s<e.length;s+=n){const i=e.subarray(s,Math.min(s+n,e.length));r+=String.fromCharCode(...i)}return btoa(r)}if(d&&t instanceof Buffer)return t.toString("base64");const a=t instanceof Uint8Array?t:new Uint8Array(t);if(d)return Buffer.from(a).toString("base64");let h="";const o=8192;for(let e=0;e<a.length;e+=o){const r=a.subarray(e,Math.min(e+o,a.length));h+=String.fromCharCode(...r)}return btoa(h)},j=globalThis.Buffer!==void 0,A=/[^\u0000-\u007F]/,S=t=>!A.test(t),U=t=>{if(S(t))return t;const a=45,h=new TextDecoder,o=j?Buffer.from(t,"utf8"):new TextEncoder().encode(t),e=[];let r=0;for(;r<o.length;){let n=Math.min(r+a,o.length);if(n<o.length)for(;n>r&&(o[n]&192)===128;)n-=1;const s=o.subarray(r,n),i=h.decode(s);e.push(`=?UTF-8?B?${$(i)}?=`),r=n}return e.join(" ")},b=t=>Array.isArray(t)?t.map(a=>l(a)).join(", "):l(t),y=/[^ -]/,C=t=>U(f(t)),D=globalThis.Buffer!==void 0,x=t=>t.replaceAll(/.{1,76}/g,`$&\r
2
+ `).trimEnd(),P=async(t,a={})=>{const{includeBcc:h=!1}=a,o=F(),e=[`From: ${l(t.from)}`,`To: ${b(t.to)}`];if(t.cc&&e.push(`Cc: ${b(t.cc)}`),h&&t.bcc&&e.push(`Bcc: ${b(t.bcc)}`),t.replyTo&&e.push(`Reply-To: ${l(t.replyTo)}`),e.push(`Subject: ${C(t.subject)}`,"MIME-Version: 1.0"),t.headers){const r=M(t.headers);Object.entries(r).forEach(([n,s])=>{const i=T(n),p=f(s);e.push(`${i}: ${p}`)})}if(e.push(`Content-Type: multipart/mixed; boundary="${o}"`,""),t.text&&(y.test(t.text)?e.push(`--${o}`,"Content-Type: text/plain; charset=UTF-8","Content-Transfer-Encoding: quoted-printable","",g(t.text),""):e.push(`--${o}`,"Content-Type: text/plain; charset=UTF-8","Content-Transfer-Encoding: 7bit","",t.text,"")),t.html&&(y.test(t.html)?e.push(`--${o}`,"Content-Type: text/html; charset=UTF-8","Content-Transfer-Encoding: quoted-printable","",g(t.html),""):e.push(`--${o}`,"Content-Type: text/html; charset=UTF-8","Content-Transfer-Encoding: 7bit","",t.html,"")),t.attachments&&t.attachments.length>0){const r=await Promise.all(t.attachments.map(async n=>{let s;if(n.raw!==void 0)s=n.raw;else{if(n.content===void 0)throw new v("attachment",`Attachment '${n.filename}' must have content, raw, or be resolved from path/href before building MIME message`);s=n.content instanceof Promise?await n.content:n.content}return{...n,resolvedContent:s}}));for(const n of r){e.push(`--${o}`);const s=f(n.contentType??"application/octet-stream"),i=C(n.filename);e.push(`Content-Type: ${s}; name="${i}"`);const p=f(n.contentDisposition??"attachment");e.push(`Content-Disposition: ${p}; filename="${i}"`),n.cid&&e.push(`Content-ID: <${f(n.cid)}>`),n.headers&&Object.entries(n.headers).forEach(([m,w])=>{const B=T(m),E=f(w);e.push(`${B}: ${E}`)});const u=f(n.encoding??"base64");e.push(`Content-Transfer-Encoding: ${u}`,"");const c=n.resolvedContent;if(u==="base64")e.push(x($(c)));else if(u==="7bit"||u==="8bit")if(typeof c=="string")e.push(c);else if(D&&c instanceof Buffer)e.push(c.toString("utf8"));else{const m=new TextDecoder;e.push(m.decode(c))}else e.push(x($(c)));e.push("")}}return e.push(`--${o}--`),e.join(`\r
3
3
  `)};export{P as F};
@@ -1 +1 @@
1
- import a from"./EmailError-B-sEf3bp.js";import m from"./RequiredOptionError-DuNNY_a5.js";import{F as d}from"./build-mime-message-Be6TOi1T.js";import{e as f}from"./generate-message-id-gXAuMz4g.js";import{s as u}from"./headers-to-record-De1Eg951.js";import{f as p}from"./validate-email-options-mCM9dVug.js";import{defineProvider as g}from"./defineProvider-C9q-7iwt.js";import{h,c as v}from"./provider-base-gIoUu9so.js";const r="cloudflare-email",C=g((t={})=>{if(typeof t.send!="function")throw new m(r,"send");const c=v(r,t.logger);return{features:{attachments:!0,batchSending:!1,customHeaders:!0,html:!0,replyTo:!0,scheduling:!1,tagging:!1,templates:!1,tracking:!1},async initialize(){await Promise.resolve()},async isAvailable(){return typeof t.send=="function"},name:r,async sendEmail(e){try{const s=p(e);if(s.length>0)return{error:new a(r,`Invalid email options: ${s.join(", ")}`),success:!1};const i=Array.isArray(e.to)?e.to:[e.to];if(i.length!==1||e.cc!==void 0||e.bcc!==void 0)return{error:new a(r,"Cloudflare Email supports exactly one `to` recipient and does not support cc/bcc"),success:!1};const[o]=i;if(!o)return{error:new a(r,"A single `to` recipient is required"),success:!1};const n=f(),l=await d({...e,headers:{...e.headers?u(e.headers):{},"Message-ID":n}});return await t.send(e.from.email,o.email,l),{data:{messageId:n,provider:r,sent:!0,timestamp:new Date},success:!0}}catch(s){return{error:h(r,"send email",s,c),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{C as default};
1
+ import a from"./EmailError-B-sEf3bp.js";import m from"./RequiredOptionError-DuNNY_a5.js";import{F as d}from"./build-mime-message-B6927SQy.js";import{e as f}from"./generate-message-id-gXAuMz4g.js";import{s as u}from"./headers-to-record-De1Eg951.js";import{f as p}from"./validate-email-options-mCM9dVug.js";import{defineProvider as g}from"./defineProvider-C9q-7iwt.js";import{h,c as v}from"./provider-base-C7PuopYK.js";const r="cloudflare-email",C=g((t={})=>{if(typeof t.send!="function")throw new m(r,"send");const c=v(r,t.logger);return{features:{attachments:!0,batchSending:!1,customHeaders:!0,html:!0,replyTo:!0,scheduling:!1,tagging:!1,templates:!1,tracking:!1},async initialize(){await Promise.resolve()},async isAvailable(){return typeof t.send=="function"},name:r,async sendEmail(e){try{const s=p(e);if(s.length>0)return{error:new a(r,`Invalid email options: ${s.join(", ")}`),success:!1};const i=Array.isArray(e.to)?e.to:[e.to];if(i.length!==1||e.cc!==void 0||e.bcc!==void 0)return{error:new a(r,"Cloudflare Email supports exactly one `to` recipient and does not support cc/bcc"),success:!1};const[o]=i;if(!o)return{error:new a(r,"A single `to` recipient is required"),success:!1};const n=f(),l=await d({...e,headers:{...e.headers?u(e.headers):{},"Message-ID":n}});return await t.send(e.from.email,o.email,l),{data:{messageId:n,provider:r,sent:!0,timestamp:new Date},success:!0}}catch(s){return{error:h(r,"send email",s,c),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{C as default};
@@ -1 +1 @@
1
- import{createMail as w}from"./Mail-DpjH0Exh.js";import u from"./mockProvider-Behywbl1.js";const d=(t,o,e,n)=>{const r=Date.now()+e;return new Promise((s,c)=>{const a=()=>{const i=t.find(m=>o(m));if(i){s(i);return}if(Date.now()>=r){c(new Error("waitFor timed out before a matching message was captured"));return}setTimeout(a,n)};a()})},l=()=>{const t=u(),o=w(t),e=t.getInstance?.();if(!e)throw new Error("mockProvider() did not expose getInstance(); cannot create a test harness");return{mail:o,reset:()=>{e.length=0},sent:()=>e,waitFor:(n,r={})=>d(e,n,r.timeout??1e3,r.interval??10)}};export{l as createTestEmail};
1
+ import{createMail as w}from"./Mail-BEuzrB00.js";import u from"./mockProvider-Behywbl1.js";const d=(t,o,e,n)=>{const r=Date.now()+e;return new Promise((s,c)=>{const a=()=>{const i=t.find(m=>o(m));if(i){s(i);return}if(Date.now()>=r){c(new Error("waitFor timed out before a matching message was captured"));return}setTimeout(a,n)};a()})},l=()=>{const t=u(),o=w(t),e=t.getInstance?.();if(!e)throw new Error("mockProvider() did not expose getInstance(); cannot create a test harness");return{mail:o,reset:()=>{e.length=0},sent:()=>e,waitFor:(n,r={})=>d(e,n,r.timeout??1e3,r.interval??10)}};export{l as createTestEmail};
@@ -0,0 +1 @@
1
+ import c from"./EmailError-B-sEf3bp.js";import v from"./RequiredOptionError-DuNNY_a5.js";import{e as w}from"./generate-message-id-gXAuMz4g.js";import{s as A}from"./headers-to-record-De1Eg951.js";import{m as d}from"./make-request-BlK_B72c.js";import{u as g}from"./retry-3pnxTuNs.js";import{f as I}from"./validate-email-options-mCM9dVug.js";import{defineProvider as P}from"./defineProvider-C9q-7iwt.js";import{P as T,h as y,c as U}from"./provider-base-C7PuopYK.js";import{d as u}from"./address-formatter-BWR2Dddx.js";import{p as z}from"./attachment-processor-CMp7qqMI.js";const r="infobip",E="https://api.infobip.com",k=3e4,j=3,H=P((s={})=>{if(!s.apiKey)throw new v(r,"apiKey");const p=s.baseUrl??E,h=s.endpoint??`${p}/email/3/send`,a={apiKey:s.apiKey,baseUrl:p,debug:s.debug??!1,endpoint:h,retries:s.retries??j,timeout:s.timeout??k,...s.logger&&{logger:s.logger}},m=new T,i=U(r,s.logger);return{features:{attachments:!0,batchSending:!0,customHeaders:!0,html:!0,replyTo:!0,scheduling:!0,tagging:!1,templates:!0,tracking:!0},async getEmail(e){try{if(!e)return{error:new c(r,"Email ID is required to retrieve email details"),success:!1};await m.ensureInitialized(()=>this.initialize(),r);const n={Authorization:`App ${a.apiKey}`,"Content-Type":"application/json"};i.debug("Retrieving email details",{id:e});const t=await g(async()=>d(`${a.baseUrl}/email/3/reports/${e}`,{headers:n,method:"GET",timeout:a.timeout}),a.retries);return t.success?(i.debug("Email details retrieved successfully"),{data:t.data?.body,success:!0}):(i.debug("API request failed when retrieving email",t.error),{error:new c(r,`Failed to retrieve email: ${t.error instanceof Error?t.error.message:"Unknown error"}`,{cause:t.error}),success:!1})}catch(n){return{error:y(r,"retrieve email",n,i),success:!1}}},async initialize(){await m.ensureInitialized(async()=>{if(!await this.isAvailable())throw new c(r,"Infobip API not available or invalid API key");i.debug("Provider initialized successfully")},r)},async isAvailable(){try{i.debug("Checking Infobip API availability");const e={Authorization:`App ${a.apiKey}`,"Content-Type":"application/json"};return(await d(`${a.baseUrl}/account/1/me`,{headers:e,method:"GET",timeout:a.timeout})).success}catch(e){return i.debug("Error checking availability:",e),!1}},name:r,options:a,async sendEmail(e){try{const n=I(e);if(n.length>0)return{error:new c(r,`Invalid email options: ${n.join(", ")}`),success:!1};await m.ensureInitialized(()=>this.initialize(),r);const t={from:typeof e.from=="string"?e.from:e.from.email,subject:e.subject,to:u(e.to)};if(e.html&&(t.html=e.html),e.text&&(t.text=e.text),e.cc&&(t.cc=u(e.cc)),e.bcc&&(t.bcc=u(e.bcc)),e.replyTo&&(t.replyTo=typeof e.replyTo=="string"?e.replyTo:e.replyTo.email),e.templateId&&(t.templateId=e.templateId,e.templateVariables&&(t.templateData=e.templateVariables)),e.trackingUrl&&(t.trackingUrl=e.trackingUrl),e.notifyUrl&&(t.notifyUrl=e.notifyUrl),e.intermediateReport!==void 0&&(t.intermediateReport=e.intermediateReport),e.sendAt&&(t.sendAt=e.sendAt),e.headers){const l=A(e.headers);t.headers=l}e.attachments&&e.attachments.length>0&&(t.attachments=await Promise.all(e.attachments.map(async l=>({content:await z(l,r),contentType:l.contentType??"application/octet-stream",name:l.filename})))),i.debug("Sending email via Infobip API",{subject:t.subject,to:t.to});const b={Authorization:`App ${a.apiKey}`,"Content-Type":"application/json"},o=await g(async()=>d(a.endpoint,{headers:b,method:"POST",timeout:a.timeout},JSON.stringify(t)),a.retries);if(!o.success)return i.debug("API request failed when sending email",o.error),{error:o.error??new c(r,"Failed to send email"),success:!1};const f=o.data?.body?.messages?.[0]?.messageId??w();return i.debug("Email sent successfully",{messageId:f}),{data:{messageId:f,provider:r,response:o.data,sent:!0,timestamp:new Date},success:!0}}catch(n){return{error:y(r,"send email",n,i),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{H as default};
@@ -1 +1 @@
1
- import o from"./EmailError-B-sEf3bp.js";import f from"./RequiredOptionError-DuNNY_a5.js";import{e as g}from"./generate-message-id-gXAuMz4g.js";import{m as h}from"./make-request-BlK_B72c.js";import{u as y}from"./retry-3pnxTuNs.js";import{defineProvider as b}from"./defineProvider-C9q-7iwt.js";import{c as v}from"./attachment-processor-BjTNoMyb.js";import{h as w,P as T,c as A}from"./provider-base-gIoUu9so.js";const t="loops",I="https://app.loops.so/api/v1/transactional",P=3e4,K=3,E=b((a={})=>{if(!a.apiKey)throw new f(t,"apiKey");const r={apiKey:a.apiKey,debug:a.debug??!1,defaultTransactionalId:a.defaultTransactionalId,endpoint:a.endpoint??I,logger:a.logger,retries:a.retries??K,timeout:a.timeout??P},m=new T,u=A(t,a.logger);return{features:{attachments:!0,batchSending:!1,customHeaders:!1,html:!1,replyTo:!1,scheduling:!1,tagging:!1,templates:!0,tracking:!0},async initialize(){m.setInitialized()},async isAvailable(){return r.apiKey.length>0},name:t,options:r,async sendEmail(e){try{const s=e.transactionalId??r.defaultTransactionalId;if(!s)return{error:new o(t,"Loops requires a `transactionalId` (on the message or as `defaultTransactionalId`)"),success:!1};const l=Array.isArray(e.to)?e.to:[e.to];if(l.length!==1||e.cc!==void 0||e.bcc!==void 0)return{error:new o(t,"Loops supports exactly one `to` recipient and does not support cc/bcc"),success:!1};const[d]=l;if(!d)return{error:new o(t,"A `to` recipient is required"),success:!1};const n={email:d.email,transactionalId:s};e.dataVariables&&(n.dataVariables=e.dataVariables),e.addToAudience&&(n.addToAudience=!0),e.attachments&&e.attachments.length>0&&(n.attachments=await Promise.all(e.attachments.map(async p=>{const c=await v(p,t);return{contentType:c.contentType,data:c.content,filename:c.filename}})));const i=await y(async()=>h(r.endpoint,{headers:{Authorization:`Bearer ${r.apiKey}`,"Content-Type":"application/json"},method:"POST",timeout:r.timeout},JSON.stringify(n)),r.retries);return i.success?{data:{messageId:g(),provider:t,response:i.data,sent:!0,timestamp:new Date},success:!0}:{error:i.error??new o(t,"Failed to send email"),success:!1}}catch(s){return{error:w(t,"send email",s,u),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{E as default};
1
+ import o from"./EmailError-B-sEf3bp.js";import f from"./RequiredOptionError-DuNNY_a5.js";import{e as g}from"./generate-message-id-gXAuMz4g.js";import{m as h}from"./make-request-BlK_B72c.js";import{u as y}from"./retry-3pnxTuNs.js";import{defineProvider as b}from"./defineProvider-C9q-7iwt.js";import{c as v}from"./attachment-processor-CMp7qqMI.js";import{h as w,P as T,c as A}from"./provider-base-C7PuopYK.js";const t="loops",I="https://app.loops.so/api/v1/transactional",P=3e4,K=3,E=b((a={})=>{if(!a.apiKey)throw new f(t,"apiKey");const r={apiKey:a.apiKey,debug:a.debug??!1,defaultTransactionalId:a.defaultTransactionalId,endpoint:a.endpoint??I,logger:a.logger,retries:a.retries??K,timeout:a.timeout??P},m=new T,u=A(t,a.logger);return{features:{attachments:!0,batchSending:!1,customHeaders:!1,html:!1,replyTo:!1,scheduling:!1,tagging:!1,templates:!0,tracking:!0},async initialize(){m.setInitialized()},async isAvailable(){return r.apiKey.length>0},name:t,options:r,async sendEmail(e){try{const s=e.transactionalId??r.defaultTransactionalId;if(!s)return{error:new o(t,"Loops requires a `transactionalId` (on the message or as `defaultTransactionalId`)"),success:!1};const l=Array.isArray(e.to)?e.to:[e.to];if(l.length!==1||e.cc!==void 0||e.bcc!==void 0)return{error:new o(t,"Loops supports exactly one `to` recipient and does not support cc/bcc"),success:!1};const[d]=l;if(!d)return{error:new o(t,"A `to` recipient is required"),success:!1};const n={email:d.email,transactionalId:s};e.dataVariables&&(n.dataVariables=e.dataVariables),e.addToAudience&&(n.addToAudience=!0),e.attachments&&e.attachments.length>0&&(n.attachments=await Promise.all(e.attachments.map(async p=>{const c=await v(p,t);return{contentType:c.contentType,data:c.content,filename:c.filename}})));const i=await y(async()=>h(r.endpoint,{headers:{Authorization:`Bearer ${r.apiKey}`,"Content-Type":"application/json"},method:"POST",timeout:r.timeout},JSON.stringify(n)),r.retries);return i.success?{data:{messageId:g(),provider:t,response:i.data,sent:!0,timestamp:new Date},success:!0}:{error:i.error??new o(t,"Failed to send email"),success:!1}}catch(s){return{error:w(t,"send email",s,u),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{E as default};
@@ -1 +1 @@
1
- import{defineProvider as l}from"./defineProvider-C9q-7iwt.js";import o from"./smtpProvider-x4WBN-3W.js";const s="mailcrab",u="localhost",n=1025,g=l((t={})=>{const e={debug:t.debug??!1,host:t.host??u,logger:t.logger,port:t.port??n,retries:t.retries,secure:t.secure??!1,timeout:t.timeout},a=o({debug:e.debug,host:e.host,logger:e.logger,port:e.port,retries:e.retries,secure:e.secure,timeout:e.timeout});return{features:{attachments:!0,batchSending:!1,customHeaders:!0,html:!0,replyTo:!0,scheduling:!1,tagging:!1,templates:!1,tracking:!1},async initialize(){await a.initialize()},async isAvailable(){return a.isAvailable()},name:s,options:e,async sendEmail(i){const r=await a.sendEmail(i);return r.success&&r.data?{data:{...r.data,provider:s},success:!0}:r},async validateCredentials(){return a.validateCredentials?.()??!1}}});export{g as default};
1
+ import{defineProvider as l}from"./defineProvider-C9q-7iwt.js";import o from"./smtpProvider-Bm0yP97W.js";const s="mailcrab",u="localhost",n=1025,g=l((t={})=>{const e={debug:t.debug??!1,host:t.host??u,logger:t.logger,port:t.port??n,retries:t.retries,secure:t.secure??!1,timeout:t.timeout},a=o({debug:e.debug,host:e.host,logger:e.logger,port:e.port,retries:e.retries,secure:e.secure,timeout:e.timeout});return{features:{attachments:!0,batchSending:!1,customHeaders:!0,html:!0,replyTo:!0,scheduling:!1,tagging:!1,templates:!1,tracking:!1},async initialize(){await a.initialize()},async isAvailable(){return a.isAvailable()},name:s,options:e,async sendEmail(i){const r=await a.sendEmail(i);return r.success&&r.data?{data:{...r.data,provider:s},success:!0}:r},async validateCredentials(){return a.validateCredentials?.()??!1}}});export{g as default};
@@ -1 +1 @@
1
- import c from"./EmailError-B-sEf3bp.js";import P from"./RequiredOptionError-DuNNY_a5.js";import{e as I}from"./generate-message-id-gXAuMz4g.js";import{s as T}from"./headers-to-record-De1Eg951.js";import{m as d}from"./make-request-BlK_B72c.js";import{u as g}from"./retry-3pnxTuNs.js";import{a as A,s as k}from"./sanitize-header-DJhgZl3y.js";import{f as z}from"./validate-email-options-mCM9dVug.js";import{defineProvider as j}from"./defineProvider-C9q-7iwt.js";import{P as E,h as f,c as C}from"./provider-base-gIoUu9so.js";import{j as u,g as h}from"./address-formatter-BWR2Dddx.js";const r="mailpace",M="https://app.mailpace.com/api/v1",S=3e4,q=3,R=j((o={})=>{if(!o.apiToken)throw new P(r,"apiToken");const s={apiToken:o.apiToken,debug:o.debug??!1,endpoint:o.endpoint??M,retries:o.retries??q,timeout:o.timeout??S,...o.logger&&{logger:o.logger}},l=new E,i=C(r,o.logger);return{features:{attachments:!0,batchSending:!1,customHeaders:!0,html:!0,replyTo:!0,scheduling:!1,tagging:!0,templates:!0,tracking:!1},async getEmail(e){try{if(!e)return{error:new c(r,"Email ID is required to retrieve email details"),success:!1};await l.ensureInitialized(()=>this.initialize(),r);const a={Authorization:`Bearer ${s.apiToken}`,"Content-Type":"application/json"};i.debug("Retrieving email details",{id:e});const t=await g(async()=>d(`${s.endpoint}/emails/${e}`,{headers:a,method:"GET",timeout:s.timeout}),s.retries);return t.success?(i.debug("Email details retrieved successfully"),{data:t.data?.body,success:!0}):(i.debug("API request failed when retrieving email",t.error),{error:new c(r,`Failed to retrieve email: ${t.error instanceof Error?t.error.message:"Unknown error"}`,{cause:t.error}),success:!1})}catch(a){return{error:f(r,"retrieve email",a,i),success:!1}}},async initialize(){await l.ensureInitialized(async()=>{if(!await this.isAvailable())throw new c(r,"MailPace API not available or invalid API token");i.debug("Provider initialized successfully")},r)},async isAvailable(){try{const e={Authorization:`Bearer ${s.apiToken}`,"Content-Type":"application/json"};i.debug("Checking MailPace API availability");const a=await d(`${s.endpoint}/account`,{headers:e,method:"GET",timeout:s.timeout});return i.debug("MailPace API availability check response:",{error:a.error instanceof Error?a.error.message:void 0,statusCode:a.data?.statusCode,success:a.success}),!!(a.success&&a.data&&typeof a.data=="object"&&"statusCode"in a.data&&typeof a.data.statusCode=="number"&&a.data.statusCode>=200&&a.data.statusCode<300)}catch(e){return i.debug("Error checking availability:",e),!1}},name:r,options:s,async sendEmail(e){try{const a=z(e);if(a.length>0)return{error:new c(r,`Invalid email options: ${a.join(", ")}`),success:!1};await l.ensureInitialized(()=>this.initialize(),r);const t={from:h(e.from),subject:e.subject,to:u(e.to)};if(e.html&&(t.htmlbody=e.html),e.text&&(t.textbody=e.text),e.cc&&(t.cc=u(e.cc)),e.bcc&&(t.bcc=u(e.bcc)),e.replyTo&&(t.replyto=h(e.replyTo)),e.templateId&&(t.template_id=e.templateId,e.templateVariables&&(t.template_variables=e.templateVariables)),e.tags&&e.tags.length>0&&(t.tags=e.tags),e.listUnsubscribe&&(t.list_unsubscribe=e.listUnsubscribe),e.headers){const y=T(e.headers),p={};Object.entries(y).forEach(([v,w])=>{p[A(v)]=k(w)}),t.headers=p}e.attachments&&e.attachments.length>0&&(t.attachments=e.attachments),i.debug("Sending email via MailPace API",{subject:t.subject,to:t.to});const b={Authorization:`Bearer ${s.apiToken}`,"Content-Type":"application/json"},n=await g(async()=>d(`${s.endpoint}/send`,{headers:b,method:"POST",timeout:s.timeout},JSON.stringify(t)),s.retries);if(!n.success)return i.debug("API request failed when sending email",n.error),{error:n.error??new c(r,"Failed to send email"),success:!1};const m=n.data?.body?.id??I();return i.debug("Email sent successfully",{messageId:m}),{data:{messageId:m,provider:r,response:n.data,sent:!0,timestamp:new Date},success:!0}}catch(a){return{error:f(r,"send email",a,i),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{R as default};
1
+ import c from"./EmailError-B-sEf3bp.js";import P from"./RequiredOptionError-DuNNY_a5.js";import{e as I}from"./generate-message-id-gXAuMz4g.js";import{s as T}from"./headers-to-record-De1Eg951.js";import{m as d}from"./make-request-BlK_B72c.js";import{u as g}from"./retry-3pnxTuNs.js";import{a as A,s as k}from"./sanitize-header-DJhgZl3y.js";import{f as z}from"./validate-email-options-mCM9dVug.js";import{defineProvider as j}from"./defineProvider-C9q-7iwt.js";import{P as E,h as f,c as C}from"./provider-base-C7PuopYK.js";import{j as u,g as h}from"./address-formatter-BWR2Dddx.js";const r="mailpace",M="https://app.mailpace.com/api/v1",S=3e4,q=3,R=j((o={})=>{if(!o.apiToken)throw new P(r,"apiToken");const s={apiToken:o.apiToken,debug:o.debug??!1,endpoint:o.endpoint??M,retries:o.retries??q,timeout:o.timeout??S,...o.logger&&{logger:o.logger}},l=new E,i=C(r,o.logger);return{features:{attachments:!0,batchSending:!1,customHeaders:!0,html:!0,replyTo:!0,scheduling:!1,tagging:!0,templates:!0,tracking:!1},async getEmail(e){try{if(!e)return{error:new c(r,"Email ID is required to retrieve email details"),success:!1};await l.ensureInitialized(()=>this.initialize(),r);const a={Authorization:`Bearer ${s.apiToken}`,"Content-Type":"application/json"};i.debug("Retrieving email details",{id:e});const t=await g(async()=>d(`${s.endpoint}/emails/${e}`,{headers:a,method:"GET",timeout:s.timeout}),s.retries);return t.success?(i.debug("Email details retrieved successfully"),{data:t.data?.body,success:!0}):(i.debug("API request failed when retrieving email",t.error),{error:new c(r,`Failed to retrieve email: ${t.error instanceof Error?t.error.message:"Unknown error"}`,{cause:t.error}),success:!1})}catch(a){return{error:f(r,"retrieve email",a,i),success:!1}}},async initialize(){await l.ensureInitialized(async()=>{if(!await this.isAvailable())throw new c(r,"MailPace API not available or invalid API token");i.debug("Provider initialized successfully")},r)},async isAvailable(){try{const e={Authorization:`Bearer ${s.apiToken}`,"Content-Type":"application/json"};i.debug("Checking MailPace API availability");const a=await d(`${s.endpoint}/account`,{headers:e,method:"GET",timeout:s.timeout});return i.debug("MailPace API availability check response:",{error:a.error instanceof Error?a.error.message:void 0,statusCode:a.data?.statusCode,success:a.success}),!!(a.success&&a.data&&typeof a.data=="object"&&"statusCode"in a.data&&typeof a.data.statusCode=="number"&&a.data.statusCode>=200&&a.data.statusCode<300)}catch(e){return i.debug("Error checking availability:",e),!1}},name:r,options:s,async sendEmail(e){try{const a=z(e);if(a.length>0)return{error:new c(r,`Invalid email options: ${a.join(", ")}`),success:!1};await l.ensureInitialized(()=>this.initialize(),r);const t={from:h(e.from),subject:e.subject,to:u(e.to)};if(e.html&&(t.htmlbody=e.html),e.text&&(t.textbody=e.text),e.cc&&(t.cc=u(e.cc)),e.bcc&&(t.bcc=u(e.bcc)),e.replyTo&&(t.replyto=h(e.replyTo)),e.templateId&&(t.template_id=e.templateId,e.templateVariables&&(t.template_variables=e.templateVariables)),e.tags&&e.tags.length>0&&(t.tags=e.tags),e.listUnsubscribe&&(t.list_unsubscribe=e.listUnsubscribe),e.headers){const y=T(e.headers),p={};Object.entries(y).forEach(([v,w])=>{p[A(v)]=k(w)}),t.headers=p}e.attachments&&e.attachments.length>0&&(t.attachments=e.attachments),i.debug("Sending email via MailPace API",{subject:t.subject,to:t.to});const b={Authorization:`Bearer ${s.apiToken}`,"Content-Type":"application/json"},n=await g(async()=>d(`${s.endpoint}/send`,{headers:b,method:"POST",timeout:s.timeout},JSON.stringify(t)),s.retries);if(!n.success)return i.debug("API request failed when sending email",n.error),{error:n.error??new c(r,"Failed to send email"),success:!1};const m=n.data?.body?.id??I();return i.debug("Email sent successfully",{messageId:m}),{data:{messageId:m,provider:r,response:n.data,sent:!0,timestamp:new Date},success:!0}}catch(a){return{error:f(r,"send email",a,i),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{R as default};
@@ -1 +1 @@
1
- import p from"./EmailError-B-sEf3bp.js";import g from"./RequiredOptionError-DuNNY_a5.js";import{e as v}from"./generate-message-id-gXAuMz4g.js";import{s as b}from"./headers-to-record-De1Eg951.js";import{m as w}from"./make-request-BlK_B72c.js";import{u as K}from"./retry-3pnxTuNs.js";import{f as S}from"./validate-email-options-mCM9dVug.js";import{defineProvider as P}from"./defineProvider-C9q-7iwt.js";import{f as l,a as u}from"./address-formatter-BWR2Dddx.js";import{c as x}from"./attachment-processor-BjTNoMyb.js";import{h as A,P as T,c as j}from"./provider-base-gIoUu9so.js";const a="mailchannels",I="https://api.mailchannels.net/tx/v1/send",_=3e4,z=3,N=P((t={})=>{if(!t.apiKey)throw new g(a,"apiKey");const r={apiKey:t.apiKey,debug:t.debug??!1,endpoint:t.endpoint??I,logger:t.logger,retries:t.retries??z,timeout:t.timeout??_},f=new T,h=j(a,t.logger);return{features:{attachments:!0,batchSending:!1,customHeaders:!0,html:!0,replyTo:!0,scheduling:!1,tagging:!1,templates:!1,tracking:!1},async initialize(){f.setInitialized()},async isAvailable(){return r.apiKey.length>0},name:a,options:r,async sendEmail(e){try{const s=S(e);if(s.length>0)return{error:new p(a,`Invalid email options: ${s.join(", ")}`),success:!1};const o=[];e.text&&o.push({type:"text/plain",value:e.text}),e.html&&o.push({type:"text/html",value:e.html});const c={to:l(e.to)};e.cc&&(c.cc=l(e.cc)),e.bcc&&(c.bcc=l(e.bcc));const n={content:o,from:u(e.from),personalizations:[c],subject:e.subject};e.replyTo&&(n.reply_to=u(e.replyTo)),e.headers&&(n.headers=b(e.headers)),e.attachments&&e.attachments.length>0&&(n.attachments=await Promise.all(e.attachments.map(async y=>{const m=await x(y,a);return{content:m.content,filename:m.filename,type:m.contentType}})));const i=await K(async()=>w(r.endpoint,{headers:{"Content-Type":"application/json","X-Api-Key":r.apiKey},method:"POST",timeout:r.timeout},JSON.stringify(n)),r.retries);if(!i.success)return{error:i.error??new p(a,"Failed to send email"),success:!1};const{body:d}=i.data;return{data:{messageId:d?.message_id??d?.request_id??v(),provider:a,response:i.data,sent:!0,timestamp:new Date},success:!0}}catch(s){return{error:A(a,"send email",s,h),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{N as default};
1
+ import p from"./EmailError-B-sEf3bp.js";import g from"./RequiredOptionError-DuNNY_a5.js";import{e as v}from"./generate-message-id-gXAuMz4g.js";import{s as b}from"./headers-to-record-De1Eg951.js";import{m as w}from"./make-request-BlK_B72c.js";import{u as K}from"./retry-3pnxTuNs.js";import{f as S}from"./validate-email-options-mCM9dVug.js";import{defineProvider as P}from"./defineProvider-C9q-7iwt.js";import{f as l,a as u}from"./address-formatter-BWR2Dddx.js";import{c as x}from"./attachment-processor-CMp7qqMI.js";import{h as A,P as T,c as j}from"./provider-base-C7PuopYK.js";const a="mailchannels",I="https://api.mailchannels.net/tx/v1/send",_=3e4,z=3,N=P((t={})=>{if(!t.apiKey)throw new g(a,"apiKey");const r={apiKey:t.apiKey,debug:t.debug??!1,endpoint:t.endpoint??I,logger:t.logger,retries:t.retries??z,timeout:t.timeout??_},f=new T,h=j(a,t.logger);return{features:{attachments:!0,batchSending:!1,customHeaders:!0,html:!0,replyTo:!0,scheduling:!1,tagging:!1,templates:!1,tracking:!1},async initialize(){f.setInitialized()},async isAvailable(){return r.apiKey.length>0},name:a,options:r,async sendEmail(e){try{const s=S(e);if(s.length>0)return{error:new p(a,`Invalid email options: ${s.join(", ")}`),success:!1};const o=[];e.text&&o.push({type:"text/plain",value:e.text}),e.html&&o.push({type:"text/html",value:e.html});const c={to:l(e.to)};e.cc&&(c.cc=l(e.cc)),e.bcc&&(c.bcc=l(e.bcc));const n={content:o,from:u(e.from),personalizations:[c],subject:e.subject};e.replyTo&&(n.reply_to=u(e.replyTo)),e.headers&&(n.headers=b(e.headers)),e.attachments&&e.attachments.length>0&&(n.attachments=await Promise.all(e.attachments.map(async y=>{const m=await x(y,a);return{content:m.content,filename:m.filename,type:m.contentType}})));const i=await K(async()=>w(r.endpoint,{headers:{"Content-Type":"application/json","X-Api-Key":r.apiKey},method:"POST",timeout:r.timeout},JSON.stringify(n)),r.retries);if(!i.success)return{error:i.error??new p(a,"Failed to send email"),success:!1};const{body:d}=i.data;return{data:{messageId:d?.message_id??d?.request_id??v(),provider:a,response:i.data,sent:!0,timestamp:new Date},success:!0}}catch(s){return{error:A(a,"send email",s,h),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{N as default};
@@ -0,0 +1 @@
1
+ import l from"./EmailError-B-sEf3bp.js";import y from"./RequiredOptionError-DuNNY_a5.js";import{e as b}from"./generate-message-id-gXAuMz4g.js";import{s as v}from"./headers-to-record-De1Eg951.js";import{m}from"./make-request-BlK_B72c.js";import{u as g}from"./retry-3pnxTuNs.js";import{f as w}from"./validate-email-options-mCM9dVug.js";import{defineProvider as I}from"./defineProvider-C9q-7iwt.js";import{P as A,h as f,c as T}from"./provider-base-C7PuopYK.js";import{f as u,a as k}from"./address-formatter-BWR2Dddx.js";import{p as P}from"./attachment-processor-CMp7qqMI.js";const r="mailersend",z="https://api.mailersend.com",C=3e4,S=3,O=I((n={})=>{if(!n.apiToken)throw new y(r,"apiToken");const i={apiToken:n.apiToken,debug:n.debug??!1,endpoint:n.endpoint??z,retries:n.retries??S,timeout:n.timeout??C,...n.logger&&{logger:n.logger}},c=new A,s=T(r,n.logger);return{features:{attachments:!0,batchSending:!0,customHeaders:!0,html:!0,replyTo:!0,scheduling:!0,tagging:!0,templates:!0,tracking:!0},async getEmail(e){try{if(!e)return{error:new l(r,"Email ID is required to retrieve email details"),success:!1};await c.ensureInitialized(()=>this.initialize(),r);const a={Authorization:`Bearer ${i.apiToken}`,"Content-Type":"application/json"};s.debug("Retrieving email details",{id:e});const t=await g(async()=>m(`${i.endpoint}/v1/activity/${e}`,{headers:a,method:"GET",timeout:i.timeout}),i.retries);return t.success?(s.debug("Email details retrieved successfully"),{data:t.data?.body,success:!0}):(s.debug("API request failed when retrieving email",t.error),{error:new l(r,`Failed to retrieve email: ${t.error instanceof Error?t.error.message:"Unknown error"}`,{cause:t.error}),success:!1})}catch(a){return{error:f(r,"retrieve email",a,s),success:!1}}},async initialize(){await c.ensureInitialized(async()=>{if(!await this.isAvailable())throw new l(r,"MailerSend API not available or invalid API token");s.debug("Provider initialized successfully")},r)},async isAvailable(){try{const e={Authorization:`Bearer ${i.apiToken}`,"Content-Type":"application/json"};s.debug("Checking MailerSend API availability");const a=await m(`${i.endpoint}/v1/tokens/verify`,{headers:e,method:"GET",timeout:i.timeout});return s.debug("MailerSend API availability check response:",{error:a.error instanceof Error?a.error.message:void 0,statusCode:a.data?.statusCode,success:a.success}),!!(a.success&&a.data&&typeof a.data=="object"&&"statusCode"in a.data&&typeof a.data.statusCode=="number"&&a.data.statusCode>=200&&a.data.statusCode<300)}catch(e){return s.debug("Error checking availability:",e),!1}},name:r,options:i,async sendEmail(e){try{const a=w(e);if(a.length>0)return{error:new l(r,`Invalid email options: ${a.join(", ")}`),success:!1};await c.ensureInitialized(()=>this.initialize(),r);const t={from:{email:e.from.email,name:e.from.name},subject:e.subject,to:u(e.to)};if(e.html&&(t.html=e.html),e.text&&(t.text=e.text),e.cc&&(t.cc=u(e.cc)),e.bcc&&(t.bcc=u(e.bcc)),e.replyTo&&(t.reply_to=k(e.replyTo)),e.templateId&&(t.template_id=e.templateId,e.templateVariables&&(t.variables=e.templateVariables)),e.personalization&&e.personalization.length>0&&(t.personalization=e.personalization),e.tags&&e.tags.length>0&&(t.tags=e.tags),e.scheduledAt&&(t.send_at=e.scheduledAt),e.domainId&&(t.domain_id=e.domainId),e.headers){const o=v(e.headers);t.headers=o}e.attachments&&e.attachments.length>0&&(t.attachments=await Promise.all(e.attachments.map(async o=>({content:await P(o,r),filename:o.filename,...o.contentType&&{type:o.contentType},...o.cid&&{id:o.cid}})))),s.debug("Sending email via MailerSend API",{subject:t.subject,to:t.to});const h={Authorization:`Bearer ${i.apiToken}`,"Content-Type":"application/json"},d=await g(async()=>m(`${i.endpoint}/v1/email`,{headers:h,method:"POST",timeout:i.timeout},JSON.stringify(t)),i.retries);if(!d.success)return s.debug("API request failed when sending email",d.error),{error:d.error??new l(r,"Failed to send email"),success:!1};const p=d.data?.body?.message_id??b();return s.debug("Email sent successfully",{messageId:p}),{data:{messageId:p,provider:r,response:d.data,sent:!0,timestamp:new Date},success:!0}}catch(a){return{error:f(r,"send email",a,s),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{O as default};
@@ -1 +1 @@
1
- import{createRequire as j}from"node:module";import m from"./EmailError-B-sEf3bp.js";import w from"./RequiredOptionError-DuNNY_a5.js";import{e as P}from"./generate-message-id-gXAuMz4g.js";import{s as R}from"./headers-to-record-De1Eg951.js";import{m as h}from"./make-request-BlK_B72c.js";import{u as T}from"./retry-3pnxTuNs.js";import{f as S}from"./validate-email-options-mCM9dVug.js";import{defineProvider as _}from"./defineProvider-C9q-7iwt.js";import{P as z,h as k,c as E}from"./provider-base-gIoUu9so.js";import{e as b,g as I}from"./address-formatter-BWR2Dddx.js";import{a as U}from"./attachment-processor-BjTNoMyb.js";const A=j(import.meta.url),u=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,C=s=>{if(typeof u<"u"&&u.versions&&u.versions.node){const[r,n]=u.versions.node.split(".").map(Number);if(r>22||r===22&&n>=3||r===20&&n>=16)return u.getBuiltinModule(s)}return A(s)},{Buffer:y}=C("node:buffer"),a="mailgun",q="https://api.mailgun.net",M=3e4,K=3,B=s=>{const r=[];for(const[n,i]of Object.entries(s))if(i!=null)if(Array.isArray(i))for(const e of i)r.push(`${encodeURIComponent(n)}=${encodeURIComponent(String(e))}`);else typeof i=="object"?r.push(`${encodeURIComponent(n)}=${encodeURIComponent(JSON.stringify(i))}`):r.push(`${encodeURIComponent(n)}=${encodeURIComponent(String(i))}`);return r.join("&")},X=_((s={})=>{if(!s.apiKey)throw new w(a,"apiKey");if(!s.domain)throw new w(a,"domain");const r={apiKey:s.apiKey,debug:s.debug??!1,domain:s.domain,endpoint:s.endpoint??q,retries:s.retries??K,timeout:s.timeout??M,...s.logger&&{logger:s.logger}},n=new z,i=E(a,s.logger);return{endpoint:r.endpoint,features:{attachments:!0,batchSending:!0,customHeaders:!0,html:!0,replyTo:!0,scheduling:!0,tagging:!0,templates:!0,tracking:!0},async getEmail(e){try{if(!e)return{error:new m(a,"Email ID is required to retrieve email details"),success:!1};await n.ensureInitialized(()=>this.initialize(),a);const o={Authorization:`Basic ${y.from(`api:${r.apiKey}`).toString("base64")}`,"Content-Type":"application/json"};i.debug("Retrieving email details",{id:e});const t=await T(async()=>h(`${r.endpoint}/v3/${r.domain}/events?message-id=${encodeURIComponent(e)}&limit=1`,{headers:o,method:"GET",timeout:r.timeout}),r.retries);if(!t.success)return i.debug("API request failed when retrieving email",t.error),{error:new m(a,`Failed to retrieve email: ${t.error instanceof Error?t.error.message:"Unknown error"}`,{cause:t.error}),success:!1};i.debug("Email details retrieved successfully");const p=t.data?.items??[],g=p.length>0?p[0]:void 0;return{data:g?.message?.headers??g?.storage??void 0,success:!0}}catch(o){return{error:k(a,"retrieve email",o,i),success:!1}}},async initialize(){await n.ensureInitialized(async()=>{if(!await this.isAvailable())throw new m(a,"Mailgun API not available or invalid API key/domain");i.debug("Provider initialized successfully")},a)},async isAvailable(){try{const e={Authorization:`Basic ${y.from(`api:${r.apiKey}`).toString("base64")}`,"Content-Type":"application/json"};i.debug("Checking Mailgun API availability");const o=await h(`${r.endpoint}/v3/domains/${r.domain}`,{headers:e,method:"GET",timeout:r.timeout});if(i.debug("Mailgun API availability check response:",{error:o.error instanceof Error?o.error.message:void 0,statusCode:o.data?.statusCode,success:o.success}),!o.success||!o.data||typeof o.data!="object")return!1;const{statusCode:t}=o.data;return typeof t=="number"&&t>=200&&t<300}catch(e){return i.debug("Error checking availability:",e),!1}},name:a,options:r,async sendEmail(e){try{const o=S(e);if(o.length>0)return{error:new m(a,`Invalid email options: ${o.join(", ")}`),success:!1};await n.ensureInitialized(()=>this.initialize(),a);const t={from:I(e.from),to:b(e.to).join(",")};if(e.subject&&(t.subject=e.subject),e.cc&&(t.cc=b(e.cc).join(",")),e.bcc&&(t.bcc=b(e.bcc).join(",")),e.replyTo&&(t["h:Reply-To"]=I(e.replyTo)),e.html&&(t.html=e.html),e.text&&(t.text=e.text),e.template&&(t.template=e.template,e.templateVariables))for(const[d,c]of Object.entries(e.templateVariables))t[`v:${d}`]=c;if(e.tags&&e.tags.length>0&&(t["o:tag"]=e.tags),e.campaignId&&(t["o:campaign"]=e.campaignId),e.deliveryTime&&(t["o:deliverytime"]=typeof e.deliveryTime=="number"?new Date(e.deliveryTime*1e3).toUTCString():e.deliveryTime),e.clickTracking!==void 0&&(t["o:clicktracking"]=e.clickTracking?"yes":"no"),e.openTracking!==void 0&&(t["o:tracking"]=e.openTracking?"yes":"no"),e.unsubscribeTracking!==void 0&&(t["o:tracking-clicks"]=e.unsubscribeTracking?"yes":"no"),e.testMode&&(t["o:testmode"]="yes"),e.requireTls&&(t["o:require-tls"]="yes"),e.skipVerification&&(t["o:skip-verification"]="yes"),e.headers){const d=R(e.headers);for(const[c,f]of Object.entries(d))t[`h:${c}`]=f}if(e.attachments&&e.attachments.length>0){const d=await Promise.all(e.attachments.map((c,f)=>U(c,a,f)));for(const c of d)t[c.key]=c.content}i.debug("Sending email via Mailgun API",{subject:t.subject,to:t.to});const p={Authorization:`Basic ${y.from(`api:${r.apiKey}`).toString("base64")}`,"Content-Type":"application/x-www-form-urlencoded"},g=B(t),l=await T(async()=>h(`${r.endpoint}/v3/${r.domain}/messages`,{headers:p,method:"POST",timeout:r.timeout},g),r.retries);if(!l.success)return i.debug("API request failed when sending email",l.error),{error:l.error??new m(a,"Failed to send email"),success:!1};const v=l.data?.body?.id??P();return i.debug("Email sent successfully",{messageId:v}),{data:{messageId:v,provider:a,response:l.data,sent:!0,timestamp:new Date},success:!0}}catch(o){return{error:k(a,"send email",o,i),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{X as default};
1
+ import{createRequire as j}from"node:module";import m from"./EmailError-B-sEf3bp.js";import w from"./RequiredOptionError-DuNNY_a5.js";import{e as P}from"./generate-message-id-gXAuMz4g.js";import{s as R}from"./headers-to-record-De1Eg951.js";import{m as h}from"./make-request-BlK_B72c.js";import{u as T}from"./retry-3pnxTuNs.js";import{f as S}from"./validate-email-options-mCM9dVug.js";import{defineProvider as _}from"./defineProvider-C9q-7iwt.js";import{P as z,h as k,c as E}from"./provider-base-C7PuopYK.js";import{e as b,g as I}from"./address-formatter-BWR2Dddx.js";import{a as U}from"./attachment-processor-CMp7qqMI.js";const A=j(import.meta.url),u=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,C=s=>{if(typeof u<"u"&&u.versions&&u.versions.node){const[r,n]=u.versions.node.split(".").map(Number);if(r>22||r===22&&n>=3||r===20&&n>=16)return u.getBuiltinModule(s)}return A(s)},{Buffer:y}=C("node:buffer"),a="mailgun",q="https://api.mailgun.net",M=3e4,K=3,B=s=>{const r=[];for(const[n,i]of Object.entries(s))if(i!=null)if(Array.isArray(i))for(const e of i)r.push(`${encodeURIComponent(n)}=${encodeURIComponent(String(e))}`);else typeof i=="object"?r.push(`${encodeURIComponent(n)}=${encodeURIComponent(JSON.stringify(i))}`):r.push(`${encodeURIComponent(n)}=${encodeURIComponent(String(i))}`);return r.join("&")},X=_((s={})=>{if(!s.apiKey)throw new w(a,"apiKey");if(!s.domain)throw new w(a,"domain");const r={apiKey:s.apiKey,debug:s.debug??!1,domain:s.domain,endpoint:s.endpoint??q,retries:s.retries??K,timeout:s.timeout??M,...s.logger&&{logger:s.logger}},n=new z,i=E(a,s.logger);return{endpoint:r.endpoint,features:{attachments:!0,batchSending:!0,customHeaders:!0,html:!0,replyTo:!0,scheduling:!0,tagging:!0,templates:!0,tracking:!0},async getEmail(e){try{if(!e)return{error:new m(a,"Email ID is required to retrieve email details"),success:!1};await n.ensureInitialized(()=>this.initialize(),a);const o={Authorization:`Basic ${y.from(`api:${r.apiKey}`).toString("base64")}`,"Content-Type":"application/json"};i.debug("Retrieving email details",{id:e});const t=await T(async()=>h(`${r.endpoint}/v3/${r.domain}/events?message-id=${encodeURIComponent(e)}&limit=1`,{headers:o,method:"GET",timeout:r.timeout}),r.retries);if(!t.success)return i.debug("API request failed when retrieving email",t.error),{error:new m(a,`Failed to retrieve email: ${t.error instanceof Error?t.error.message:"Unknown error"}`,{cause:t.error}),success:!1};i.debug("Email details retrieved successfully");const p=t.data?.items??[],g=p.length>0?p[0]:void 0;return{data:g?.message?.headers??g?.storage??void 0,success:!0}}catch(o){return{error:k(a,"retrieve email",o,i),success:!1}}},async initialize(){await n.ensureInitialized(async()=>{if(!await this.isAvailable())throw new m(a,"Mailgun API not available or invalid API key/domain");i.debug("Provider initialized successfully")},a)},async isAvailable(){try{const e={Authorization:`Basic ${y.from(`api:${r.apiKey}`).toString("base64")}`,"Content-Type":"application/json"};i.debug("Checking Mailgun API availability");const o=await h(`${r.endpoint}/v3/domains/${r.domain}`,{headers:e,method:"GET",timeout:r.timeout});if(i.debug("Mailgun API availability check response:",{error:o.error instanceof Error?o.error.message:void 0,statusCode:o.data?.statusCode,success:o.success}),!o.success||!o.data||typeof o.data!="object")return!1;const{statusCode:t}=o.data;return typeof t=="number"&&t>=200&&t<300}catch(e){return i.debug("Error checking availability:",e),!1}},name:a,options:r,async sendEmail(e){try{const o=S(e);if(o.length>0)return{error:new m(a,`Invalid email options: ${o.join(", ")}`),success:!1};await n.ensureInitialized(()=>this.initialize(),a);const t={from:I(e.from),to:b(e.to).join(",")};if(e.subject&&(t.subject=e.subject),e.cc&&(t.cc=b(e.cc).join(",")),e.bcc&&(t.bcc=b(e.bcc).join(",")),e.replyTo&&(t["h:Reply-To"]=I(e.replyTo)),e.html&&(t.html=e.html),e.text&&(t.text=e.text),e.template&&(t.template=e.template,e.templateVariables))for(const[d,c]of Object.entries(e.templateVariables))t[`v:${d}`]=c;if(e.tags&&e.tags.length>0&&(t["o:tag"]=e.tags),e.campaignId&&(t["o:campaign"]=e.campaignId),e.deliveryTime&&(t["o:deliverytime"]=typeof e.deliveryTime=="number"?new Date(e.deliveryTime*1e3).toUTCString():e.deliveryTime),e.clickTracking!==void 0&&(t["o:clicktracking"]=e.clickTracking?"yes":"no"),e.openTracking!==void 0&&(t["o:tracking"]=e.openTracking?"yes":"no"),e.unsubscribeTracking!==void 0&&(t["o:tracking-clicks"]=e.unsubscribeTracking?"yes":"no"),e.testMode&&(t["o:testmode"]="yes"),e.requireTls&&(t["o:require-tls"]="yes"),e.skipVerification&&(t["o:skip-verification"]="yes"),e.headers){const d=R(e.headers);for(const[c,f]of Object.entries(d))t[`h:${c}`]=f}if(e.attachments&&e.attachments.length>0){const d=await Promise.all(e.attachments.map((c,f)=>U(c,a,f)));for(const c of d)t[c.key]=c.content}i.debug("Sending email via Mailgun API",{subject:t.subject,to:t.to});const p={Authorization:`Basic ${y.from(`api:${r.apiKey}`).toString("base64")}`,"Content-Type":"application/x-www-form-urlencoded"},g=B(t),l=await T(async()=>h(`${r.endpoint}/v3/${r.domain}/messages`,{headers:p,method:"POST",timeout:r.timeout},g),r.retries);if(!l.success)return i.debug("API request failed when sending email",l.error),{error:l.error??new m(a,"Failed to send email"),success:!1};const v=l.data?.body?.id??P();return i.debug("Email sent successfully",{messageId:v}),{data:{messageId:v,provider:a,response:l.data,sent:!0,timestamp:new Date},success:!0}}catch(o){return{error:k(a,"send email",o,i),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{X as default};
@@ -0,0 +1 @@
1
+ import{createRequire as S}from"node:module";import u from"./EmailError-B-sEf3bp.js";import h from"./RequiredOptionError-DuNNY_a5.js";import{e as E}from"./generate-message-id-gXAuMz4g.js";import{s as M}from"./headers-to-record-De1Eg951.js";import{m as g}from"./make-request-BlK_B72c.js";import{u as b}from"./retry-3pnxTuNs.js";import{f as _}from"./validate-email-options-mCM9dVug.js";import{defineProvider as z}from"./defineProvider-C9q-7iwt.js";import{P as D,h as v,c as B}from"./provider-base-C7PuopYK.js";import{h as f,i as T}from"./address-formatter-BWR2Dddx.js";import{p as R}from"./attachment-processor-CMp7qqMI.js";const P=S(import.meta.url),d=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,A=s=>{if(typeof d<"u"&&d.versions&&d.versions.node){const[a,c]=d.versions.node.split(".").map(Number);if(a>22||a===22&&c>=3||a===20&&c>=16)return d.getBuiltinModule(s)}return P(s)},{Buffer:p}=A("node:buffer"),i="mailjet",k="https://api.mailjet.com",q=3e4,K=3,X=z((s={})=>{if(!s.apiKey)throw new h(i,"apiKey");if(!s.apiSecret)throw new h(i,"apiSecret");const a={apiKey:s.apiKey,apiSecret:s.apiSecret,debug:s.debug??!1,endpoint:s.endpoint??k,retries:s.retries??K,timeout:s.timeout??q,...s.logger&&{logger:s.logger}},c=new D,o=B(i,s.logger);return{endpoint:a.endpoint,features:{attachments:!0,batchSending:!0,customHeaders:!0,html:!0,replyTo:!0,scheduling:!0,tagging:!0,templates:!0,tracking:!0},async getEmail(e){try{if(!e)return{error:new u(i,"Email ID is required to retrieve email details"),success:!1};await c.ensureInitialized(()=>this.initialize(),i);const r={Authorization:`Basic ${p.from(`${a.apiKey}:${a.apiSecret}`).toString("base64")}`,"Content-Type":"application/json"};o.debug("Retrieving email details",{id:e});const t=await b(async()=>g(`${a.endpoint}/v3.1/REST/message/${e}`,{headers:r,method:"GET",timeout:a.timeout}),a.retries);return t.success?(o.debug("Email details retrieved successfully"),{data:t.data?.body,success:!0}):(o.debug("API request failed when retrieving email",t.error),{error:new u(i,`Failed to retrieve email: ${t.error instanceof Error?t.error.message:"Unknown error"}`,{cause:t.error}),success:!1})}catch(r){return{error:v(i,"retrieve email",r,o),success:!1}}},async initialize(){await c.ensureInitialized(async()=>{if(!await this.isAvailable())throw new u(i,"Mailjet API not available or invalid API credentials");o.debug("Provider initialized successfully")},i)},async isAvailable(){try{const e={Authorization:`Basic ${p.from(`${a.apiKey}:${a.apiSecret}`).toString("base64")}`,"Content-Type":"application/json"};o.debug("Checking Mailjet API availability");const r=await g(`${a.endpoint}/v3.1/REST/user`,{headers:e,method:"GET",timeout:a.timeout});return o.debug("Mailjet API availability check response:",{error:r.error instanceof Error?r.error.message:void 0,statusCode:r.data?.statusCode,success:r.success}),!!(r.success&&r.data&&typeof r.data=="object"&&"statusCode"in r.data&&typeof r.data.statusCode=="number"&&r.data.statusCode>=200&&r.data.statusCode<300)}catch(e){return o.debug("Error checking availability:",e),!1}},name:i,options:a,async sendEmail(e){try{const r=_(e);if(r.length>0)return{error:new u(i,`Invalid email options: ${r.join(", ")}`),success:!1};await c.ensureInitialized(()=>this.initialize(),i);const t={From:T(e.from),Subject:e.subject,To:f(e.to)};if(e.html&&(t.HTMLPart=e.html),e.text&&(t.TextPart=e.text),e.cc&&(t.Cc=f(e.cc)),e.bcc&&(t.Bcc=f(e.bcc)),e.replyTo&&(t.ReplyTo=T(e.replyTo)),e.templateId&&(t.TemplateID=e.templateId,t.TemplateLanguage=e.templateLanguage??!0,e.templateVariables&&(t.Variables=e.templateVariables)),e.customId&&(t.CustomID=e.customId),e.eventPayload&&(t.EventPayload=e.eventPayload),e.campaign&&(t.Campaign=e.campaign),e.deduplicateCampaign!==void 0&&(t.DeduplicateCampaign=e.deduplicateCampaign),e.deliveryTime&&(t.Deliverytime=new Date(e.deliveryTime*1e3).toISOString()),e.priority!==void 0&&(t.Priority=e.priority),e.urlTags&&(t.URLTags=e.urlTags),e.tags&&e.tags.length>0&&(t.CustomCampaign=e.tags.join(",")),e.headers){const n=M(e.headers),m=[];for(const[C,I]of Object.entries(n))m.push({Name:C,Value:String(I)});m.length>0&&(t.Headers=m)}e.attachments&&e.attachments.length>0&&(t.Attachments=await Promise.all(e.attachments.map(async n=>({Base64Content:await R(n,i),ContentType:n.contentType??"application/octet-stream",Filename:n.filename,...n.cid&&{ContentID:n.cid}}))));const j={Messages:[t]};o.debug("Sending email via Mailjet API",{subject:t.Subject,to:t.To});const w={Authorization:`Basic ${p.from(`${a.apiKey}:${a.apiSecret}`).toString("base64")}`,"Content-Type":"application/json"},l=await b(async()=>g(`${a.endpoint}/v3.1/send`,{headers:w,method:"POST",timeout:a.timeout},JSON.stringify(j)),a.retries);if(!l.success)return o.debug("API request failed when sending email",l.error),{error:l.error??new u(i,"Failed to send email"),success:!1};const y=l.data?.body?.Messages?.[0]?.To?.[0]?.MessageID?.toString()??E();return o.debug("Email sent successfully",{messageId:y}),{data:{messageId:y,provider:i,response:l.data,sent:!0,timestamp:new Date},success:!0}}catch(r){return{error:v(i,"send email",r,o),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{X as default};
@@ -0,0 +1 @@
1
+ import c from"./EmailError-B-sEf3bp.js";import b from"./RequiredOptionError-DuNNY_a5.js";import{e as v}from"./generate-message-id-gXAuMz4g.js";import{s as w}from"./headers-to-record-De1Eg951.js";import{m as g}from"./make-request-BlK_B72c.js";import{u as f}from"./retry-3pnxTuNs.js";import{f as I}from"./validate-email-options-mCM9dVug.js";import{defineProvider as P}from"./defineProvider-C9q-7iwt.js";import{P as A,h,c as T}from"./provider-base-C7PuopYK.js";import{f as d,a as E}from"./address-formatter-BWR2Dddx.js";import{p as K}from"./attachment-processor-CMp7qqMI.js";const a="mailomat",S="https://api.mailomat.com",j=3e4,k=3,X=P((i={})=>{if(!i.apiKey)throw new b(a,"apiKey");const s={apiKey:i.apiKey,debug:i.debug??!1,endpoint:i.endpoint??S,retries:i.retries??k,timeout:i.timeout??j,...i.logger&&{logger:i.logger}},m=new A,r=T(a,i.logger);return{features:{attachments:!0,batchSending:!0,customHeaders:!0,html:!0,replyTo:!0,scheduling:!1,tagging:!0,templates:!0,tracking:!0},async getEmail(e){try{if(!e)return{error:new c(a,"Email ID is required to retrieve email details"),success:!1};await m.ensureInitialized(()=>this.initialize(),a);const o={"Content-Type":"application/json","X-API-Key":s.apiKey};r.debug("Retrieving email details",{id:e});const t=await f(async()=>g(`${s.endpoint}/emails/${e}`,{headers:o,method:"GET",timeout:s.timeout}),s.retries);return t.success?(r.debug("Email details retrieved successfully"),{data:t.data?.body,success:!0}):(r.debug("API request failed when retrieving email",t.error),{error:new c(a,`Failed to retrieve email: ${t.error instanceof Error?t.error.message:"Unknown error"}`,{cause:t.error}),success:!1})}catch(o){return{error:h(a,"retrieve email",o,r),success:!1}}},async initialize(){await m.ensureInitialized(async()=>{if(!await this.isAvailable())throw new c(a,"Mailomat API not available or invalid API key");r.debug("Provider initialized successfully")},a)},async isAvailable(){try{return r.debug("Checking Mailomat API availability"),!0}catch(e){return r.debug("Error checking availability:",e),!1}},name:a,options:s,async sendEmail(e){try{const o=I(e);if(o.length>0)return{error:new c(a,`Invalid email options: ${o.join(", ")}`),success:!1};await m.ensureInitialized(()=>this.initialize(),a);const t={from:{email:e.from.email,name:e.from.name},subject:e.subject,to:d(e.to)};if(e.html&&(t.html=e.html),e.text&&(t.text=e.text),e.cc&&(t.cc=d(e.cc)),e.bcc&&(t.bcc=d(e.bcc)),e.replyTo&&(t.replyTo=E(e.replyTo)),e.templateId&&(t.templateId=e.templateId,e.templateVariables&&(t.templateVariables=e.templateVariables)),e.tags&&e.tags.length>0&&(t.tags=e.tags),e.headers){const n=w(e.headers);t.headers=n}e.attachments&&e.attachments.length>0&&(t.attachments=await Promise.all(e.attachments.map(async n=>({content:await K(n,a),contentType:n.contentType??"application/octet-stream",filename:n.filename,...n.cid&&{cid:n.cid}})))),r.debug("Sending email via Mailomat API",{subject:t.subject,to:t.to});const y={"Content-Type":"application/json","X-API-Key":s.apiKey},l=await f(async()=>g(`${s.endpoint}/send`,{headers:y,method:"POST",timeout:s.timeout},JSON.stringify(t)),s.retries);if(!l.success)return r.debug("API request failed when sending email",l.error),{error:l.error??new c(a,"Failed to send email"),success:!1};const u=l.data?.body,p=u?.messageId??u?.id??v();return r.debug("Email sent successfully",{messageId:p}),{data:{messageId:p,provider:a,response:l.data,sent:!0,timestamp:new Date},success:!0}}catch(o){return{error:h(a,"send email",o,r),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{X as default};