@visulima/email 2.1.6 → 2.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/dist/crypto/index.d.ts +183 -183
- package/dist/crypto/index.js +1 -1
- package/dist/deliverability/dmarc-report.d.ts +43 -43
- package/dist/deliverability/dmarc-report.js +1 -1
- package/dist/deliverability/index.d.ts +201 -201
- package/dist/events/index.d.ts +17 -17
- package/dist/inbound/index.d.ts +180 -180
- package/dist/index.d.ts +35 -46
- package/dist/index.js +1 -1
- package/dist/middleware/index.d.ts +213 -216
- package/dist/middleware/index.js +1 -1
- package/dist/packem_shared/{DkimSigner-CiLBaXrg.js → DkimSigner-sLcIw9bp.js} +6 -6
- package/dist/packem_shared/{DraftMailMessage-CGTVuy2z.js → DraftMailMessage-C3YTXqWo.js} +1 -1
- package/dist/packem_shared/EmailError-CDvYwuqz.js +1 -0
- package/dist/packem_shared/{Mail-CYAwMRnX.js → Mail-CIyxkmxu.js} +1 -1
- package/dist/packem_shared/MailMessage-DuEXJiCg.js +1 -0
- package/dist/packem_shared/{RequiredOptionError-DuNNY_a5.js → RequiredOptionError-DU2lxzk3.js} +1 -1
- package/dist/packem_shared/SmimeEncrypter-CzTbQM-z.js +6 -0
- package/dist/packem_shared/SmimeSigner-DjLShaOw.js +8 -0
- package/dist/packem_shared/{ahaSendProvider-DSuZIzaQ.js → ahaSendProvider-br1yB2un.js} +1 -1
- package/dist/packem_shared/arcMessageSignatureBase-D54jQIWu.js +17 -0
- package/dist/packem_shared/attachment-processor-D1cbAhQi.js +1 -0
- package/dist/packem_shared/{autoSendProvider-DqAoelWR.js → autoSendProvider-BSP8ueOC.js} +1 -1
- package/dist/packem_shared/{awsSesProvider-ClK1FUln.js → awsSesProvider-zRICW1pH.js} +13 -13
- package/dist/packem_shared/azureProvider-DwN4c5dC.js +1 -0
- package/dist/packem_shared/{brevoProvider-CIzuIDlt.js → brevoProvider-C491beE_.js} +1 -1
- package/dist/packem_shared/{build-mime-message-BW5FQ2Bt.js → build-mime-message-DT67qfMp.js} +1 -1
- package/dist/packem_shared/{circuitBreakerMiddleware-D2SA_07f.js → circuitBreakerMiddleware-N0CKF90q.js} +1 -1
- package/dist/packem_shared/{cloudflareEmailProvider-B8mOEl3N.js → cloudflareEmailProvider-8JxzLbpX.js} +1 -1
- package/dist/packem_shared/{createTestEmail-f12yLlWn.js → createTestEmail-D_ksEez3.js} +1 -1
- package/dist/packem_shared/dedupeMiddleware-CYYI_O7S.js +1 -0
- package/dist/packem_shared/{detectMimeType-DFH3kp6K.js → detectMimeType-CmYmWDXE.js} +1 -1
- package/dist/packem_shared/event-bus.d-BNQA-FZE.d.ts +104 -0
- package/dist/packem_shared/{failoverProvider-BgX6zfnY.js → failoverProvider-6qwE_HSJ.js} +1 -1
- package/dist/packem_shared/generate-boundary-0xGe9GqK.js +1 -0
- package/dist/packem_shared/{httpProvider-aBfTXyCT.js → httpProvider-BqrdZhGw.js} +1 -1
- package/dist/packem_shared/index-Gd7m-UQA.js +11 -0
- package/dist/packem_shared/{infobipProvider-DxzsONUX.js → infobipProvider-C2FU6VMP.js} +1 -1
- package/dist/packem_shared/isValidSigningCertUrl-DNxPA0Q-.js +3 -0
- package/dist/packem_shared/{loopsProvider-QBsAH6Ee.js → loopsProvider-Bz63so6m.js} +1 -1
- package/dist/packem_shared/mail.d-xKtvoKMK.d.ts +909 -0
- package/dist/packem_shared/{mailCrabProvider-DRE5snM9.js → mailCrabProvider-bkQy-2a1.js} +1 -1
- package/dist/packem_shared/{mailPaceProvider-DCa-4ghl.js → mailPaceProvider-S1AB-AYq.js} +1 -1
- package/dist/packem_shared/{mailchannelsProvider-GiwkYBdD.js → mailchannelsProvider-B_K6X4VY.js} +1 -1
- package/dist/packem_shared/{mailerSendProvider-RK6IbUrL.js → mailerSendProvider-DPEww2H1.js} +1 -1
- package/dist/packem_shared/mailgunProvider-DKxzVbDW.js +1 -0
- package/dist/packem_shared/mailjetProvider-C2TQcujL.js +1 -0
- package/dist/packem_shared/{mailomatProvider-DPDpVS8r.js → mailomatProvider-B8-5bQsu.js} +1 -1
- package/dist/packem_shared/{mailtrapProvider-DtrS4Q34.js → mailtrapProvider-DW7TLOdG.js} +1 -1
- package/dist/packem_shared/{make-request-B9XjBynA.js → make-request-CylyuRaN.js} +1 -1
- package/dist/packem_shared/{mandrillProvider-B84zH-eV.js → mandrillProvider-S-0lKNGd.js} +1 -1
- package/dist/packem_shared/{mockProvider-Behywbl1.js → mockProvider-BAl292mW.js} +1 -1
- package/dist/packem_shared/{netcoreProvider-D-wtCyJj.js → netcoreProvider-DajMprlo.js} +1 -1
- package/dist/packem_shared/{nodemailerProvider-BFHobXxt.js → nodemailerProvider-DRo0lJ6g.js} +1 -1
- package/dist/packem_shared/{opentelemetryProvider-ByHC01ub.js → opentelemetryProvider-C6spx2CD.js} +1 -1
- package/dist/packem_shared/{outlook365Provider-Btk4Emig.js → outlook365Provider-B0o7UZBW.js} +1 -1
- package/dist/packem_shared/{plunkProvider-Bw8e6460.js → plunkProvider-DJzEUEtU.js} +1 -1
- package/dist/packem_shared/{postalProvider-CT8zr89z.js → postalProvider-DHFjFE3Y.js} +1 -1
- package/dist/packem_shared/{postmarkProvider-CQSqZWDs.js → postmarkProvider-Dt1EGGBA.js} +1 -1
- package/dist/packem_shared/{provider-base-C7PuopYK.js → provider-base-DjPzWncP.js} +1 -1
- package/dist/packem_shared/{provider.d-J-y6iogK.d.ts → provider.d-Cx5YQJdP.d.ts} +9 -9
- package/dist/packem_shared/{resendProvider-drJYlvLP.js → resendProvider-qjI86j_d.js} +1 -1
- package/dist/packem_shared/{retry-ipI5DRJ8.js → retry-CG9iT2wF.js} +1 -1
- package/dist/packem_shared/{roundRobinProvider-D1by5KGW.js → roundRobinProvider-CO5YvhgR.js} +1 -1
- package/dist/packem_shared/{scalewayProvider-DU5gXQrl.js → scalewayProvider-CihQKhw6.js} +1 -1
- package/dist/packem_shared/{sendGridProvider-BuTbEXW8.js → sendGridProvider-Dkc5AKlC.js} +1 -1
- package/dist/packem_shared/{smtpProvider-5MI3-EPh.js → smtpProvider-CIXMxPu-.js} +12 -12
- package/dist/packem_shared/{sparkpostProvider-UAsFYIjP.js → sparkpostProvider-CKxQhpyB.js} +1 -1
- package/dist/packem_shared/{sweegoProvider-SUz0LIcA.js → sweegoProvider-DjmAs6La.js} +1 -1
- package/dist/packem_shared/{tracer.d-MU42G1jG.d.ts → tracer.d-sb5yrt_n.d.ts} +2 -2
- package/dist/packem_shared/types.d-B0t3PQ3t.d.ts +107 -0
- package/dist/packem_shared/{types.d-ejzh-xBP.d.ts → types.d-B9295M4_.d.ts} +82 -82
- package/dist/packem_shared/types.d-BzoHR9nB.d.ts +61 -0
- package/dist/packem_shared/types.d-C5geVKes.d.ts +51 -0
- package/dist/packem_shared/types.d-GKqPNk0I.d.ts +24 -0
- package/dist/packem_shared/types.d-I-KeZ5w2.d.ts +9 -0
- package/dist/packem_shared/types.d-kHO4kX9q.d.ts +69 -0
- package/dist/packem_shared/utils-DjEtR3qT.js +1 -0
- package/dist/packem_shared/verifyMailgunWebhook-DNk080BF.js +1 -0
- package/dist/packem_shared/verifyPostmarkWebhook-B4OIEHQF.js +1 -0
- package/dist/packem_shared/verifyResendWebhook-C7E32LZ1.js +1 -0
- package/dist/packem_shared/verifySendGridWebhook-1l9bqIMw.js +1 -0
- package/dist/packem_shared/withEvents-CytsykaK.js +1 -0
- package/dist/packem_shared/{withSuppression-DBaZDMAr.js → withSuppression-BoaO4Qdz.js} +1 -1
- package/dist/packem_shared/{zeptomailProvider-DXNX9mG_.js → zeptomailProvider-DSTC9pUi.js} +1 -1
- package/dist/providers/ahasend/index.d.ts +18 -18
- package/dist/providers/ahasend/index.js +1 -1
- package/dist/providers/autosend/index.d.ts +30 -30
- package/dist/providers/autosend/index.js +1 -1
- package/dist/providers/aws-ses/index.d.ts +20 -20
- package/dist/providers/aws-ses/index.js +1 -1
- package/dist/providers/azure/index.d.ts +26 -26
- package/dist/providers/azure/index.js +1 -1
- package/dist/providers/brevo/index.d.ts +35 -35
- package/dist/providers/brevo/index.js +1 -1
- package/dist/providers/cloudflare-email/index.d.ts +25 -25
- package/dist/providers/cloudflare-email/index.js +1 -1
- package/dist/providers/failover/index.d.ts +14 -14
- package/dist/providers/failover/index.js +1 -1
- package/dist/providers/http/index.d.ts +15 -15
- package/dist/providers/http/index.js +1 -1
- package/dist/providers/infobip/index.d.ts +28 -28
- package/dist/providers/infobip/index.js +1 -1
- package/dist/providers/loops/index.d.ts +25 -25
- package/dist/providers/loops/index.js +1 -1
- package/dist/providers/mailchannels/index.d.ts +13 -13
- package/dist/providers/mailchannels/index.js +1 -1
- package/dist/providers/mailcrab/index.d.ts +17 -17
- package/dist/providers/mailcrab/index.js +1 -1
- package/dist/providers/mailersend/index.d.ts +24 -24
- package/dist/providers/mailersend/index.js +1 -1
- package/dist/providers/mailgun/index.d.ts +37 -37
- package/dist/providers/mailgun/index.js +1 -1
- package/dist/providers/mailjet/index.d.ts +36 -36
- package/dist/providers/mailjet/index.js +1 -1
- package/dist/providers/mailomat/index.d.ts +20 -20
- package/dist/providers/mailomat/index.js +1 -1
- package/dist/providers/mailpace/index.d.ts +24 -24
- package/dist/providers/mailpace/index.js +1 -1
- package/dist/providers/mailtrap/index.d.ts +22 -22
- package/dist/providers/mailtrap/index.js +1 -1
- package/dist/providers/mandrill/index.d.ts +36 -36
- package/dist/providers/mandrill/index.js +1 -1
- package/dist/providers/mock/index.d.ts +8 -8
- package/dist/providers/mock/index.js +1 -1
- package/dist/providers/netcore/index.d.ts +17 -17
- package/dist/providers/netcore/index.js +1 -1
- package/dist/providers/nodemailer/index.d.ts +22 -22
- package/dist/providers/nodemailer/index.js +1 -1
- package/dist/providers/opentelemetry/index.d.ts +20 -20
- package/dist/providers/opentelemetry/index.js +1 -1
- package/dist/providers/outlook365/index.d.ts +82 -82
- package/dist/providers/outlook365/index.js +1 -1
- package/dist/providers/plunk/index.d.ts +18 -18
- package/dist/providers/plunk/index.js +1 -1
- package/dist/providers/postal/index.d.ts +24 -24
- package/dist/providers/postal/index.js +1 -1
- package/dist/providers/postmark/index.d.ts +30 -30
- package/dist/providers/postmark/index.js +1 -1
- package/dist/providers/resend/index.d.ts +24 -24
- package/dist/providers/resend/index.js +1 -1
- package/dist/providers/roundrobin/index.d.ts +14 -14
- package/dist/providers/roundrobin/index.js +1 -1
- package/dist/providers/scaleway/index.d.ts +22 -22
- package/dist/providers/scaleway/index.js +1 -1
- package/dist/providers/sendgrid/index.d.ts +25 -25
- package/dist/providers/sendgrid/index.js +1 -1
- package/dist/providers/smtp/index.d.ts +11 -11
- package/dist/providers/smtp/index.js +1 -1
- package/dist/providers/sparkpost/index.d.ts +21 -21
- package/dist/providers/sparkpost/index.js +1 -1
- package/dist/providers/sweego/index.d.ts +20 -20
- package/dist/providers/sweego/index.js +1 -1
- package/dist/providers/zeptomail/index.d.ts +17 -17
- package/dist/providers/zeptomail/index.js +1 -1
- package/dist/queue/bullmq-queue.d.ts +26 -26
- package/dist/queue/index.d.ts +86 -86
- package/dist/queue/pg-boss-queue.d.ts +13 -13
- package/dist/queue/sqs-queue.d.ts +20 -20
- package/dist/queue/unstorage-queue.d.ts +47 -47
- package/dist/queue/unstorage-queue.js +1 -1
- package/dist/render/cid.d.ts +12 -12
- package/dist/render/css-inline.d.ts +12 -12
- package/dist/render/css-inline.js +1 -1
- package/dist/render/dark-mode.d.ts +12 -12
- package/dist/render/preheader.d.ts +16 -16
- package/dist/template-engines/handlebars.d.ts +19 -19
- package/dist/template-engines/handlebars.js +1 -1
- package/dist/template-engines/html-to-text.d.ts +12 -12
- package/dist/template-engines/html-to-text.js +1 -1
- package/dist/template-engines/i18n.d.ts +43 -43
- package/dist/template-engines/i18n.js +1 -1
- package/dist/template-engines/jsx-email.d.ts +8 -8
- package/dist/template-engines/jsx-email.js +1 -1
- package/dist/template-engines/liquid.d.ts +9 -9
- package/dist/template-engines/liquid.js +1 -1
- package/dist/template-engines/mjml.d.ts +9 -9
- package/dist/template-engines/mjml.js +1 -1
- package/dist/template-engines/react-email.d.ts +8 -8
- package/dist/template-engines/react-email.js +1 -1
- package/dist/template-engines/vue-email.d.ts +8 -8
- package/dist/template-engines/vue-email.js +1 -1
- package/dist/test/index.d.ts +89 -89
- package/dist/test/index.js +1 -1
- package/dist/utils/cache.d.ts +27 -27
- package/dist/utils/format-email-address.d.ts +6 -6
- package/dist/utils/format-email-address.js +1 -1
- package/dist/utils/normalize-email-aliases.d.ts +19 -19
- package/dist/utils/parse-address.d.ts +16 -16
- package/dist/utils/parse-eml.d.ts +18 -18
- package/dist/utils/result.d.ts +30 -30
- package/dist/utils/result.js +1 -1
- package/dist/utils/validation/check-feature-support.d.ts +33 -33
- package/dist/utils/validation/validate-email.d.ts +4 -4
- package/dist/webhooks/index.d.ts +134 -134
- package/dist/webhooks/index.js +1 -1
- package/package.json +1 -1
- package/dist/packem_shared/EmailError-B-sEf3bp.js +0 -1
- package/dist/packem_shared/MailMessage-DQRgs5Dz.js +0 -1
- package/dist/packem_shared/SmimeEncrypter-DavopRlE.js +0 -6
- package/dist/packem_shared/SmimeSigner-0onWksAv.js +0 -8
- package/dist/packem_shared/arcMessageSignatureBase-DDLEHW2E.js +0 -17
- package/dist/packem_shared/attachment-processor-CMp7qqMI.js +0 -1
- package/dist/packem_shared/azureProvider-Cw_Tmde6.js +0 -1
- package/dist/packem_shared/dedupeMiddleware-B6ajWOTi.js +0 -1
- package/dist/packem_shared/event-bus.d-DEl3w_EW.d.ts +0 -104
- package/dist/packem_shared/generate-boundary-DQbzDiOI.js +0 -1
- package/dist/packem_shared/index-BoZvzveg.js +0 -11
- package/dist/packem_shared/isValidSigningCertUrl-Bii1AMGC.js +0 -3
- package/dist/packem_shared/mail.d-B9SSqyy0.d.ts +0 -909
- package/dist/packem_shared/mailgunProvider-D9HUWGKN.js +0 -1
- package/dist/packem_shared/mailjetProvider-DelLs2Vt.js +0 -1
- package/dist/packem_shared/types.d-BId55FW2.d.ts +0 -107
- package/dist/packem_shared/types.d-CmoWvdZi.d.ts +0 -61
- package/dist/packem_shared/types.d-DCkecJse.d.ts +0 -51
- package/dist/packem_shared/types.d-Mpu0HZoG.d.ts +0 -24
- package/dist/packem_shared/types.d-lcJZmwRK.d.ts +0 -69
- package/dist/packem_shared/types.d-nyR1ty1Q.d.ts +0 -9
- package/dist/packem_shared/utils-BfYfPB_I.js +0 -1
- package/dist/packem_shared/verifyMailgunWebhook-Cwl0OD3P.js +0 -1
- package/dist/packem_shared/verifyPostmarkWebhook-C72ZvbrG.js +0 -1
- package/dist/packem_shared/verifyResendWebhook-YK2zNDXR.js +0 -1
- package/dist/packem_shared/verifySendGridWebhook-Dbwc1tfG.js +0 -1
- package/dist/packem_shared/withEvents-CCVblSqj.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import h from"./DraftMailMessage-
|
|
1
|
+
import h from"./DraftMailMessage-C3YTXqWo.js";import v from"./EmailError-CDvYwuqz.js";import f from"./MailMessage-DuEXJiCg.js";import{composeMiddleware as C}from"./composeMiddleware-BHwLLEzK.js";import{F as w}from"./build-mime-message-DT67qfMp.js";import{c as M}from"./create-logger-BQTS3f-I.js";import{s as l}from"./headers-to-record-De1Eg951.js";import T from"../utils/validation/check-feature-support.js";const S=(i,e,r)=>{e.success&&e.data?i&&i.info("Email sent successfully",{messageId:e.data.messageId,provider:e.data.provider}):i&&i.error("Email send failed",{error:e.error,provider:r})},j=async(i,e,r)=>{const s={...i,to:e.to};return e.cc&&(s.cc=e.cc),e.bcc&&(s.bcc=e.bcc),e.replyTo&&(s.replyTo=e.replyTo),e.headers&&(s.headers={...l(i.headers??{}),...l(e.headers)}),s.subject=e.subject??i.subject,r&&e.data&&(s.subject=await r(s.subject,e.data),i.html!==void 0&&(s.html=await r(i.html,e.data)),i.text!==void 0&&(s.text=await r(i.text,e.data))),s};class u{static extractErrorMessages(e){return e instanceof Error?[e.message]:[String(e??"Unknown error")]}provider;logger;loggerInstance;globalConfig;featureCheck;middlewares=[];composedSend;mountedProviders=new Map;constructor(e,r){this.provider=e,this.featureCheck=r?.featureCheck??"error"}setLogger(e){return this.loggerInstance=e,this.logger=M("Mail",e),this}use(e){return this.middlewares.push(e),this.composedSend=void 0,this}mount(e,r){return this.mountedProviders.set(e,r),this}setFrom(e){return this.globalConfig??={},this.globalConfig.from=e,this.logger&&this.logger.debug("Default from address updated",{from:e.email}),this}setReplyTo(e){return this.globalConfig??={},this.globalConfig.replyTo=e,this.logger&&this.logger.debug("Default reply-to address updated",{replyTo:e.email}),this}setHeaders(e){if(this.globalConfig??={},this.globalConfig.headers=e,this.logger){const r=l(e);this.logger.debug("Default headers updated",{count:Object.keys(r).length,headers:Object.keys(r)})}return this}async draft(e){let r=e instanceof f||e instanceof h?await this.buildDraftFromMessage(e):await this.buildDraftFromOptions(e);r=this.applyGlobalConfig(r);const s=r.headers?l(r.headers):{};r.headers={...s,"X-Unsent":"1"};const t=await w(r,{includeBcc:!0});return this.logger&&this.logger.debug("Draft created successfully in EML format",{from:r.from.email,size:t.length,subject:r.subject,to:Array.isArray(r.to)?r.to.length:1}),t}async send(e){if(e instanceof h)throw new TypeError("Cannot send draft messages. Convert to MailMessage first or remove X-Unsent header.");let r;if(e instanceof f)this.logger&&this.logger.debug("Sending MailMessage instance"),this.loggerInstance&&e.setLogger(this.loggerInstance),r=await e.build();else{const o=e;this.logger&&this.logger.debug("Sending email with options",{subject:o.subject,to:Array.isArray(o.to)?o.to.length:1}),r=o}r=this.applyGlobalConfig(r);const s=this.assertFeatureSupport(r);if(s)return{error:s,success:!1};const t=await this.dispatch(r);return S(this.logger,t,this.provider.name??"unknown"),t}sendMany(e,r){const s=Math.max(1,Math.floor(r?.concurrency??1));return s===1?this.sendManySerial(e,r?.signal):this.sendManyConcurrent(e,s,r?.signal)}sendBatch(e,r,s){const t=async function*(){const o=e instanceof f?await e.build():e;for(const a of r)yield await j(o,a,s?.render)};return this.sendMany(t(),{concurrency:s?.concurrency,signal:s?.signal})}async sendOneToReceipt(e){const r=this.provider.name;try{const s=await this.send(e);return s.success&&s.data?{messageId:s.data.messageId,provider:s.data.provider??r,response:s.data.response,successful:!0,timestamp:s.data.timestamp}:{errorMessages:u.extractErrorMessages(s.error),provider:r,successful:!1}}catch(s){return{errorMessages:u.extractErrorMessages(s),provider:r,successful:!1}}}async*sendManySerial(e,r){const s=this.provider.name;let t=0,o=0,a=0;this.logger&&this.logger.debug("Starting batch email send",{provider:s});for await(const n of e){if(n instanceof h)throw new TypeError("Cannot send draft messages. Convert to MailMessage first or remove X-Unsent header.");if(r?.aborted){this.logger&&this.logger.warn("Batch send operation was aborted",{failed:a,processed:t,successful:o}),yield{errorMessages:["Send operation was aborted"],provider:s,successful:!1};return}t+=1;const g=await this.sendOneToReceipt(n);g.successful?o+=1:a+=1,yield g}this.logger&&this.logger.debug("Batch email send completed",{failureCount:a,processedCount:t,provider:s,successCount:o})}async*sendManyConcurrent(e,r,s){const t=this.provider.name;this.logger&&this.logger.debug("Starting concurrent batch email send",{concurrency:r,provider:t});const o=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator](),a=new Map;let n=0,g=!1,p=!1;const m=async()=>{for(;!g&&!p&&a.size<r;){const d=await o.next();if(d.done){g=!0;break}const c=d.value;if(c instanceof h)throw new TypeError("Cannot send draft messages. Convert to MailMessage first or remove X-Unsent header.");const b=n;n+=1,a.set(b,this.sendOneToReceipt(c).then(y=>({id:b,receipt:y})))}};for(await m();a.size>0;){if(s?.aborted){p=!0,yield{errorMessages:["Send operation was aborted"],provider:t,successful:!1};return}const{id:d,receipt:c}=await Promise.race(a.values());a.delete(d),yield c,await m()}this.logger&&this.logger.debug("Concurrent batch email send completed",{processedCount:n,provider:t})}async dispatch(e){return this.middlewares.length===0?await this.resolveProvider(e).sendEmail(e):(this.composedSend??=C(this.middlewares,r=>Promise.resolve(this.resolveProvider(r).sendEmail(r))),await this.composedSend(e))}resolveProvider(e){return e.stream!==void 0?this.mountedProviders.get(e.stream)??this.provider:this.provider}assertFeatureSupport(e){if(this.featureCheck==="off")return;const{supported:r,violations:s}=T(e,this.provider.features);if(r)return;const t=this.provider.name??"unknown",o=s.map(n=>n.field),a=s.map(n=>n.message);if(this.featureCheck==="warn"){this.logger&&this.logger.warn("Message uses capabilities the provider does not support",{fields:o,provider:t});return}return this.logger&&this.logger.error("Message rejected by capability guard",{fields:o,provider:t}),new v(t,`Provider does not support the following message fields: ${o.join(", ")}`,{code:"UNSUPPORTED_FEATURES",hint:a})}async buildDraftFromMessage(e){return this.logger&&this.logger.debug("Creating draft from MailMessage instance"),this.loggerInstance&&e.setLogger(this.loggerInstance),this.applyGlobalConfigToMessage(e),await e.build()}async buildDraftFromOptions(e){return this.logger&&this.logger.debug("Creating draft from email options",{subject:e.subject,to:Array.isArray(e.to)?e.to.length:1}),e}applyGlobalConfigToMessage(e){const r=this.globalConfig?.from;r&&!e.getFrom()&&e.from(r);const s=this.globalConfig?.replyTo;if(s&&!e.getReplyTo()&&e.replyTo(s),this.globalConfig?.headers){const t=l(this.globalConfig.headers);Object.entries(t).forEach(([o,a])=>{e.header(o,a)})}}applyGlobalConfig(e){if(!this.globalConfig)return e;const r={...e};if(!r.from&&this.globalConfig.from&&(r.from=this.globalConfig.from,this.logger&&this.logger.debug("Applied global from address",{from:this.globalConfig.from.email})),!r.replyTo&&this.globalConfig.replyTo&&(r.replyTo=this.globalConfig.replyTo,this.logger&&this.logger.debug("Applied global reply-to address",{replyTo:this.globalConfig.replyTo.email})),this.globalConfig.headers){const s=l(this.globalConfig.headers),t=r.headers?l(r.headers):{};r.headers={...s,...t},this.logger&&this.logger.debug("Merged global headers",{globalCount:Object.keys(s).length,messageCount:Object.keys(t).length})}return r}}const D=(i,e)=>new u(i,e);export{u as Mail,D as createMail};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createRequire as f}from"node:module";import{readFileAsBuffer as c,detectMimeType as d,generateContentId as u}from"./detectMimeType-CmYmWDXE.js";import{c as T}from"./create-logger-BQTS3f-I.js";import{s as l}from"./headers-to-record-De1Eg951.js";let y;const A=n=>(y??=f(import.meta.url))(n),o=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,p=n=>{if(typeof o<"u"&&o.versions&&o.versions.node){const[e,t]=o.versions.node.split(".").map(Number);if(e>22||e===22&&t>=3||e===20&&t>=16)return o.getBuiltinModule(n)}return A(n)},{basename:g}=p("node:path"),{fileURLToPath:b}=p("node:url"),m=async()=>(await import("../template-engines/html-to-text.js")).default,x=async()=>(await import("ical-generator")).default,a=n=>Array.isArray(n)?n.map(e=>typeof e=="string"?{email:e}:e):typeof n=="string"?[{email:n}]:[n];class D{fromAddress;toAddresses=[];ccAddresses=[];bccAddresses=[];subjectText="";textContent;textCharset="utf8";autoTextEnabled=!0;htmlContent;htmlCharset="utf8";dateValue;returnPathAddress;senderAddress;headers={};attachments=[];replyToAddress;priorityValue;tagsValue=[];signer;encrypter;logger;icalEventData;icalEventBuilder;from(e){return this.fromAddress=typeof e=="string"?{email:e}:e,this}to(e){return this.toAddresses.length=0,this.toAddresses.push(...a(e)),this}cc(e){return this.ccAddresses.length=0,this.ccAddresses.push(...a(e)),this}bcc(e){return this.bccAddresses.length=0,this.bccAddresses.push(...a(e)),this}subject(e){return this.subjectText=e,this}text(e,t="utf8"){return this.textContent=e,this.textCharset=t,this}html(e,t="utf8"){return this.htmlContent=e,this.htmlCharset=t,this}header(e,t){return this.headers[e]=t,this}setHeaders(e){const t=l(e);return Object.assign(this.headers,t),this}async attachFromPath(e,t){try{const s=await c(e),i=t?.filename??(g(e)||"attachment"),r=t?.contentType??d(i);this.attachments.push({cid:t?.cid,content:s,contentDisposition:t?.contentDisposition??"attachment",contentType:r,encoding:t?.encoding,filename:i,headers:t?.headers}),this.logger&&this.logger.debug(`Attachment added from path: ${e}`,{contentType:r,filename:i})}catch(s){throw this.logger&&this.logger.error(`Failed to attach file from path: ${e}`,s),s}return this}attachData(e,t){const s=t.contentType??d(t.filename);return this.attachments.push({cid:t.cid,content:e,contentDisposition:t.contentDisposition??"attachment",contentType:s,encoding:t.encoding,filename:t.filename,headers:t.headers}),this.logger&&this.logger.debug("Attachment added from data",{contentType:s,filename:t.filename}),this}async embedFromPath(e,t){try{const s=await c(e),i=t?.filename??(g(e)||"inline"),r=t?.contentType??d(i),h=u(i);return this.attachments.push({cid:h,content:s,contentDisposition:"inline",contentType:r,filename:i}),this.logger&&this.logger.debug(`Inline attachment embedded from path: ${e}`,{cid:h,contentType:r,filename:i}),h}catch(s){throw this.logger&&this.logger.error(`Failed to embed file from path: ${e}`,s),s}}embedData(e,t,s){const i=s?.contentType??d(t),r=u(t);return this.attachments.push({cid:r,content:e,contentDisposition:"inline",contentType:i,filename:t}),this.logger&&this.logger.debug("Inline attachment embedded from data",{cid:r,contentType:i,filename:t}),r}replyTo(e){return this.replyToAddress=typeof e=="string"?{email:e}:e,this}date(e){return this.dateValue=typeof e=="string"?new Date(e):e,this.logger&&this.logger.debug("Date header set",{date:this.dateValue.toISOString()}),this}returnPath(e){return this.returnPathAddress=typeof e=="string"?{email:e}:e,this.logger&&this.logger.debug("Return-path address set",{returnPath:this.returnPathAddress.email}),this}sender(e){return this.senderAddress=typeof e=="string"?{email:e}:e,this.logger&&this.logger.debug("Sender address set",{sender:this.senderAddress.email}),this}addTo(e){return this.toAddresses.push(...a(e)),this}addCc(e){return this.ccAddresses.push(...a(e)),this}addBcc(e){return this.bccAddresses.push(...a(e)),this}addReplyTo(e){const t=Array.isArray(e)?e:[e];if(t.length>0){const s=t[0];this.replyToAddress=typeof s=="string"?{email:s}:s}return this}addFrom(e){const t=Array.isArray(e)?e:[e];if(t.length>0){const s=t[0];this.fromAddress=typeof s=="string"?{email:s}:s}return this}priority(e){return this.priorityValue=e,this}tags(e){return this.tagsValue=Array.isArray(e)?e:[e],this}sign(e){return this.signer=e,this.logger&&this.logger.debug("Email signer configured"),this}encrypt(e){return this.encrypter=e,this.logger&&this.logger.debug("Email encrypter configured"),this}setLogger(e){return this.logger=T("MailMessage",e),this}icalEvent(e,t){return typeof e=="function"?(this.icalEventBuilder={build:e,options:t},this.icalEventData=void 0):(this.icalEventBuilder=void 0,this.icalEventData={content:e,...t}),this.logger&&this.logger.debug("Calendar event attached",{method:t?.method}),this}icalEventFromFile(e,t){const s=typeof e=="string"?e:b(e);return this.icalEventData={path:s,...t},this.logger&&this.logger.debug(`Calendar event attached from file: ${s}`,{method:t?.method}),this}icalEventFromUrl(e,t){return this.icalEventData={href:e,...t},this.logger&&this.logger.debug(`Calendar event attached from URL: ${e}`,{method:t?.method}),this}async view(e,t,s,i){try{const r=i?.autoText!==!1;this.autoTextEnabled=r,this.logger&&this.logger.debug("Rendering template",{autoText:r});const h=await e(t,s,i);this.html(h),r&&h&&await this.tryAutoGenerateText(h),this.logger&&this.logger.debug("Template rendered successfully")}catch(r){throw this.logger&&this.logger.error("Failed to render template",r),new Error(`Failed to render template: ${r.message}`)}return this}async viewText(e,t,s,i){try{this.logger&&this.logger.debug("Rendering text template");const r=await e(t,s,i);if(typeof r=="string")this.text(r),this.logger&&this.logger.debug("Text template rendered successfully");else throw new TypeError("Text renderer must return a string")}catch(r){throw this.logger&&this.logger.error("Failed to render text template",r),new Error(`Failed to render text template: ${r.message}`)}return this}async build(){if(this.logger&&this.logger.debug("Building email message"),this.fromAddress||this.throwAndLogError("From address is required","Build failed: from address is required"),this.toAddresses.length===0&&this.throwAndLogError("At least one recipient is required","Build failed: at least one recipient is required"),this.subjectText||this.throwAndLogError("Subject is required","Build failed: subject is required"),this.htmlContent&&!this.textContent&&this.autoTextEnabled)try{const t=await m();this.textContent=t(this.htmlContent),this.logger&&this.logger.debug("Auto-generated text content from HTML")}catch{this.logger&&this.logger.debug("Failed to convert HTML to text; proceeding without text content.")}!this.textContent&&!this.htmlContent&&this.throwAndLogError("Either text or html content is required","Build failed: either text or html content is required");let e={from:this.fromAddress,html:this.htmlContent,subject:this.subjectText,text:this.textContent,to:this.toAddresses.length===1?this.toAddresses[0]:this.toAddresses};if(this.ccAddresses.length>0&&(e.cc=this.ccAddresses.length===1?this.ccAddresses[0]:this.ccAddresses),this.bccAddresses.length>0&&(e.bcc=this.bccAddresses.length===1?this.bccAddresses[0]:this.bccAddresses),Object.keys(this.headers).length>0&&(e.headers=this.headers),this.attachments.length>0&&(e.attachments=this.attachments,this.logger&&this.logger.debug(`Email includes ${this.attachments.length} attachment(s)`)),this.replyToAddress&&(e.replyTo=this.replyToAddress),this.priorityValue&&(e.priority=this.priorityValue),this.tagsValue.length>0&&(e.tags=this.tagsValue),this.icalEventBuilder){const t=(await x())();this.icalEventBuilder.build(t),this.icalEventData={content:t.toString(),...this.icalEventBuilder.options}}return this.icalEventData&&(e.icalEvent=this.icalEventData,this.logger&&this.logger.debug("Email includes calendar event")),this.dateValue&&(e.headers={...l(e.headers??{}),Date:this.dateValue.toUTCString()}),this.returnPathAddress&&(e.headers={...l(e.headers??{}),"Return-Path":this.returnPathAddress.email}),this.senderAddress&&(e.headers={...l(e.headers??{}),Sender:this.senderAddress.email}),this.signer&&(this.logger&&this.logger.debug("Signing email message"),e=await this.signer.sign(e),this.logger&&this.logger.debug("Email message signed successfully")),this.encrypter&&(this.logger&&this.logger.debug("Encrypting email message"),e=await this.encrypter.encrypt(e),this.logger&&this.logger.debug("Email message encrypted successfully")),this.logger&&this.logger.debug("Email message built successfully",{bcc:this.bccAddresses.length,cc:this.ccAddresses.length,hasHtml:!!this.htmlContent,hasText:!!this.textContent,to:this.toAddresses.length}),e}getSubject(){return this.subjectText}getFrom(){return this.fromAddress}getTo(){return[...this.toAddresses]}getCc(){return[...this.ccAddresses]}getBcc(){return[...this.bccAddresses]}getReplyTo(){return this.replyToAddress}getSender(){return this.senderAddress}getReturnPath(){return this.returnPathAddress}getDate(){return this.dateValue}getPriority(){return this.priorityValue}getTextBody(){return this.textContent}getTextCharset(){return this.textCharset}getHtmlBody(){return this.htmlContent}getHtmlCharset(){return this.htmlCharset}getAttachments(){return[...this.attachments]}async tryAutoGenerateText(e){try{const t=(await m())(e);t&&!this.textContent&&this.text(t),this.logger&&this.logger.debug("Auto-generated text content from HTML template")}catch(t){this.logger&&this.logger.warn("Failed to auto-generate text from HTML template",t)}}throwAndLogError(e,t){const s=new Error(e);throw this.logger&&this.logger.error(t??e),s}}export{D as default};
|
package/dist/packem_shared/{RequiredOptionError-DuNNY_a5.js → RequiredOptionError-DU2lxzk3.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import s from"./EmailError-
|
|
1
|
+
import s from"./EmailError-CDvYwuqz.js";class a extends s{constructor(r,e){const o=Array.isArray(e)?`Missing required options: ${e.map(i=>`'${i}'`).join(", ")}`:`Missing required option: '${e}'`;super(r,o,{hint:Array.isArray(e)?`Please provide the following required options: ${e.map(i=>`'${i}'`).join(", ")}`:`Please provide the required option: '${e}'`}),this.name="RequiredOptionError"}}export{a as default};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{createRequire as O}from"node:module";import{q as I}from"./index-Gd7m-UQA.js";import{fromBER as B,OctetString as E}from"asn1js";import{Certificate as $,EnvelopedData as G,EncryptedContentInfo as V,id_ContentType_Data as z,RecipientInfo as J,KeyTransRecipientInfo as Q,IssuerAndSerialNumber as W,AlgorithmIdentifier as S,ContentInfo as X,id_ContentType_EnvelopedData as Y}from"pkijs";let q;const F=o=>(q??=O(import.meta.url))(o),h=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,K=o=>{if(typeof h<"u"&&h.versions&&h.versions.node){const[e,t]=h.versions.node.split(".").map(Number);if(e>22||e===22&&t>=3||e===20&&t>=16)return h.getBuiltinModule(o)}return F(o)},{randomBytes:v,createCipheriv:U,createPublicKey:H,publicEncrypt:L}=K("node:crypto"),b=globalThis.Buffer!==void 0,j=o=>{const e=o.replaceAll(/-----BEGIN[^-]+-----/g,"").replaceAll(/-----END[^-]+-----/g,"").replaceAll(/\s/g,"");if(b)return Buffer.from(e,"base64");const t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r+=1)n[r]=t.charCodeAt(r);return n},R=(o,e)=>{let t;if(b)t=Buffer.from(o).toString("base64");else{const r=new Uint8Array(o);let p="";const s=8192;for(let a=0;a<r.length;a+=s){const d=r.subarray(a,Math.min(a+s,r.length));p+=String.fromCharCode(...d)}t=btoa(p)}const n=t.match(/.{1,64}/g)??[];return`-----BEGIN ${e}-----
|
|
2
|
+
${n.join(`
|
|
3
|
+
`)}
|
|
4
|
+
-----END ${e}-----
|
|
5
|
+
`};class i{static collectRecipients(e){const t=[],n=r=>{if(!r)return;const p=Array.isArray(r)?r:[r];for(const s of p){const a=typeof s=="string"?s:s.email;a&&t.push(a)}};return n(e.to),n(e.cc),n(e.bcc),[...new Set(t)]}static formatAddress(e){return typeof e=="string"?e:e.name?`"${e.name}" <${e.email}>`:e.email}static formatAddresses(e){return(Array.isArray(e)?e:[e]).map(t=>i.formatAddress(t)).join(", ")}options;constructor(e){this.options=e}async encrypt(e){const t=i.collectRecipients(e),n=[];if(typeof this.options.certificates=="string"){const c=await I(this.options.certificates,{encoding:"utf8"}),f=j(c),l=B(f);if(l.offset===-1)throw new Error("Failed to parse certificate: Invalid ASN.1 structure");n.push(new $({schema:l.result}))}else{const c=t.map(async f=>{const l=this.options.certificates[f];if(!l)throw new Error(`No certificate found for recipient: ${f}`);const C=await I(l,{encoding:"utf8"}),A=j(C),u=B(A);if(u.offset===-1)throw new Error(`Failed to parse certificate for ${f}: Invalid ASN.1 structure`);return new $({schema:u.result})});n.push(...await Promise.all(c))}const r=await this.buildMessage(e),p=new TextEncoder().encode(r),s=new G({version:0});s.encryptedContentInfo=new V({contentType:z});const a=(this.options.algorithm??"aes-256-cbc").toLowerCase();if(a==="3des"||a==="des-ede3-cbc")throw new Error("3DES/DES-EDE3-CBC is deprecated and insecure (Sweet32 vulnerability). Please use AES-256-CBC, AES-192-CBC, or AES-128-CBC instead.");let d,m;switch(a){case"aes128":case"aes-128-cbc":{d="2.16.840.1.101.3.4.1.2",m=16;break}case"aes192":case"aes-192-cbc":{d="2.16.840.1.101.3.4.1.22",m=24;break}default:{d="2.16.840.1.101.3.4.1.42",m=32;break}}const g=v(m),_=b?g:new Uint8Array(g),w=v(16),x=b?w:new Uint8Array(w),T=U(`aes-${m*8}-cbc`,g,w),N=Buffer.from(p),D=[T.update(N),T.final()],y=Buffer.concat(D);s.encryptedContentInfo.encryptedContent=new E({valueHex:y.buffer.slice(y.byteOffset,y.byteOffset+y.byteLength)});const P=await Promise.all(n.map(async c=>{const f=c.toSchema().toBER(!1),l=R(f,"CERTIFICATE"),C=H(l),A=Buffer.from(_),u=L({key:C,padding:1},A);return new J({value:new Q({encryptedKey:new E({valueHex:u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength)}),keyEncryptionAlgorithm:new S({algorithmId:"1.2.840.113549.1.1.1"}),rid:new W({issuer:c.issuer,serialNumber:c.serialNumber}),version:0}),variant:0})}));s.recipientInfos.push(...P),s.encryptedContentInfo.contentEncryptionAlgorithm=new S({algorithmId:d,algorithmParams:new E({valueHex:x.buffer})});const k=new X({content:s.toSchema(),contentType:Y}).toSchema().toBER(!1),M=R(k,"PKCS7");return{...e,headers:{...e.headers,"Content-Disposition":"attachment; filename=smime.p7m","Content-Transfer-Encoding":"base64","Content-Type":"application/pkcs7-mime; smime-type=enveloped-data; name=smime.p7m"},html:void 0,text:M}}async buildMessage(e){const t=[`From: ${i.formatAddress(e.from)}`,`To: ${i.formatAddresses(e.to)}`,...e.cc?[`Cc: ${i.formatAddresses(e.cc)}`]:[]];if(e.replyTo&&t.push(`Reply-To: ${i.formatAddress(e.replyTo)}`),t.push(`Subject: ${e.subject}`,"MIME-Version: 1.0"),e.headers)for(const[n,r]of Object.entries(e.headers))t.push(`${n}: ${r}`);return e.html?t.push("Content-Type: text/html; charset=utf-8"):e.text&&t.push("Content-Type: text/plain; charset=utf-8"),t.push(""),e.html?t.push(e.html):e.text&&t.push(e.text),t.join(`\r
|
|
6
|
+
`)}}const ne=o=>new i(o);export{i as SmimeEncrypter,ne as createSmimeEncrypter};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{createRequire as K}from"node:module";import{q as y}from"./index-Gd7m-UQA.js";import{fromBER as I,ObjectIdentifier as W,OctetString as x,UTCTime as X}from"asn1js";import{Certificate as E,SignedData as Y,EncapsulatedContentInfo as Z,id_ContentType_Data as B,SignerInfo as ee,AlgorithmIdentifier as N,IssuerAndSerialNumber as te,id_sha256 as re,SignedAndUnsignedAttributes as ne,Attribute as w,ContentInfo as se,id_ContentType_SignedData as oe}from"pkijs";import{r as ie}from"./generate-boundary-0xGe9GqK.js";let G;const L=s=>(G??=K(import.meta.url))(s),u=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,V=s=>{if(typeof u<"u"&&u.versions&&u.versions.node){const[e,t]=u.versions.node.split(".").map(Number);if(e>22||e===22&&t>=3||e===20&&t>=16)return u.getBuiltinModule(s)}return L(s)},{createPrivateKey:j,createHash:z,createSign:J,randomBytes:Q}=V("node:crypto"),ae="1.2.840.113549.1.9.3",ce="1.2.840.113549.1.9.4",le="1.2.840.113549.1.9.5",pe="1.2.840.113549.1.1.1",ue={v1:1},fe={v1:1},f=globalThis.Buffer!==void 0,D=s=>{const e=s.replaceAll(/-----BEGIN[^-]+-----/g,"").replaceAll(/-----END[^-]+-----/g,"").replaceAll(/\s/g,"");if(f)return Buffer.from(e,"base64");const t=atob(e),o=new Uint8Array(t.length);for(let r=0;r<t.length;r+=1)o[r]=t.codePointAt(r);return o},me=(s,e)=>{let t;if(f)t=Buffer.from(s).toString("base64");else{const r=new Uint8Array(s);let n="";const a=8192;for(let i=0;i<r.length;i+=a){const d=r.subarray(i,Math.min(i+a,r.length));n+=String.fromCharCode(...d)}t=btoa(n)}const o=t.match(/.{1,64}/g)??[];return`-----BEGIN ${e}-----
|
|
2
|
+
${o.join(`
|
|
3
|
+
`)}
|
|
4
|
+
-----END ${e}-----
|
|
5
|
+
`};class m{static formatAddress(e){return e.name?`"${e.name.replaceAll("\\","\\\\").replaceAll('"',String.raw`\"`)}" <${e.email}>`:e.email}options;constructor(e){this.options=e}async sign(e){const t=await y(this.options.certificate,{encoding:"utf8"}),o=await y(this.options.privateKey,{encoding:"utf8"}),r=D(t),n=I(r);if(n.offset===-1)throw new Error("Failed to parse certificate: Invalid ASN.1 structure");const a=new E({schema:n.result});let i;try{i=this.options.passphrase?j({key:o,passphrase:this.options.passphrase}):j(o)}catch(c){throw new Error(`Failed to parse private key: ${c.message}`)}const d=[];if(this.options.intermediateCerts){const c=this.options.intermediateCerts.map(async _=>{const F=await y(_,{encoding:"utf8"}),H=D(F),S=I(H);if(S.offset===-1)throw new Error(`Failed to parse intermediate certificate ${_}: Invalid ASN.1 structure`);return new E({schema:S.result})});d.push(...await Promise.all(c))}const b=this.buildMessage(e),A=new TextEncoder().encode(b),h=new Y({version:ue.v1});h.encapContentInfo=new Z({eContentType:B});const g=new ee({digestAlgorithm:new N({algorithmId:re}),sid:new te({issuer:a.issuer,serialNumber:a.serialNumber}),signatureAlgorithm:new N({algorithmId:pe}),version:fe.v1}),$=z("sha256");$.update(f?Buffer.from(A):A);const R=$.digest(),M=new Uint8Array(R),C=new ne({attributes:[new w({type:ae,values:[new W({value:B})]}),new w({type:ce,values:[new x({valueHex:M.buffer.slice(0)})]}),new w({type:le,values:[new X({valueDate:new Date})]})]});g.signedAttrs=C;const T=C.toSchema().toBER(!1),P=f?Buffer.from(T):new Uint8Array(T),v=J("RSA-SHA256");v.update(P);const l=v.sign(i),U=f?l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength):l.buffer;g.signature=new x({valueHex:U}),h.signerInfos.push(g),h.certificates=[a,...d];const k=new se({content:h.toSchema(),contentType:oe}).toSchema().toBER(!1),O=me(k,"PKCS7"),p=`----_=_NextPart_${Date.now()}_${Q(8).toString("hex")}`,q=[`Content-Type: multipart/signed; protocol="application/pkcs7-signature"; micalg=sha-256; boundary="${p}"`,"",`--${p}`,b,`--${p}`,"Content-Type: application/pkcs7-signature; name=smime.p7s","Content-Transfer-Encoding: base64","Content-Disposition: attachment; filename=smime.p7s","",O.split(`
|
|
6
|
+
`).filter(c=>c.trim()&&!c.includes("-----")).join(""),`--${p}--`].join(`\r
|
|
7
|
+
`);return{...e,headers:{...e.headers,"Content-Type":`multipart/signed; protocol="application/pkcs7-signature"; micalg=sha-256; boundary="${p}"`},html:void 0,text:q}}buildMessage(e){const t=[`From: ${m.formatAddress(e.from)}`,`To: ${this.formatAddresses(e.to)}`];if(e.cc&&t.push(`Cc: ${this.formatAddresses(e.cc)}`),e.replyTo&&t.push(`Reply-To: ${m.formatAddress(e.replyTo)}`),t.push(`Subject: ${e.subject}`,"MIME-Version: 1.0"),e.headers)for(const[a,i]of Object.entries(e.headers))t.push(`${a}: ${i}`);const o=!!e.text,r=!!e.html;let n;return o&&r?(n=ie(),t.push(`Content-Type: multipart/alternative; boundary="${n}"`)):r?t.push("Content-Type: text/html; charset=utf-8"):t.push("Content-Type: text/plain; charset=utf-8"),t.push(""),o&&r&&n?t.push(`--${n}`,"Content-Type: text/plain; charset=utf-8","",e.text,"",`--${n}`,"Content-Type: text/html; charset=utf-8","",e.html,"",`--${n}--`):o?t.push(e.text):r&&t.push(e.html),t.join(`\r
|
|
8
|
+
`)}formatAddresses(e){return(Array.isArray(e)?e:[e]).map(t=>m.formatAddress(t)).join(", ")}}const be=s=>new m(s);export{m as SmimeSigner,be as createSmimeSigner};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import l from"./EmailError-
|
|
1
|
+
import l from"./EmailError-CDvYwuqz.js";import b from"./RequiredOptionError-DU2lxzk3.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-CylyuRaN.js";import{i as g}from"./retry-CG9iT2wF.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-D1cbAhQi.js";import{h,P as E,c as S}from"./provider-base-DjPzWncP.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,17 @@
|
|
|
1
|
+
import{createRequire as T}from"node:module";import{q as I}from"./index-Gd7m-UQA.js";import{s as x}from"./headers-to-record-De1Eg951.js";import{f as b}from"./format-address-DTl-9O70.js";let E;const N=s=>(E??=T(import.meta.url))(s),g=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,B=s=>{if(typeof g<"u"&&g.versions&&g.versions.node){const[e,r]=g.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return g.getBuiltinModule(s)}return N(s)},{Buffer:$}=B("node:buffer"),{createPublicKey:D,createHash:v,createPrivateKey:P,sign:W,createSign:F,verify:R}=B("node:crypto"),H=/\s+/g,V=/ $/,z=/^\s*i=(\d+)\s*;/,G=["from","to","cc","subject","date","message-id","mime-version"],u=(s,e)=>`${s.toLowerCase()}:${e.replaceAll(H," ").trim()}`,J=s=>{let e=s.replaceAll(`\r
|
|
2
|
+
`,`
|
|
3
|
+
`).replaceAll("\r",`
|
|
4
|
+
`).split(`
|
|
5
|
+
`).map(r=>r.replaceAll(H," ").replace(V,"")).join(`\r
|
|
6
|
+
`);for(;e.endsWith(`\r
|
|
7
|
+
`);)e=e.slice(0,-2);return e.length>0?`${e}\r
|
|
8
|
+
`:`\r
|
|
9
|
+
`},k=s=>{const e={...s.headers?x(s.headers):{},From:b(s.from),Subject:s.subject,To:b(s.to)};return s.cc&&(e.Cc=b(s.cc)),e["MIME-Version"]??="1.0",e},C=s=>{const e={};for(const r of s.split(";")){const a=r.indexOf("=");a!==-1&&(e[r.slice(0,a).trim()]=r.slice(a+1).trim())}return e},w=s=>{const e=s.lastIndexOf("b=");return e===-1?s:s.slice(0,e+2)},q=s=>{const e=[s.text,s.html].filter(r=>r!==void 0).join(`
|
|
10
|
+
|
|
11
|
+
`);return v("sha256").update(J(e)).digest("base64")},_=(s,e,r)=>r==="ed25519-sha256"?W(null,v("sha256").update(s).digest(),e).toString("base64"):F("RSA-SHA256").update(s).sign(e,"base64"),M=(s,e,r,a)=>{const t=$.from(e,"base64");try{return a==="ed25519-sha256"?R(null,v("sha256").update(s).digest(),r,t):R("RSA-SHA256",$.from(s),r,t)}catch{return!1}},U=(s,e)=>{const r=e.instance??1,a=e.algorithm??"rsa-sha256",t=e.timestamp??Math.floor(Date.now()/1e3),n=k(s),l=(e.headersToSign??G).filter(i=>{const d=Object.keys(n).find(h=>h.toLowerCase()===i);return d!==void 0&&n[d]!==void 0&&n[d]!==""}),c=[`i=${String(r)}`,`a=${a}`,"c=relaxed/relaxed",`d=${e.domainName}`,`s=${e.keySelector}`,`t=${String(t)}`,`h=${l.join(":")}`,`bh=${q(s)}`,"b="].join("; "),o=`${l.map(i=>{const d=Object.keys(n).find(h=>h.toLowerCase()===i);return u(i,n[d]??"")}).join(`\r
|
|
12
|
+
`)}\r
|
|
13
|
+
${u("ARC-Message-Signature",c)}`;return{header:c,signBase:o}},Q=(s,e,r)=>{const a=r.instance??1,t=r.algorithm??"rsa-sha256",n=r.timestamp??Math.floor(Date.now()/1e3),l=r.cv??"none",c=[`i=${String(a)}`,`a=${t}`,`cv=${l}`,`d=${r.domainName}`,`s=${r.keySelector}`,`t=${String(n)}`,"b="].join("; "),o=[u("ARC-Authentication-Results",s),u("ARC-Message-Signature",e),u("ARC-Seal",c)].join(`\r
|
|
14
|
+
`);return{header:c,signBase:o}},X=async(s,e)=>{let r=s;return r.startsWith("file://")&&(r=await I(r.slice(7),{encoding:"utf8"})),P({key:r,passphrase:e})},re=async(s,e)=>{const r=e.instance??1,a=e.cv??"none";if(r!==1)throw new Error(`signArc only supports an originating sealer (instance 1); received i=${String(r)}`);if(a!=="none")throw new Error(`signArc only supports cv=none for an originating sealer; received cv=${a}`);const t=e.algorithm??"rsa-sha256",n={...e,cv:"none",timestamp:e.timestamp??Math.floor(Date.now()/1e3)},l=await X(e.privateKey,e.passphrase),c=`i=${String(r)}; ${e.authenticationResults}`,o=U(s,n),i=`${o.header}${_(o.signBase,l,t)}`,d=Q(c,i,n),h=`${d.header}${_(d.signBase,l,t)}`,m={"ARC-Authentication-Results":c,"ARC-Message-Signature":i,"ARC-Seal":h};return{email:{...s,headers:{...s.headers?x(s.headers):{},...m}},headers:m}},ae=(s,e,r)=>{const a=Object.fromEntries(Object.entries(e).map(([f,p])=>[f.toLowerCase(),p])),t=a["arc-message-signature"],n=a["arc-seal"],l=a["arc-authentication-results"];if(!t||!n||!l)return{components:{ams:!1,bodyHash:!1,seal:!1},reason:"missing-arc-headers",valid:!1};let c;try{c=typeof r.publicKey=="string"?D(r.publicKey):r.publicKey}catch{return{components:{ams:!1,bodyHash:!1,seal:!1},reason:"invalid-public-key",valid:!1}}const o=C(t),i=C(n);if(z.exec(l)?.[1]!=="1"||o.i!=="1"||i.i!=="1"||i.cv!=="none")return{components:{ams:!1,bodyHash:!1,seal:!1},cv:i.cv,reason:"unsupported-arc-instance",valid:!1};const d=o.a==="ed25519-sha256"?"ed25519-sha256":"rsa-sha256",h=i.a==="ed25519-sha256"?"ed25519-sha256":"rsa-sha256",m=o.bh!==void 0&&o.bh===q(s),y=k(s),K=`${(o.h??"").split(":").map(f=>f.trim().toLowerCase()).filter(Boolean).map(f=>{const p=Object.keys(y).find(L=>L.toLowerCase()===f);return u(f,p?y[p]??"":"")}).join(`\r
|
|
15
|
+
`)}\r
|
|
16
|
+
${u("ARC-Message-Signature",w(t))}`,A=M(K,o.b??"",c,d),O=[u("ARC-Authentication-Results",l),u("ARC-Message-Signature",t),u("ARC-Seal",w(n))].join(`\r
|
|
17
|
+
`),S=M(O,i.b??"",c,h),j=A&&S&&m;return{components:{ams:A,bodyHash:m,seal:S},cv:i.cv,reason:j?void 0:"signature-mismatch",valid:j}};export{U as arcMessageSignatureBase,Q as arcSealBase,re as signArc,ae as verifyArc};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createRequire as c}from"node:module";import f from"./EmailError-CDvYwuqz.js";let s;const r=e=>(s??=c(import.meta.url))(e),o=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,p=e=>{if(typeof o<"u"&&o.versions&&o.versions.node){const[t,n]=o.versions.node.split(".").map(Number);if(t>22||t===22&&n>=3||t===20&&n>=16)return o.getBuiltinModule(e)}return r(e)},{Buffer:m}=p("node:buffer"),a=async(e,t)=>{let n;if(e.content)if(typeof e.content=="string")n=e.content;else if(e.content instanceof Promise){const i=await e.content;n=m.from(i).toString("base64")}else n=e.content.toString("base64");else if(e.raw)n=typeof e.raw=="string"?e.raw:e.raw.toString("base64");else throw new f(t,`Attachment ${e.filename} has no content`);return n},u=async(e,t)=>({content:await a(e,t),contentType:e.contentType??"application/octet-stream",disposition:e.contentDisposition??"attachment",filename:e.filename,...e.cid&&{contentId:e.cid}}),y=async(e,t)=>({content:await a(e,t),disposition:e.contentDisposition??"attachment",filename:e.filename,type:e.contentType??"application/octet-stream",...e.cid&&{content_id:e.cid}}),_=async(e,t)=>({Content:await a(e,t),ContentType:e.contentType??"application/octet-stream",Name:e.filename,...e.cid&&{ContentID:e.cid}}),h=async(e,t,n)=>({content:await a(e,t),key:`attachment[${n}]`});export{h as a,_ as b,u as c,y as d,a as p};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import c from"./EmailError-
|
|
1
|
+
import c from"./EmailError-CDvYwuqz.js";import T from"./RequiredOptionError-DU2lxzk3.js";import{s as x}from"./headers-to-record-De1Eg951.js";import{m as z}from"./make-request-CylyuRaN.js";import{i as K}from"./retry-CG9iT2wF.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-DjPzWncP.js";import{c as F}from"./attachment-processor-D1cbAhQi.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,19 +1,19 @@
|
|
|
1
|
-
import{createRequire as D}from"node:module";import E from"./EmailError-
|
|
1
|
+
import{createRequire as D}from"node:module";import E from"./EmailError-CDvYwuqz.js";import F from"./RequiredOptionError-DU2lxzk3.js";import{c as G}from"./create-logger-BQTS3f-I.js";import h from"../utils/format-email-address.js";import{s as Q}from"./headers-to-record-De1Eg951.js";import{m as X}from"./make-request-CylyuRaN.js";import{a as _,s as Y}from"./sanitize-header-DtQwAnzg.js";import{f as Z}from"./validate-email-options-mCM9dVug.js";import{defineProvider as J}from"./defineProvider-C9q-7iwt.js";let N;const V=p=>(N??=D(import.meta.url))(p),A=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,L=p=>{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(p)}return V(p)},{randomUUID:R,createHash:v,createHmac:$}=L("node:crypto"),ee=globalThis.Buffer!==void 0,I=()=>{if(!ee)throw new Error("Buffer is required for AWS SES provider");return globalThis.Buffer},S="aws-ses",j={apiVersion:"2010-12-01",maxAttempts:3,region:"us-east-1"},ge=J((p={})=>{const a={...j,...p},d=G("AWS-SES",p.logger),q=(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
|
-
`,n=Object.keys(s).toSorted().map(c=>c.toLowerCase()).join(";"),g=
|
|
4
|
-
`)},
|
|
5
|
-
`)},
|
|
6
|
-
`,r+=Array.isArray(e.to)?`To: ${e.to.map(n=>
|
|
7
|
-
`:`To: ${
|
|
8
|
-
`,e.cc&&(r+=Array.isArray(e.cc)?`Cc: ${e.cc.map(n=>
|
|
9
|
-
`:`Cc: ${
|
|
10
|
-
`),e.bcc&&(r+=Array.isArray(e.bcc)?`Bcc: ${e.bcc.map(n=>
|
|
11
|
-
`:`Bcc: ${
|
|
12
|
-
`),r+=`Subject: ${
|
|
3
|
+
`,n=Object.keys(s).toSorted().map(c=>c.toLowerCase()).join(";"),g=v("sha256").update(o).digest("hex");return[e,i,u,r,n,g].join(`
|
|
4
|
+
`)},P=(e,i,t)=>{const s=e.slice(0,8),o=v("sha256").update(t).digest("hex");return["AWS4-HMAC-SHA256",e,`${s}/${i}/ses/aws4_request`,o].join(`
|
|
5
|
+
`)},W=(e,i,t,s)=>{const o=i.slice(0,8),u=$("sha256",`AWS4${e}`).update(o).digest(),r=$("sha256",u).update(t).digest(),n=$("sha256",r).update("ses").digest(),g=$("sha256",n).update("aws4_request").digest();return $("sha256",g).update(s).digest("hex")},k=(e,i,t,s,o)=>{const u=i.slice(0,8),r=Object.keys(s).toSorted().map(n=>n.toLowerCase()).join(";");return[`AWS4-HMAC-SHA256 Credential=${e}/${u}/${t}/ses/aws4_request`,`SignedHeaders=${r}`,`Signature=${o}`].join(", ")},M=async(e,i)=>{if(!a.accessKeyId||!a.secretAccessKey)throw d.debug("Missing required credentials: accessKeyId or secretAccessKey"),new F(S,["accessKeyId","secretAccessKey"]);try{const t=a.region||j.region,s=a.apiVersion||j.apiVersion,o=a.endpoint||`email.${t}.amazonaws.com`,u="/",r="POST";d.debug("Making request to AWS SES:",{action:e,host:o,region:t});const n=new URLSearchParams;n.append("Action",e),n.append("Version",s),Object.entries(i).forEach(([f,m])=>{m!=null&&n.append(f,String(m))});const g=n.toString();d.debug("Request body:",g);const c=new Date().toISOString().replaceAll(/[:-]|\.\d{3}/g,""),l={"Content-Length":I().byteLength(g).toString(),"Content-Type":"application/x-www-form-urlencoded",Host:o,"X-Amz-Date":c};a.sessionToken&&(l["X-Amz-Security-Token"]=a.sessionToken),d.debug("Request headers:",l);const y=q(r,u,{},l,g),U=P(c,t,y),O=W(a.secretAccessKey,c,t,U);l.Authorization=k(a.accessKeyId,c,t,l,O),d.debug("Making HTTPS request to:",`https://${o}${u}`);const z=`https://${o}${u}`,w=await X(z,{headers:l,method:r},g);if(!w.success)throw w.error??new Error("AWS SES API request failed");const b=w.data?.body;if(!b)throw new Error("No response body from AWS SES");const C=w.data?.statusCode;d.debug("Response status:",C),d.debug("Response data:",b);const T=C;if(T&&T>=200&&T<300){const f={};if(e==="SendRawEmail"){const m=b.match(/<MessageId>(.*?)<\/MessageId>/);if(m){const[,B]=m;f.MessageId=B,d.debug("Extracted MessageId:",f.MessageId)}}else if(e==="GetSendQuota"){const m=b.match(/<Max24HourSend>(.*?)<\/Max24HourSend>/);m?.[1]&&(f.Max24HourSend=Number.parseFloat(m[1]),d.debug("Extracted Max24HourSend:",f.Max24HourSend))}return f}const x=b.match(/<Message>(.*?)<\/Message>/),H=x?x[1]:"Unknown AWS SES error";throw d.debug("AWS SES Error:",H),new Error(`AWS SES API Error: ${H}`)}catch(t){const s=t instanceof Error?t.message:String(t);throw d.debug("makeAwsRequest exception:",s),t instanceof Error?t:new Error(s)}},K=e=>{const i=`----=${R().replaceAll("-","")}`,t=new Date().toUTCString(),s=e.from.email.includes("@")?e.from.email.split("@")[1]:"localhost",o=`<${R().replaceAll("-","")}@${s}>`,u=I();let r="";if(r+=`From: ${h(e.from)}\r
|
|
6
|
+
`,r+=Array.isArray(e.to)?`To: ${e.to.map(n=>h(n)).join(", ")}\r
|
|
7
|
+
`:`To: ${h(e.to)}\r
|
|
8
|
+
`,e.cc&&(r+=Array.isArray(e.cc)?`Cc: ${e.cc.map(n=>h(n)).join(", ")}\r
|
|
9
|
+
`:`Cc: ${h(e.cc)}\r
|
|
10
|
+
`),e.bcc&&(r+=Array.isArray(e.bcc)?`Bcc: ${e.bcc.map(n=>h(n)).join(", ")}\r
|
|
11
|
+
`:`Bcc: ${h(e.bcc)}\r
|
|
12
|
+
`),r+=`Subject: ${_(e.subject)}\r
|
|
13
13
|
`,r+=`Date: ${t}\r
|
|
14
14
|
`,r+=`Message-ID: ${o}\r
|
|
15
15
|
`,r+=`MIME-Version: 1.0\r
|
|
16
|
-
`,e.headers){const n=
|
|
16
|
+
`,e.headers){const n=Q(e.headers);for(const[g,c]of Object.entries(n)){const l=Y(g),y=_(c);r+=`${l}: ${y}\r
|
|
17
17
|
`}}return r+=`Content-Type: multipart/alternative; boundary="${i}"\r
|
|
18
18
|
\r
|
|
19
19
|
`,e.text&&(r+=`--${i}\r
|
|
@@ -29,4 +29,4 @@ import{createRequire as D}from"node:module";import E from"./EmailError-B-sEf3bp.
|
|
|
29
29
|
`,r+=`${u.from(e.html,"utf8").toString("base64")}\r
|
|
30
30
|
\r
|
|
31
31
|
`),r+=`--${i}--\r
|
|
32
|
-
`,r};return{features:{attachments:!1,batchSending:!1,customHeaders:!0,html:!0,replyTo:!1,scheduling:!1,tagging:!1,templates:!1,tracking:!1},getInstance:()=>{},initialize(){d.debug("Initializing AWS SES provider with options:",{accessKeyId:a.accessKeyId?`***${a.accessKeyId.slice(-4)}`:void 0,endpoint:a.endpoint,region:a.region,secretAccessKey:a.secretAccessKey?"***":void 0})},async isAvailable(){try{return!!(await M("GetSendQuota",{})).Max24HourSend}catch{return!1}},name:
|
|
32
|
+
`,r};return{features:{attachments:!1,batchSending:!1,customHeaders:!0,html:!0,replyTo:!1,scheduling:!1,tagging:!1,templates:!1,tracking:!1},getInstance:()=>{},initialize(){d.debug("Initializing AWS SES provider with options:",{accessKeyId:a.accessKeyId?`***${a.accessKeyId.slice(-4)}`:void 0,endpoint:a.endpoint,region:a.region,secretAccessKey:a.secretAccessKey?"***":void 0})},async isAvailable(){try{return!!(await M("GetSendQuota",{})).Max24HourSend}catch{return!1}},name:S,options:a,async sendEmail(e){const i=t=>{const s=[];return t.attachments&&t.attachments.length>0&&s.push("attachments"),t.priority&&s.push("priority"),t.tags&&t.tags.length>0&&s.push("tags (use messageTags instead)"),t.replyTo&&s.push("replyTo"),s};try{const t=Z(e);if(t.length>0)throw new E(S,`Invalid email options: ${t.join(", ")}`);const s=i(e);if(s.length>0)throw new E(S,`Unsupported fields provided: ${s.join(", ")}. These fields are not supported by AWS SES Raw Email API and would be silently ignored.`);const o={};e.configurationSetName&&(o.ConfigurationSetName=e.configurationSetName),e.sourceArn&&(o.SourceArn=e.sourceArn),e.returnPath&&(o.ReturnPath=e.returnPath),e.returnPathArn&&(o.ReturnPathArn=e.returnPathArn),e.messageTags&&Object.keys(e.messageTags).length>0&&Object.entries(e.messageTags).forEach(([c,l],y)=>{o[`Tags.member.${y+1}.Name`]=c,o[`Tags.member.${y+1}.Value`]=l});const u=K(e),r=I().from(u).toString("base64");o["RawMessage.Data"]=r;const n=await M("SendRawEmail",o),g=n.MessageId;return!g||g.trim()===""?{error:new E(S,"AWS SES API returned a response without a MessageId. The email may not have been sent successfully."),success:!1}:{data:{messageId:g,provider:S,response:n,sent:!0,timestamp:new Date},success:!0}}catch(t){return{error:new E(S,`Failed to send email: ${t instanceof Error?t.message:String(t)}`,{cause:t instanceof Error?t:new Error(String(t))}),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{ge as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createRequire as A}from"node:module";import l from"./EmailError-CDvYwuqz.js";import w from"./RequiredOptionError-DU2lxzk3.js";import{e as P}from"./generate-message-id-gXAuMz4g.js";import{s as _}from"./headers-to-record-De1Eg951.js";import{m as h}from"./make-request-CylyuRaN.js";import{i as v}from"./retry-CG9iT2wF.js";import{f as j}from"./validate-email-options-mCM9dVug.js";import{defineProvider as B}from"./defineProvider-C9q-7iwt.js";import{P as C,h as T,c as E}from"./provider-base-DjPzWncP.js";import{b as y,c as q}from"./address-formatter-BWR2Dddx.js";let z;const k=n=>(z??=A(import.meta.url))(n),f=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,I=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 k(n)},{Buffer:p}=I("node:buffer"),i="azure",R=3e4,x=3,Q=B((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??x,timeout:n.timeout??R,...n.connectionString&&{connectionString:n.connectionString},...n.accessToken&&{accessToken:n.accessToken},...n.logger&&{logger:n.logger}},g=new C,a=E(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=q(e.replyTo).email),e.importance&&(r.importance=e.importance),e.headers){const s=_(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??P();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{Q as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import d from"./EmailError-
|
|
1
|
+
import d from"./EmailError-CDvYwuqz.js";import T from"./RequiredOptionError-DU2lxzk3.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-CylyuRaN.js";import{i as g}from"./retry-CG9iT2wF.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-DjPzWncP.js";import{f as p,a as y}from"./address-formatter-BWR2Dddx.js";import{p as j}from"./attachment-processor-D1cbAhQi.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};
|
package/dist/packem_shared/{build-mime-message-BW5FQ2Bt.js → build-mime-message-DT67qfMp.js}
RENAMED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import v from"./EmailError-
|
|
1
|
+
import v from"./EmailError-CDvYwuqz.js";import l from"../utils/format-email-address.js";import{r as F}from"./generate-boundary-0xGe9GqK.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 w from"./EmailError-
|
|
1
|
+
import w from"./EmailError-CDvYwuqz.js";const C=(c={})=>{const{failureThreshold:u=5,now:s=Date.now,onStateChange:p,resetTimeout:d=3e4}=c;let e="closed",n=0,l=0,t=!1;const a=r=>{e!==r&&(e=r,p?.(r))},i=()=>({error:new w("middleware","Circuit breaker is open",{code:"CIRCUIT_OPEN"}),success:!1});return async(r,h)=>{if(e==="open"&&s()-l>=d&&(a("half-open"),t=!1),e==="open")return i();let f=!1;if(e==="half-open"){if(t)return i();t=!0,f=!0}let o;try{o=await h(r)}finally{f&&(t=!1)}return o.success?(n=0,a("closed"),o):(n+=1,(e==="half-open"||n>=u)&&(l=s(),a("open")),o)}};export{C as circuitBreakerMiddleware};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import a from"./EmailError-
|
|
1
|
+
import a from"./EmailError-CDvYwuqz.js";import m from"./RequiredOptionError-DU2lxzk3.js";import{F as d}from"./build-mime-message-DT67qfMp.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-DjPzWncP.js";const r="cloudflare-email",C=g((t={})=>{if(typeof t.send!="function")throw new m(r,"send");const c=v(r,t.logger);return{features:{attachments:!0,batchSending:!1,customHeaders:!0,html:!0,replyTo:!0,scheduling:!1,tagging:!1,templates:!1,tracking:!1},async initialize(){await Promise.resolve()},async isAvailable(){return typeof t.send=="function"},name:r,async sendEmail(e){try{const s=p(e);if(s.length>0)return{error:new a(r,`Invalid email options: ${s.join(", ")}`),success:!1};const i=Array.isArray(e.to)?e.to:[e.to];if(i.length!==1||e.cc!==void 0||e.bcc!==void 0)return{error:new a(r,"Cloudflare Email supports exactly one `to` recipient and does not support cc/bcc"),success:!1};const[o]=i;if(!o)return{error:new a(r,"A single `to` recipient is required"),success:!1};const n=f(),l=await d({...e,headers:{...e.headers?u(e.headers):{},"Message-ID":n}});return await t.send(e.from.email,o.email,l),{data:{messageId:n,provider:r,sent:!0,timestamp:new Date},success:!0}}catch(s){return{error:h(r,"send email",s,c),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{C as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createMail as w}from"./Mail-
|
|
1
|
+
import{createMail as w}from"./Mail-CIyxkmxu.js";import u from"./mockProvider-BAl292mW.js";const d=(t,o,e,n)=>{const r=Date.now()+e;return new Promise((s,c)=>{const a=()=>{const i=t.find(m=>o(m));if(i){s(i);return}if(Date.now()>=r){c(new Error("waitFor timed out before a matching message was captured"));return}setTimeout(a,n)};a()})},l=()=>{const t=u(),o=w(t),e=t.getInstance?.();if(!e)throw new Error("mockProvider() did not expose getInstance(); cannot create a test harness");return{mail:o,reset:()=>{e.length=0},sent:()=>e,waitFor:(n,r={})=>d(e,n,r.timeout??1e3,r.interval??10)}};export{l as createTestEmail};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createRequire as _}from"node:module";let m;const f=t=>(m??=_(import.meta.url))(t),s=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,g=t=>{if(typeof s<"u"&&s.versions&&s.versions.node){const[e,r]=s.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return s.getBuiltinModule(t)}return f(t)},{createHash:h}=g("node:crypto"),p=t=>t?(Array.isArray(t)?t:[t]).map(e=>e.email.toLowerCase()).toSorted((e,r)=>e.localeCompare(r)).join(","):"",j=t=>{const e=h("sha256");return e.update(p(t.to)),e.update("\0"),e.update(p(t.cc)),e.update("\0"),e.update(t.subject),e.update("\0"),e.update(t.text??t.html??""),e.digest("hex")},w=(t={})=>{const{keyFn:e=j,now:r=Date.now,ttl:d=6e4}=t,a=new Map;return async(c,l)=>{const u=e(c),i=r(),o=a.get(u);if(o&&o.expires>i)return o.result;const n=await l(c);return n.success&&a.set(u,{expires:i+d,result:n}),n}};export{w as dedupeMiddleware};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{q as o}from"./index-Gd7m-UQA.js";import a from"mime";const n=e=>a.getType(e)??"application/octet-stream",p=e=>{const t=e.replaceAll(/[^a-z0-9]/gi,"-").replaceAll(/-+/g,"-").replaceAll(/^-|-$/g,"").toLowerCase(),r=Math.random().toString(36).slice(2,9);return`${t}-${r}@email`},c=e=>o(e,{buffer:!0});export{n as detectMimeType,p as generateContentId,c as readFileAsBuffer};
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The lifecycle/engagement event types that converge onto a single {@link EmailEvent} shape.
|
|
3
|
+
*
|
|
4
|
+
* The first group (`queued` → `failed`) is emitted by the send pipeline; the rest typically originate
|
|
5
|
+
* from provider webhooks (delivery/engagement signals).
|
|
6
|
+
*/
|
|
7
|
+
type EmailEventType = "attempt" | "bounced" | "clicked" | "complained" | "deferred" | "delivered" | "failed" | "opened" | "queued" | "sent" | "unsubscribed";
|
|
8
|
+
/**
|
|
9
|
+
* A single, provider-agnostic email event. Both internal send-lifecycle signals and normalized
|
|
10
|
+
* webhook events use this shape so a timeline can be reconstructed from one stream.
|
|
11
|
+
*/
|
|
12
|
+
interface EmailEvent {
|
|
13
|
+
/**
|
|
14
|
+
* Arbitrary structured payload (provider response, bounce sub-type, click URL, …).
|
|
15
|
+
*/
|
|
16
|
+
data?: Record<string, unknown>;
|
|
17
|
+
/**
|
|
18
|
+
* A unique id for this event.
|
|
19
|
+
*/
|
|
20
|
+
id: string;
|
|
21
|
+
/**
|
|
22
|
+
* The message this event concerns.
|
|
23
|
+
*/
|
|
24
|
+
messageId?: string;
|
|
25
|
+
/**
|
|
26
|
+
* The provider that produced (or will produce) the message.
|
|
27
|
+
*/
|
|
28
|
+
provider?: string;
|
|
29
|
+
/**
|
|
30
|
+
* The recipient address this event concerns, when applicable.
|
|
31
|
+
*/
|
|
32
|
+
recipient?: string;
|
|
33
|
+
/**
|
|
34
|
+
* When the event occurred.
|
|
35
|
+
*/
|
|
36
|
+
timestamp: Date;
|
|
37
|
+
/**
|
|
38
|
+
* The kind of event.
|
|
39
|
+
*/
|
|
40
|
+
type: EmailEventType;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* A listener invoked for matching {@link EmailEvent}s.
|
|
44
|
+
*/
|
|
45
|
+
type EmailEventListener = (event: EmailEvent) => void;
|
|
46
|
+
/**
|
|
47
|
+
* A persistence backend for {@link EmailEvent}s.
|
|
48
|
+
*/
|
|
49
|
+
interface EventStore {
|
|
50
|
+
/**
|
|
51
|
+
* Appends an event.
|
|
52
|
+
* @param event The event to store.
|
|
53
|
+
*/
|
|
54
|
+
append: (event: EmailEvent) => Promise<void> | void;
|
|
55
|
+
/**
|
|
56
|
+
* Returns the full, time-ordered timeline for a message.
|
|
57
|
+
* @param messageId The message to reconstruct.
|
|
58
|
+
*/
|
|
59
|
+
timeline: (messageId: string) => EmailEvent[] | Promise<EmailEvent[]>;
|
|
60
|
+
}
|
|
61
|
+
type Selector = "*" | EmailEventType;
|
|
62
|
+
/**
|
|
63
|
+
* The wildcard selector that subscribes to every event type.
|
|
64
|
+
*/
|
|
65
|
+
declare const ALL_EVENTS: "*";
|
|
66
|
+
/**
|
|
67
|
+
* A tiny synchronous pub/sub bus for {@link EmailEvent}s.
|
|
68
|
+
*
|
|
69
|
+
* Subscribe to a specific {@link EmailEventType} or to {@link ALL_EVENTS} (`"*"`) for every event.
|
|
70
|
+
*/
|
|
71
|
+
declare class EventBus {
|
|
72
|
+
private readonly listeners;
|
|
73
|
+
/**
|
|
74
|
+
* Subscribes a listener to an event type (or all events).
|
|
75
|
+
* @param type The event type, or `"*"` for all events.
|
|
76
|
+
* @param listener The listener to invoke.
|
|
77
|
+
* @returns An unsubscribe function.
|
|
78
|
+
*/
|
|
79
|
+
on(type: Selector, listener: EmailEventListener): () => void;
|
|
80
|
+
/**
|
|
81
|
+
* Subscribes a listener that is removed after its first invocation.
|
|
82
|
+
* @param type The event type, or `"*"` for all events.
|
|
83
|
+
* @param listener The listener to invoke once.
|
|
84
|
+
* @returns An unsubscribe function.
|
|
85
|
+
*/
|
|
86
|
+
once(type: Selector, listener: EmailEventListener): () => void;
|
|
87
|
+
/**
|
|
88
|
+
* Removes a previously-added listener.
|
|
89
|
+
* @param type The event type the listener was registered under.
|
|
90
|
+
* @param listener The listener to remove.
|
|
91
|
+
*/
|
|
92
|
+
off(type: Selector, listener: EmailEventListener): void;
|
|
93
|
+
/**
|
|
94
|
+
* Emits an event to all matching listeners (type-specific first, then wildcard).
|
|
95
|
+
* @param event The event to dispatch.
|
|
96
|
+
*/
|
|
97
|
+
emit(event: EmailEvent): void;
|
|
98
|
+
/**
|
|
99
|
+
* Removes all listeners (optionally for a single type).
|
|
100
|
+
* @param type When provided, only listeners for this type are removed.
|
|
101
|
+
*/
|
|
102
|
+
clear(type?: Selector): void;
|
|
103
|
+
}
|
|
104
|
+
export { ALL_EVENTS as A, EmailEvent as E, EventStore as a, EmailEventListener as b, EmailEventType as c, EventBus as d };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import u from"./EmailError-
|
|
1
|
+
import u from"./EmailError-CDvYwuqz.js";import b from"./RequiredOptionError-DU2lxzk3.js";import{c as w}from"./create-logger-BQTS3f-I.js";import{e as y}from"./generate-message-id-gXAuMz4g.js";import{defineProvider as $}from"./defineProvider-C9q-7iwt.js";import{d as A}from"./aggregate-features-BqEjPd42.js";const E=i=>typeof i=="function",z=i=>i!==null&&typeof i=="object"&&"sendEmail"in i&&"initialize"in i&&"isAvailable"in i,o="failover",j=$((i={})=>{if(!i.mailers||i.mailers.length===0)throw new b(o,"mailers");const d={debug:i.debug??!1,mailers:i.mailers,retryAfter:i.retryAfter??60};let v=!1;const t=[],n=w(o,i.logger);let g;const m=async()=>g||(g=(async()=>{t.length=0;for(const a of d.mailers)try{let e;if(E(a))e=a({});else if(z(a))e=a;else{n.debug(`Skipping invalid mailer: ${a}`);continue}try{await e.initialize(),t.push(e),n.debug(`Initialized provider: ${e.name??"unknown"}`)}catch(l){n.debug(`Failed to initialize provider ${e.name??"unknown"}:`,l)}}catch(e){n.debug("Error processing mailer:",e)}if(t.length===0)throw new u(o,"No providers could be initialized")})(),g);return{features:A(d.mailers),async initialize(){if(!v)try{await m(),v=!0,n.debug(`Failover provider initialized with ${t.length} provider(s)`)}catch(a){throw new u(o,`Failed to initialize: ${a.message}`,{cause:a})}},async isAvailable(){try{t.length===0&&await m();for(const a of t)try{if(await a.isAvailable())return!0}catch{}return!1}catch{return!1}},name:o,options:d,async sendEmail(a){try{if(t.length===0&&await m(),t.length===0)return{error:new u(o,"No providers available"),success:!1};const e=[];let l;for(let s=0;s<t.length;s+=1){const f=t[s];if(!f)continue;const c=f.name??`provider-${s+1}`;n.debug(`Attempting to send email via ${c} (${s+1}/${t.length})`);try{if(!await f.isAvailable()){n.debug(`Provider ${c} is not available, skipping`),e.push(new u(o,`Provider ${c} is not available`));continue}const r=await f.sendEmail(a);if(r.success&&r.data)return n.debug(`Email sent successfully via ${c}`),{data:{...r.data,messageId:r.data.messageId||y(),provider:`${o}(${c})`},success:!0};if(r.error){l=r.error,e.push(r.error);const p=r.error instanceof Error?r.error.message:String(r.error);n.debug(`Failed to send via ${c}:`,p)}}catch(r){l=r instanceof Error?r:new Error(String(r)),e.push(l);const p=l instanceof Error?l.message:String(l);n.debug(`Exception sending via ${c}:`,p)}s<t.length-1&&d.retryAfter>0&&(n.debug(`Waiting ${d.retryAfter}ms before trying next provider`),await new Promise(r=>{setTimeout(()=>{r()},d.retryAfter)}))}const h=e.map(s=>s instanceof Error?s.message:String(s)).join("; ");return{error:new u(o,`All providers failed. Errors: ${h}`,{cause:l}),success:!1}}catch(e){return{error:new u(o,`Failed to send email: ${e.message}`,{cause:e}),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{j as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createRequire as t}from"node:module";let n;const i=r=>(n??=t(import.meta.url))(r),e=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,c=r=>{if(typeof e<"u"&&e.versions&&e.versions.node){const[o,s]=e.versions.node.split(".").map(Number);if(o>22||o===22&&s>=3||o===20&&s>=16)return e.getBuiltinModule(r)}return i(r)},{randomBytes:_}=c("node:crypto"),a=()=>`----_=_NextPart_${_(16).toString("hex")}`;export{a as r};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import c from"./EmailError-
|
|
1
|
+
import c from"./EmailError-CDvYwuqz.js";import g from"./RequiredOptionError-DU2lxzk3.js";import{e as w}from"./generate-message-id-gXAuMz4g.js";import{m as u}from"./make-request-CylyuRaN.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};
|