UNPKG

@visulima/email

Version:

A comprehensive email library with multi-provider support, crypto utilities, and template engines

2 lines (1 loc) 4.43 kB
var P=Object.defineProperty;var y=(i,r)=>P(i,"name",{value:r,configurable:!0});import{createRequire as $}from"node:module";import c from"./EmailError-zm2ffVav.js";import S from"./RequiredOptionError-CevW3u2K.js";import _ from"./generateMessageId-11Ls5JsR.js";import E from"./headersToRecord-BKUTr40L.js";import{makeRequest as f}from"./makeRequest-DwxHX0xo.js";import b from"./retry-D1MBqS49.js";import z from"./validateEmailOptions-BzlJECG5.js";import{defineProvider as k}from"./defineProvider-B9rSklAJ.js";import{c as q,h as w,P as K}from"./provider-base-_hbWXBdK.js";import{f as p,a as B}from"./address-formatter-Cm_E_ZMa.js";const I=$(import.meta.url),m=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,T=y(i=>{if(typeof m<"u"&&m.versions&&m.versions.node){const[r,u]=m.versions.node.split(".").map(Number);if(r>22||r===22&&u>=3||r===20&&u>=16)return m.getBuiltinModule(i)}return I(i)},"__cjs_getBuiltinModule"),{Buffer:j}=T("node:buffer"),s="ahasend",C="https://api.ahasend.com",x=3e4,G=3,W=k((i={})=>{if(!i.apiKey)throw new S(s,"apiKey");const r={apiKey:i.apiKey,debug:i.debug||!1,endpoint:i.endpoint||C,retries:i.retries||G,timeout:i.timeout||x,...i.logger&&{logger:i.logger}},u=new K,n=q(s,i.logger);return{features:{attachments:!0,batchSending:!0,customHeaders:!0,html:!0,replyTo:!0,scheduling:!1,tagging:!0,templates:!0,tracking:!0},async getEmail(e){try{if(!e)return{error:new c(s,"Email ID is required to retrieve email details"),success:!1};await this.initialize();const o={Authorization:`Bearer ${r.apiKey}`,"Content-Type":"application/json"};n.debug("Retrieving email details",{id:e});const t=await b(async()=>f(`${r.endpoint}/emails/${e}`,{headers:o,method:"GET",timeout:r.timeout}),r.retries);return t.success?(n.debug("Email details retrieved successfully"),{data:t.data?.body,success:!0}):(n.debug("API request failed when retrieving email",t.error),{error:new c(s,`Failed to retrieve email: ${t.error instanceof Error?t.error.message:"Unknown error"}`,{cause:t.error}),success:!1})}catch(o){return{error:w(s,"retrieve email",o,n),success:!1}}},async initialize(){await u.ensureInitialized(async()=>{if(!await this.isAvailable())throw new c(s,"AhaSend API not available or invalid API key");n.debug("Provider initialized successfully")},s)},async isAvailable(){try{return n.debug("Checking AhaSend API availability"),!!(await f(`${r.endpoint}/v2/ping`,{headers:{Authorization:`Bearer ${r.apiKey}`,"Content-Type":"application/json"},method:"GET",timeout:r.timeout})).success}catch(e){return n.debug("Error checking availability:",e),!1}},name:s,options:r,async sendEmail(e){try{const o=z(e);if(o.length>0)return{error:new c(s,`Invalid email options: ${o.join(", ")}`),success:!1};await this.initialize();const t={from:{email:e.from.email,name:e.from.name},subject:e.subject,to:p(e.to)};if(e.html&&(t.html=e.html),e.text&&(t.text=e.text),e.cc&&(t.cc=p(e.cc)),e.bcc&&(t.bcc=p(e.bcc)),e.replyTo&&(t.replyTo=B(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 a=E(e.headers);t.headers=a}e.attachments&&e.attachments.length>0&&(t.attachments=await Promise.all(e.attachments.map(async a=>{let d;if(a.content)if(typeof a.content=="string")d=a.content;else if(a.content instanceof Promise){const A=await a.content;d=j.from(A).toString("base64")}else d=a.content.toString("base64");else if(a.raw)d=typeof a.raw=="string"?a.raw:a.raw.toString("base64");else throw new c(s,`Attachment ${a.filename} has no content`);return{content:d,contentType:a.contentType||"application/octet-stream",filename:a.filename,...a.cid&&{cid:a.cid}}}))),n.debug("Sending email via AhaSend API",{subject:t.subject,to:t.to});const v={Authorization:`Bearer ${r.apiKey}`,"Content-Type":"application/json"},l=await b(async()=>f(`${r.endpoint}/send`,{headers:v,method:"POST",timeout:r.timeout},JSON.stringify(t)),r.retries);if(!l.success)return n.debug("API request failed when sending email",l.error),{error:l.error||new c(s,"Failed to send email"),success:!1};const g=l.data?.body,h=g?.messageId||g?.id||_();return n.debug("Email sent successfully",{messageId:h}),{data:{messageId:h,provider:s,response:l.data,sent:!0,timestamp:new Date},success:!0}}catch(o){return{error:w(s,"send email",o,n),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{W as default};