@visulima/email 2.1.9 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/crypto/index.d.ts +50 -47
  3. package/dist/crypto/index.js +1 -1
  4. package/dist/index.d.ts +2 -2
  5. package/dist/index.js +1 -1
  6. package/dist/middleware/index.d.ts +19 -6
  7. package/dist/middleware/index.js +1 -1
  8. package/dist/packem_chunks/index.js +27 -0
  9. package/dist/packem_shared/DkimSigner-CCxFKitN.js +4 -0
  10. package/dist/packem_shared/{DraftMailMessage-Tj3sH8nn.js → DraftMailMessage-B0gwf8n_.js} +1 -1
  11. package/dist/packem_shared/{Mail-Cm24B3w0.js → Mail-DmYNQ0KK.js} +1 -1
  12. package/dist/packem_shared/{MailMessage-BtI4qMU1.js → MailMessage-DmmaNHHc.js} +1 -1
  13. package/dist/packem_shared/{SmimeEncrypter-BjBwjaTg.js → SmimeEncrypter-DnlfpjUX.js} +3 -3
  14. package/dist/packem_shared/{SmimeSigner-CK5TITxI.js → SmimeSigner-DTvclzLq.js} +2 -2
  15. package/dist/packem_shared/{address-formatter-CXZ1aWBX.js → address-formatter-w36S9ZYj.js} +1 -1
  16. package/dist/packem_shared/{ahaSendProvider-DY559XjD.js → ahaSendProvider-C1qvG8Cj.js} +1 -1
  17. package/dist/packem_shared/arcMessageSignatureBase-su9VTRB7.js +9 -0
  18. package/dist/packem_shared/{autoSendProvider-BgdWf422.js → autoSendProvider-yxUx3sEj.js} +1 -1
  19. package/dist/packem_shared/{azureProvider-Bs4BGYR1.js → azureProvider-CLLRKtOf.js} +1 -1
  20. package/dist/packem_shared/{brevoProvider-xoRTeFIx.js → brevoProvider-CHlodyzV.js} +1 -1
  21. package/dist/packem_shared/build-mime-message-BCFKPqaW.js +3 -0
  22. package/dist/packem_shared/canonicalize-BEjQUnUe.js +11 -0
  23. package/dist/packem_shared/cloudflareEmailProvider-Ckh_u-0D.js +1 -0
  24. package/dist/packem_shared/{createTestEmail-CPnHNKBT.js → createTestEmail-sB6z8m6Z.js} +1 -1
  25. package/dist/packem_shared/detectMimeType-BRz3Qjyz.js +1 -0
  26. package/dist/packem_shared/format-address-Bb7xk8G_.js +1 -0
  27. package/dist/packem_shared/{infobipProvider-mEYgfWJ7.js → infobipProvider-BEu1ycxS.js} +1 -1
  28. package/dist/packem_shared/{mail.d-8M9NjOr0.d.ts → mail.d-BdyyyQO5.d.ts} +10 -7
  29. package/dist/packem_shared/{mailCrabProvider-Cx9rnuyE.js → mailCrabProvider-BQ5ELwPU.js} +1 -1
  30. package/dist/packem_shared/{mailPaceProvider-DvSlan-v.js → mailPaceProvider-Ca3cz8JU.js} +1 -1
  31. package/dist/packem_shared/{mailchannelsProvider-Cgb8el7C.js → mailchannelsProvider-BZeuZk3d.js} +1 -1
  32. package/dist/packem_shared/{mailerSendProvider-BvRIjuVE.js → mailerSendProvider-C_Db652T.js} +1 -1
  33. package/dist/packem_shared/{mailgunProvider-kNcvF_z6.js → mailgunProvider-CU2b8ie8.js} +1 -1
  34. package/dist/packem_shared/{mailjetProvider-DqJUhLuH.js → mailjetProvider-VqvqCS7I.js} +1 -1
  35. package/dist/packem_shared/{mailomatProvider-BBOqRhV_.js → mailomatProvider-FMk4FZZz.js} +1 -1
  36. package/dist/packem_shared/{mailtrapProvider-CeBW2Gzg.js → mailtrapProvider-Qs0exKiJ.js} +1 -1
  37. package/dist/packem_shared/{mandrillProvider-Dab8i0gF.js → mandrillProvider-Co_EfMxl.js} +1 -1
  38. package/dist/packem_shared/{netcoreProvider-DMJsQ8IM.js → netcoreProvider-_kXjZ0bE.js} +1 -1
  39. package/dist/packem_shared/oauth2Middleware-C0M1w3_2.js +1 -0
  40. package/dist/packem_shared/{postalProvider-COVY4T94.js → postalProvider-tEBNXL3h.js} +1 -1
  41. package/dist/packem_shared/{postmarkProvider-Cj64C4dc.js → postmarkProvider-DdavP5x5.js} +1 -1
  42. package/dist/packem_shared/{resendProvider-Da5r7dMe.js → resendProvider-CMtlyIye.js} +1 -1
  43. package/dist/packem_shared/{scalewayProvider-CDjpYmJc.js → scalewayProvider-BFA1PQ73.js} +1 -1
  44. package/dist/packem_shared/{sendGridProvider-C1rp9hpg.js → sendGridProvider-DV80Lg7a.js} +1 -1
  45. package/dist/packem_shared/smtpProvider-BCEzJmay.js +14 -0
  46. package/dist/packem_shared/{sparkpostProvider-DKon_hyx.js → sparkpostProvider-C3pATjJX.js} +1 -1
  47. package/dist/packem_shared/{sweegoProvider-BclZuNBf.js → sweegoProvider-CkFtUAzq.js} +1 -1
  48. package/dist/packem_shared/{types.d-B0t3PQ3t.d.ts → types.d-Cb5fls_X.d.ts} +1 -1
  49. package/dist/packem_shared/{zeptomailProvider-D5B3kqFm.js → zeptomailProvider-tqRYpQlv.js} +1 -1
  50. package/dist/providers/ahasend/index.js +1 -1
  51. package/dist/providers/autosend/index.js +1 -1
  52. package/dist/providers/azure/index.js +1 -1
  53. package/dist/providers/brevo/index.js +1 -1
  54. package/dist/providers/cloudflare-email/index.d.ts +17 -1
  55. package/dist/providers/cloudflare-email/index.js +1 -1
  56. package/dist/providers/infobip/index.js +1 -1
  57. package/dist/providers/mailchannels/index.js +1 -1
  58. package/dist/providers/mailcrab/index.js +1 -1
  59. package/dist/providers/mailersend/index.js +1 -1
  60. package/dist/providers/mailgun/index.js +1 -1
  61. package/dist/providers/mailjet/index.js +1 -1
  62. package/dist/providers/mailomat/index.js +1 -1
  63. package/dist/providers/mailpace/index.js +1 -1
  64. package/dist/providers/mailtrap/index.js +1 -1
  65. package/dist/providers/mandrill/index.js +1 -1
  66. package/dist/providers/netcore/index.js +1 -1
  67. package/dist/providers/postal/index.js +1 -1
  68. package/dist/providers/postmark/index.js +1 -1
  69. package/dist/providers/resend/index.js +1 -1
  70. package/dist/providers/scaleway/index.js +1 -1
  71. package/dist/providers/sendgrid/index.js +1 -1
  72. package/dist/providers/smtp/index.d.ts +9 -5
  73. package/dist/providers/smtp/index.js +1 -1
  74. package/dist/providers/sparkpost/index.js +1 -1
  75. package/dist/providers/sweego/index.js +1 -1
  76. package/dist/providers/zeptomail/index.js +1 -1
  77. package/dist/test/index.d.ts +2 -2
  78. package/dist/test/index.js +1 -1
  79. package/dist/utils/format-email-address.js +1 -1
  80. package/package.json +1 -1
  81. package/dist/packem_shared/DkimSigner-B_pEwGCS.js +0 -18
  82. package/dist/packem_shared/arcMessageSignatureBase-B0Qi-724.js +0 -17
  83. package/dist/packem_shared/build-mime-message-QNCMA6oQ.js +0 -3
  84. package/dist/packem_shared/cloudflareEmailProvider-BkR-P0YD.js +0 -1
  85. package/dist/packem_shared/detectMimeType-DVC9Uvy9.js +0 -1
  86. package/dist/packem_shared/format-address-BDKhXcXV.js +0 -1
  87. package/dist/packem_shared/index-B8wiKJdh.js +0 -1
  88. package/dist/packem_shared/oauth2Middleware-DbKGd7Z9.js +0 -1
  89. package/dist/packem_shared/smtpProvider-Dr2XAFQu.js +0 -27
