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