@visulima/email 2.0.0 → 2.1.1

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 (81) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/README.md +48 -5
  3. package/dist/index.js +1 -1
  4. package/dist/middleware/index.d.ts +9 -2
  5. package/dist/middleware/index.js +1 -1
  6. package/dist/packem_shared/{Mail-C1zp-fqt.js → Mail-CYAwMRnX.js} +1 -1
  7. package/dist/packem_shared/{ahaSendProvider-D81_wUA1.js → ahaSendProvider-DSuZIzaQ.js} +1 -1
  8. package/dist/packem_shared/autoSendProvider-DqAoelWR.js +1 -0
  9. package/dist/packem_shared/{awsSesProvider-BGZJUIep.js → awsSesProvider-ClK1FUln.js} +1 -1
  10. package/dist/packem_shared/{azureProvider-CmcK4bsf.js → azureProvider-Cw_Tmde6.js} +1 -1
  11. package/dist/packem_shared/{brevoProvider-C1BDXr41.js → brevoProvider-CIzuIDlt.js} +1 -1
  12. package/dist/packem_shared/{build-mime-message-B6927SQy.js → build-mime-message-BW5FQ2Bt.js} +1 -1
  13. package/dist/packem_shared/{cloudflareEmailProvider-Bv-ty-74.js → cloudflareEmailProvider-B8mOEl3N.js} +1 -1
  14. package/dist/packem_shared/create-token-cache-D56KQGVQ.js +1 -0
  15. package/dist/packem_shared/{createTestEmail-D3XPGiHY.js → createTestEmail-f12yLlWn.js} +1 -1
  16. package/dist/packem_shared/{httpProvider-DJAsYSun.js → httpProvider-aBfTXyCT.js} +1 -1
  17. package/dist/packem_shared/{infobipProvider-lHyGrXgZ.js → infobipProvider-DxzsONUX.js} +1 -1
  18. package/dist/packem_shared/{loopsProvider-DyloxzNC.js → loopsProvider-QBsAH6Ee.js} +1 -1
  19. package/dist/packem_shared/{mailCrabProvider-CPtBT6Th.js → mailCrabProvider-DRE5snM9.js} +1 -1
  20. package/dist/packem_shared/{mailPaceProvider-CJEvOFBh.js → mailPaceProvider-DCa-4ghl.js} +1 -1
  21. package/dist/packem_shared/{mailchannelsProvider-osRkW_tz.js → mailchannelsProvider-GiwkYBdD.js} +1 -1
  22. package/dist/packem_shared/{mailerSendProvider-C_6LzARK.js → mailerSendProvider-RK6IbUrL.js} +1 -1
  23. package/dist/packem_shared/{mailgunProvider-DkISvMPe.js → mailgunProvider-D9HUWGKN.js} +1 -1
  24. package/dist/packem_shared/{mailjetProvider-CV0i4Xzh.js → mailjetProvider-DelLs2Vt.js} +1 -1
  25. package/dist/packem_shared/{mailomatProvider-B5YFonEO.js → mailomatProvider-DPDpVS8r.js} +1 -1
  26. package/dist/packem_shared/{mailtrapProvider-C4ZquIPz.js → mailtrapProvider-DtrS4Q34.js} +1 -1
  27. package/dist/packem_shared/make-request-B9XjBynA.js +1 -0
  28. package/dist/packem_shared/{mandrillProvider-DWPFh_Sj.js → mandrillProvider-B84zH-eV.js} +1 -1
  29. package/dist/packem_shared/{netcoreProvider-C5TEciaN.js → netcoreProvider-D-wtCyJj.js} +1 -1
  30. package/dist/packem_shared/oauth2Middleware-DQh-hIkv.js +1 -0
  31. package/dist/packem_shared/outlook365Provider-Btk4Emig.js +1 -0
  32. package/dist/packem_shared/{plunkProvider-yTlrJVEp.js → plunkProvider-Bw8e6460.js} +1 -1
  33. package/dist/packem_shared/{postalProvider-CRX_bMYD.js → postalProvider-CT8zr89z.js} +1 -1
  34. package/dist/packem_shared/{postmarkProvider-CDx85Yge.js → postmarkProvider-CQSqZWDs.js} +1 -1
  35. package/dist/packem_shared/{resendProvider-CiclWxzr.js → resendProvider-drJYlvLP.js} +1 -1
  36. package/dist/packem_shared/retry-ipI5DRJ8.js +1 -0
  37. package/dist/packem_shared/{sanitize-header-DJhgZl3y.js → sanitize-header-DtQwAnzg.js} +1 -1
  38. package/dist/packem_shared/{scalewayProvider-BcND48qO.js → scalewayProvider-DU5gXQrl.js} +1 -1
  39. package/dist/packem_shared/{sendGridProvider-D8ZLgY62.js → sendGridProvider-BuTbEXW8.js} +1 -1
  40. package/dist/packem_shared/{smtpProvider-Bm0yP97W.js → smtpProvider-5MI3-EPh.js} +1 -1
  41. package/dist/packem_shared/{sparkpostProvider-CTYfSRaV.js → sparkpostProvider-UAsFYIjP.js} +1 -1
  42. package/dist/packem_shared/{sweegoProvider-DOoin_vi.js → sweegoProvider-SUz0LIcA.js} +1 -1
  43. package/dist/packem_shared/{zeptomailProvider-DKBPSHPj.js → zeptomailProvider-DXNX9mG_.js} +1 -1
  44. package/dist/providers/ahasend/index.js +1 -1
  45. package/dist/providers/autosend/index.d.ts +56 -0
  46. package/dist/providers/autosend/index.js +1 -0
  47. package/dist/providers/aws-ses/index.js +1 -1
  48. package/dist/providers/azure/index.js +1 -1
  49. package/dist/providers/brevo/index.js +1 -1
  50. package/dist/providers/cloudflare-email/index.js +1 -1
  51. package/dist/providers/http/index.js +1 -1
  52. package/dist/providers/infobip/index.js +1 -1
  53. package/dist/providers/loops/index.js +1 -1
  54. package/dist/providers/mailchannels/index.js +1 -1
  55. package/dist/providers/mailcrab/index.js +1 -1
  56. package/dist/providers/mailersend/index.js +1 -1
  57. package/dist/providers/mailgun/index.js +1 -1
  58. package/dist/providers/mailjet/index.js +1 -1
  59. package/dist/providers/mailomat/index.js +1 -1
  60. package/dist/providers/mailpace/index.js +1 -1
  61. package/dist/providers/mailtrap/index.js +1 -1
  62. package/dist/providers/mandrill/index.js +1 -1
  63. package/dist/providers/netcore/index.js +1 -1
  64. package/dist/providers/outlook365/index.d.ts +83 -5
  65. package/dist/providers/outlook365/index.js +1 -1
  66. package/dist/providers/plunk/index.js +1 -1
  67. package/dist/providers/postal/index.js +1 -1
  68. package/dist/providers/postmark/index.js +1 -1
  69. package/dist/providers/resend/index.js +1 -1
  70. package/dist/providers/scaleway/index.js +1 -1
  71. package/dist/providers/sendgrid/index.js +1 -1
  72. package/dist/providers/smtp/index.js +1 -1
  73. package/dist/providers/sparkpost/index.js +1 -1
  74. package/dist/providers/sweego/index.js +1 -1
  75. package/dist/providers/zeptomail/index.js +1 -1
  76. package/dist/test/index.js +1 -1
  77. package/package.json +5 -1
  78. package/dist/packem_shared/make-request-BlK_B72c.js +0 -1
  79. package/dist/packem_shared/oauth2Middleware-CodqXkyj.js +0 -1
  80. package/dist/packem_shared/outlook365Provider-63ggDpqV.js +0 -1
  81. package/dist/packem_shared/retry-3pnxTuNs.js +0 -1