@@ -1 +0,0 @@
1
- import a from"./EmailError-BIaHK1Uw.js";import l from"./RequiredOptionError-ctDEEB1s.js";import{b as u}from"./build-mime-message-QNCMA6oQ.js";import{g as f}from"./generate-message-id-B2n2yqR6.js";import{h as m}from"./headers-to-record-ZOZ7Dubo.js";import{v as g}from"./validate-email-options-DxdAVLlu.js";import{defineProvider as p}from"./defineProvider-C9q-7iwt.js";import{c as h,h as v}from"./provider-base-BEz00m9R.js";const r="cloudflare-email",R=p((s={})=>{if(typeof s.send!="function")throw new l(r,"send");const c=h(r,s.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 s.send=="function"},name:r,async sendEmail(e){try{const t=g(e);if(t.length>0)return{error:new a(r,`Invalid email options: ${t.join(", ")}`),success:!1};const o=Array.isArray(e.to)?e.to:[e.to];if(o.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[i]=o;if(!i)return{error:new a(r,"A single `to` recipient is required"),success:!1};const n=f(),d=await u({...e,headers:{...e.headers?m(e.headers):{},"Message-ID":n}});return await s.send(e.from.email,i.email,d),{data:{messageId:n,provider:r,sent:!0,timestamp:new Date},success:!0}}catch(t){return{error:v(r,"send email",t,c),success:!1}}},async validateCredentials(){return this.isAvailable()}}});export{R as default};
@@ -1 +0,0 @@
1
- import{z as o}from"./index-B8wiKJdh.js";import a from"mime";const c=e=>a.getType(e)??"application/octet-stream",m=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`},i=e=>o(e,{buffer:!0});export{c as detectMimeType,m as generateContentId,i as readFileAsBuffer};
@@ -1 +0,0 @@
1
- const l=/[\r\n<>]/,o=t=>{let r=t.replaceAll(/[\r\n\t]+/g," ");r=[...r].filter(i=>{const a=i.codePointAt(0);return a===void 0?!1:a>=32&&a<=126||a>159}).join("");const e="\\",n='"';return r=r.replaceAll(e,e+e).replaceAll(n,e+n),r.trim().replaceAll(/\s+/g," ")},s=t=>{if(l.test(t.email))throw new Error("Invalid email address for header formatting");if(t.name){const r=o(t.name);if(r)return`"${r}" <${t.email}>`}return t.email},c=t=>(Array.isArray(t)?t:[t]).map(e=>s(e)).join(", ");export{s as a,c as f,o as s};
@@ -1 +0,0 @@
1
- import{createRequire as k}from"node:module";let T;const C=e=>(T??=k(import.meta.url))(e),m=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,N=e=>{if(typeof m<"u"&&m.versions&&m.versions.node){const[t,r]=m.versions.node.split(".").map(Number);if(t>22||t===22&&r>=3||t===20&&r>=16)return m.getBuiltinModule(e)}return C(e)},{createRequire:x}=N("node:module"),S=/^[A-Z]:\//i,P=(e="")=>e&&e.replaceAll("\\","/").replace(S,t=>t.toUpperCase());let R;const M=e=>(R??=x(import.meta.url))(e),u=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,F=e=>{if(typeof u<"u"&&u.versions&&u.versions.node){const[t,r]=u.versions.node.split(".").map(Number);if(t>22||t===22&&r>=3||t===20&&r>=16)return u.getBuiltinModule(e)}return M(e)},{fileURLToPath:O}=F("node:url");function q(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var z,_;function U(){return _||(_=1,z=["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cr3","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),z}var B=U();const D=q(B);new Set(D);const L=e=>P(e instanceof URL?O(e):e),A=e=>{if(!e||!(e instanceof URL)&&typeof e!="string")throw new TypeError("Path must be a non-empty string or URL.")};let W=class extends Error{constructor(t){super(`ENOENT: ${t}`)}get code(){return"ENOENT"}set code(t){throw new Error("Cannot overwrite code ENOENT")}get name(){return"NotFoundError"}set name(t){throw new Error("Cannot overwrite name of NotFoundError")}};class V extends Error{constructor(t){super(`EPERM: Operation not permitted, ${t}`)}get code(){return"EPERM"}set code(t){throw new Error("Cannot overwrite code EPERM")}get name(){return"PermissionError"}set name(t){throw new Error("Cannot overwrite name of PermissionError")}}const Z=(e,t)=>{const r=e?.code;return r==="ENOENT"?new W(`no such file or directory, open '${t}'`):r==="EACCES"||r==="EPERM"?new V(`unable to read the non-readable file: ${t}`):e};let G;const H=e=>(G??=x(import.meta.url))(e),f=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,$=e=>{if(typeof f<"u"&&f.versions&&f.versions.node){const[t,r]=f.versions.node.split(".").map(Number);if(t>22||t===22&&r>=3||t===20&&r>=16)return f.getBuiltinModule(e)}return H(e)},{readFile:I}=$("node:fs/promises"),{unzip:J,brotliDecompress:K}=$("node:zlib"),Q={brotli:K,gzip:J,none:(e,t)=>{t(null,e)}},ae=async(e,t)=>{A(e),e=L(e);const{buffer:r,compression:b,encoding:v,flag:l}=t??{};let p;try{p=await I(e,l?{flag:l}:{})}catch(c){throw Z(c,e)}return await new Promise((c,w)=>{Q[b??"none"](p,(g,o)=>{g?w(g):c(r?o:o.toString(v??"utf8"))})})};let X;const Y=e=>(X??=x(import.meta.url))(e),d=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,y=e=>{if(typeof d<"u"&&d.versions&&d.versions.node){const[t,r]=d.versions.node.split(".").map(Number);if(t>22||t===22&&r>=3||t===20&&r>=16)return d.getBuiltinModule(e)}return Y(e)},ee=y("fs"),te=y("os"),re=y("path");var h={},j;function oe(){if(j)return h;j=1;var e=Object.defineProperty,t=(o,s)=>e(o,"name",{value:s,configurable:!0}),r=ee,b=te,v=re;const l=t(o=>{let s="";for(let n=0;n<o.length;n+=1){const i=o[n],a=i.toUpperCase();s+=i===a?i.toLowerCase():a}return s},"invertCase"),p=new Map,c=t((o,s)=>{const n=v.join(o,`.is-fs-case-sensitive-test-${process.pid}`);try{return s.writeFileSync(n,""),!s.existsSync(l(n))}finally{try{s.unlinkSync(n)}catch{}}},"checkDirectoryCaseWithWrite"),w=t((o,s,n)=>{try{return c(o,n)}catch(i){if(s===void 0)return c(b.tmpdir(),n);throw i}},"checkDirectoryCaseWithFallback"),g=t((o,s=r,n=!0)=>{const i=o??process.cwd();if(n&&p.has(i))return p.get(i);let a;const E=l(i);return E!==i&&s.existsSync(i)?a=!s.existsSync(E):a=w(i,o,s),n&&p.set(i,a),a},"isFsCaseSensitive");return h.isFsCaseSensitive=g,h}var se=oe();se.isFsCaseSensitive;export{ae as z};
@@ -1 +0,0 @@
1
- import{c as T}from"./create-token-cache-BdMsMzf7.js";import{h as u}from"./headers-to-record-ZOZ7Dubo.js";const i=o=>{const{fetchToken:r,headerName:a="Authorization",now:t=Date.now,onToken:n,scheme:s="Bearer",skewMs:c=6e4}=o,h=T(async()=>{const e=await r();return n?.(e),e},{now:t,skewMs:c});return async(e,d)=>{const k=await h(),w=e.headers?u(e.headers):{};return d({...e,headers:{...w,[a]:`${s} ${k.accessToken}`}})}};export{i as oauth2Middleware};
@@ -1,27 +0,0 @@
1
- import{createRequire as z}from"node:module";import h from"./EmailError-BIaHK1Uw.js";import Y from"./RequiredOptionError-ctDEEB1s.js";import{b as K}from"./build-mime-message-QNCMA6oQ.js";import{g as Q}from"./generate-message-id-B2n2yqR6.js";import{v as J}from"./validate-email-options-DxdAVLlu.js";import{defineProvider as Z}from"./defineProvider-C9q-7iwt.js";let B;const q=n=>(B??=z(import.meta.url))(n),R=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,H=n=>{if(typeof R<"u"&&R.versions&&R.versions.node){const[t,m]=R.versions.node.split(".").map(Number);if(t>22||t===22&&m>=3||t===20&&m>=16)return R.getBuiltinModule(n)}return q(n)},{Buffer:I}=H("node:buffer"),{createHash:G,createSign:X,createHmac:W}=H("node:crypto"),{Socket:O,createConnection:V}=H("node:net"),{connect:k}=H("node:tls"),ee=(n,t)=>new Promise(m=>{const w=new O,g=()=>{w.destroy(),m(!1)};w.setTimeout(1e3),w.on("error",g),w.on("timeout",g),w.connect(t,n,()=>{w.end(),m(!0)})}),te=n=>{const t=n.replaceAll(`\r
2
- `,`
3
- `).split(`
4
- `).map(w=>w.replaceAll(/[ \t]+/g," ").replace(/ +$/,""));let m=t.length;for(;m>0&&t[m-1]==="";)m-=1;return m>0?`${t.slice(0,m).join(`\r
5
- `)}\r
6
- `:""},re=n=>{const t=n.indexOf(":");if(t===-1)return`${n.toLowerCase().trim()}:`;const m=n.slice(0,t).toLowerCase().trim(),w=n.slice(t+1).replaceAll(/\s+/g," ").trim();return`${m}:${w}`},se=(n,t)=>{const{domainName:m,keySelector:w,privateKey:g}=t,b=n.indexOf(`\r
7
- \r
8
- `);if(b===-1)return n;const P=n.slice(0,b),L=n.slice(b+4),T=P.split(`\r
9
- `),S=te(L),p=G("sha256").update(S).digest("base64"),v=["from","to","subject","date"],C=T.filter(i=>v.some(c=>i.toLowerCase().startsWith(`${c}:`))),_=C.map(i=>i.split(":")[0]?.toLowerCase()??"").filter(Boolean).join(":"),$=Math.floor(Date.now()/1e3),U={a:"rsa-sha256",bh:p,c:"relaxed/relaxed",d:m,h:_,s:w,t:$.toString(),v:"1"},D=`DKIM-Signature: ${Object.entries(U).map(([i,c])=>`${i}=${c}`).join("; ")}; b=`,e=[...C,D].map(i=>re(i)).join(`\r
10
- `),a=X("RSA-SHA256");a.update(e);const o=a.sign(g,"base64");return`${`${D}${o}`}\r
11
- ${T.join(`\r
12
- `)}\r
13
- \r
14
- ${L}`},d="smtp",oe=25,ne=465,ae=1e4,ie=!1,ce=5,F=3e4,ue=/^\./,ye=Z((n={})=>{if(!n.host)throw new Y(d,"host");const t={authMethod:n.authMethod??"LOGIN",debug:n.debug??!1,dkim:n.dkim,host:n.host,maxConnections:n.maxConnections??ce,oauth2:n.oauth2,password:n.password,pool:n.pool??!1,port:n.port!==void 0?n.port:n.secure?ne:oe,rejectUnauthorized:n.rejectUnauthorized??!0,retries:n.retries??0,secure:n.secure??ie,timeout:n.timeout??ae,user:n.user,...n.logger&&{logger:n.logger}};let m=!1;const w=[],g=[];let b=0;const P=()=>{b+=1},L=()=>{b>0&&(b-=1)},T=e=>e.replaceAll(/[\r\n\t\v\f]/g," ").trim(),S=e=>{const a=e.split(`\r
15
- `),o={};for(const l of a)if(l.startsWith("250-")||l.startsWith("250 ")){const c=l.slice(4).trim().split(" "),s=c[0];s&&(o[s]=c.slice(1))}return o},p=async(e,a,o)=>new Promise((l,i)=>{const c=Array.isArray(o)?o:[o];let s="",u="";const f=setTimeout(()=>{A(),i(new h(d,`Command timeout after ${t.timeout}ms: ${a?.slice(0,50)}...`))},t.timeout),A=()=>{e.removeListener("data",E),e.removeListener("error",r),f&&clearTimeout(f)},E=y=>{s+=y.toString();const M=s.split(`\r
16
- `).filter(Boolean);if(M.length>0){const j=M.at(-1);if(j){const N=j.match(/^(\d{3})[\s-]/);if(N){const[,x]=N;u=x,j[3]===" "&&(A(),c.includes(u)?l(s):i(new h(d,`Expected ${c.join(" or ")}, got ${u}: ${s.trim()}`)))}}}},r=y=>{A(),i(new h(d,`Socket error: ${y.message}`,{cause:y}))};e.on("data",E),e.on("error",r),a&&e.write(`${a}\r
17
- `)}),v=async()=>{if(t.pool&&w.length>0){const e=w.pop();if(e&&!e.destroyed)return e;e&&L()}return t.pool&&b>=t.maxConnections?new Promise((e,a)=>{const o={reject:a,resolve:e};o.timeout=setTimeout(()=>{const l=g.indexOf(o);l!==-1&&g.splice(l,1),a(new h(d,`Connection queue timeout after ${F}ms`))},F),g.push(o)}):new Promise((e,a)=>{let o,l=!1,i;const c=()=>{o&&clearTimeout(o)};o=setTimeout(()=>{l||(l=!0,i&&!i.destroyed&&i.destroy(),c(),a(new h(d,`Connection timeout to ${t.host}:${t.port} after ${t.timeout}ms`)))},t.timeout);try{i=t.secure?k({host:t.host,port:t.port,rejectUnauthorized:t.rejectUnauthorized}):V(t.port,t.host),i.on("error",s=>{l||(l=!0,c(),a(new h(d,`Connection error: ${s.message}`,{cause:s})))}),i.once("data",s=>{if(!l&&i){l=!0,c();const u=s.toString();u.slice(0,3)==="220"?(P(),e(i)):(i.destroy(),a(new h(d,`Unexpected server greeting: ${u.trim()}`)))}})}catch(s){l||(l=!0,c(),a(new h(d,`Failed to create connection: ${s.message}`,{cause:s})))}})},C=async e=>new Promise((a,o)=>{let l,i=!1,c;const s=()=>{l&&clearTimeout(l)};l=setTimeout(()=>{i||(i=!0,c&&!c.destroyed&&c.destroy(),s(),o(new h(d,`TLS connection timeout after ${t.timeout}ms`)))},t.timeout);try{const u={host:t.host,rejectUnauthorized:t.rejectUnauthorized,socket:e};c=k(u),c.on("error",f=>{i||(i=!0,s(),o(new h(d,`TLS connection error: ${f.message}`,{cause:f})))}),c.once("secure",()=>{!i&&c&&(i=!0,s(),a(c))})}catch(u){i||(i=!0,s(),o(new h(d,`Failed to upgrade to TLS: ${u.message}`,{cause:u})))}}),_=e=>{if(e.destroyed||!t.pool){try{e.destroy()}catch{}L();return}if(g.length>0){const a=g.shift();if(a){clearTimeout(a.timeout),a.resolve(e);return}}w.push(e)},$=async(e,a=!1)=>{if(a){if(!e.destroyed)try{await p(e,"RSET","250")}catch{e.destroy()}_(e);return}await new Promise(o=>{try{L(),e.write(`QUIT\r
18
- `),e.end(),e.once("close",()=>{o()})}catch{o()}})},U=async e=>{if(!t.user)return;const a=await p(e,`EHLO ${t.host}`,"250"),o=S(a),l=Object.keys(o).find(s=>s.toUpperCase()==="AUTH");if(!l&&(t.user||t.password))throw new h(d,"Server does not support authentication");const i=l?o[l]??[]:[];let{authMethod:c}=t;if(c||(i.includes("CRAM-MD5")?c="CRAM-MD5":i.includes("LOGIN")?c="LOGIN":i.includes("PLAIN")&&(c="PLAIN")),!c)throw new h(d,"No supported authentication methods");if(c==="OAUTH2"&&t.oauth2)try{const{accessToken:s,user:u}=t.oauth2,f=`user=${u}auth=Bearer ${s}`,A=I.from(f).toString("base64");await p(e,`AUTH XOAUTH2 ${A}`,"235");return}catch(s){const u=s.message;throw u.includes("535")||u.includes("Authentication failed")?new h(d,"Authentication failed: Invalid OAuth2 credentials"):s}if(c==="CRAM-MD5"&&t.password)try{const u=(await p(e,"AUTH CRAM-MD5","334")).split(" ")[1];if(!u)throw new h(d,"Invalid CRAM-MD5 challenge response");const f=I.from(u,"base64").toString("utf8"),A=W("md5",t.password);A.update(f);const E=A.digest("hex"),r=`${t.user} ${E}`;await p(e,I.from(r).toString("base64"),"235");return}catch(s){const u=s.message;throw u.includes("535")||u.includes("Authentication failed")?new h(d,"Authentication failed: Invalid username or password"):s}if(c==="LOGIN"&&t.password)try{await p(e,"AUTH LOGIN","334"),await p(e,I.from(t.user).toString("base64"),"334"),await p(e,I.from(t.password).toString("base64"),"235");return}catch(s){const u=s.message;throw u.includes("535")||u.includes("Authentication failed")?new h(d,"Authentication failed: Invalid username or password"):s}if(c==="PLAIN"&&t.password)try{const s=I.from(`\0${t.user}\0${t.password}`).toString("base64");await p(e,`AUTH PLAIN ${s}`,"235");return}catch(s){const u=s.message;throw u.includes("535")||u.includes("Authentication failed")?new h(d,"Authentication failed: Invalid username or password"):s}throw new h(d,"Authentication failed - no valid credentials or method")},D=e=>{if(!t.dkim)return e;try{return se(e,t.dkim)}catch(a){return console.error(`[${d}] DKIM signing error:`,a),e}};return{features:{attachments:!0,batchSending:t.pool,customHeaders:!0,html:!0,replyTo:!0,scheduling:!1,tagging:!1,templates:!1,tracking:!1},async initialize(){if(!m)try{if(!await this.isAvailable())throw new h(d,`SMTP server not available at ${t.host}:${t.port}`);m=!0}catch(e){throw new h(d,`Failed to initialize: ${e.message}`,{cause:e})}},async isAvailable(){try{if(!await ee(t.host,t.port))return!1;const a=await v();return await $(a),!0}catch{return!1}},name:d,options:t,async sendEmail(e){try{const a=J(e);if(a.length>0)return{error:new h(d,`Invalid email options: ${a.join(", ")}`),success:!1};m||await this.initialize();let o=await v();try{let l=S(await p(o,`EHLO ${t.host}`,"250"));if(!t.secure)try{const r=await p(o,`EHLO ${t.host}`,"250"),y=S(r);l=y,Object.keys(y).includes("STARTTLS")&&(await p(o,"STARTTLS","220"),o=await C(o),l=S(await p(o,`EHLO ${t.host}`,"250")))}catch(r){if(t.rejectUnauthorized)throw new h(d,`STARTTLS failed or not supported: ${r.message}`,{cause:r})}await U(o);const i=Object.keys(l).some(r=>r.toUpperCase()==="DSN");let c="";if(e.dsn&&i){const r=[];e.dsn.success&&r.push("SUCCESS"),e.dsn.failure&&r.push("FAILURE"),e.dsn.delay&&r.push("DELAY"),r.length>0&&(c=` NOTIFY=${r.join(",")}`)}await p(o,`MAIL FROM:<${e.from.email}>`,"250");const s=[];Array.isArray(e.to)?s.push(...e.to.map(r=>r.email)):s.push(e.to.email),e.cc&&(Array.isArray(e.cc)?s.push(...e.cc.map(r=>r.email)):s.push(e.cc.email)),e.bcc&&(Array.isArray(e.bcc)?s.push(...e.bcc.map(r=>r.email)):s.push(e.bcc.email));for(const r of s)await p(o,`RCPT TO:<${r}>${c}`,"250");await p(o,"DATA","354");let u=await K(e);const f=[];if(e.dsn&&!i){const r=[];e.dsn.success&&r.push("SUCCESS"),e.dsn.failure&&r.push("FAILURE"),e.dsn.delay&&r.push("DELAY"),r.length>0&&f.push(`X-DSN-NOTIFY: ${r.join(",")}`)}if(e.priority){let r="";switch(e.priority){case"high":{r="1 (Highest)",f.push("Importance: High");break}case"low":{r="5 (Lowest)",f.push("Importance: Low");break}case"normal":{r="3 (Normal)",f.push("Importance: Normal");break}default:{r="3 (Normal)";break}}f.push(`X-Priority: ${r}`)}if(e.inReplyTo&&f.push(`In-Reply-To: ${T(e.inReplyTo)}`),e.references){const r=Array.isArray(e.references)?e.references.map(y=>T(y)).join(" "):T(e.references);f.push(`References: ${r}`)}if(e.listUnsubscribe){const r=Array.isArray(e.listUnsubscribe)?e.listUnsubscribe.map(y=>`<${T(y)}>`).join(", "):`<${T(e.listUnsubscribe)}>`;f.push(`List-Unsubscribe: ${r}`)}if(e.googleMailHeaders){const{googleMailHeaders:r}=e;r.feedbackId&&f.push(`Feedback-ID: ${T(r.feedbackId)}`),r.promotionalContent&&f.push("X-Google-Promotion: promotional"),r.category&&f.push(`X-Gmail-Labels: ${r.category}`)}if(f.length>0){const r=u.indexOf(`\r
19
- \r
20
- `);if(r!==-1){const y=u.slice(0,r),M=u.slice(r+4);u=`${y}\r
21
- ${f.join(`\r
22
- `)}\r
23
- \r
24
- ${M}`}}t.dkim&&(e.useDkim||e.useDkim===void 0)&&(u=D(u));const A=u.replaceAll(`\r
25
- .`,`\r
26
- ..`).replace(ue,"..");await p(o,`${A}\r
27
- .`,"250");const E=Q();return await $(o,t.pool),{data:{messageId:E,provider:d,response:"Message accepted",sent:!0,timestamp:new Date},success:!0}}catch(l){try{await $(o)}catch{}throw l}}catch(a){return{error:new h(d,`Failed to send email: ${a.message}`,{cause:a}),success:!1}}},async shutdown(){for(const e of w)try{await $(e)}catch{}w.length=0;for(const e of g)clearTimeout(e.timeout),e.reject(new Error("Provider shutdown"));g.length=0},async validateCredentials(){try{if(!await this.isAvailable())return!1;let e=await v();try{if(await p(e,`EHLO ${t.host}`,"250"),!t.secure)try{const a=await p(e,`EHLO ${t.host}`,"250"),o=S(a);Object.keys(o).includes("STARTTLS")&&(await p(e,"STARTTLS","220"),e=await C(e),await p(e,`EHLO ${t.host}`,"250"))}catch{if(t.rejectUnauthorized)return await $(e),!1}return await U(e),await $(e),!0}catch{return await $(e),!1}}catch{return!1}}}});export{ye as default};