package/CHANGELOG.md CHANGED
@@ -1,6 +1,60 @@
1
+ ## @visulima/email [2.1.1](https://github.com/visulima/visulima/compare/%40visulima%2Femail%402.1.0...%40visulima%2Femail%402.1.1) (2026-07-17)
2
+
3
+
4
+ ### Dependencies
5
+
6
+ * **@visulima/fs:** upgraded to 5.0.4
7
+
8
+ ## @visulima/email [2.1.0](https://github.com/visulima/visulima/compare/%40visulima%2Femail%402.0.0...%40visulima%2Femail%402.1.0) (2026-07-17)
9
+
10
+
11
+ ### Dependencies
12
+
13
+ * **@visulima/fs:** upgraded to 5.0.3
14
+
1
15
  ## @visulima/email [2.0.0](https://github.com/visulima/visulima/compare/%40visulima%2Femail%401.0.1...%40visulima%2Femail%402.0.0) (2026-07-15)
2
16
 
3
17
 
18
+ ### ⚠ BREAKING CHANGES
19
+
20
+ * **email:** the `@visulima/email/render` barrel and the `postProcessHtml` helper (with `PostProcessOptions`) have been removed, and the CSS inliner now resolves the optional `juice` peer at import time.
21
+
22
+ **Why:** importing `@visulima/email` eagerly evaluated `createRequire(import.meta.url)` from the render `css-inline` module, which the bundler folds into the shared chunk that the package root pulls. In bundled non-Node runtimes (Cloudflare Workers/workerd, Vite production builds) `import.meta.url` is `undefined`, so the worker crashed at boot — before serving any request — even for consumers that never inline CSS ([#723](https://github.com/visulima/visulima/issues/723)).
23
+
24
+ **Migration:**
25
+
26
+ 1. Import each render helper from its own subpath instead of the removed `@visulima/email/render` barrel:
27
+
28
+ ```diff
29
+ - import { injectPreheader, addDarkModeSupport, rewriteCidLinks, extractCidReferences } from "@visulima/email/render";
30
+ + import { injectPreheader } from "@visulima/email/render/preheader";
31
+ + import { addDarkModeSupport } from "@visulima/email/render/dark-mode";
32
+ + import { rewriteCidLinks, extractCidReferences } from "@visulima/email/render/cid";
33
+ ```
34
+
35
+ 2. Replace `postProcessHtml(...)` by composing the helpers yourself (order: inline CSS → preheader → dark-mode → CID rewrite):
36
+
37
+ ```diff
38
+ - import { postProcessHtml } from "@visulima/email/render";
39
+ -
40
+ - const out = postProcessHtml(html, { inlineCss: true, preheader: "Hi", darkMode: true });
41
+ + import inlineCss from "@visulima/email/render/css-inline";
42
+ + import { injectPreheader } from "@visulima/email/render/preheader";
43
+ + import { addDarkModeSupport } from "@visulima/email/render/dark-mode";
44
+ +
45
+ + const out = addDarkModeSupport(injectPreheader(inlineCss(html), "Hi"));
46
+ ```
47
+
48
+ Read the nesting inside-out to follow the pipeline order: `inlineCss` runs first, then `injectPreheader`, then `addDarkModeSupport`. CID rewriting is intentionally omitted here because the original `postProcessHtml` call set no `cidResolver`; if you used one, apply it as the outermost call — `rewriteCidLinks(out, resolver)`.
49
+
50
+ 3. `inlineCss` now lives at `@visulima/email/render/css-inline` (default export) and imports `juice` eagerly. Install the optional peer (`pnpm add juice`) before importing it — a missing peer now surfaces as a module-resolution error at import time rather than an `EmailError` on first call. Import it only where you actually inline CSS so `juice` (a Node-only library) stays out of edge/worker bundles.
51
+
52
+
53
+ ### Bug Fixes
54
+
55
+ * **email:** make render exports worker-safe ([#726](https://github.com/visulima/visulima/pull/726)) ([2d09b49](https://github.com/visulima/visulima/commit/2d09b4985e78c71c208b12b3507659b9ab5594cf))
56
+
57
+
4
58
  ### Dependencies
5
59
 
6
60
  * **@visulima/fs:** upgraded to 5.0.2
package/README.md CHANGED
@@ -341,6 +341,33 @@ const roundRobin = roundRobinProvider({
341
341
 
342
342
  **Note:** The round-robin provider starts at a random provider and then rotates through providers for each subsequent email. If a provider is unavailable, it will automatically try the next provider in the rotation.
343
343
 
344
+ ### AutoSend Provider
345
+
346
+ AutoSend is a transactional and marketing email service with volume-based pricing. Universal runtime (Fetch API).
347
+
348
+ ```typescript
349
+ import { createMail } from "@visulima/email";
350
+ import { autoSendProvider } from "@visulima/email/providers/autosend";
351
+
352
+ const mail = createMail(
353
+ autoSendProvider({
354
+ apiKey: process.env.AUTOSEND_API_KEY,
355
+ }),
356
+ );
357
+
358
+ await mail.send({
359
+ from: { email: "hello@mail.yourdomain.com", name: "Your Company" },
360
+ to: { email: "customer@example.com", name: "Jane Doe" },
361
+ subject: "Welcome!",
362
+ html: "<h1>Thanks for signing up.</h1>",
363
+ // AutoSend-specific: templateId, dynamicData, trackingOpen, trackingClick,
364
+ // unsubscribeGroupId, bypassSuppressions
365
+ });
366
+ ```
367
+
368
+ AutoSend's send endpoint takes a **single** `to` recipient (max 50 across to/cc/bcc). Passing several
369
+ is rejected rather than silently truncated.
370
+
344
371
  ### Mailgun Provider
345
372
 
346
373
  Mailgun is a developer-friendly email API service built for transactional emails and automated messaging.
@@ -955,16 +982,32 @@ await mail.send({
955
982
 
956
983
  ### Outlook365 Provider
957
984
 
958
- Sends through Microsoft Graph `sendMail`. Universal runtime (Fetch API). Bring your own OAuth2 token (`Mail.Send` scope)
959
- via `accessToken` or `getAccessToken` no auth SDK is bundled.
985
+ Sends through Microsoft Graph `sendMail`. Universal runtime (Fetch API). No auth SDK is bundled authenticate with
986
+ the built-in app-only (client credentials) or delegated (refresh token) flow, or bring your own OAuth2 token
987
+ (`Mail.Send` scope) via `accessToken` / `getAccessToken`.
960
988
 
961
989
  ```typescript
962
- import { createMail, outlook365Provider } from "@visulima/email/providers/outlook365";
990
+ import { createMail } from "@visulima/email";
991
+ import { outlook365Provider } from "@visulima/email/providers/outlook365";
963
992
 
993
+ // App-only (client credentials) — userId is required, app-only tokens have no "me" mailbox.
964
994
  const mail = createMail(
965
995
  outlook365Provider({
966
- getAccessToken: async () => getGraphAccessToken(),
967
- userId: "sender@contoso.com", // or "me" (default)
996
+ tenantId: process.env.AZURE_TENANT_ID,
997
+ clientId: process.env.AZURE_CLIENT_ID,
998
+ clientSecret: process.env.AZURE_CLIENT_SECRET,
999
+ userId: "sender@contoso.com",
1000
+ }),
1001
+ );
1002
+
1003
+ // Delegated (refresh token) — sends as the consenting user.
1004
+ const delegated = createMail(
1005
+ outlook365Provider({
1006
+ tenantId: process.env.AZURE_TENANT_ID,
1007
+ clientId: process.env.AZURE_CLIENT_ID,
1008
+ refreshToken: await loadRefreshToken(),
1009
+ // Azure AD may rotate the refresh token; this is awaited before the token is used.
1010
+ onRefreshToken: async (token) => saveRefreshToken(token),
968
1011
  }),
969
1012
  );
970
1013
 
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{detectMimeType as a,generateContentId as t,readFileAsBuffer as o}from"./packem_shared/detectMimeType-DFH3kp6K.js";import{default as p}from"./packem_shared/DraftMailMessage-CGTVuy2z.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-C1zp-fqt.js";import{default as M}from"./packem_shared/MailMessage-DQRgs5Dz.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};
1
+ import{detectMimeType as a,generateContentId as t,readFileAsBuffer as o}from"./packem_shared/detectMimeType-DFH3kp6K.js";import{default as p}from"./packem_shared/DraftMailMessage-CGTVuy2z.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-CYAwMRnX.js";import{default as M}from"./packem_shared/MailMessage-DQRgs5Dz.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};
@@ -150,9 +150,9 @@ interface MetricsMiddlewareOptions {
150
150
  */
151
151
  declare const withMetrics: (recorder: MetricsRecorder, options?: MetricsMiddlewareOptions) => Middleware;
152
152
  /**
153
- * An OAuth2 access token plus its expiry.
153
+ * A token that may carry an absolute expiry.
154
154
  */
155
- interface OAuth2Token {
155
+ interface CacheableToken {
156
156
  /**
157
157
  * The bearer access token.
158
158
  */
@@ -163,6 +163,13 @@ interface OAuth2Token {
163
163
  expiresAt?: number;
164
164
  }
165
165
  /**
166
+ * Options for {@link createTokenCache}.
167
+ */
168
+ /**
169
+ * An OAuth2 access token plus its expiry.
170
+ */
171
+ type OAuth2Token = CacheableToken;
172
+ /**
166
173
  * Options for the {@link oauth2Middleware}.
167
174
  */
168
175
  interface OAuth2MiddlewareOptions {
@@ -1 +1 @@
1
- import{circuitBreakerMiddleware as o}from"../packem_shared/circuitBreakerMiddleware-D2SA_07f.js";import{dedupeMiddleware as i}from"../packem_shared/dedupeMiddleware-B6ajWOTi.js";import{withEvents as p}from"../packem_shared/withEvents-CCVblSqj.js";import{loggingMiddleware as f}from"../packem_shared/loggingMiddleware-CZIiVMVp.js";import{withMetrics as w}from"../packem_shared/withMetrics-DWywX_6M.js";import{oauth2Middleware as l}from"../packem_shared/oauth2Middleware-CodqXkyj.js";import{RATE_LIMIT_PRESETS as h,rateLimitMiddleware as s}from"../packem_shared/RATE_LIMIT_PRESETS-BPADLgcA.js";import{default as c}from"../packem_shared/withRender-VP9wE5Yr.js";import{retryMiddleware as E}from"../packem_shared/retryMiddleware-DbViDX4r.js";import{withSuppression as g}from"../packem_shared/withSuppression-DBaZDMAr.js";import{withTelemetry as S}from"../packem_shared/withTelemetry-DL2qo0Hp.js";import{composeMiddleware as I}from"../packem_shared/composeMiddleware-BHwLLEzK.js";export{h as RATE_LIMIT_PRESETS,o as circuitBreakerMiddleware,I as composeMiddleware,i as dedupeMiddleware,f as loggingMiddleware,l as oauth2Middleware,s as rateLimitMiddleware,E as retryMiddleware,p as withEvents,w as withMetrics,c as withRender,g as withSuppression,S as withTelemetry};
1
+ import{circuitBreakerMiddleware as o}from"../packem_shared/circuitBreakerMiddleware-D2SA_07f.js";import{dedupeMiddleware as i}from"../packem_shared/dedupeMiddleware-B6ajWOTi.js";import{withEvents as p}from"../packem_shared/withEvents-CCVblSqj.js";import{loggingMiddleware as f}from"../packem_shared/loggingMiddleware-CZIiVMVp.js";import{withMetrics as w}from"../packem_shared/withMetrics-DWywX_6M.js";import{oauth2Middleware as l}from"../packem_shared/oauth2Middleware-DQh-hIkv.js";import{RATE_LIMIT_PRESETS as h,rateLimitMiddleware as s}from"../packem_shared/RATE_LIMIT_PRESETS-BPADLgcA.js";import{default as c}from"../packem_shared/withRender-VP9wE5Yr.js";import{retryMiddleware as E}from"../packem_shared/retryMiddleware-DbViDX4r.js";import{withSuppression as g}from"../packem_shared/withSuppression-DBaZDMAr.js";import{withTelemetry as S}from"../packem_shared/withTelemetry-DL2qo0Hp.js";import{composeMiddleware as I}from"../packem_shared/composeMiddleware-BHwLLEzK.js";export{h as RATE_LIMIT_PRESETS,o as circuitBreakerMiddleware,I as composeMiddleware,i as dedupeMiddleware,f as loggingMiddleware,l as oauth2Middleware,s as rateLimitMiddleware,E as retryMiddleware,p as withEvents,w as withMetrics,c as withRender,g as withSuppression,S as withTelemetry};
@@ -1 +1 @@
1
- import h from"./DraftMailMessage-CGTVuy2z.js";import v from"./EmailError-B-sEf3bp.js";import f from"./MailMessage-DQRgs5Dz.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};
1
+ import h from"./DraftMailMessage-CGTVuy2z.js";import v from"./EmailError-B-sEf3bp.js";import f from"./MailMessage-DQRgs5Dz.js";import{composeMiddleware as C}from"./composeMiddleware-BHwLLEzK.js";import{F as w}from"./build-mime-message-BW5FQ2Bt.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};
@@ -1 +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
+ 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-B9XjBynA.js";import{i as g}from"./retry-ipI5DRJ8.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};
@@ -0,0 +1 @@
1
+ import c from"./EmailError-B-sEf3bp.js";import T from"./RequiredOptionError-DuNNY_a5.js";import{s as x}from"./headers-to-record-De1Eg951.js";import{m as z}from"./make-request-B9XjBynA.js";import{i as K}from"./retry-ipI5DRJ8.js";import{s as P,a as G}from"./sanitize-header-DtQwAnzg.js";import{f as C}from"./validate-email-options-mCM9dVug.js";import{defineProvider as E}from"./defineProvider-C9q-7iwt.js";import{a as y,f as w}from"./address-formatter-BWR2Dddx.js";import{h as q,P as D,c as B}from"./provider-base-C7PuopYK.js";import{c as F}from"./attachment-processor-CMp7qqMI.js";const n="autosend",H="https://api.autosend.com/v1",N=3e4,R=3,v=50,$=20,A=40*1024*1024,k=20,I=1e3,j=998,Z=/^[A-Z0-9-]{1,76}$/i,J="^[A-Za-z0-9-]{1,76}$",L="Either text or html content is required",g=t=>[t].flat(),V=async t=>{const s=await F(t,n);return{content:s.content,contentType:s.contentType,fileName:s.filename}},U=(t,s)=>{const i=g(t.to);if(i.length!==1)return`AutoSend's send endpoint takes exactly one 'to' recipient, but ${String(i.length)} were given — use 'cc'/'bcc', or send one message per recipient`;const o=i.length+(t.cc?g(t.cc).length:0)+(t.bcc?g(t.bcc).length:0);if(o>v)return`AutoSend allows at most ${String(v)} recipients across to/cc/bcc, but ${String(o)} were given`;if(t.attachments&&t.attachments.length>$)return`AutoSend allows at most ${String($)} attachments, but ${String(t.attachments.length)} were given`;const e=t.attachments?.find(r=>r.cid);if(e)return`AutoSend does not support inline (cid) attachments, but '${e.filename}' sets one — host the image and reference it by URL instead`;if(t.subject.length>j)return`AutoSend allows a subject of at most ${String(j)} characters, but ${String(t.subject.length)} were given`;const a=Object.keys(s);if(a.length>k)return`AutoSend allows at most ${String(k)} custom headers, but ${String(a.length)} were given`;const d=a.find(r=>!Z.test(r));if(d!==void 0)return`AutoSend header names must match ${J}, but '${d}' does not`;const u=a.find(r=>s[r].length>I);if(u!==void 0)return`AutoSend allows header values of at most ${String(I)} characters, but '${u}' is longer`},X=t=>{if(typeof t!="object"||t===null)return{};const s=t;if(s.success===!0)return{emailId:typeof s.data?.emailId=="string"?s.data.emailId:void 0};const i=[s.message,s.error].find(o=>typeof o=="string");return{reason:typeof i=="string"?i:void 0}},ie=E((t={})=>{if(!t.apiKey)throw new T(n,"apiKey");const s={apiKey:t.apiKey,debug:t.debug??!1,endpoint:t.endpoint??H,logger:t.logger,retries:t.retries??R,timeout:t.timeout??N},i=new D,o=B(n,t.logger);return{features:{attachments:!0,batchSending:!1,customHeaders:!0,html:!0,replyTo:!0,scheduling:!1,tagging:!1,templates:!0,tracking:!0},async initialize(){i.setInitialized()},async isAvailable(){return s.apiKey.length>0},name:n,options:s,async sendEmail(e){try{const a=C(e).filter(l=>!(e.templateId!==void 0&&l===L));if(a.length>0)return{error:new c(n,`Invalid email options: ${a.join(", ")}`),success:!1};const d=e.headers?x(e.headers):{},u=U(e,d);if(u)return{error:new c(n,u),success:!1};const r={from:y(e.from),subject:e.subject,to:y(g(e.to)[0])};if(e.templateId?r.templateId=e.templateId:(e.html&&(r.html=e.html),e.text&&(r.text=e.text)),e.cc&&(r.cc=w(e.cc)),e.bcc&&(r.bcc=w(e.bcc)),e.replyTo&&(r.replyTo=y(e.replyTo)),e.dynamicData&&(r.dynamicData=e.dynamicData),e.unsubscribeGroupId&&(r.unsubscribeGroupId=e.unsubscribeGroupId),e.trackingClick!==void 0&&(r.trackingClick=e.trackingClick),e.trackingOpen!==void 0&&(r.trackingOpen=e.trackingOpen),e.bypassSuppressions!==void 0&&(r.bypassSuppressions=e.bypassSuppressions),Object.keys(d).length>0&&(r.headers=Object.fromEntries(Object.entries(d).map(([l,p])=>[P(l),G(p)]))),e.attachments&&e.attachments.length>0){const l=await Promise.all(e.attachments.map(async b=>V(b))),p=l.reduce((b,O)=>b+O.content.length,0);if(p>A)return{error:new c(n,`AutoSend allows at most ${String(A)} bytes of attachments after Base64 encoding, but this message carries ${String(p)}`),success:!1};r.attachments=l}const f=await K(async()=>z(`${s.endpoint}/mails/send`,{headers:{Authorization:`Bearer ${s.apiKey}`,"Content-Type":"application/json"},method:"POST",timeout:s.timeout},JSON.stringify(r)),s.retries),S=f.data?.body,{emailId:h,reason:m}=X(S);return f.success?m?{error:new c(n,`Failed to send email: ${m}`),success:!1}:h?(o.debug(`Email queued successfully: ${h}`),{data:{messageId:h,provider:n,response:S,sent:!0,timestamp:new Date},success:!0}):{error:new c(n,"AutoSend accepted the message but returned no emailId"),success:!1}:{error:m?new c(n,`Failed to send email: ${m}`):f.error??new c(n,"Failed to send email"),success:!1}}catch(a){return{error:q(n,"send email",a,o),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{ie as default};
@@ -1,4 +1,4 @@
1
- import{createRequire as D}from"node:module";import E from"./EmailError-B-sEf3bp.js";import L from"./RequiredOptionError-DuNNY_a5.js";import{c as F}from"./create-logger-BQTS3f-I.js";import f from"../utils/format-email-address.js";import{s as G}from"./headers-to-record-De1Eg951.js";import{m as Q}from"./make-request-BlK_B72c.js";import{s as q,a as X}from"./sanitize-header-DJhgZl3y.js";import{f as Y}from"./validate-email-options-mCM9dVug.js";import{defineProvider as Z}from"./defineProvider-C9q-7iwt.js";const N=D(import.meta.url),A=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,V=y=>{if(typeof A<"u"&&A.versions&&A.versions.node){const[a,d]=A.versions.node.split(".").map(Number);if(a>22||a===22&&d>=3||a===20&&d>=16)return A.getBuiltinModule(y)}return N(y)},{randomUUID:v,createHash:R,createHmac:$}=V("node:crypto"),J=globalThis.Buffer!==void 0,I=()=>{if(!J)throw new Error("Buffer is required for AWS SES provider");return globalThis.Buffer},h="aws-ses",j={apiVersion:"2010-12-01",maxAttempts:3,region:"us-east-1"},ue=Z((y={})=>{const a={...j,...y},d=F("AWS-SES",y.logger),P=(e,i,t,s,o)=>{const u=Object.keys(t).toSorted().map(c=>{const l=t[c];return l===void 0?"":`${encodeURIComponent(c)}=${encodeURIComponent(l)}`}).filter(Boolean).join("&"),r=`${Object.keys(s).toSorted().map(c=>`${c.toLowerCase()}:${s[c]}`).join(`
1
+ import{createRequire as D}from"node:module";import E from"./EmailError-B-sEf3bp.js";import L from"./RequiredOptionError-DuNNY_a5.js";import{c as F}from"./create-logger-BQTS3f-I.js";import f from"../utils/format-email-address.js";import{s as G}from"./headers-to-record-De1Eg951.js";import{m as Q}from"./make-request-B9XjBynA.js";import{a as q,s as X}from"./sanitize-header-DtQwAnzg.js";import{f as Y}from"./validate-email-options-mCM9dVug.js";import{defineProvider as Z}from"./defineProvider-C9q-7iwt.js";const N=D(import.meta.url),A=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,V=y=>{if(typeof A<"u"&&A.versions&&A.versions.node){const[a,d]=A.versions.node.split(".").map(Number);if(a>22||a===22&&d>=3||a===20&&d>=16)return A.getBuiltinModule(y)}return N(y)},{randomUUID:v,createHash:R,createHmac:$}=V("node:crypto"),J=globalThis.Buffer!==void 0,I=()=>{if(!J)throw new Error("Buffer is required for AWS SES provider");return globalThis.Buffer},h="aws-ses",j={apiVersion:"2010-12-01",maxAttempts:3,region:"us-east-1"},ue=Z((y={})=>{const a={...j,...y},d=F("AWS-SES",y.logger),P=(e,i,t,s,o)=>{const u=Object.keys(t).toSorted().map(c=>{const l=t[c];return l===void 0?"":`${encodeURIComponent(c)}=${encodeURIComponent(l)}`}).filter(Boolean).join("&"),r=`${Object.keys(s).toSorted().map(c=>`${c.toLowerCase()}:${s[c]}`).join(`
2
2
  `)}
3
3
  `,n=Object.keys(s).toSorted().map(c=>c.toLowerCase()).join(";"),g=R("sha256").update(o).digest("hex");return[e,i,u,r,n,g].join(`
4
4
  `)},W=(e,i,t)=>{const s=e.slice(0,8),o=R("sha256").update(t).digest("hex");return["AWS4-HMAC-SHA256",e,`${s}/${i}/ses/aws4_request`,o].join(`
@@ -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-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};
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-B9XjBynA.js";import{i as v}from"./retry-ipI5DRJ8.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};
@@ -1 +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
+ 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-B9XjBynA.js";import{i as g}from"./retry-ipI5DRJ8.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 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
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{s as T,a as f}from"./sanitize-header-DtQwAnzg.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
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-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
+ import a from"./EmailError-B-sEf3bp.js";import m from"./RequiredOptionError-DuNNY_a5.js";import{F as d}from"./build-mime-message-BW5FQ2Bt.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};
@@ -0,0 +1 @@
1
+ const w=(a,s={})=>{const{now:i=Date.now,skewMs:o=6e4}=s,c=Math.max(0,o);let t,n;const r=e=>e.expiresAt===void 0||e.expiresAt-c>i();return async()=>t&&r(t)?t:(n??=a().then(e=>(t=e,e)).finally(()=>{n=void 0}),await n)};export{w as d};
@@ -1 +1 @@
1
- import{createMail as w}from"./Mail-C1zp-fqt.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-CYAwMRnX.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 +1 @@
1
- import c from"./EmailError-B-sEf3bp.js";import g from"./RequiredOptionError-DuNNY_a5.js";import{e as w}from"./generate-message-id-gXAuMz4g.js";import{m as u}from"./make-request-BlK_B72c.js";import{f as A}from"./validate-email-options-mCM9dVug.js";import{defineProvider as j}from"./defineProvider-C9q-7iwt.js";const i="http",v="POST",f=3e4,S=j((o={})=>{if(!o.endpoint)throw new g(i,"endpoint");const a={apiKey:o.apiKey??"",endpoint:o.endpoint,headers:o.headers??{},method:o.method??v},d=()=>{const e={"Content-Type":"application/json",...a.headers};return a.apiKey&&(e.Authorization=`Bearer ${a.apiKey}`),e},p=e=>{const t={from:e.from.email,from_name:e.from.name,html:e.html,subject:e.subject,text:e.text,to:Array.isArray(e.to)?e.to.map(s=>s.email):e.to.email};return e.cc&&(t.cc=Array.isArray(e.cc)?e.cc.map(s=>s.email):e.cc.email),e.bcc&&(t.bcc=Array.isArray(e.bcc)?e.bcc.map(s=>s.email):e.bcc.email),e.customParams&&Object.assign(t,e.customParams),t};let m=!1;return{features:{attachments:!1,batchSending:!1,customHeaders:!0,html:!0,replyTo:!1,scheduling:!1,tagging:!1,templates:!1,tracking:!1},async initialize(){if(!m){if(!await this.isAvailable())throw new c(i,"API endpoint not available");m=!0}},async isAvailable(){try{return!!(await u(a.endpoint,{headers:d(),method:"OPTIONS",timeout:f})).success}catch(e){if(e instanceof Error){const t=e.message;if(t.includes("401")||t.includes("403"))return!1}return!1}},name:i,options:a,async sendEmail(e){try{const t=A(e);if(t.length>0)return{error:new c(i,`Invalid email options: ${t.join(", ")}`),success:!1};m||await this.initialize();const s=d();e.headers&&Object.assign(s,e.headers);const h=p(e),y=e.endpointOverride??a.endpoint,b=e.methodOverride??a.method,n=await u(y,{headers:s,method:b,timeout:f},JSON.stringify(h));if(!n.success)return{error:new c(i,`Failed to send email: ${n.error?.message||"Unknown error"}`,{cause:n.error}),success:!1};let l;const r=n.data?.body;return r&&typeof r=="object"&&(l=r.id??r.messageId??(r.data&&typeof r.data=="object"&&(r.data.id??r.data.messageId))),l??=w(),{data:{messageId:l,provider:i,response:n.data?.body,sent:!0,timestamp:new Date},success:!0}}catch(t){return{error:new c(i,`Failed to send email: ${t.message}`,{cause:t}),success:!1}}},async validateCredentials(){try{const e=await u(a.endpoint,{headers:d(),method:"GET",timeout:f});return!!(e.data&&typeof e.data=="object"&&"statusCode"in e.data&&typeof e.data.statusCode=="number"&&e.data.statusCode>=200&&e.data.statusCode<300)}catch{return!1}}}});export{S as default};
1
+ import c from"./EmailError-B-sEf3bp.js";import g from"./RequiredOptionError-DuNNY_a5.js";import{e as w}from"./generate-message-id-gXAuMz4g.js";import{m as u}from"./make-request-B9XjBynA.js";import{f as A}from"./validate-email-options-mCM9dVug.js";import{defineProvider as j}from"./defineProvider-C9q-7iwt.js";const i="http",v="POST",f=3e4,S=j((o={})=>{if(!o.endpoint)throw new g(i,"endpoint");const a={apiKey:o.apiKey??"",endpoint:o.endpoint,headers:o.headers??{},method:o.method??v},d=()=>{const e={"Content-Type":"application/json",...a.headers};return a.apiKey&&(e.Authorization=`Bearer ${a.apiKey}`),e},p=e=>{const t={from:e.from.email,from_name:e.from.name,html:e.html,subject:e.subject,text:e.text,to:Array.isArray(e.to)?e.to.map(s=>s.email):e.to.email};return e.cc&&(t.cc=Array.isArray(e.cc)?e.cc.map(s=>s.email):e.cc.email),e.bcc&&(t.bcc=Array.isArray(e.bcc)?e.bcc.map(s=>s.email):e.bcc.email),e.customParams&&Object.assign(t,e.customParams),t};let m=!1;return{features:{attachments:!1,batchSending:!1,customHeaders:!0,html:!0,replyTo:!1,scheduling:!1,tagging:!1,templates:!1,tracking:!1},async initialize(){if(!m){if(!await this.isAvailable())throw new c(i,"API endpoint not available");m=!0}},async isAvailable(){try{return!!(await u(a.endpoint,{headers:d(),method:"OPTIONS",timeout:f})).success}catch(e){if(e instanceof Error){const t=e.message;if(t.includes("401")||t.includes("403"))return!1}return!1}},name:i,options:a,async sendEmail(e){try{const t=A(e);if(t.length>0)return{error:new c(i,`Invalid email options: ${t.join(", ")}`),success:!1};m||await this.initialize();const s=d();e.headers&&Object.assign(s,e.headers);const h=p(e),y=e.endpointOverride??a.endpoint,b=e.methodOverride??a.method,n=await u(y,{headers:s,method:b,timeout:f},JSON.stringify(h));if(!n.success)return{error:new c(i,`Failed to send email: ${n.error?.message||"Unknown error"}`,{cause:n.error}),success:!1};let l;const r=n.data?.body;return r&&typeof r=="object"&&(l=r.id??r.messageId??(r.data&&typeof r.data=="object"&&(r.data.id??r.data.messageId))),l??=w(),{data:{messageId:l,provider:i,response:n.data?.body,sent:!0,timestamp:new Date},success:!0}}catch(t){return{error:new c(i,`Failed to send email: ${t.message}`,{cause:t}),success:!1}}},async validateCredentials(){try{const e=await u(a.endpoint,{headers:d(),method:"GET",timeout:f});return!!(e.data&&typeof e.data=="object"&&"statusCode"in e.data&&typeof e.data.statusCode=="number"&&e.data.statusCode>=200&&e.data.statusCode<300)}catch{return!1}}}});export{S as default};
@@ -1 +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
+ 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-B9XjBynA.js";import{i as g}from"./retry-ipI5DRJ8.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-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
+ 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-B9XjBynA.js";import{i as y}from"./retry-ipI5DRJ8.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,p=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 u=>{const c=await v(u,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,p),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-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
+ import{defineProvider as l}from"./defineProvider-C9q-7iwt.js";import o from"./smtpProvider-5MI3-EPh.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-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
+ 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-B9XjBynA.js";import{i as g}from"./retry-ipI5DRJ8.js";import{s as A,a as k}from"./sanitize-header-DtQwAnzg.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-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};
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-B9XjBynA.js";import{i as K}from"./retry-ipI5DRJ8.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};
@@ -1 +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
+ 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-B9XjBynA.js";import{i as g}from"./retry-ipI5DRJ8.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-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};
1
+ import{createRequire as j}from"node:module";import u 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-B9XjBynA.js";import{i as T}from"./retry-ipI5DRJ8.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),m=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,C=s=>{if(typeof m<"u"&&m.versions&&m.versions.node){const[i,n]=m.versions.node.split(".").map(Number);if(i>22||i===22&&n>=3||i===20&&n>=16)return m.getBuiltinModule(s)}return A(s)},{Buffer:y}=C("node:buffer"),a="mailgun",q="https://api.mailgun.net",M=3e4,K=3,B=s=>{const i=[];for(const[n,r]of Object.entries(s))if(r!=null)if(Array.isArray(r))for(const e of r)i.push(`${encodeURIComponent(n)}=${encodeURIComponent(String(e))}`);else typeof r=="object"?i.push(`${encodeURIComponent(n)}=${encodeURIComponent(JSON.stringify(r))}`):i.push(`${encodeURIComponent(n)}=${encodeURIComponent(String(r))}`);return i.join("&")},X=_((s={})=>{if(!s.apiKey)throw new w(a,"apiKey");if(!s.domain)throw new w(a,"domain");const i={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,r=E(a,s.logger);return{endpoint:i.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(a,"Email ID is required to retrieve email details"),success:!1};await n.ensureInitialized(()=>this.initialize(),a);const o={Authorization:`Basic ${y.from(`api:${i.apiKey}`).toString("base64")}`,"Content-Type":"application/json"};r.debug("Retrieving email details",{id:e});const t=await T(async()=>h(`${i.endpoint}/v3/${i.domain}/events?message-id=${encodeURIComponent(e)}&limit=1`,{headers:o,method:"GET",timeout:i.timeout}),i.retries);if(!t.success)return r.debug("API request failed when retrieving email",t.error),{error:new u(a,`Failed to retrieve email: ${t.error instanceof Error?t.error.message:"Unknown error"}`,{cause:t.error}),success:!1};r.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,r),success:!1}}},async initialize(){await n.ensureInitialized(async()=>{if(!await this.isAvailable())throw new u(a,"Mailgun API not available or invalid API key/domain");r.debug("Provider initialized successfully")},a)},async isAvailable(){try{const e={Authorization:`Basic ${y.from(`api:${i.apiKey}`).toString("base64")}`,"Content-Type":"application/json"};r.debug("Checking Mailgun API availability");const o=await h(`${i.endpoint}/v3/domains/${i.domain}`,{headers:e,method:"GET",timeout:i.timeout});if(r.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 r.debug("Error checking availability:",e),!1}},name:a,options:i,async sendEmail(e){try{const o=S(e);if(o.length>0)return{error:new u(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}r.debug("Sending email via Mailgun API",{subject:t.subject,to:t.to});const p={Authorization:`Basic ${y.from(`api:${i.apiKey}`).toString("base64")}`,"Content-Type":"application/x-www-form-urlencoded"},g=B(t),l=await T(async()=>h(`${i.endpoint}/v3/${i.domain}/messages`,{headers:p,method:"POST",timeout:i.timeout},g),i.retries);if(!l.success)return r.debug("API request failed when sending email",l.error),{error:l.error??new u(a,"Failed to send email"),success:!1};const v=l.data?.body?.id??P();return r.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,r),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{X as default};
@@ -1 +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};
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-B9XjBynA.js";import{i as b}from"./retry-ipI5DRJ8.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};