@stacksjs/ts-cloud 0.16.52 → 0.16.53

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 (199) hide show
  1. package/dist/aws/index.js +1 -1
  2. package/dist/bin/{chunk-z06jkvvr.js → chunk-0xfy78nc.js} +4 -4
  3. package/dist/bin/chunk-1cccv502.js +1 -0
  4. package/dist/bin/{chunk-n5kdne4p.js → chunk-1q6wqzh1.js} +3 -3
  5. package/dist/bin/{chunk-ddyd6f14.js → chunk-28124w0n.js} +2 -2
  6. package/dist/bin/{chunk-ppd463ev.js → chunk-3mhzd931.js} +1 -1
  7. package/dist/bin/{chunk-q2rqmc2x.js → chunk-4crz28b9.js} +1 -1
  8. package/dist/bin/chunk-5s91mpty.js +1 -0
  9. package/dist/bin/chunk-6sfn8fjv.js +1 -0
  10. package/dist/bin/chunk-6tdt3ea9.js +1 -0
  11. package/dist/bin/{chunk-dv2he3vc.js → chunk-7cactd6c.js} +2 -2
  12. package/dist/bin/{chunk-2wh45zhk.js → chunk-7p70c4br.js} +2 -2
  13. package/dist/bin/{chunk-93yw46n7.js → chunk-8fh0gv4q.js} +1 -1
  14. package/dist/bin/chunk-8nfrknq3.js +1 -0
  15. package/dist/bin/{chunk-0wtshht7.js → chunk-95djv2ja.js} +1 -1
  16. package/dist/bin/{chunk-te52z1wk.js → chunk-9t78j764.js} +1 -1
  17. package/dist/bin/chunk-a4z8b18n.js +1 -0
  18. package/dist/bin/chunk-apqyj6gr.js +1 -0
  19. package/dist/bin/chunk-bn2sn094.js +1 -0
  20. package/dist/bin/chunk-bzbah8jm.js +1 -0
  21. package/dist/bin/chunk-bzpeqh5z.js +1 -0
  22. package/dist/bin/{chunk-mcg4wg4j.js → chunk-bzzwbkrx.js} +4 -4
  23. package/dist/bin/{chunk-f78wmcvb.js → chunk-cdseg15k.js} +2 -2
  24. package/dist/bin/{chunk-wv8060cw.js → chunk-dg8ceycc.js} +5 -5
  25. package/dist/bin/chunk-e0d34gcp.js +1 -0
  26. package/dist/bin/chunk-e3zsrpbj.js +1 -0
  27. package/dist/bin/{chunk-t970yjvz.js → chunk-ek27709c.js} +5 -5
  28. package/dist/bin/chunk-erdz4875.js +1 -0
  29. package/dist/bin/chunk-et6hzqpx.js +1 -0
  30. package/dist/bin/chunk-gee6a9zv.js +740 -0
  31. package/dist/bin/{chunk-ngmewar1.js → chunk-hkx5j0bn.js} +3 -3
  32. package/dist/bin/chunk-hrg9ygbz.js +1 -0
  33. package/dist/bin/{chunk-fjbhvhqb.js → chunk-hzc049ns.js} +1 -1
  34. package/dist/bin/{chunk-rwbdtxte.js → chunk-jvbe549p.js} +1 -1
  35. package/dist/bin/{chunk-5c4xh61a.js → chunk-jxm62h8r.js} +16 -16
  36. package/dist/bin/{chunk-a7hhzbvm.js → chunk-jyvr7eh5.js} +3 -3
  37. package/dist/bin/{chunk-cjagqdk3.js → chunk-k1kk78qg.js} +5 -5
  38. package/dist/bin/chunk-kj1e4xvg.js +1 -0
  39. package/dist/bin/{chunk-811k54jq.js → chunk-kqd186ky.js} +2 -2
  40. package/dist/bin/{chunk-we2raqk3.js → chunk-mdcv2vw1.js} +2 -2
  41. package/dist/bin/chunk-mpawwybt.js +1 -0
  42. package/dist/bin/{chunk-da6dmacg.js → chunk-n2jh5p5x.js} +2 -2
  43. package/dist/bin/chunk-n6hngvvb.js +1 -0
  44. package/dist/bin/chunk-n9aeark7.js +1 -0
  45. package/dist/bin/{chunk-7czb1kgg.js → chunk-nva480hg.js} +2 -2
  46. package/dist/bin/{chunk-yfa84s0c.js → chunk-p23wfy3r.js} +1 -1
  47. package/dist/bin/{chunk-ytzcsskk.js → chunk-p6qa21fr.js} +2 -2
  48. package/dist/bin/chunk-pexjxc5g.js +1 -0
  49. package/dist/bin/{chunk-sa9c8vb5.js → chunk-pr5c0q0k.js} +5 -5
  50. package/dist/bin/{chunk-m3xap663.js → chunk-q0takzyx.js} +4 -4
  51. package/dist/bin/{chunk-hhmqsrfc.js → chunk-rbyrd9we.js} +1 -1
  52. package/dist/bin/{chunk-0e9yddgc.js → chunk-rmxexkvr.js} +60 -60
  53. package/dist/bin/{chunk-45thdtvf.js → chunk-rqvrjp8g.js} +36 -36
  54. package/dist/bin/chunk-s98wngxx.js +1 -0
  55. package/dist/bin/{chunk-83brtkvn.js → chunk-sbate1ky.js} +1 -1
  56. package/dist/bin/{chunk-5ny7rggt.js → chunk-sy4zws71.js} +1 -1
  57. package/dist/bin/chunk-t2ec6d8h.js +1 -0
  58. package/dist/bin/{chunk-fhe0mdjg.js → chunk-tbp1gf1p.js} +1 -1
  59. package/dist/bin/{chunk-734n0gkw.js → chunk-v0g82agx.js} +1 -1
  60. package/dist/bin/{chunk-f0vedy45.js → chunk-v9js2b1d.js} +1 -1
  61. package/dist/bin/{chunk-33ntxz01.js → chunk-z6xnegpe.js} +3 -3
  62. package/dist/bin/cli.js +239 -239
  63. package/dist/bin/dashboard-server.js +1 -1
  64. package/dist/{chunk-qcv4twc6.js → chunk-184bvh5s.js} +19 -19
  65. package/dist/chunk-27ny16g8.js +1 -0
  66. package/dist/{chunk-pz33w7gv.js → chunk-2hma3g5q.js} +2 -2
  67. package/dist/chunk-2n3c5axm.js +1 -0
  68. package/dist/{chunk-6gnmrtp9.js → chunk-430acqjk.js} +19 -19
  69. package/dist/chunk-5yrabpmr.js +1 -0
  70. package/dist/{chunk-9ggg2ktx.js → chunk-7ag4wc74.js} +2 -2
  71. package/dist/{chunk-thdfk76k.js → chunk-80bgb48v.js} +2 -2
  72. package/dist/{chunk-8b2mxhcm.js → chunk-94z7s8ky.js} +5 -5
  73. package/dist/{chunk-rjaa4epz.js → chunk-9fvtnx6h.js} +90 -90
  74. package/dist/{chunk-6m8p1n88.js → chunk-a99wz633.js} +12 -12
  75. package/dist/{chunk-x4qye2rc.js → chunk-apj1eqcy.js} +4 -4
  76. package/dist/chunk-bg89ad2e.js +1 -0
  77. package/dist/{chunk-erfh93dq.js → chunk-c482jhc6.js} +2 -2
  78. package/dist/{chunk-zf5wdx6v.js → chunk-d245va6b.js} +1 -1
  79. package/dist/{chunk-ca191b00.js → chunk-e42gpavb.js} +5 -5
  80. package/dist/chunk-e5xg3p1x.js +1 -0
  81. package/dist/{chunk-ffyx50xx.js → chunk-gmtds745.js} +1 -1
  82. package/dist/chunk-hwm83kj0.js +464 -0
  83. package/dist/{chunk-p101nhg2.js → chunk-hybz2q8w.js} +4 -4
  84. package/dist/{chunk-j99nkav5.js → chunk-jyvnfny6.js} +3 -3
  85. package/dist/{chunk-4abbccq7.js → chunk-mp2y4t6w.js} +1 -1
  86. package/dist/{chunk-jytama4e.js → chunk-nhsefr22.js} +5 -5
  87. package/dist/{chunk-3ncnrrvm.js → chunk-qjp3f5y8.js} +7 -7
  88. package/dist/{chunk-0qgfe5ff.js → chunk-qyr5hn6v.js} +3 -3
  89. package/dist/{chunk-m9r0a1v9.js → chunk-smt4t6rc.js} +2 -2
  90. package/dist/{chunk-0cz2s19h.js → chunk-stc3ykm3.js} +2 -2
  91. package/dist/{chunk-4yqd62rd.js → chunk-v4vz0e85.js} +1 -1
  92. package/dist/{chunk-qcj3hkba.js → chunk-vgtqd3sb.js} +1 -1
  93. package/dist/{chunk-r5mk071y.js → chunk-wbbbpt4v.js} +5 -5
  94. package/dist/chunk-xfced13z.js +1 -0
  95. package/dist/{chunk-jtvw9d4x.js → chunk-y7k5872m.js} +1 -1
  96. package/dist/{chunk-xgc6hskd.js → chunk-yt8qgn5d.js} +6 -6
  97. package/dist/{chunk-prtvb2fh.js → chunk-zvcd6x45.js} +83 -83
  98. package/dist/deploy/index.js +1 -1
  99. package/dist/dns/index.js +1 -1
  100. package/dist/drivers/hetzner/client.d.ts +30 -0
  101. package/dist/drivers/hetzner/driver.d.ts +3 -2
  102. package/dist/drivers/hetzner/volumes.d.ts +9 -0
  103. package/dist/drivers/index.d.ts +4 -0
  104. package/dist/drivers/index.js +1 -1
  105. package/dist/drivers/shared/compute-storage-agent.d.ts +3 -0
  106. package/dist/drivers/shared/compute-storage.d.ts +21 -0
  107. package/dist/drivers/shared/notifications.d.ts +3 -1
  108. package/dist/index.d.ts +1 -1
  109. package/dist/index.js +19 -19
  110. package/dist/mail/index.js +2 -2
  111. package/dist/operations/index.js +1 -1
  112. package/dist/protection/index.js +1 -1
  113. package/dist/spend/index.js +1 -1
  114. package/dist/ui/404.html +1 -1
  115. package/dist/ui/accept-invitation.html +1 -1
  116. package/dist/ui/access-denied.html +1 -1
  117. package/dist/ui/account/automation.html +6 -6
  118. package/dist/ui/account/security.html +2 -2
  119. package/dist/ui/applications/compose.html +6 -6
  120. package/dist/ui/applications/new.html +2 -2
  121. package/dist/ui/data/backups.html +6 -6
  122. package/dist/ui/data/services.html +6 -6
  123. package/dist/ui/data/volumes.html +5 -5
  124. package/dist/ui/index.html +6 -6
  125. package/dist/ui/infrastructure/topology.html +5 -5
  126. package/dist/ui/integrations.html +2 -2
  127. package/dist/ui/operations/alerts.html +6 -6
  128. package/dist/ui/operations/configuration.html +6 -6
  129. package/dist/ui/operations/jobs.html +6 -6
  130. package/dist/ui/operations/maintenance.html +6 -6
  131. package/dist/ui/operations/observability.html +6 -6
  132. package/dist/ui/operations/previews.html +6 -6
  133. package/dist/ui/operations/queue.html +6 -6
  134. package/dist/ui/operations/regions.html +6 -6
  135. package/dist/ui/operations/releases.html +6 -6
  136. package/dist/ui/operations/spend.html +6 -6
  137. package/dist/ui/operations/workloads.html +6 -6
  138. package/dist/ui/security.html +2 -2
  139. package/dist/ui/server/actions.html +6 -6
  140. package/dist/ui/server/activity.html +2 -2
  141. package/dist/ui/server/capacity.html +6 -6
  142. package/dist/ui/server/database.html +6 -6
  143. package/dist/ui/server/deployments.html +5 -5
  144. package/dist/ui/server/diagnostics.html +2 -2
  145. package/dist/ui/server/firewall.html +6 -6
  146. package/dist/ui/server/fleet.html +6 -6
  147. package/dist/ui/server/logs.html +6 -6
  148. package/dist/ui/server/metrics.html +6 -6
  149. package/dist/ui/server/security.html +2 -2
  150. package/dist/ui/server/services.html +1 -1
  151. package/dist/ui/server/sites.html +5 -5
  152. package/dist/ui/server/ssh-keys.html +6 -6
  153. package/dist/ui/server/team.html +5 -5
  154. package/dist/ui/server/terminal.html +1 -1
  155. package/dist/ui/serverless/alarms.html +5 -5
  156. package/dist/ui/serverless/assets.html +2 -2
  157. package/dist/ui/serverless/cost.html +2 -2
  158. package/dist/ui/serverless/data.html +6 -6
  159. package/dist/ui/serverless/deployments.html +2 -2
  160. package/dist/ui/serverless/firewall.html +1 -1
  161. package/dist/ui/serverless/functions.html +6 -6
  162. package/dist/ui/serverless/logs.html +6 -6
  163. package/dist/ui/serverless/metrics.html +2 -2
  164. package/dist/ui/serverless/queues.html +6 -6
  165. package/dist/ui/serverless/secrets.html +6 -6
  166. package/dist/ui/serverless/traces.html +6 -6
  167. package/dist/ui/serverless.html +6 -6
  168. package/dist/ui-src/pages/server/metrics.stx +9 -0
  169. package/package.json +3 -3
  170. package/dist/bin/chunk-20dp8658.js +0 -1
  171. package/dist/bin/chunk-334jngt2.js +0 -1
  172. package/dist/bin/chunk-3k7y1h18.js +0 -1
  173. package/dist/bin/chunk-626npmtj.js +0 -1
  174. package/dist/bin/chunk-67vf8myy.js +0 -1
  175. package/dist/bin/chunk-74wppexz.js +0 -1
  176. package/dist/bin/chunk-87g6jcfm.js +0 -1
  177. package/dist/bin/chunk-8ya34jz7.js +0 -1
  178. package/dist/bin/chunk-964xmgb6.js +0 -1
  179. package/dist/bin/chunk-9qdrv6zp.js +0 -1
  180. package/dist/bin/chunk-azarn24c.js +0 -1
  181. package/dist/bin/chunk-dpk5r544.js +0 -1
  182. package/dist/bin/chunk-f578z20t.js +0 -1
  183. package/dist/bin/chunk-f9469h6q.js +0 -1
  184. package/dist/bin/chunk-g6ph425d.js +0 -1
  185. package/dist/bin/chunk-k6g1c681.js +0 -1
  186. package/dist/bin/chunk-m7pbssep.js +0 -1
  187. package/dist/bin/chunk-n7xadeqe.js +0 -1
  188. package/dist/bin/chunk-nxvtya6v.js +0 -724
  189. package/dist/bin/chunk-p6wxv8yq.js +0 -1
  190. package/dist/bin/chunk-vpt43nwa.js +0 -1
  191. package/dist/bin/chunk-wgh66c5r.js +0 -1
  192. package/dist/bin/chunk-zywk12mp.js +0 -1
  193. package/dist/chunk-09d6pdgx.js +0 -1
  194. package/dist/chunk-21mmcmm7.js +0 -1
  195. package/dist/chunk-2gqm2h84.js +0 -1
  196. package/dist/chunk-ggtsfsxx.js +0 -448
  197. package/dist/chunk-jgsey18z.js +0 -1
  198. package/dist/chunk-qbsrs1gp.js +0 -1
  199. package/dist/chunk-tnqj2en4.js +0 -1
@@ -1,7 +1,7 @@
1
- var Qd={newConnectionsPerSecond:50,concurrentPerSource:100,synPerSecond:2000,burst:100,icmpPerSecond:5,banSeconds:600};function h(e){return{...Qd,...e.thresholds}}var _=/^(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{1,2})?$|^[0-9a-f:]+(?:\/\d{1,3})?$/i;function rn(e){if(!_.test(e))return!1;let[t,n]=e.split("/");if(t.includes(":"))return n==null||Number(n)>=0&&Number(n)<=128;let s=t.split(".");if(s.length!==4||s.some((a)=>Number(a)>255||a===""))return!1;return n==null||Number(n)>=0&&Number(n)<=32}function f(e){return[...new Set((e??[]).map((t)=>t.trim()).filter(rn))]}function y(e){let t=(e??[80,443]).filter((n)=>Number.isInteger(n)&&n>=1&&n<=65535);return[...new Set(t)].sort((n,s)=>n-s)}function Hd(e={}){let t=h(e);return{"net.ipv4.tcp_syncookies":"1","net.ipv4.tcp_max_syn_backlog":String(Math.max(4096,t.synPerSecond*4)),"net.ipv4.tcp_synack_retries":"2","net.ipv4.tcp_abort_on_overflow":"1","net.ipv4.tcp_fin_timeout":"15","net.ipv4.tcp_keepalive_time":"300","net.ipv4.tcp_keepalive_intvl":"30","net.ipv4.tcp_keepalive_probes":"3","net.core.somaxconn":"4096","net.core.netdev_max_backlog":"16384","net.ipv4.conf.all.rp_filter":"1","net.ipv4.conf.default.rp_filter":"1","net.ipv4.conf.all.accept_source_route":"0","net.ipv4.conf.all.accept_redirects":"0","net.ipv4.conf.all.send_redirects":"0","net.ipv6.conf.all.accept_redirects":"0","net.ipv6.conf.all.accept_source_route":"0","net.ipv4.icmp_echo_ignore_broadcasts":"1","net.ipv4.icmp_ignore_bogus_error_responses":"1","net.netfilter.nf_conntrack_max":"262144","net.netfilter.nf_conntrack_tcp_timeout_established":"3600"}}function Gd(e={}){let t=["# Managed by ts-cloud. Edits are overwritten on the next deploy.","# Network hardening against L3/L4 floods.",""];for(let[n,s]of Object.entries(Hd(e)))t.push(`${n} = ${s}`);return`${t.join(`
1
+ var Jd={newConnectionsPerSecond:50,concurrentPerSource:100,synPerSecond:2000,burst:100,icmpPerSecond:5,banSeconds:600};function h(e){return{...Jd,...e.thresholds}}var _=/^(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{1,2})?$|^[0-9a-f:]+(?:\/\d{1,3})?$/i;function nn(e){if(!_.test(e))return!1;let[t,n]=e.split("/");if(t.includes(":"))return n==null||Number(n)>=0&&Number(n)<=128;let s=t.split(".");if(s.length!==4||s.some((a)=>Number(a)>255||a===""))return!1;return n==null||Number(n)>=0&&Number(n)<=32}function f(e){return[...new Set((e??[]).map((t)=>t.trim()).filter(nn))]}function y(e){let t=(e??[80,443]).filter((n)=>Number.isInteger(n)&&n>=1&&n<=65535);return[...new Set(t)].sort((n,s)=>n-s)}function Xd(e={}){let t=h(e);return{"net.ipv4.tcp_syncookies":"1","net.ipv4.tcp_max_syn_backlog":String(Math.max(4096,t.synPerSecond*4)),"net.ipv4.tcp_synack_retries":"2","net.ipv4.tcp_abort_on_overflow":"1","net.ipv4.tcp_fin_timeout":"15","net.ipv4.tcp_keepalive_time":"300","net.ipv4.tcp_keepalive_intvl":"30","net.ipv4.tcp_keepalive_probes":"3","net.core.somaxconn":"4096","net.core.netdev_max_backlog":"16384","net.ipv4.conf.all.rp_filter":"1","net.ipv4.conf.default.rp_filter":"1","net.ipv4.conf.all.accept_source_route":"0","net.ipv4.conf.all.accept_redirects":"0","net.ipv4.conf.all.send_redirects":"0","net.ipv6.conf.all.accept_redirects":"0","net.ipv6.conf.all.accept_source_route":"0","net.ipv4.icmp_echo_ignore_broadcasts":"1","net.ipv4.icmp_ignore_bogus_error_responses":"1","net.netfilter.nf_conntrack_max":"262144","net.netfilter.nf_conntrack_tcp_timeout_established":"3600"}}function Yd(e={}){let t=["# Managed by ts-cloud. Edits are overwritten on the next deploy.","# Network hardening against L3/L4 floods.",""];for(let[n,s]of Object.entries(Xd(e)))t.push(`${n} = ${s}`);return`${t.join(`
2
2
  `)}
3
- `}function Vd(e={}){let t=h(e),n=y(e.ports),s=f(e.allowlist),a=f(e.blocklist),l=e.monitorOnly?"counter":"counter drop",i=e.originProtection?.enabled?f(e.originProtection.cdnRanges):[],c=s.filter((r)=>!r.includes(":")),p=s.filter((r)=>r.includes(":")),u=a.filter((r)=>!r.includes(":")),o=["#!/usr/sbin/nft -f","# Managed by ts-cloud. Edits are overwritten on the next deploy.","","table inet ts_cloud_ddos","delete table inet ts_cloud_ddos","","table inet ts_cloud_ddos {"," # Sources that tripped a limit, with a timeout so a ban self-expires.",` set banned4 { type ipv4_addr; flags timeout; timeout ${t.banSeconds}s; }`,` set banned6 { type ipv6_addr; flags timeout; timeout ${t.banSeconds}s; }`];if(c.length>0)o.push(` set allow4 { type ipv4_addr; flags interval; elements = { ${c.join(", ")} } }`);if(p.length>0)o.push(` set allow6 { type ipv6_addr; flags interval; elements = { ${p.join(", ")} } }`);if(u.length>0)o.push(` set block4 { type ipv4_addr; flags interval; elements = { ${u.join(", ")} } }`);if(i.length>0)o.push(` set cdn4 { type ipv4_addr; flags interval; elements = { ${i.filter((r)=>!r.includes(":")).join(", ")} } }`);if(o.push(""," chain input {"," type filter hook input priority -150; policy accept;",""," # Established traffic is already paid for; never re-inspect it."," ct state established,related accept"," iif lo accept",""," # Invalid packets are never legitimate and are cheap to drop early."," ct state invalid counter drop"),c.length>0)o.push(" ip saddr @allow4 accept");if(p.length>0)o.push(" ip6 saddr @allow6 accept");if(u.length>0)o.push(" ip saddr @block4 counter drop");if(o.push(" ip saddr @banned4 counter drop"," ip6 saddr @banned6 counter drop",""),o.push(" # Nonsense TCP flag combinations: scanners and stack fingerprinting."," tcp flags & (fin|syn) == (fin|syn) counter drop"," tcp flags & (syn|rst) == (syn|rst) counter drop"," tcp flags & (fin|rst) == (fin|rst) counter drop"," tcp flags & (fin|ack) == fin counter drop"," tcp flags & (syn|fin|ack|rst|psh|urg) == 0x0 counter drop",""," # Ping stays usable, ping floods do not.",` ip protocol icmp icmp type echo-request limit rate ${t.icmpPerSecond}/second burst ${t.burst} packets accept`," ip protocol icmp icmp type echo-request counter drop",""),n.length>0){let r=n.join(", ");if(o.push(" # Platform-wide SYN ceiling. Above it the kernel falls back to cookies.",` tcp dport { ${r} } ct state new limit rate ${t.synPerSecond}/second burst ${t.burst} packets accept`,""," # Per-source new-connection rate. This is what stops one host hammering.",` tcp dport { ${r} } ct state new meter conn_rate4 { ip saddr limit rate over ${t.newConnectionsPerSecond}/second burst ${t.burst} packets } add @banned4 { ip saddr } ${l}`,` tcp dport { ${r} } ct state new meter conn_rate6 { ip6 saddr limit rate over ${t.newConnectionsPerSecond}/second burst ${t.burst} packets } add @banned6 { ip6 saddr } ${l}`,""," # Concurrency ceiling per source: the slow-loris defence.",` tcp dport { ${r} } ct state new meter conn_count4 { ip saddr ct count over ${t.concurrentPerSource} } ${l}`,` tcp dport { ${r} } ct state new meter conn_count6 { ip6 saddr ct count over ${t.concurrentPerSource} } ${l}`,""),i.length>0)o.push(" # Origin protection: reject traffic that skipped the CDN and came"," # straight to the box, which is how an attacker bypasses the edge.",` tcp dport { ${r} } ip saddr != @cdn4 counter drop`,"")}return o.push(" }","}",""),o.join(`
4
- `)}function Qi(e={}){return`#!/usr/bin/env bash
3
+ `}function Zd(e={}){let t=h(e),n=y(e.ports),s=f(e.allowlist),a=f(e.blocklist),l=e.monitorOnly?"counter":"counter drop",i=e.originProtection?.enabled?f(e.originProtection.cdnRanges):[],c=s.filter((r)=>!r.includes(":")),p=s.filter((r)=>r.includes(":")),u=a.filter((r)=>!r.includes(":")),o=["#!/usr/sbin/nft -f","# Managed by ts-cloud. Edits are overwritten on the next deploy.","","table inet ts_cloud_ddos","delete table inet ts_cloud_ddos","","table inet ts_cloud_ddos {"," # Sources that tripped a limit, with a timeout so a ban self-expires.",` set banned4 { type ipv4_addr; flags timeout; timeout ${t.banSeconds}s; }`,` set banned6 { type ipv6_addr; flags timeout; timeout ${t.banSeconds}s; }`];if(c.length>0)o.push(` set allow4 { type ipv4_addr; flags interval; elements = { ${c.join(", ")} } }`);if(p.length>0)o.push(` set allow6 { type ipv6_addr; flags interval; elements = { ${p.join(", ")} } }`);if(u.length>0)o.push(` set block4 { type ipv4_addr; flags interval; elements = { ${u.join(", ")} } }`);if(i.length>0)o.push(` set cdn4 { type ipv4_addr; flags interval; elements = { ${i.filter((r)=>!r.includes(":")).join(", ")} } }`);if(o.push(""," chain input {"," type filter hook input priority -150; policy accept;",""," # Established traffic is already paid for; never re-inspect it."," ct state established,related accept"," iif lo accept",""," # Invalid packets are never legitimate and are cheap to drop early."," ct state invalid counter drop"),c.length>0)o.push(" ip saddr @allow4 accept");if(p.length>0)o.push(" ip6 saddr @allow6 accept");if(u.length>0)o.push(" ip saddr @block4 counter drop");if(o.push(" ip saddr @banned4 counter drop"," ip6 saddr @banned6 counter drop",""),o.push(" # Nonsense TCP flag combinations: scanners and stack fingerprinting."," tcp flags & (fin|syn) == (fin|syn) counter drop"," tcp flags & (syn|rst) == (syn|rst) counter drop"," tcp flags & (fin|rst) == (fin|rst) counter drop"," tcp flags & (fin|ack) == fin counter drop"," tcp flags & (syn|fin|ack|rst|psh|urg) == 0x0 counter drop",""," # Ping stays usable, ping floods do not.",` ip protocol icmp icmp type echo-request limit rate ${t.icmpPerSecond}/second burst ${t.burst} packets accept`," ip protocol icmp icmp type echo-request counter drop",""),n.length>0){let r=n.join(", ");if(o.push(" # Platform-wide SYN ceiling. Above it the kernel falls back to cookies.",` tcp dport { ${r} } ct state new limit rate ${t.synPerSecond}/second burst ${t.burst} packets accept`,""," # Per-source new-connection rate. This is what stops one host hammering.",` tcp dport { ${r} } ct state new meter conn_rate4 { ip saddr limit rate over ${t.newConnectionsPerSecond}/second burst ${t.burst} packets } add @banned4 { ip saddr } ${l}`,` tcp dport { ${r} } ct state new meter conn_rate6 { ip6 saddr limit rate over ${t.newConnectionsPerSecond}/second burst ${t.burst} packets } add @banned6 { ip6 saddr } ${l}`,""," # Concurrency ceiling per source: the slow-loris defence.",` tcp dport { ${r} } ct state new meter conn_count4 { ip saddr ct count over ${t.concurrentPerSource} } ${l}`,` tcp dport { ${r} } ct state new meter conn_count6 { ip6 saddr ct count over ${t.concurrentPerSource} } ${l}`,""),i.length>0)o.push(" # Origin protection: reject traffic that skipped the CDN and came"," # straight to the box, which is how an attacker bypasses the edge.",` tcp dport { ${r} } ip saddr != @cdn4 counter drop`,"")}return o.push(" }","}",""),o.join(`
4
+ `)}function ji(e={}){return`#!/usr/bin/env bash
5
5
  # Managed by ts-cloud. Installs L3/L4 flood mitigation.
6
6
  set -euo pipefail
7
7
 
@@ -13,11 +13,11 @@ fi
13
13
 
14
14
  install -d -m 0755 /etc/ts-cloud /etc/nftables.d
15
15
  cat > /etc/sysctl.d/90-ts-cloud-ddos.conf <<'SYSCTL_EOF'
16
- ${Gd(e)}SYSCTL_EOF
16
+ ${Yd(e)}SYSCTL_EOF
17
17
  sysctl --system >/dev/null
18
18
 
19
19
  cat > /etc/nftables.d/ts-cloud-ddos.nft.new <<'NFT_EOF'
20
- ${Vd(e)}NFT_EOF
20
+ ${Zd(e)}NFT_EOF
21
21
 
22
22
  # Syntax-check before applying: a bad ruleset would leave the box unprotected.
23
23
  if ! nft -c -f /etc/nftables.d/ts-cloud-ddos.nft.new; then
@@ -40,5 +40,5 @@ include "/etc/nftables.d/ts-cloud-ddos.nft"
40
40
  fi
41
41
  systemctl enable nftables >/dev/null 2>&1 || true
42
42
  echo "ts-cloud: L3/L4 mitigation active"
43
- `}var b=["off","monitor","rate_limit","challenge","lockdown"];function rm(e,t=[]){let n=[],s=Math.max(1,e.baselineRequestsPerSecond),a=e.requestsPerSecond/s,l=0,i=(g,v)=>{n.push(v),l=Math.max(l,b.indexOf(g))},c=a>=3;if(c)i("monitor",`Traffic is ${a.toFixed(1)}x the baseline.`);let p=e.topSourceShare>=0.25,u=e.errorRate>=0.25,o=(e.suspiciousAgentShare??0)>=0.5,r=e.uniqueSources>0&&e.requestsPerSecond/e.uniqueSources>=50;if(c&&p)i("rate_limit",`One source accounts for ${(e.topSourceShare*100).toFixed(0)}% of traffic.`);if(c&&r)i("rate_limit","Request rate per unique source is far above what a browser produces.");if(c&&u)i("challenge",`Error rate is ${(e.errorRate*100).toFixed(0)}% under load.`);if(c&&o)i("challenge","Most requests carry no recognisable browser agent.");if(a>=20&&(p||u||o||r))i("lockdown",`Traffic is ${a.toFixed(0)}x the baseline with attack-shaped characteristics.`);if(!c&&e.topSourceShare>=0.6&&e.requestsPerSecond>s)i("rate_limit","A single source dominates traffic without an overall surge.");let d=b[l],m={off:1,monitor:1,rate_limit:0.5,challenge:0.25,lockdown:0.1}[d];return{level:d,reasons:n,rateLimitFactor:m,challengeEnabled:d==="challenge"||d==="lockdown",staticOnly:d==="lockdown",banCandidates:d==="off"||d==="monitor"?[]:f(t)}}function nn(e,t){return Math.max(1,Math.floor(e*t.rateLimitFactor))}
44
- export{Qd,rn,Hd,Gd,Vd,Qi,rm,nn};
43
+ `}var b=["off","monitor","rate_limit","challenge","lockdown"];function lm(e,t=[]){let n=[],s=Math.max(1,e.baselineRequestsPerSecond),a=e.requestsPerSecond/s,l=0,i=(g,v)=>{n.push(v),l=Math.max(l,b.indexOf(g))},c=a>=3;if(c)i("monitor",`Traffic is ${a.toFixed(1)}x the baseline.`);let p=e.topSourceShare>=0.25,u=e.errorRate>=0.25,o=(e.suspiciousAgentShare??0)>=0.5,r=e.uniqueSources>0&&e.requestsPerSecond/e.uniqueSources>=50;if(c&&p)i("rate_limit",`One source accounts for ${(e.topSourceShare*100).toFixed(0)}% of traffic.`);if(c&&r)i("rate_limit","Request rate per unique source is far above what a browser produces.");if(c&&u)i("challenge",`Error rate is ${(e.errorRate*100).toFixed(0)}% under load.`);if(c&&o)i("challenge","Most requests carry no recognisable browser agent.");if(a>=20&&(p||u||o||r))i("lockdown",`Traffic is ${a.toFixed(0)}x the baseline with attack-shaped characteristics.`);if(!c&&e.topSourceShare>=0.6&&e.requestsPerSecond>s)i("rate_limit","A single source dominates traffic without an overall surge.");let d=b[l],m={off:1,monitor:1,rate_limit:0.5,challenge:0.25,lockdown:0.1}[d];return{level:d,reasons:n,rateLimitFactor:m,challengeEnabled:d==="challenge"||d==="lockdown",staticOnly:d==="lockdown",banCandidates:d==="off"||d==="monitor"?[]:f(t)}}function sn(e,t){return Math.max(1,Math.floor(e*t.rateLimitFactor))}
44
+ export{Jd,nn,Xd,Yd,Zd,ji,lm,sn};
@@ -1,4 +1,4 @@
1
- import{St,n}from"./chunk-ca191b00.js";import{o}from"./chunk-j99nkav5.js";import{I}from"./chunk-jtvw9d4x.js";import{f}from"./chunk-9ggg2ktx.js";import{nt}from"./chunk-erfh93dq.js";function R(e,t){let r=[`Action=${e}`,"Version=2010-05-08"];for(let[a,i]of Object.entries(t)){if(i===void 0||i===null)continue;if(Array.isArray(i))i.forEach((c,l)=>{if(typeof c==="object"&&c!==null)for(let[d,m]of Object.entries(c))r.push(`${a}.member.${l+1}.${d}=${encodeURIComponent(String(m))}`);else r.push(`${a}.member.${l+1}=${encodeURIComponent(String(c))}`)});else if(typeof i==="object"){for(let[c,l]of Object.entries(i))if(l!==void 0&&l!==null)r.push(`${a}.${c}=${encodeURIComponent(String(l))}`)}else r.push(`${a}=${encodeURIComponent(String(i))}`)}return r.join("&")}var S=new St({ignoreAttributes:!0,parseTagValue:!1,trimValues:!0});function b(e){if(typeof e!=="string"||!e.trim())return{};return S.parse(e)}function s(e,t){let r=[e];while(r.length>0){let a=[];for(let i of r){if(!i||typeof i!=="object")continue;if(Array.isArray(i)){a.push(...i);continue}if(t in i){let c=i[t];return typeof c==="string"?c:void 0}a.push(...Object.values(i))}r=a}return}function u(e,t,r){let a=[e];while(a.length>0){let i=[];for(let c of a){if(!c||typeof c!=="object")continue;if(Array.isArray(c)){i.push(...c);continue}if(t in c){let l=c[t]?.[r];return l===void 0||l===null?[]:Array.isArray(l)?l:[l]}i.push(...Object.values(c))}a=i}return[]}class Re{client;region;constructor(e="us-east-1",t){this.client=new n(void 0,{profile:t}),this.region=e}async request(e,t={}){let r=R(e,t),a=await this.client.request({service:"iam",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r,rawResponse:!0});return b(a)}async createUser(e){let t=await this.request("CreateUser",e);return this.parseUser(t)}async getUser(e={}){let t=await this.request("GetUser",e);return this.parseUser(t)}async listUsers(e={}){let t=await this.request("ListUsers",e),r=this.parseUsers(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Users:r,IsTruncated:a,Marker:i}}async updateUser(e){await this.request("UpdateUser",e)}async deleteUser(e){await this.request("DeleteUser",e)}parseUser(e){return{UserName:s(e,"UserName")||"",UserId:s(e,"UserId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),CreateDate:s(e,"CreateDate"),PasswordLastUsed:s(e,"PasswordLastUsed")}}parseUsers(e){return u(e,"Users","member").map((r)=>({UserName:s(r,"UserName")||"",UserId:s(r,"UserId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),CreateDate:s(r,"CreateDate"),PasswordLastUsed:s(r,"PasswordLastUsed")}))}async createGroup(e){let t=await this.request("CreateGroup",e);return this.parseGroup(t)}async getGroup(e){let t=await this.request("GetGroup",e),r=this.parseGroup(t),a=this.parseUsers(t),i=s(t,"IsTruncated")==="true",c=s(t,"Marker");return{Group:r,Users:a,IsTruncated:i,Marker:c}}async listGroups(e={}){let t=await this.request("ListGroups",e),r=this.parseGroups(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Groups:r,IsTruncated:a,Marker:i}}async updateGroup(e){await this.request("UpdateGroup",e)}async deleteGroup(e){await this.request("DeleteGroup",e)}async addUserToGroup(e){await this.request("AddUserToGroup",e)}async removeUserFromGroup(e){await this.request("RemoveUserFromGroup",e)}async listGroupsForUser(e){let t=await this.request("ListGroupsForUser",e),r=this.parseGroups(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Groups:r,IsTruncated:a,Marker:i}}parseGroup(e){return{GroupName:s(e,"GroupName")||"",GroupId:s(e,"GroupId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),CreateDate:s(e,"CreateDate")}}parseGroups(e){return u(e,"Groups","member").map((r)=>({GroupName:s(r,"GroupName")||"",GroupId:s(r,"GroupId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),CreateDate:s(r,"CreateDate")}))}async createRole(e){let t=await this.request("CreateRole",e);return this.parseRole(t)}async getRole(e){let t=await this.request("GetRole",e);return this.parseRole(t)}async listRoles(e={}){let t=await this.request("ListRoles",e),r=this.parseRoles(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Roles:r,IsTruncated:a,Marker:i}}async updateRole(e){await this.request("UpdateRole",e)}async updateRoleDescription(e){let t=await this.request("UpdateRoleDescription",e);return this.parseRole(t)}async updateAssumeRolePolicy(e){await this.request("UpdateAssumeRolePolicy",e)}async deleteRole(e){await this.request("DeleteRole",e)}async tagRole(e){await this.request("TagRole",e)}async untagRole(e){await this.request("UntagRole",e)}async listRoleTags(e){let t=await this.request("ListRoleTags",e),r=this.parseTags(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Tags:r,IsTruncated:a,Marker:i}}parseRole(e){return{RoleName:s(e,"RoleName")||"",RoleId:s(e,"RoleId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),CreateDate:s(e,"CreateDate"),AssumeRolePolicyDocument:s(e,"AssumeRolePolicyDocument"),Description:s(e,"Description"),MaxSessionDuration:s(e,"MaxSessionDuration")?Number.parseInt(s(e,"MaxSessionDuration"),10):void 0}}parseRoles(e){return u(e,"Roles","member").map((r)=>({RoleName:s(r,"RoleName")||"",RoleId:s(r,"RoleId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),CreateDate:s(r,"CreateDate"),AssumeRolePolicyDocument:s(r,"AssumeRolePolicyDocument"),Description:s(r,"Description"),MaxSessionDuration:s(r,"MaxSessionDuration")?Number.parseInt(s(r,"MaxSessionDuration"),10):void 0}))}parseTags(e){return u(e,"Tags","member").map((r)=>({Key:s(r,"Key")||"",Value:s(r,"Value")||""}))}async createPolicy(e){let t=await this.request("CreatePolicy",e);return this.parsePolicy(t)}async getPolicy(e){let t=await this.request("GetPolicy",e);return this.parsePolicy(t)}async getPolicyVersion(e){let t=await this.request("GetPolicyVersion",e);return{VersionId:s(t,"VersionId")||"",IsDefaultVersion:s(t,"IsDefaultVersion")==="true",CreateDate:s(t,"CreateDate"),Document:s(t,"Document")}}async listPolicies(e={}){let t=await this.request("ListPolicies",e),r=this.parsePolicies(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Policies:r,IsTruncated:a,Marker:i}}async listPolicyVersions(e){let t=await this.request("ListPolicyVersions",e),r=this.parsePolicyVersions(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Versions:r,IsTruncated:a,Marker:i}}async createPolicyVersion(e){let t=await this.request("CreatePolicyVersion",e);return{VersionId:s(t,"VersionId")||"",IsDefaultVersion:s(t,"IsDefaultVersion")==="true",CreateDate:s(t,"CreateDate")}}async deletePolicyVersion(e){await this.request("DeletePolicyVersion",e)}async setDefaultPolicyVersion(e){await this.request("SetDefaultPolicyVersion",e)}async deletePolicy(e){await this.request("DeletePolicy",e)}async attachUserPolicy(e){await this.request("AttachUserPolicy",e)}async detachUserPolicy(e){await this.request("DetachUserPolicy",e)}async attachGroupPolicy(e){await this.request("AttachGroupPolicy",e)}async detachGroupPolicy(e){await this.request("DetachGroupPolicy",e)}async attachRolePolicy(e){await this.request("AttachRolePolicy",e)}async detachRolePolicy(e){await this.request("DetachRolePolicy",e)}async listAttachedUserPolicies(e){let t=await this.request("ListAttachedUserPolicies",e),r=this.parseAttachedPolicies(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{AttachedPolicies:r,IsTruncated:a,Marker:i}}async listAttachedGroupPolicies(e){let t=await this.request("ListAttachedGroupPolicies",e),r=this.parseAttachedPolicies(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{AttachedPolicies:r,IsTruncated:a,Marker:i}}async listAttachedRolePolicies(e){let t=await this.request("ListAttachedRolePolicies",e),r=this.parseAttachedPolicies(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{AttachedPolicies:r,IsTruncated:a,Marker:i}}parsePolicy(e){return{PolicyName:s(e,"PolicyName")||"",PolicyId:s(e,"PolicyId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),DefaultVersionId:s(e,"DefaultVersionId"),AttachmentCount:s(e,"AttachmentCount")?Number.parseInt(s(e,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:s(e,"PermissionsBoundaryUsageCount")?Number.parseInt(s(e,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:s(e,"IsAttachable")==="true",Description:s(e,"Description"),CreateDate:s(e,"CreateDate"),UpdateDate:s(e,"UpdateDate")}}parsePolicies(e){return u(e,"Policies","member").map((r)=>({PolicyName:s(r,"PolicyName")||"",PolicyId:s(r,"PolicyId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),DefaultVersionId:s(r,"DefaultVersionId"),AttachmentCount:s(r,"AttachmentCount")?Number.parseInt(s(r,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:s(r,"PermissionsBoundaryUsageCount")?Number.parseInt(s(r,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:s(r,"IsAttachable")==="true",Description:s(r,"Description"),CreateDate:s(r,"CreateDate"),UpdateDate:s(r,"UpdateDate")}))}parsePolicyVersions(e){return u(e,"Versions","member").map((r)=>({VersionId:s(r,"VersionId")||"",IsDefaultVersion:s(r,"IsDefaultVersion")==="true",CreateDate:s(r,"CreateDate")}))}parseAttachedPolicies(e){return u(e,"AttachedPolicies","member").map((r)=>({PolicyName:s(r,"PolicyName")||"",PolicyArn:s(r,"PolicyArn")||""}))}async putUserPolicy(e){await this.request("PutUserPolicy",e)}async getUserPolicy(e){let t=await this.request("GetUserPolicy",e);return{UserName:s(t,"UserName")||"",PolicyName:s(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(s(t,"PolicyDocument")||"")}}async deleteUserPolicy(e){await this.request("DeleteUserPolicy",e)}async listUserPolicies(e){let t=await this.request("ListUserPolicies",e),r=u(t,"PolicyNames","member"),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{PolicyNames:r,IsTruncated:a,Marker:i}}async putGroupPolicy(e){await this.request("PutGroupPolicy",e)}async getGroupPolicy(e){let t=await this.request("GetGroupPolicy",e);return{GroupName:s(t,"GroupName")||"",PolicyName:s(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(s(t,"PolicyDocument")||"")}}async deleteGroupPolicy(e){await this.request("DeleteGroupPolicy",e)}async listGroupPolicies(e){let t=await this.request("ListGroupPolicies",e),r=u(t,"PolicyNames","member"),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{PolicyNames:r,IsTruncated:a,Marker:i}}async putRolePolicy(e){await this.request("PutRolePolicy",e)}async getRolePolicy(e){let t=await this.request("GetRolePolicy",e);return{RoleName:s(t,"RoleName")||"",PolicyName:s(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(s(t,"PolicyDocument")||"")}}async deleteRolePolicy(e){await this.request("DeleteRolePolicy",e)}async listRolePolicies(e){let t=await this.request("ListRolePolicies",e),r=u(t,"PolicyNames","member"),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{PolicyNames:r,IsTruncated:a,Marker:i}}async createAccessKey(e={}){let t=await this.request("CreateAccessKey",e);if(typeof t==="object"){let r=t?.CreateAccessKeyResult?.AccessKey||t?.AccessKey;if(r)return{AccessKey:{UserName:r.UserName||"",AccessKeyId:r.AccessKeyId||"",Status:r.Status||"Active",SecretAccessKey:r.SecretAccessKey||"",CreateDate:r.CreateDate}}}return{AccessKey:{UserName:s(t,"UserName")||"",AccessKeyId:s(t,"AccessKeyId")||"",Status:s(t,"Status")||"Active",SecretAccessKey:s(t,"SecretAccessKey")||"",CreateDate:s(t,"CreateDate")}}}async listAccessKeys(e={}){let t=await this.request("ListAccessKeys",e),r=this.parseAccessKeys(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{AccessKeyMetadata:r,IsTruncated:a,Marker:i}}async updateAccessKey(e){await this.request("UpdateAccessKey",e)}async deleteAccessKey(e){await this.request("DeleteAccessKey",e)}async getAccessKeyLastUsed(e){let t=await this.request("GetAccessKeyLastUsed",e);return{UserName:s(t,"UserName")||"",AccessKeyLastUsed:{LastUsedDate:s(t,"LastUsedDate"),ServiceName:s(t,"ServiceName"),Region:s(t,"Region")}}}parseAccessKeys(e){return u(e,"AccessKeyMetadata","member").map((r)=>({UserName:s(r,"UserName"),AccessKeyId:s(r,"AccessKeyId")||"",Status:s(r,"Status")||"Active",CreateDate:s(r,"CreateDate")}))}async createInstanceProfile(e){let t=await this.request("CreateInstanceProfile",e);return this.parseInstanceProfile(t)}async getInstanceProfile(e){let t=await this.request("GetInstanceProfile",e);return this.parseInstanceProfile(t)}async listInstanceProfiles(e={}){let t=await this.request("ListInstanceProfiles",e),r=this.parseInstanceProfiles(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{InstanceProfiles:r,IsTruncated:a,Marker:i}}async listInstanceProfilesForRole(e){let t=await this.request("ListInstanceProfilesForRole",e),r=this.parseInstanceProfiles(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{InstanceProfiles:r,IsTruncated:a,Marker:i}}async addRoleToInstanceProfile(e){await this.request("AddRoleToInstanceProfile",e)}async removeRoleFromInstanceProfile(e){await this.request("RemoveRoleFromInstanceProfile",e)}async deleteInstanceProfile(e){await this.request("DeleteInstanceProfile",e)}parseInstanceProfile(e){return{InstanceProfileName:s(e,"InstanceProfileName")||"",InstanceProfileId:s(e,"InstanceProfileId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),CreateDate:s(e,"CreateDate")}}parseInstanceProfiles(e){return u(e,"InstanceProfiles","member").map((r)=>({InstanceProfileName:s(r,"InstanceProfileName")||"",InstanceProfileId:s(r,"InstanceProfileId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),CreateDate:s(r,"CreateDate")}))}async getAccountPasswordPolicy(){let e=await this.request("GetAccountPasswordPolicy");return{MinimumPasswordLength:s(e,"MinimumPasswordLength")?Number.parseInt(s(e,"MinimumPasswordLength"),10):void 0,RequireSymbols:s(e,"RequireSymbols")==="true",RequireNumbers:s(e,"RequireNumbers")==="true",RequireUppercaseCharacters:s(e,"RequireUppercaseCharacters")==="true",RequireLowercaseCharacters:s(e,"RequireLowercaseCharacters")==="true",AllowUsersToChangePassword:s(e,"AllowUsersToChangePassword")==="true",ExpirePasswords:s(e,"ExpirePasswords")==="true",MaxPasswordAge:s(e,"MaxPasswordAge")?Number.parseInt(s(e,"MaxPasswordAge"),10):void 0,PasswordReusePrevention:s(e,"PasswordReusePrevention")?Number.parseInt(s(e,"PasswordReusePrevention"),10):void 0,HardExpiry:s(e,"HardExpiry")==="true"}}async updateAccountPasswordPolicy(e){await this.request("UpdateAccountPasswordPolicy",e)}async deleteAccountPasswordPolicy(){await this.request("DeleteAccountPasswordPolicy")}async getAccountSummary(){let e=await this.request("GetAccountSummary"),t={},r=u(e,"SummaryMap","entry");for(let a of r){let i=s(a,"key"),c=s(a,"value");if(i&&c)t[i]=Number.parseInt(c,10)}return t}async listAccountAliases(){let e=await this.request("ListAccountAliases"),t=u(e,"AccountAliases","member"),r=s(e,"IsTruncated")==="true",a=s(e,"Marker");return{AccountAliases:t,IsTruncated:r,Marker:a}}async createAccountAlias(e){await this.request("CreateAccountAlias",e)}async deleteAccountAlias(e){await this.request("DeleteAccountAlias",e)}async simulatePrincipalPolicy(e){let t=await this.request("SimulatePrincipalPolicy",e);return this.parseSimulationResults(t)}parseSimulationResults(e){let r=u(e,"EvaluationResults","member").map((c)=>{let d=u(c,"MatchedStatements","member").map((m)=>({SourcePolicyId:s(m,"SourcePolicyId"),SourcePolicyType:s(m,"SourcePolicyType")}));return{EvalActionName:s(c,"EvalActionName")||"",EvalResourceName:s(c,"EvalResourceName"),EvalDecision:s(c,"EvalDecision")||"",MatchedStatements:d.length>0?d:void 0}}),a=s(e,"IsTruncated")==="true",i=s(e,"Marker");return{EvaluationResults:r,IsTruncated:a,Marker:i}}}class gt{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new n(t)}async createEmailIdentity(e){return await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/identities",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async getEmailIdentity(e){let t=await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/identities/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}});return{IdentityType:t.IdentityType,IdentityName:e,SendingEnabled:t.VerifiedForSendingStatus,VerificationStatus:t.VerificationStatus,DkimAttributes:t.DkimAttributes,MailFromAttributes:t.MailFromAttributes}}async putEmailIdentityMailFromAttributes(e,t){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(e)}/mail-from`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async listEmailIdentities(e){let t="/v2/email/identities",r=[];if(e?.PageSize)r.push(`PageSize=${e.PageSize}`);if(e?.NextToken)r.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(r.length>0)t+=`?${r.join("&")}`;let a=await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}});return{EmailIdentities:a.EmailIdentities,NextToken:a.NextToken}}async deleteEmailIdentity(e){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/identities/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async putEmailIdentityDkimAttributes(e){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(e.EmailIdentity)}/dkim`,headers:{"Content-Type":"application/json"},body:JSON.stringify({SigningEnabled:e.SigningEnabled})})}async sendEmail(e){return{MessageId:(await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/outbound-emails",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).MessageId}}async sendBulkEmail(e){return{BulkEmailEntryResults:(await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/outbound-bulk-emails",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).BulkEmailEntryResults}}async createEmailTemplate(e){await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/templates",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async getEmailTemplate(e){return await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/templates/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async deleteEmailTemplate(e){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/templates/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async listEmailTemplates(e){let t="/v2/email/templates",r=[];if(e?.PageSize)r.push(`PageSize=${e.PageSize}`);if(e?.NextToken)r.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(r.length>0)t+=`?${r.join("&")}`;return await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}})}async getSendStatistics(){let e=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendStatistics&Version=2010-12-01"}),t=f(e,"GetSendStatistics")?.SendDataPoints?.member;return{SendDataPoints:t==null?[]:Array.isArray(t)?t:[t]}}async getSendQuota(){let e=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendQuota&Version=2010-12-01"}),t=f(e,"GetSendQuota"),r=(a)=>a==null||a===""?void 0:Number(a);return{Max24HourSend:r(t?.Max24HourSend),MaxSendRate:r(t?.MaxSendRate),SentLast24Hours:r(t?.SentLast24Hours)}}async verifyDomain(e){let t=await this.createEmailIdentity({EmailIdentity:e});return{dkimTokens:t.DkimAttributes?.Tokens,verificationStatus:t.DkimAttributes?.Status}}async sendSimpleEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],r=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0,a={};if(e.text)a.Text={Data:e.text};if(e.html)a.Html={Data:e.html};return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Simple:{Subject:{Data:e.subject},Body:a}},ReplyToAddresses:r})}async sendTemplatedEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],r=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0;return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Template:{TemplateName:e.templateName,TemplateData:JSON.stringify(e.templateData)}},ReplyToAddresses:r})}async getDkimRecords(e){let t=await this.getEmailIdentity(e);if(!t.DkimAttributes?.Tokens)return[];return t.DkimAttributes.Tokens.map((r)=>({name:`${r}._domainkey.${e}`,type:"CNAME",value:`${r}.dkim.amazonses.com`}))}async isDomainVerified(e){try{let t=await this.getEmailIdentity(e);return t.VerificationStatus==="SUCCESS"&&t.SendingEnabled===!0}catch{return!1}}async waitForDomainVerification(e,t=60,r=30000){for(let a=0;a<t;a++){if(await this.isDomainVerified(e))return!0;await new Promise((c)=>setTimeout(c,r))}return!1}buildFormBody(e){return Object.entries(e).filter(([,r])=>r!==void 0).map(([r,a])=>`${encodeURIComponent(r)}=${encodeURIComponent(a)}`).join("&")}async createReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"CreateReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async deleteReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async setActiveReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"SetActiveReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async listReceiptRuleSets(e){let t={Action:"ListReceiptRuleSets",Version:"2010-12-01"};if(e)t.NextToken=e;let r=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)}),a=r?.ListReceiptRuleSetsResponse?.ListReceiptRuleSetsResult||r?.ListReceiptRuleSetsResult,i=a?.RuleSets?.member;return{RuleSets:Array.isArray(i)?i:i?[i]:[],NextToken:a?.NextToken}}async describeReceiptRuleSet(e){let t=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DescribeReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})}),r=t?.DescribeReceiptRuleSetResponse?.DescribeReceiptRuleSetResult||t?.DescribeReceiptRuleSetResult,a=r?.Rules?.member;return{Metadata:r?.Metadata,Rules:Array.isArray(a)?a:a?[a]:[]}}async createReceiptRule(e){let t={Action:"CreateReceiptRule",Version:"2010-12-01",RuleSetName:e.RuleSetName,"Rule.Name":e.Rule.Name,"Rule.Enabled":e.Rule.Enabled!==!1?"true":"false"};if(e.Rule.TlsPolicy)t["Rule.TlsPolicy"]=e.Rule.TlsPolicy;if(e.Rule.ScanEnabled!==void 0)t["Rule.ScanEnabled"]=e.Rule.ScanEnabled?"true":"false";if(e.After)t.After=e.After;if(e.Rule.Recipients)e.Rule.Recipients.forEach((r,a)=>{t[`Rule.Recipients.member.${a+1}`]=r});e.Rule.Actions.forEach((r,a)=>{let i=a+1;if(r.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=r.S3Action.BucketName,r.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=r.S3Action.ObjectKeyPrefix;if(r.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=r.S3Action.KmsKeyArn}if(r.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=r.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=r.LambdaAction.InvocationType||"Event";if(r.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=r.SNSAction.TopicArn,r.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=r.SNSAction.Encoding}if(r.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=r.StopAction.Scope,r.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=r.StopAction.TopicArn}}),await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)})}async deleteReceiptRule(e,t){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteReceiptRule",Version:"2010-12-01",RuleSetName:e,RuleName:t})})}async receiptRuleSetExists(e){try{return await this.describeReceiptRuleSet(e),!0}catch(t){if(t.code==="RuleSetDoesNotExist"||t.statusCode===400)return!1;throw t}}async getActiveReceiptRuleSet(){let e=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DescribeActiveReceiptRuleSet",Version:"2010-12-01"})}),t=e?.DescribeActiveReceiptRuleSetResponse?.DescribeActiveReceiptRuleSetResult||e?.DescribeActiveReceiptRuleSetResult;if(!t?.Metadata)return null;let r=t?.Rules?.member;return{Metadata:t?.Metadata,Rules:Array.isArray(r)?r:r?[r]:[]}}async updateReceiptRule(e){let t={Action:"UpdateReceiptRule",Version:"2010-12-01",RuleSetName:e.RuleSetName,"Rule.Name":e.Rule.Name};if(e.Rule.Enabled!==void 0)t["Rule.Enabled"]=e.Rule.Enabled?"true":"false";if(e.Rule.TlsPolicy)t["Rule.TlsPolicy"]=e.Rule.TlsPolicy;if(e.Rule.ScanEnabled!==void 0)t["Rule.ScanEnabled"]=e.Rule.ScanEnabled?"true":"false";if(e.Rule.Recipients)e.Rule.Recipients.forEach((r,a)=>{t[`Rule.Recipients.member.${a+1}`]=r});e.Rule.Actions.forEach((r,a)=>{let i=a+1;if(r.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=r.S3Action.BucketName,r.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=r.S3Action.ObjectKeyPrefix;if(r.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=r.S3Action.KmsKeyArn}if(r.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=r.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=r.LambdaAction.InvocationType||"Event";if(r.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=r.SNSAction.TopicArn,r.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=r.SNSAction.Encoding}if(r.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=r.StopAction.Scope,r.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=r.StopAction.TopicArn}}),await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)})}async sendRawEmail(e){let t=Buffer.from(e.rawMessage).toString("base64"),r={Action:"SendRawEmail",Version:"2010-12-01",Source:e.source,"RawMessage.Data":t};e.destinations.forEach((c,l)=>{r[`Destinations.member.${l+1}`]=c});let a=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(r)});return{MessageId:(a?.SendRawEmailResponse?.SendRawEmailResult||a?.SendRawEmailResult)?.MessageId}}async getSuppressedDestination(e){try{return(await this.client.request({service:"ses",region:this.region,method:"GET",path:`/v2/email/suppression/addresses/${encodeURIComponent(e)}`}))?.SuppressedDestination||null}catch(t){if(t.message?.includes("404")||t.message?.includes("NotFoundException"))return null;throw t}}async deleteSuppressedDestination(e){await this.client.request({service:"ses",region:this.region,method:"DELETE",path:`/v2/email/suppression/addresses/${encodeURIComponent(e)}`})}}class Gn{ses;s3;iam;route53;region;domain;defaultFrom;constructor(e={}){this.region=e.region||"us-east-1",this.domain=e.domain,this.defaultFrom=e.defaultFrom,this.ses=new gt(this.region),this.s3=new o(this.region),this.iam=new Re(this.region),this.route53=new I(this.region)}async send(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required. Set defaultFrom in constructor or provide from in options.");let r=e.fromName?`${e.fromName} <${t}>`:t,a=Array.isArray(e.to)?e.to:[e.to];if(!e.attachments||e.attachments.length===0)return{messageId:(await this.ses.sendSimpleEmail({from:r,to:a,subject:e.subject,text:e.text,html:e.html,replyTo:e.replyTo})).MessageId||""};let i=this.buildRawEmail(e,r,a);return{messageId:(await this.ses.sendEmail({FromEmailAddress:r,Destination:{ToAddresses:a,CcAddresses:e.cc?Array.isArray(e.cc)?e.cc:[e.cc]:void 0,BccAddresses:e.bcc?Array.isArray(e.bcc)?e.bcc:[e.bcc]:void 0},Content:{Raw:{Data:Buffer.from(i).toString("base64")}}})).MessageId||""}}async sendTemplate(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required");let r=e.fromName?`${e.fromName} <${t}>`:t;return{messageId:(await this.ses.sendTemplatedEmail({from:r,to:e.to,templateName:e.templateName,templateData:e.templateData,replyTo:e.replyTo})).MessageId||""}}async sendBulk(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required");let r=e.recipients.map((i)=>({Destination:{ToAddresses:Array.isArray(i.to)?i.to:[i.to]},ReplacementEmailContent:i.templateData?{ReplacementTemplate:{ReplacementTemplateData:JSON.stringify(i.templateData)}}:void 0}));return{results:(await this.ses.sendBulkEmail({FromEmailAddress:t,BulkEmailEntries:r,DefaultContent:{Template:{TemplateName:e.templateName,TemplateData:JSON.stringify(e.defaultTemplateData)}}})).BulkEmailEntryResults?.map((i)=>({status:i.Status||"UNKNOWN",messageId:i.MessageId,error:i.Error}))||[]}}async setupDomain(e){let t;try{t=await this.ses.getEmailIdentity(e)}catch{let a=await this.ses.createEmailIdentity({EmailIdentity:e});t={VerificationStatus:a.DkimAttributes?.Status,DkimAttributes:a.DkimAttributes,SendingEnabled:a.VerifiedForSendingStatus}}try{await this.ses.putEmailIdentityDkimAttributes({EmailIdentity:e,SigningEnabled:!0})}catch{}try{await this.ses.putEmailIdentityMailFromAttributes(e,{MailFromDomain:`mail.${e}`,BehaviorOnMxFailure:"USE_DEFAULT_VALUE"})}catch{}let r=await this.ses.getDkimRecords(e);return{domainVerified:t.SendingEnabled===!0,dkimStatus:t.DkimAttributes?.Status||"UNKNOWN",dkimTokens:t.DkimAttributes?.Tokens,mailFromStatus:t.MailFromAttributes?.MailFromDomainStatus}}async getDnsRecords(e){let t=[],r=await this.ses.getDkimRecords(e);for(let a of r)t.push({type:a.type,name:a.name,value:a.value,ttl:1800});return t.push({type:"MX",name:e,value:`inbound-smtp.${this.region}.amazonaws.com`,priority:10,ttl:3600}),t.push({type:"MX",name:`mail.${e}`,value:`feedback-smtp.${this.region}.amazonses.com`,priority:10,ttl:3600}),t.push({type:"TXT",name:`mail.${e}`,value:"v=spf1 include:amazonses.com ~all",ttl:3600}),t.push({type:"TXT",name:`_dmarc.${e}`,value:`v=DMARC1;p=quarantine;pct=25;rua=mailto:dmarcreports@${e}`,ttl:3600}),t}async isDomainReady(e){try{let t=await this.ses.getEmailIdentity(e);return t.SendingEnabled===!0&&t.DkimAttributes?.Status==="SUCCESS"}catch{return!1}}async setupReceiving(e){let t={Version:"2012-10-17",Statement:[{Sid:"AllowSESPuts",Effect:"Allow",Principal:{Service:"ses.amazonaws.com"},Action:"s3:PutObject",Resource:`arn:aws:s3:::${e.bucketName}/*`,Condition:{StringEquals:{"AWS:SourceAccount":e.accountId}}}]};await this.s3.putBucketPolicy(e.bucketName,t);try{await this.ses.createReceiptRuleSet(e.ruleSetName)}catch(a){if(!a.message?.includes("already exists")&&a.code!=="AlreadyExists")throw a}let r=[{S3Action:{BucketName:e.bucketName,ObjectKeyPrefix:e.prefix||"inbox/"}}];if(e.lambdaArn)r.push({LambdaAction:{FunctionArn:e.lambdaArn,InvocationType:"Event"}});try{await this.ses.createReceiptRule({RuleSetName:e.ruleSetName,Rule:{Name:e.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:e.recipients||[e.domain],ScanEnabled:e.scanEnabled!==!1,Actions:r}})}catch(a){if(a.message?.includes("already exists"))await this.ses.deleteReceiptRule(e.ruleSetName,e.ruleName),await this.ses.createReceiptRule({RuleSetName:e.ruleSetName,Rule:{Name:e.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:e.recipients||[e.domain],ScanEnabled:e.scanEnabled!==!1,Actions:r}});else throw a}await this.ses.setActiveReceiptRuleSet(e.ruleSetName)}async getIncomingEmails(e){return(await this.s3.list({bucket:e.bucket,prefix:e.prefix||"incoming/",maxKeys:e.maxResults||100})).map((r)=>({key:r.Key||"",lastModified:r.LastModified||"",size:r.Size||0}))}async readEmail(e){return await this.s3.getObject(e.bucket,e.key)}async createSmtpCredentials(e){let t=`ses-smtp-${e.username.replace(/[^a-zA-Z0-9]/g,"-")}`,{AWSClient:r}=await import("./chunk-tnqj2en4.js"),a=new r,i=(p,y)=>{let P={Action:p,Version:"2010-05-08",...y};return Object.entries(P).map(([A,h])=>`${encodeURIComponent(A)}=${encodeURIComponent(h)}`).join("&")};try{await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateUser",{UserName:t})})}catch(p){if(!p.message?.includes("EntityAlreadyExists"))throw p}let c={Version:"2012-10-17",Statement:[{Effect:"Allow",Action:"ses:SendRawEmail",Resource:"*",Condition:{StringLike:{"ses:FromAddress":`*@${e.domain}`}}}]},l=`ses-smtp-policy-${e.domain.replace(/\./g,"-")}`;try{await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("PutUserPolicy",{UserName:t,PolicyName:l,PolicyDocument:JSON.stringify(c)})})}catch{}let m=(await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateAccessKey",{UserName:t})}))?.CreateAccessKeyResult?.AccessKey;if(!m?.AccessKeyId||!m?.SecretAccessKey)throw Error("Failed to create access key");let g=this.deriveSmtpPassword(m.SecretAccessKey);return{username:m.AccessKeyId,password:g,server:`email-smtp.${this.region}.amazonaws.com`,port:587}}deriveSmtpPassword(e){let t=nt("node:crypto"),r="SendRawEmail",a=Buffer.from([4]),i=t.createHmac("sha256",`AWS4${e}`).update("11111111").digest();return i=t.createHmac("sha256",i).update(this.region).digest(),i=t.createHmac("sha256",i).update("ses").digest(),i=t.createHmac("sha256",i).update("aws4_request").digest(),i=t.createHmac("sha256",i).update("SendRawEmail").digest(),Buffer.concat([a,i]).toString("base64")}async createTemplate(e){await this.ses.createEmailTemplate({TemplateName:e.name,TemplateContent:{Subject:e.subject,Text:e.text,Html:e.html}})}async getTemplate(e){try{let t=await this.ses.getEmailTemplate(e);return{name:t.TemplateName||e,subject:t.TemplateContent?.Subject,text:t.TemplateContent?.Text,html:t.TemplateContent?.Html}}catch{return null}}async deleteTemplate(e){await this.ses.deleteEmailTemplate(e)}async listTemplates(){return(await this.ses.listEmailTemplates()).TemplatesMetadata?.map((t)=>({name:t.TemplateName||"",createdAt:t.CreatedTimestamp}))||[]}async deploy(e){let t=`${e.appName}-${e.environment}-email-rules`,r=`${e.appName}-inbound-email`,a=e.storage?.bucketName||`${e.appName}-${e.environment}-email`,i=await this.setupDomain(e.domain);if(!(await this.s3.listBuckets()).Buckets?.some((m)=>m.Name===a))await this.s3.createBucket(a);await this.setupReceiving({domain:e.domain,ruleSetName:t,ruleName:r,bucketName:a,prefix:e.storage?.prefix||"inbox/",accountId:e.accountId,recipients:e.catchAll?[e.domain]:e.mailboxes,scanEnabled:!0});let d=await this.getDnsRecords(e.domain);return{success:!0,domainVerified:i.domainVerified,dkimStatus:i.dkimStatus,receiptRuleSet:t,storageBucket:a,dnsRecords:d}}async undeploy(e){let t=`${e.appName}-${e.environment}-email-rules`,r=`${e.appName}-inbound-email`,a=`${e.appName}-${e.environment}-email`;try{await this.ses.deleteReceiptRule(t,r)}catch{}try{await this.ses.deleteReceiptRuleSet(t)}catch{}if(e.deleteBucket)try{await this.s3.emptyAndDeleteBucket(a)}catch{}}async getSendingStats(){let e=await this.ses.getSendQuota();return{sentLast24Hours:e.SentLast24Hours||0,maxSendRate:e.MaxSendRate||0,max24HourSend:e.Max24HourSend||0}}buildRawEmail(e,t,r){let a=`----=_Part_${Date.now()}_${Math.random().toString(36).substring(2)}`,i="";if(i+=`From: ${t}\r
1
+ import{St,n}from"./chunk-e42gpavb.js";import{o}from"./chunk-jyvnfny6.js";import{I}from"./chunk-y7k5872m.js";import{f}from"./chunk-7ag4wc74.js";import{nt}from"./chunk-c482jhc6.js";function R(e,t){let r=[`Action=${e}`,"Version=2010-05-08"];for(let[a,i]of Object.entries(t)){if(i===void 0||i===null)continue;if(Array.isArray(i))i.forEach((c,l)=>{if(typeof c==="object"&&c!==null)for(let[d,m]of Object.entries(c))r.push(`${a}.member.${l+1}.${d}=${encodeURIComponent(String(m))}`);else r.push(`${a}.member.${l+1}=${encodeURIComponent(String(c))}`)});else if(typeof i==="object"){for(let[c,l]of Object.entries(i))if(l!==void 0&&l!==null)r.push(`${a}.${c}=${encodeURIComponent(String(l))}`)}else r.push(`${a}=${encodeURIComponent(String(i))}`)}return r.join("&")}var S=new St({ignoreAttributes:!0,parseTagValue:!1,trimValues:!0});function b(e){if(typeof e!=="string"||!e.trim())return{};return S.parse(e)}function s(e,t){let r=[e];while(r.length>0){let a=[];for(let i of r){if(!i||typeof i!=="object")continue;if(Array.isArray(i)){a.push(...i);continue}if(t in i){let c=i[t];return typeof c==="string"?c:void 0}a.push(...Object.values(i))}r=a}return}function u(e,t,r){let a=[e];while(a.length>0){let i=[];for(let c of a){if(!c||typeof c!=="object")continue;if(Array.isArray(c)){i.push(...c);continue}if(t in c){let l=c[t]?.[r];return l===void 0||l===null?[]:Array.isArray(l)?l:[l]}i.push(...Object.values(c))}a=i}return[]}class Re{client;region;constructor(e="us-east-1",t){this.client=new n(void 0,{profile:t}),this.region=e}async request(e,t={}){let r=R(e,t),a=await this.client.request({service:"iam",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r,rawResponse:!0});return b(a)}async createUser(e){let t=await this.request("CreateUser",e);return this.parseUser(t)}async getUser(e={}){let t=await this.request("GetUser",e);return this.parseUser(t)}async listUsers(e={}){let t=await this.request("ListUsers",e),r=this.parseUsers(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Users:r,IsTruncated:a,Marker:i}}async updateUser(e){await this.request("UpdateUser",e)}async deleteUser(e){await this.request("DeleteUser",e)}parseUser(e){return{UserName:s(e,"UserName")||"",UserId:s(e,"UserId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),CreateDate:s(e,"CreateDate"),PasswordLastUsed:s(e,"PasswordLastUsed")}}parseUsers(e){return u(e,"Users","member").map((r)=>({UserName:s(r,"UserName")||"",UserId:s(r,"UserId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),CreateDate:s(r,"CreateDate"),PasswordLastUsed:s(r,"PasswordLastUsed")}))}async createGroup(e){let t=await this.request("CreateGroup",e);return this.parseGroup(t)}async getGroup(e){let t=await this.request("GetGroup",e),r=this.parseGroup(t),a=this.parseUsers(t),i=s(t,"IsTruncated")==="true",c=s(t,"Marker");return{Group:r,Users:a,IsTruncated:i,Marker:c}}async listGroups(e={}){let t=await this.request("ListGroups",e),r=this.parseGroups(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Groups:r,IsTruncated:a,Marker:i}}async updateGroup(e){await this.request("UpdateGroup",e)}async deleteGroup(e){await this.request("DeleteGroup",e)}async addUserToGroup(e){await this.request("AddUserToGroup",e)}async removeUserFromGroup(e){await this.request("RemoveUserFromGroup",e)}async listGroupsForUser(e){let t=await this.request("ListGroupsForUser",e),r=this.parseGroups(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Groups:r,IsTruncated:a,Marker:i}}parseGroup(e){return{GroupName:s(e,"GroupName")||"",GroupId:s(e,"GroupId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),CreateDate:s(e,"CreateDate")}}parseGroups(e){return u(e,"Groups","member").map((r)=>({GroupName:s(r,"GroupName")||"",GroupId:s(r,"GroupId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),CreateDate:s(r,"CreateDate")}))}async createRole(e){let t=await this.request("CreateRole",e);return this.parseRole(t)}async getRole(e){let t=await this.request("GetRole",e);return this.parseRole(t)}async listRoles(e={}){let t=await this.request("ListRoles",e),r=this.parseRoles(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Roles:r,IsTruncated:a,Marker:i}}async updateRole(e){await this.request("UpdateRole",e)}async updateRoleDescription(e){let t=await this.request("UpdateRoleDescription",e);return this.parseRole(t)}async updateAssumeRolePolicy(e){await this.request("UpdateAssumeRolePolicy",e)}async deleteRole(e){await this.request("DeleteRole",e)}async tagRole(e){await this.request("TagRole",e)}async untagRole(e){await this.request("UntagRole",e)}async listRoleTags(e){let t=await this.request("ListRoleTags",e),r=this.parseTags(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Tags:r,IsTruncated:a,Marker:i}}parseRole(e){return{RoleName:s(e,"RoleName")||"",RoleId:s(e,"RoleId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),CreateDate:s(e,"CreateDate"),AssumeRolePolicyDocument:s(e,"AssumeRolePolicyDocument"),Description:s(e,"Description"),MaxSessionDuration:s(e,"MaxSessionDuration")?Number.parseInt(s(e,"MaxSessionDuration"),10):void 0}}parseRoles(e){return u(e,"Roles","member").map((r)=>({RoleName:s(r,"RoleName")||"",RoleId:s(r,"RoleId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),CreateDate:s(r,"CreateDate"),AssumeRolePolicyDocument:s(r,"AssumeRolePolicyDocument"),Description:s(r,"Description"),MaxSessionDuration:s(r,"MaxSessionDuration")?Number.parseInt(s(r,"MaxSessionDuration"),10):void 0}))}parseTags(e){return u(e,"Tags","member").map((r)=>({Key:s(r,"Key")||"",Value:s(r,"Value")||""}))}async createPolicy(e){let t=await this.request("CreatePolicy",e);return this.parsePolicy(t)}async getPolicy(e){let t=await this.request("GetPolicy",e);return this.parsePolicy(t)}async getPolicyVersion(e){let t=await this.request("GetPolicyVersion",e);return{VersionId:s(t,"VersionId")||"",IsDefaultVersion:s(t,"IsDefaultVersion")==="true",CreateDate:s(t,"CreateDate"),Document:s(t,"Document")}}async listPolicies(e={}){let t=await this.request("ListPolicies",e),r=this.parsePolicies(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Policies:r,IsTruncated:a,Marker:i}}async listPolicyVersions(e){let t=await this.request("ListPolicyVersions",e),r=this.parsePolicyVersions(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Versions:r,IsTruncated:a,Marker:i}}async createPolicyVersion(e){let t=await this.request("CreatePolicyVersion",e);return{VersionId:s(t,"VersionId")||"",IsDefaultVersion:s(t,"IsDefaultVersion")==="true",CreateDate:s(t,"CreateDate")}}async deletePolicyVersion(e){await this.request("DeletePolicyVersion",e)}async setDefaultPolicyVersion(e){await this.request("SetDefaultPolicyVersion",e)}async deletePolicy(e){await this.request("DeletePolicy",e)}async attachUserPolicy(e){await this.request("AttachUserPolicy",e)}async detachUserPolicy(e){await this.request("DetachUserPolicy",e)}async attachGroupPolicy(e){await this.request("AttachGroupPolicy",e)}async detachGroupPolicy(e){await this.request("DetachGroupPolicy",e)}async attachRolePolicy(e){await this.request("AttachRolePolicy",e)}async detachRolePolicy(e){await this.request("DetachRolePolicy",e)}async listAttachedUserPolicies(e){let t=await this.request("ListAttachedUserPolicies",e),r=this.parseAttachedPolicies(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{AttachedPolicies:r,IsTruncated:a,Marker:i}}async listAttachedGroupPolicies(e){let t=await this.request("ListAttachedGroupPolicies",e),r=this.parseAttachedPolicies(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{AttachedPolicies:r,IsTruncated:a,Marker:i}}async listAttachedRolePolicies(e){let t=await this.request("ListAttachedRolePolicies",e),r=this.parseAttachedPolicies(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{AttachedPolicies:r,IsTruncated:a,Marker:i}}parsePolicy(e){return{PolicyName:s(e,"PolicyName")||"",PolicyId:s(e,"PolicyId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),DefaultVersionId:s(e,"DefaultVersionId"),AttachmentCount:s(e,"AttachmentCount")?Number.parseInt(s(e,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:s(e,"PermissionsBoundaryUsageCount")?Number.parseInt(s(e,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:s(e,"IsAttachable")==="true",Description:s(e,"Description"),CreateDate:s(e,"CreateDate"),UpdateDate:s(e,"UpdateDate")}}parsePolicies(e){return u(e,"Policies","member").map((r)=>({PolicyName:s(r,"PolicyName")||"",PolicyId:s(r,"PolicyId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),DefaultVersionId:s(r,"DefaultVersionId"),AttachmentCount:s(r,"AttachmentCount")?Number.parseInt(s(r,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:s(r,"PermissionsBoundaryUsageCount")?Number.parseInt(s(r,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:s(r,"IsAttachable")==="true",Description:s(r,"Description"),CreateDate:s(r,"CreateDate"),UpdateDate:s(r,"UpdateDate")}))}parsePolicyVersions(e){return u(e,"Versions","member").map((r)=>({VersionId:s(r,"VersionId")||"",IsDefaultVersion:s(r,"IsDefaultVersion")==="true",CreateDate:s(r,"CreateDate")}))}parseAttachedPolicies(e){return u(e,"AttachedPolicies","member").map((r)=>({PolicyName:s(r,"PolicyName")||"",PolicyArn:s(r,"PolicyArn")||""}))}async putUserPolicy(e){await this.request("PutUserPolicy",e)}async getUserPolicy(e){let t=await this.request("GetUserPolicy",e);return{UserName:s(t,"UserName")||"",PolicyName:s(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(s(t,"PolicyDocument")||"")}}async deleteUserPolicy(e){await this.request("DeleteUserPolicy",e)}async listUserPolicies(e){let t=await this.request("ListUserPolicies",e),r=u(t,"PolicyNames","member"),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{PolicyNames:r,IsTruncated:a,Marker:i}}async putGroupPolicy(e){await this.request("PutGroupPolicy",e)}async getGroupPolicy(e){let t=await this.request("GetGroupPolicy",e);return{GroupName:s(t,"GroupName")||"",PolicyName:s(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(s(t,"PolicyDocument")||"")}}async deleteGroupPolicy(e){await this.request("DeleteGroupPolicy",e)}async listGroupPolicies(e){let t=await this.request("ListGroupPolicies",e),r=u(t,"PolicyNames","member"),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{PolicyNames:r,IsTruncated:a,Marker:i}}async putRolePolicy(e){await this.request("PutRolePolicy",e)}async getRolePolicy(e){let t=await this.request("GetRolePolicy",e);return{RoleName:s(t,"RoleName")||"",PolicyName:s(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(s(t,"PolicyDocument")||"")}}async deleteRolePolicy(e){await this.request("DeleteRolePolicy",e)}async listRolePolicies(e){let t=await this.request("ListRolePolicies",e),r=u(t,"PolicyNames","member"),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{PolicyNames:r,IsTruncated:a,Marker:i}}async createAccessKey(e={}){let t=await this.request("CreateAccessKey",e);if(typeof t==="object"){let r=t?.CreateAccessKeyResult?.AccessKey||t?.AccessKey;if(r)return{AccessKey:{UserName:r.UserName||"",AccessKeyId:r.AccessKeyId||"",Status:r.Status||"Active",SecretAccessKey:r.SecretAccessKey||"",CreateDate:r.CreateDate}}}return{AccessKey:{UserName:s(t,"UserName")||"",AccessKeyId:s(t,"AccessKeyId")||"",Status:s(t,"Status")||"Active",SecretAccessKey:s(t,"SecretAccessKey")||"",CreateDate:s(t,"CreateDate")}}}async listAccessKeys(e={}){let t=await this.request("ListAccessKeys",e),r=this.parseAccessKeys(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{AccessKeyMetadata:r,IsTruncated:a,Marker:i}}async updateAccessKey(e){await this.request("UpdateAccessKey",e)}async deleteAccessKey(e){await this.request("DeleteAccessKey",e)}async getAccessKeyLastUsed(e){let t=await this.request("GetAccessKeyLastUsed",e);return{UserName:s(t,"UserName")||"",AccessKeyLastUsed:{LastUsedDate:s(t,"LastUsedDate"),ServiceName:s(t,"ServiceName"),Region:s(t,"Region")}}}parseAccessKeys(e){return u(e,"AccessKeyMetadata","member").map((r)=>({UserName:s(r,"UserName"),AccessKeyId:s(r,"AccessKeyId")||"",Status:s(r,"Status")||"Active",CreateDate:s(r,"CreateDate")}))}async createInstanceProfile(e){let t=await this.request("CreateInstanceProfile",e);return this.parseInstanceProfile(t)}async getInstanceProfile(e){let t=await this.request("GetInstanceProfile",e);return this.parseInstanceProfile(t)}async listInstanceProfiles(e={}){let t=await this.request("ListInstanceProfiles",e),r=this.parseInstanceProfiles(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{InstanceProfiles:r,IsTruncated:a,Marker:i}}async listInstanceProfilesForRole(e){let t=await this.request("ListInstanceProfilesForRole",e),r=this.parseInstanceProfiles(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{InstanceProfiles:r,IsTruncated:a,Marker:i}}async addRoleToInstanceProfile(e){await this.request("AddRoleToInstanceProfile",e)}async removeRoleFromInstanceProfile(e){await this.request("RemoveRoleFromInstanceProfile",e)}async deleteInstanceProfile(e){await this.request("DeleteInstanceProfile",e)}parseInstanceProfile(e){return{InstanceProfileName:s(e,"InstanceProfileName")||"",InstanceProfileId:s(e,"InstanceProfileId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),CreateDate:s(e,"CreateDate")}}parseInstanceProfiles(e){return u(e,"InstanceProfiles","member").map((r)=>({InstanceProfileName:s(r,"InstanceProfileName")||"",InstanceProfileId:s(r,"InstanceProfileId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),CreateDate:s(r,"CreateDate")}))}async getAccountPasswordPolicy(){let e=await this.request("GetAccountPasswordPolicy");return{MinimumPasswordLength:s(e,"MinimumPasswordLength")?Number.parseInt(s(e,"MinimumPasswordLength"),10):void 0,RequireSymbols:s(e,"RequireSymbols")==="true",RequireNumbers:s(e,"RequireNumbers")==="true",RequireUppercaseCharacters:s(e,"RequireUppercaseCharacters")==="true",RequireLowercaseCharacters:s(e,"RequireLowercaseCharacters")==="true",AllowUsersToChangePassword:s(e,"AllowUsersToChangePassword")==="true",ExpirePasswords:s(e,"ExpirePasswords")==="true",MaxPasswordAge:s(e,"MaxPasswordAge")?Number.parseInt(s(e,"MaxPasswordAge"),10):void 0,PasswordReusePrevention:s(e,"PasswordReusePrevention")?Number.parseInt(s(e,"PasswordReusePrevention"),10):void 0,HardExpiry:s(e,"HardExpiry")==="true"}}async updateAccountPasswordPolicy(e){await this.request("UpdateAccountPasswordPolicy",e)}async deleteAccountPasswordPolicy(){await this.request("DeleteAccountPasswordPolicy")}async getAccountSummary(){let e=await this.request("GetAccountSummary"),t={},r=u(e,"SummaryMap","entry");for(let a of r){let i=s(a,"key"),c=s(a,"value");if(i&&c)t[i]=Number.parseInt(c,10)}return t}async listAccountAliases(){let e=await this.request("ListAccountAliases"),t=u(e,"AccountAliases","member"),r=s(e,"IsTruncated")==="true",a=s(e,"Marker");return{AccountAliases:t,IsTruncated:r,Marker:a}}async createAccountAlias(e){await this.request("CreateAccountAlias",e)}async deleteAccountAlias(e){await this.request("DeleteAccountAlias",e)}async simulatePrincipalPolicy(e){let t=await this.request("SimulatePrincipalPolicy",e);return this.parseSimulationResults(t)}parseSimulationResults(e){let r=u(e,"EvaluationResults","member").map((c)=>{let d=u(c,"MatchedStatements","member").map((m)=>({SourcePolicyId:s(m,"SourcePolicyId"),SourcePolicyType:s(m,"SourcePolicyType")}));return{EvalActionName:s(c,"EvalActionName")||"",EvalResourceName:s(c,"EvalResourceName"),EvalDecision:s(c,"EvalDecision")||"",MatchedStatements:d.length>0?d:void 0}}),a=s(e,"IsTruncated")==="true",i=s(e,"Marker");return{EvaluationResults:r,IsTruncated:a,Marker:i}}}class gt{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new n(t)}async createEmailIdentity(e){return await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/identities",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async getEmailIdentity(e){let t=await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/identities/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}});return{IdentityType:t.IdentityType,IdentityName:e,SendingEnabled:t.VerifiedForSendingStatus,VerificationStatus:t.VerificationStatus,DkimAttributes:t.DkimAttributes,MailFromAttributes:t.MailFromAttributes}}async putEmailIdentityMailFromAttributes(e,t){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(e)}/mail-from`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async listEmailIdentities(e){let t="/v2/email/identities",r=[];if(e?.PageSize)r.push(`PageSize=${e.PageSize}`);if(e?.NextToken)r.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(r.length>0)t+=`?${r.join("&")}`;let a=await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}});return{EmailIdentities:a.EmailIdentities,NextToken:a.NextToken}}async deleteEmailIdentity(e){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/identities/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async putEmailIdentityDkimAttributes(e){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(e.EmailIdentity)}/dkim`,headers:{"Content-Type":"application/json"},body:JSON.stringify({SigningEnabled:e.SigningEnabled})})}async sendEmail(e){return{MessageId:(await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/outbound-emails",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).MessageId}}async sendBulkEmail(e){return{BulkEmailEntryResults:(await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/outbound-bulk-emails",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).BulkEmailEntryResults}}async createEmailTemplate(e){await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/templates",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async getEmailTemplate(e){return await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/templates/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async deleteEmailTemplate(e){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/templates/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async listEmailTemplates(e){let t="/v2/email/templates",r=[];if(e?.PageSize)r.push(`PageSize=${e.PageSize}`);if(e?.NextToken)r.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(r.length>0)t+=`?${r.join("&")}`;return await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}})}async getSendStatistics(){let e=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendStatistics&Version=2010-12-01"}),t=f(e,"GetSendStatistics")?.SendDataPoints?.member;return{SendDataPoints:t==null?[]:Array.isArray(t)?t:[t]}}async getSendQuota(){let e=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendQuota&Version=2010-12-01"}),t=f(e,"GetSendQuota"),r=(a)=>a==null||a===""?void 0:Number(a);return{Max24HourSend:r(t?.Max24HourSend),MaxSendRate:r(t?.MaxSendRate),SentLast24Hours:r(t?.SentLast24Hours)}}async verifyDomain(e){let t=await this.createEmailIdentity({EmailIdentity:e});return{dkimTokens:t.DkimAttributes?.Tokens,verificationStatus:t.DkimAttributes?.Status}}async sendSimpleEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],r=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0,a={};if(e.text)a.Text={Data:e.text};if(e.html)a.Html={Data:e.html};return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Simple:{Subject:{Data:e.subject},Body:a}},ReplyToAddresses:r})}async sendTemplatedEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],r=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0;return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Template:{TemplateName:e.templateName,TemplateData:JSON.stringify(e.templateData)}},ReplyToAddresses:r})}async getDkimRecords(e){let t=await this.getEmailIdentity(e);if(!t.DkimAttributes?.Tokens)return[];return t.DkimAttributes.Tokens.map((r)=>({name:`${r}._domainkey.${e}`,type:"CNAME",value:`${r}.dkim.amazonses.com`}))}async isDomainVerified(e){try{let t=await this.getEmailIdentity(e);return t.VerificationStatus==="SUCCESS"&&t.SendingEnabled===!0}catch{return!1}}async waitForDomainVerification(e,t=60,r=30000){for(let a=0;a<t;a++){if(await this.isDomainVerified(e))return!0;await new Promise((c)=>setTimeout(c,r))}return!1}buildFormBody(e){return Object.entries(e).filter(([,r])=>r!==void 0).map(([r,a])=>`${encodeURIComponent(r)}=${encodeURIComponent(a)}`).join("&")}async createReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"CreateReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async deleteReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async setActiveReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"SetActiveReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async listReceiptRuleSets(e){let t={Action:"ListReceiptRuleSets",Version:"2010-12-01"};if(e)t.NextToken=e;let r=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)}),a=r?.ListReceiptRuleSetsResponse?.ListReceiptRuleSetsResult||r?.ListReceiptRuleSetsResult,i=a?.RuleSets?.member;return{RuleSets:Array.isArray(i)?i:i?[i]:[],NextToken:a?.NextToken}}async describeReceiptRuleSet(e){let t=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DescribeReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})}),r=t?.DescribeReceiptRuleSetResponse?.DescribeReceiptRuleSetResult||t?.DescribeReceiptRuleSetResult,a=r?.Rules?.member;return{Metadata:r?.Metadata,Rules:Array.isArray(a)?a:a?[a]:[]}}async createReceiptRule(e){let t={Action:"CreateReceiptRule",Version:"2010-12-01",RuleSetName:e.RuleSetName,"Rule.Name":e.Rule.Name,"Rule.Enabled":e.Rule.Enabled!==!1?"true":"false"};if(e.Rule.TlsPolicy)t["Rule.TlsPolicy"]=e.Rule.TlsPolicy;if(e.Rule.ScanEnabled!==void 0)t["Rule.ScanEnabled"]=e.Rule.ScanEnabled?"true":"false";if(e.After)t.After=e.After;if(e.Rule.Recipients)e.Rule.Recipients.forEach((r,a)=>{t[`Rule.Recipients.member.${a+1}`]=r});e.Rule.Actions.forEach((r,a)=>{let i=a+1;if(r.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=r.S3Action.BucketName,r.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=r.S3Action.ObjectKeyPrefix;if(r.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=r.S3Action.KmsKeyArn}if(r.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=r.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=r.LambdaAction.InvocationType||"Event";if(r.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=r.SNSAction.TopicArn,r.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=r.SNSAction.Encoding}if(r.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=r.StopAction.Scope,r.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=r.StopAction.TopicArn}}),await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)})}async deleteReceiptRule(e,t){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteReceiptRule",Version:"2010-12-01",RuleSetName:e,RuleName:t})})}async receiptRuleSetExists(e){try{return await this.describeReceiptRuleSet(e),!0}catch(t){if(t.code==="RuleSetDoesNotExist"||t.statusCode===400)return!1;throw t}}async getActiveReceiptRuleSet(){let e=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DescribeActiveReceiptRuleSet",Version:"2010-12-01"})}),t=e?.DescribeActiveReceiptRuleSetResponse?.DescribeActiveReceiptRuleSetResult||e?.DescribeActiveReceiptRuleSetResult;if(!t?.Metadata)return null;let r=t?.Rules?.member;return{Metadata:t?.Metadata,Rules:Array.isArray(r)?r:r?[r]:[]}}async updateReceiptRule(e){let t={Action:"UpdateReceiptRule",Version:"2010-12-01",RuleSetName:e.RuleSetName,"Rule.Name":e.Rule.Name};if(e.Rule.Enabled!==void 0)t["Rule.Enabled"]=e.Rule.Enabled?"true":"false";if(e.Rule.TlsPolicy)t["Rule.TlsPolicy"]=e.Rule.TlsPolicy;if(e.Rule.ScanEnabled!==void 0)t["Rule.ScanEnabled"]=e.Rule.ScanEnabled?"true":"false";if(e.Rule.Recipients)e.Rule.Recipients.forEach((r,a)=>{t[`Rule.Recipients.member.${a+1}`]=r});e.Rule.Actions.forEach((r,a)=>{let i=a+1;if(r.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=r.S3Action.BucketName,r.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=r.S3Action.ObjectKeyPrefix;if(r.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=r.S3Action.KmsKeyArn}if(r.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=r.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=r.LambdaAction.InvocationType||"Event";if(r.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=r.SNSAction.TopicArn,r.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=r.SNSAction.Encoding}if(r.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=r.StopAction.Scope,r.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=r.StopAction.TopicArn}}),await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)})}async sendRawEmail(e){let t=Buffer.from(e.rawMessage).toString("base64"),r={Action:"SendRawEmail",Version:"2010-12-01",Source:e.source,"RawMessage.Data":t};e.destinations.forEach((c,l)=>{r[`Destinations.member.${l+1}`]=c});let a=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(r)});return{MessageId:(a?.SendRawEmailResponse?.SendRawEmailResult||a?.SendRawEmailResult)?.MessageId}}async getSuppressedDestination(e){try{return(await this.client.request({service:"ses",region:this.region,method:"GET",path:`/v2/email/suppression/addresses/${encodeURIComponent(e)}`}))?.SuppressedDestination||null}catch(t){if(t.message?.includes("404")||t.message?.includes("NotFoundException"))return null;throw t}}async deleteSuppressedDestination(e){await this.client.request({service:"ses",region:this.region,method:"DELETE",path:`/v2/email/suppression/addresses/${encodeURIComponent(e)}`})}}class Vn{ses;s3;iam;route53;region;domain;defaultFrom;constructor(e={}){this.region=e.region||"us-east-1",this.domain=e.domain,this.defaultFrom=e.defaultFrom,this.ses=new gt(this.region),this.s3=new o(this.region),this.iam=new Re(this.region),this.route53=new I(this.region)}async send(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required. Set defaultFrom in constructor or provide from in options.");let r=e.fromName?`${e.fromName} <${t}>`:t,a=Array.isArray(e.to)?e.to:[e.to];if(!e.attachments||e.attachments.length===0)return{messageId:(await this.ses.sendSimpleEmail({from:r,to:a,subject:e.subject,text:e.text,html:e.html,replyTo:e.replyTo})).MessageId||""};let i=this.buildRawEmail(e,r,a);return{messageId:(await this.ses.sendEmail({FromEmailAddress:r,Destination:{ToAddresses:a,CcAddresses:e.cc?Array.isArray(e.cc)?e.cc:[e.cc]:void 0,BccAddresses:e.bcc?Array.isArray(e.bcc)?e.bcc:[e.bcc]:void 0},Content:{Raw:{Data:Buffer.from(i).toString("base64")}}})).MessageId||""}}async sendTemplate(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required");let r=e.fromName?`${e.fromName} <${t}>`:t;return{messageId:(await this.ses.sendTemplatedEmail({from:r,to:e.to,templateName:e.templateName,templateData:e.templateData,replyTo:e.replyTo})).MessageId||""}}async sendBulk(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required");let r=e.recipients.map((i)=>({Destination:{ToAddresses:Array.isArray(i.to)?i.to:[i.to]},ReplacementEmailContent:i.templateData?{ReplacementTemplate:{ReplacementTemplateData:JSON.stringify(i.templateData)}}:void 0}));return{results:(await this.ses.sendBulkEmail({FromEmailAddress:t,BulkEmailEntries:r,DefaultContent:{Template:{TemplateName:e.templateName,TemplateData:JSON.stringify(e.defaultTemplateData)}}})).BulkEmailEntryResults?.map((i)=>({status:i.Status||"UNKNOWN",messageId:i.MessageId,error:i.Error}))||[]}}async setupDomain(e){let t;try{t=await this.ses.getEmailIdentity(e)}catch{let a=await this.ses.createEmailIdentity({EmailIdentity:e});t={VerificationStatus:a.DkimAttributes?.Status,DkimAttributes:a.DkimAttributes,SendingEnabled:a.VerifiedForSendingStatus}}try{await this.ses.putEmailIdentityDkimAttributes({EmailIdentity:e,SigningEnabled:!0})}catch{}try{await this.ses.putEmailIdentityMailFromAttributes(e,{MailFromDomain:`mail.${e}`,BehaviorOnMxFailure:"USE_DEFAULT_VALUE"})}catch{}let r=await this.ses.getDkimRecords(e);return{domainVerified:t.SendingEnabled===!0,dkimStatus:t.DkimAttributes?.Status||"UNKNOWN",dkimTokens:t.DkimAttributes?.Tokens,mailFromStatus:t.MailFromAttributes?.MailFromDomainStatus}}async getDnsRecords(e){let t=[],r=await this.ses.getDkimRecords(e);for(let a of r)t.push({type:a.type,name:a.name,value:a.value,ttl:1800});return t.push({type:"MX",name:e,value:`inbound-smtp.${this.region}.amazonaws.com`,priority:10,ttl:3600}),t.push({type:"MX",name:`mail.${e}`,value:`feedback-smtp.${this.region}.amazonses.com`,priority:10,ttl:3600}),t.push({type:"TXT",name:`mail.${e}`,value:"v=spf1 include:amazonses.com ~all",ttl:3600}),t.push({type:"TXT",name:`_dmarc.${e}`,value:`v=DMARC1;p=quarantine;pct=25;rua=mailto:dmarcreports@${e}`,ttl:3600}),t}async isDomainReady(e){try{let t=await this.ses.getEmailIdentity(e);return t.SendingEnabled===!0&&t.DkimAttributes?.Status==="SUCCESS"}catch{return!1}}async setupReceiving(e){let t={Version:"2012-10-17",Statement:[{Sid:"AllowSESPuts",Effect:"Allow",Principal:{Service:"ses.amazonaws.com"},Action:"s3:PutObject",Resource:`arn:aws:s3:::${e.bucketName}/*`,Condition:{StringEquals:{"AWS:SourceAccount":e.accountId}}}]};await this.s3.putBucketPolicy(e.bucketName,t);try{await this.ses.createReceiptRuleSet(e.ruleSetName)}catch(a){if(!a.message?.includes("already exists")&&a.code!=="AlreadyExists")throw a}let r=[{S3Action:{BucketName:e.bucketName,ObjectKeyPrefix:e.prefix||"inbox/"}}];if(e.lambdaArn)r.push({LambdaAction:{FunctionArn:e.lambdaArn,InvocationType:"Event"}});try{await this.ses.createReceiptRule({RuleSetName:e.ruleSetName,Rule:{Name:e.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:e.recipients||[e.domain],ScanEnabled:e.scanEnabled!==!1,Actions:r}})}catch(a){if(a.message?.includes("already exists"))await this.ses.deleteReceiptRule(e.ruleSetName,e.ruleName),await this.ses.createReceiptRule({RuleSetName:e.ruleSetName,Rule:{Name:e.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:e.recipients||[e.domain],ScanEnabled:e.scanEnabled!==!1,Actions:r}});else throw a}await this.ses.setActiveReceiptRuleSet(e.ruleSetName)}async getIncomingEmails(e){return(await this.s3.list({bucket:e.bucket,prefix:e.prefix||"incoming/",maxKeys:e.maxResults||100})).map((r)=>({key:r.Key||"",lastModified:r.LastModified||"",size:r.Size||0}))}async readEmail(e){return await this.s3.getObject(e.bucket,e.key)}async createSmtpCredentials(e){let t=`ses-smtp-${e.username.replace(/[^a-zA-Z0-9]/g,"-")}`,{AWSClient:r}=await import("./chunk-5yrabpmr.js"),a=new r,i=(p,y)=>{let P={Action:p,Version:"2010-05-08",...y};return Object.entries(P).map(([A,h])=>`${encodeURIComponent(A)}=${encodeURIComponent(h)}`).join("&")};try{await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateUser",{UserName:t})})}catch(p){if(!p.message?.includes("EntityAlreadyExists"))throw p}let c={Version:"2012-10-17",Statement:[{Effect:"Allow",Action:"ses:SendRawEmail",Resource:"*",Condition:{StringLike:{"ses:FromAddress":`*@${e.domain}`}}}]},l=`ses-smtp-policy-${e.domain.replace(/\./g,"-")}`;try{await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("PutUserPolicy",{UserName:t,PolicyName:l,PolicyDocument:JSON.stringify(c)})})}catch{}let m=(await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateAccessKey",{UserName:t})}))?.CreateAccessKeyResult?.AccessKey;if(!m?.AccessKeyId||!m?.SecretAccessKey)throw Error("Failed to create access key");let g=this.deriveSmtpPassword(m.SecretAccessKey);return{username:m.AccessKeyId,password:g,server:`email-smtp.${this.region}.amazonaws.com`,port:587}}deriveSmtpPassword(e){let t=nt("node:crypto"),r="SendRawEmail",a=Buffer.from([4]),i=t.createHmac("sha256",`AWS4${e}`).update("11111111").digest();return i=t.createHmac("sha256",i).update(this.region).digest(),i=t.createHmac("sha256",i).update("ses").digest(),i=t.createHmac("sha256",i).update("aws4_request").digest(),i=t.createHmac("sha256",i).update("SendRawEmail").digest(),Buffer.concat([a,i]).toString("base64")}async createTemplate(e){await this.ses.createEmailTemplate({TemplateName:e.name,TemplateContent:{Subject:e.subject,Text:e.text,Html:e.html}})}async getTemplate(e){try{let t=await this.ses.getEmailTemplate(e);return{name:t.TemplateName||e,subject:t.TemplateContent?.Subject,text:t.TemplateContent?.Text,html:t.TemplateContent?.Html}}catch{return null}}async deleteTemplate(e){await this.ses.deleteEmailTemplate(e)}async listTemplates(){return(await this.ses.listEmailTemplates()).TemplatesMetadata?.map((t)=>({name:t.TemplateName||"",createdAt:t.CreatedTimestamp}))||[]}async deploy(e){let t=`${e.appName}-${e.environment}-email-rules`,r=`${e.appName}-inbound-email`,a=e.storage?.bucketName||`${e.appName}-${e.environment}-email`,i=await this.setupDomain(e.domain);if(!(await this.s3.listBuckets()).Buckets?.some((m)=>m.Name===a))await this.s3.createBucket(a);await this.setupReceiving({domain:e.domain,ruleSetName:t,ruleName:r,bucketName:a,prefix:e.storage?.prefix||"inbox/",accountId:e.accountId,recipients:e.catchAll?[e.domain]:e.mailboxes,scanEnabled:!0});let d=await this.getDnsRecords(e.domain);return{success:!0,domainVerified:i.domainVerified,dkimStatus:i.dkimStatus,receiptRuleSet:t,storageBucket:a,dnsRecords:d}}async undeploy(e){let t=`${e.appName}-${e.environment}-email-rules`,r=`${e.appName}-inbound-email`,a=`${e.appName}-${e.environment}-email`;try{await this.ses.deleteReceiptRule(t,r)}catch{}try{await this.ses.deleteReceiptRuleSet(t)}catch{}if(e.deleteBucket)try{await this.s3.emptyAndDeleteBucket(a)}catch{}}async getSendingStats(){let e=await this.ses.getSendQuota();return{sentLast24Hours:e.SentLast24Hours||0,maxSendRate:e.MaxSendRate||0,max24HourSend:e.Max24HourSend||0}}buildRawEmail(e,t,r){let a=`----=_Part_${Date.now()}_${Math.random().toString(36).substring(2)}`,i="";if(i+=`From: ${t}\r
2
2
  `,i+=`To: ${r.join(", ")}\r
3
3
  `,e.cc){let c=Array.isArray(e.cc)?e.cc:[e.cc];i+=`Cc: ${c.join(", ")}\r
4
4
  `}if(i+=`Subject: ${e.subject}\r
@@ -30,5 +30,5 @@ import{St,n}from"./chunk-ca191b00.js";import{o}from"./chunk-j99nkav5.js";import{
30
30
  `,i+=`\r
31
31
  `,i+=`${c.content}\r
32
32
  `;return i+=`--${a}--\r
33
- `,i}}var Ch=new Gn;
34
- export{Re,gt,Gn,Ch};
33
+ `,i}}var kh=new Vn;
34
+ export{Re,gt,Vn,kh};
@@ -1,2 +1,2 @@
1
- import{n}from"./chunk-ca191b00.js";import{I}from"./chunk-jtvw9d4x.js";var pt=new Set(["A","AAAA","CNAME"]);function V(e,t=""){return e===408||e===409||e===425||e===429||e>=500||/rate limit|temporar|timed? ?out|try again/i.test(t)}async function b(e,t){let r=t?.headers.get("retry-after"),s=r===null||r===void 0?void 0:Number(r)*1000,i=Number.isFinite(s)?Math.max(0,s):Math.min(1000*2**(e-1),30000);await new Promise((o)=>setTimeout(o,i))}class he{name="porkbun";apiKey;secretKey;requestTimeoutMs;constructor(e,t,r=15000){this.apiKey=e,this.secretKey=t,this.requestTimeoutMs=r}async request(e,t={}){let r;for(let s=1;s<=8;s+=1){let i,o=new AbortController,a=setTimeout(()=>{o.abort(Error(`Porkbun API request timed out after ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);try{i=await fetch(`https://api.porkbun.com/api/json/v3${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apikey:this.apiKey,secretapikey:this.secretKey,...t}),signal:o.signal})}catch(d){if(r=d,s===8)throw d;await b(s);continue}finally{clearTimeout(a)}if(!i.ok){let d=await i.clone().json().then((u)=>u?.message).catch(()=>{return});if(r=Error(`Porkbun API error: ${i.status} ${i.statusText}${d?`: ${d}`:""}`),!V(i.status)||s===8)throw r;await b(s,i);continue}let c=await i.json();if(c.status==="ERROR"){if(r=Error(`Porkbun API error: ${c.message||"Unknown error"}`),!V(0,c.message)||s===8)throw r;await b(s,i);continue}return c}throw r}getSubdomain(e,t){let r=e.replace(/\.$/,""),s=t.replace(/\.$/,"");if(r===s)return"";if(r.endsWith(`.${s}`))return r.slice(0,-(s.length+1));return r}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}static ADDRESS_TYPES=new Set(["A","AAAA"]);async clearConflictingAliases(e,t){if(!he.ADDRESS_TYPES.has(t.type))return[];let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),i=await this.listRecords(e);if(!i.success)return[`could not list records to clear ALIAS/CNAME conflicts: ${i.message??"unknown provider error"}`];let o=[];for(let a of i.records){if(a.type!=="ALIAS"&&a.type!=="CNAME")continue;if(this.getSubdomain(a.name,r)!==s)continue;let c=await this.deleteRecord(e,a);if(!c.success)o.push(`could not remove conflicting ${a.type} on ${a.name}: ${c.message??"unknown provider error"}`)}return o}async addressRecordExists(e,t){let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),i=await this.listRecords(e);if(!i.success)return!0;return i.records.some((o)=>o.type===t.type&&this.getSubdomain(o.name,r)===s&&o.content===t.content)}async createRecord(e,t){try{let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),i={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(s)i.name=s;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)i.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)i.content=`${t.weight} ${t.port} ${t.content}`;let o=await this.clearConflictingAliases(e,t),a=await this.request(`/dns/create/${r}`,i);if(he.ADDRESS_TYPES.has(t.type)&&!await this.addressRecordExists(e,t))return{success:!1,message:`Porkbun reported success but no ${t.type} record for ${t.name} exists${o.length>0?` (${o.join("; ")})`:""}. A conflicting ALIAS/CNAME on the same name silently voids the write.`};return{success:!0,id:a.id?.toString(),message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),i=await this.listRecords(e);if(i.success){let o=i.records.find((a)=>this.getSubdomain(a.name,r)===s&&a.type===t.type);if(o?.id&&o.content===t.content&&(t.ttl===void 0||o.ttl===t.ttl)&&(t.type!=="MX"&&t.type!=="SRV"||t.priority===void 0||o.priority===t.priority))return{success:!0,id:o.id,message:"Record already up to date"};if(o?.id){let a={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(s)a.name=s;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)a.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)a.content=`${t.weight} ${t.port} ${t.content}`;return await this.request(`/dns/edit/${r}/${o.id}`,a),{success:!0,id:o.id,message:"Record updated successfully"}}}return this.createRecord(e,t)}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=this.getRootDomain(e);if("id"in t&&t.id)return await this.request(`/dns/delete/${r}/${t.id}`),{success:!0,message:"Record deleted successfully"};let s=this.getSubdomain(t.name,r),i=await this.listRecords(e);if(!i.success)return{success:!1,message:"Failed to list records"};let o=i.records.find((a)=>this.getSubdomain(a.name,r)===s&&a.type===t.type&&a.content===t.content);if(!o?.id)return{success:!1,message:"Record not found"};return await this.request(`/dns/delete/${r}/${o.id}`),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=this.getRootDomain(e),s=`/dns/retrieve/${r}`;if(t)s=`/dns/retrieveByNameType/${r}/${t}`;return{success:!0,records:((await this.request(s)).records||[]).map((a)=>({id:a.id,name:a.name||r,type:a.type,content:a.content,ttl:Number.parseInt(a.ttl,10),priority:a.prio?Number.parseInt(a.prio,10):void 0}))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{let t=this.getRootDomain(e);return await this.request(`/dns/retrieve/${t}`),!0}catch{return!1}}async listDomains(){try{return((await this.request("/domain/listAll")).domains||[]).map((t)=>t.domain)}catch{return[]}}async getNameServers(e){try{let t=this.getRootDomain(e);return(await this.request(`/domain/getNs/${t}`)).ns||[]}catch{return[]}}async updateNameServers(e,t){try{let r=this.getRootDomain(e);return await this.request(`/domain/updateNs/${r}`,{ns:t}),!0}catch{return!1}}}class Ge{name="godaddy";apiKey;apiSecret;baseUrl;constructor(e,t="",r="production"){this.apiKey=e,this.apiSecret=t,this.baseUrl=r==="ote"?"https://api.ote-godaddy.com":"https://api.godaddy.com"}authorization(){if(!this.apiSecret||this.apiKey.startsWith("gd_pat_"))return`Bearer ${this.apiKey}`;return`sso-key ${this.apiKey}:${this.apiSecret}`}async request(e,t,r){let s=`${this.baseUrl}${t}`,i={Authorization:this.authorization(),"Content-Type":"application/json",Accept:"application/json"},o={method:e,headers:i};if(r)o.body=JSON.stringify(r);let a=await fetch(s,o);if(a.status===204)return{};if(a.ok){let d=await a.text();if(d)return JSON.parse(d);return{}}let c=`GoDaddy API error: ${a.status} ${a.statusText}`;try{let d=await a.json();if(d.message)c=`GoDaddy API error: ${d.message}`;if(d.fields)c+=` - Fields: ${JSON.stringify(d.fields)}`}catch{}throw Error(c)}getSubdomain(e,t){let r=e.replace(/\.$/,""),s=t.replace(/\.$/,"");if(r===s)return"@";if(r.endsWith(`.${s}`))return r.slice(0,-(s.length+1));return r}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}toGoDaddyRecord(e,t){let r=this.getRootDomain(t),s=this.getSubdomain(e.name,r),i={type:e.type,name:s,data:e.content,ttl:e.ttl||600};if(e.type==="MX"&&e.priority!==void 0)i.priority=e.priority;return i}fromGoDaddyRecord(e,t){let r=this.getRootDomain(t),s=e.name;if(s==="@")s=r;else if(!s.endsWith(r))s=`${s}.${r}`;return{name:s,type:e.type,content:e.data,ttl:e.ttl,priority:e.priority}}async createRecord(e,t){try{let r=this.getRootDomain(e),s=this.toGoDaddyRecord(t,e);return await this.request("PATCH",`/v1/domains/${r}/records`,[s]),{success:!0,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=this.getRootDomain(e),s=this.toGoDaddyRecord(t,e);return await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${s.name}`,[s]),{success:!0,message:"Record upserted successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),i=await this.request("GET",`/v1/domains/${r}/records/${t.type}/${s}`),o=i.filter((a)=>a.data!==t.content);if(o.length===i.length)return{success:!1,message:"Record not found"};if(o.length===0)try{await this.request("DELETE",`/v1/domains/${r}/records/${t.type}/${s}`)}catch{}else await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${s}`,o);return{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=this.getRootDomain(e),s=`/v1/domains/${r}/records`;if(t)s=`/v1/domains/${r}/records/${t}`;return{success:!0,records:(await this.request("GET",s)).map((o)=>this.fromGoDaddyRecord(o,e))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{let t=this.getRootDomain(e);return await this.request("GET",`/v1/domains/${t}`),!0}catch{return!1}}async listDomains(){try{return(await this.request("GET","/v1/domains")).map((t)=>t.domain)}catch{return[]}}async getDomainDetails(e){try{let t=this.getRootDomain(e),r=await this.request("GET",`/v1/domains/${t}`);return{domain:r.domain,status:r.status,nameServers:r.nameServers,expires:r.expires}}catch{return null}}async getNameServers(e){return(await this.getDomainDetails(e))?.nameServers??[]}async updateNameServers(e,t){try{let r=this.getRootDomain(e);return await this.request("PATCH",`/v1/domains/${r}`,{nameServers:t}),!0}catch{return!1}}async checkDomainAvailability(e){try{let t=await this.request("GET",`/v1/domains/available?domain=${encodeURIComponent(e)}`);return{available:t.available,price:t.price,currency:t.currency}}catch{return{available:!1}}}}var yg=["js","mjs","cjs","css","map","woff","woff2","ttf","otf","eot","png","jpg","jpeg","gif","webp","avif","svg","ico","mp4","webm","ogg","mp3","wav","pdf","wasm"],U=[{name:"x-stx-router",value:"true"}];function C(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function Z(e){return`{${e.map(C).join(" ")}}`}function j(e){let t=`http.request.headers[${C(e.name.toLowerCase())}]`;return e.value===void 0?`len(${t}) > 0`:`any(${t}[*] == ${C(e.value)})`}function Ht(e){if(e.length===1)return`http.host eq ${C(e[0])}`;return`http.host in ${Z(e)}`}function Ic(e,t={}){if(t.enabled===!1||e.length===0)return[];let r=Ht(e),s=[],o=(t.bypassPaths??[]).map((v)=>`starts_with(http.request.uri.path, ${C(v)})`),c=(t.negotiatedRequestHeaders??U).map(j),d=[...o,...c],u=d.length>0?`(${d.join(" or ")})`:void 0;if(u)s.push({action:"set_cache_settings",description:"bypass cache",expression:`(${r} and ${u})`,enabled:!0,action_parameters:{cache:!1}});let g=u?`${r} and not ${u}`:r,m=t.assetExtensions??yg,p=m.length>0?`lower(http.request.uri.path.extension) in ${Z([...m])}`:void 0;if(p)s.push({action:"set_cache_settings",description:"cache fingerprinted assets",expression:`(${g} and ${p})`,enabled:!0,action_parameters:{cache:!0,edge_ttl:{mode:"override_origin",default:t.assetEdgeTtl??2592000},browser_ttl:{mode:"override_origin",default:t.assetBrowserTtl??31536000}}});let y=p?`(${g} and not ${p})`:`(${g})`;if(t.documentEdgeTtl===0)return s.push({action:"set_cache_settings",description:"bypass documents",expression:y,enabled:!0,action_parameters:{cache:!1}}),s;return s.push({action:"set_cache_settings",description:"cache documents",expression:y,enabled:!0,action_parameters:{cache:!0,edge_ttl:{mode:"override_origin",default:t.documentEdgeTtl??3600},browser_ttl:{mode:"override_origin",default:t.documentBrowserTtl??0}}}),s}function bc(e,t,r){if(e.length===0||!t||!r)return[];return[{action:"rewrite",description:"origin guard header",expression:`(${Ht(e)})`,enabled:!0,action_parameters:{headers:{[t]:{operation:"set",value:r}}}}]}var F="https://api.cloudflare.com/client/v4",Gt="[ts-cloud]";class H{name="cloudflare";apiToken;zoneCache=new Map;configuredZoneId;accountId;configuredZoneName;constructor(e,t={}){this.apiToken=e,this.configuredZoneId=t.zoneId,this.accountId=t.accountId}async request(e,t,r){let s=`${F}${t}`,i={Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},o={method:e,headers:i};if(r)o.body=JSON.stringify(r);let c=await(await fetch(s,o)).json();if(!c.success){let d=c.errors.map((u)=>u.message).join(", ");throw Error(`Cloudflare API error: ${d}`)}return c}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}async resolveZone(e){let t=e.replace(/\.$/,"").toLowerCase();if(this.configuredZoneId){let a=await this.resolveConfiguredZoneName();if(a&&(t===a||t.endsWith(`.${a}`)))return{id:this.configuredZoneId,name:a}}let r=this.getRootDomain(t),s=this.zoneCache.get(r);if(s)return{id:s,name:r};let i=await this.request("GET",`/zones?name=${encodeURIComponent(r)}`);if(!i.result||i.result.length===0)throw Error(`Zone not found for domain: ${r}. `+"If the API token is scoped to a single zone, set its zone id (CLOUDFLARE_ZONE_ID) — "+"zone lookup by name needs account-wide Zone:Read.");let o=i.result[0].id;return this.zoneCache.set(r,o),{id:o,name:i.result[0].name||r}}async resolveConfiguredZoneName(){if(!this.configuredZoneId)return;if(this.configuredZoneName)return this.configuredZoneName;try{let t=(await this.request("GET",`/zones/${this.configuredZoneId}`)).result?.name?.toLowerCase();if(!t)return;return this.configuredZoneName=t,this.zoneCache.set(t,this.configuredZoneId),t}catch{return}}async getZoneId(e){return(await this.resolveZone(e)).id}getFullRecordName(e,t){let r=e.replace(/\.$/,"");if(!r||r===t||r==="@")return t;if(r.endsWith(`.${t}`))return r;return`${r}.${t}`}toCloudflareRecord(e,t,r){let s={type:e.type,name:this.getFullRecordName(e.name,t),content:e.content||e.value||"",ttl:e.ttl||1},i=r??e.proxied;if(i!==void 0&&pt.has(e.type)){if(s.proxied=i,i)s.ttl=1}if(e.type==="MX"&&e.priority!==void 0)s.priority=e.priority;if(e.type==="SRV"){let o=W(e);if(o)s.data=o,delete s.content,delete s.priority;else if(e.priority!==void 0)s.priority=e.priority}return s}fromCloudflareRecord(e){return{id:e.id,name:e.name,type:e.type,content:e.content,ttl:e.ttl,priority:e.priority,proxied:e.proxied}}async createRecord(e,t){try{let r=await this.resolveZone(e),s=this.toCloudflareRecord(t,r.name);return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,s)).result.id,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=await this.resolveZone(e),s=this.getFullRecordName(t.name,r.name),o=(await this.request("GET",`/zones/${r.id}/dns_records?type=${t.type}&name=${encodeURIComponent(s)}`)).result?.[0],a=t.proxied??o?.proxied,c=this.toCloudflareRecord(t,r.name,a);if(o)return{success:!0,id:(await this.request("PUT",`/zones/${r.id}/dns_records/${o.id}`,c)).result.id,message:"Record updated successfully"};return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,c)).result.id,message:"Record created successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=await this.resolveZone(e),s=r.id,i=this.getFullRecordName(t.name,r.name),o=await this.request("GET",`/zones/${s}/dns_records?type=${t.type}&name=${encodeURIComponent(i)}`);if(!o.result||o.result.length===0)return{success:!1,message:"Record not found"};let a=o.result.find((c)=>c.content===t.content);if(!a)return{success:!1,message:"Record with matching content not found"};return await this.request("DELETE",`/zones/${s}/dns_records/${a.id}`),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let s=`/zones/${await this.getZoneId(e)}/dns_records?per_page=100`;if(t)s+=`&type=${t}`;let i=[],o=1,a=!0;while(a){let c=await this.request("GET",`${s}&page=${o}`);if(i.push(...c.result||[]),c.result_info)a=o<c.result_info.total_pages,o++;else a=!1}return{success:!0,records:i.map((c)=>this.fromCloudflareRecord(c))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{return await this.getZoneId(e),!0}catch{return!1}}async listDomains(){try{let e=[],t=1,r=!0;while(r){let s=await this.request("GET",`/zones?per_page=50&page=${t}`);if(e.push(...s.result||[]),s.result_info)r=t<s.result_info.total_pages,t++;else r=!1}return e.map((s)=>s.name)}catch{return[]}}async createZone(e,t={}){let r=e.replace(/\.$/,"").toLowerCase(),s=t.accountId??this.accountId;if(!s)throw Error(`Cannot create zone ${r}: no Cloudflare account id. Set CLOUDFLARE_ACCOUNT_ID, or pass accountId.`);let i=await this.getZoneDetails(r);if(i)return{...i,created:!1};try{let a=(await this.request("POST","/zones",{name:r,account:{id:s},jump_start:t.jumpStart??!1})).result;return this.zoneCache.set(a.name,a.id),{id:a.id,name:a.name,status:a.status,nameServers:a.name_servers??[],created:!0}}catch(o){let a=o instanceof Error?o.message:String(o);if(!/already exists|1061/i.test(a))throw o;let c=await this.getZoneDetails(r);if(!c)throw o;return{...c,created:!1}}}async getZoneDetails(e){try{let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}`);return{id:r.result.id,name:r.result.name,status:r.result.status,nameServers:r.result.name_servers,paused:r.result.paused}}catch{return null}}async listEdgeCertificateHosts(e){try{let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/ssl/certificate_packs?per_page=50`),s=new Set;for(let i of r.result||[]){if(i.status!=="active")continue;for(let o of i.hosts||[])s.add(o.toLowerCase())}return[...s]}catch{return null}}async purgeCache(e,t){try{let r=await this.getZoneId(e),s={};if(t?.purgeEverything)s.purge_everything=!0;else{if(t?.files)s.files=t.files;if(t?.tags)s.tags=t.tags;if(t?.hosts)s.hosts=t.hosts}if(Object.keys(s).length===0)s.purge_everything=!0;return await this.request("POST",`/zones/${r}/purge_cache`,s),!0}catch{return!1}}async getRecordProxyStatus(e,t){try{let r=await this.resolveZone(e),s=r.id,i=this.getFullRecordName(t.name,r.name),o=await this.request("GET",`/zones/${s}/dns_records?type=${t.type}&name=${encodeURIComponent(i)}`);if(o.result&&o.result.length>0)return o.result.find((c)=>c.content===t.content)?.proxied??null;return null}catch{return null}}async setRecordProxyStatus(e,t,r){try{let s=await this.resolveZone(e),i=s.id,o=this.getFullRecordName(t.name,s.name),a=await this.request("GET",`/zones/${i}/dns_records?type=${t.type}&name=${encodeURIComponent(o)}`);if(!a.result||a.result.length===0)return!1;let c=a.result.find((d)=>d.content===t.content);if(!c)return!1;return await this.request("PATCH",`/zones/${i}/dns_records/${c.id}`,{proxied:r}),!0}catch{return!1}}async zoneIdFor(e){return this.getZoneId(e)}get account(){return this.accountId}async getZoneSettings(e){let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/settings`),s={};for(let i of r.result||[])s[i.id]=i.value;return s}async applyZoneSettings(e,t){let r=await this.getZoneId(e),s=await this.getZoneSettings(e).catch(()=>({})),i=[],o=[];for(let[a,c]of Object.entries(t)){if(c===void 0)continue;let d=s[a];if(d!==void 0&&x(d,c))continue;try{await this.request("PATCH",`/zones/${r}/settings/${a}`,{value:c}),i.push({id:a,from:d,to:c})}catch(u){o.push({id:a,error:u instanceof Error?u.message:String(u)})}}return{changed:i,failed:o}}async getManagedRequestHeaders(e){let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/managed_headers`),s={};for(let i of r.result?.managed_request_headers||[])s[i.id]=i.enabled===!0;return s}async applyTieredCache(e,t){let r=[],s=[],i=await this.getZoneId(e),o=[["tiered_caching",`/zones/${i}/argo/tiered_caching`,t==="off"?"off":"on"],["tiered_cache_smart_topology_enable",`/zones/${i}/cache/tiered_cache_smart_topology_enable`,t==="smart"?"on":"off"]];if(t==="off")o.reverse();for(let[a,c,d]of o)try{let g=(await this.request("GET",c)).result?.value;if(g===d)continue;await this.request("PATCH",c,{value:d}),r.push({id:a,from:g,to:d})}catch(u){s.push({id:a,error:u instanceof Error?u.message:String(u)})}return{changed:r,failed:s}}async applyManagedRequestHeaders(e,t){let r=[],s=[],i=Object.entries(t).filter(([,d])=>d!==void 0);if(i.length===0)return{changed:r,failed:s};let o=await this.getZoneId(e),a;try{a=await this.getManagedRequestHeaders(e)}catch(d){let u=d instanceof Error?d.message:String(d);for(let[g]of i)s.push({id:g,error:`could not read managed headers — ${u}`});return{changed:r,failed:s}}let c=[];for(let[d,u]of i){if(!(d in a)){s.push({id:d,error:"not a managed request header transform on this zone"});continue}if(a[d]!==u)c.push([d,u])}if(c.length===0)return{changed:r,failed:s};try{await this.request("PATCH",`/zones/${o}/managed_headers`,{managed_request_headers:c.map(([d,u])=>({id:d,enabled:u})),managed_response_headers:[]});for(let[d,u]of c)r.push({id:d,from:a[d],to:u})}catch(d){let u=d instanceof Error?d.message:String(d);for(let[g]of c)s.push({id:g,error:u})}return{changed:r,failed:s}}async getPhaseRules(e,t){let r=await this.getZoneId(e);try{return(await this.request("GET",`/zones/${r}/rulesets/phases/${t}/entrypoint`)).result?.rules||[]}catch{return[]}}async putManagedPhaseRules(e,t,r){try{let s=await this.getZoneId(e),i=await this.getPhaseRules(e,t),o=r.map((d)=>({...d,description:d.description?.startsWith(Gt)?d.description:`${Gt} ${d.description||t}`})),c=K(i,o).map(({id:d,...u})=>u);return await this.request("PUT",`/zones/${s}/rulesets/phases/${t}/entrypoint`,{rules:c}),{success:!0}}catch(s){return{success:!1,message:s instanceof Error?s.message:String(s)}}}}var E=/http\.host (?:eq "[^"]+"|in \{[^}]*\})/;function Vn(e){return E.test(e)?e.replace(E,"\x00hosts\x00"):null}function O(e,t){return e.replace(E,Ht(t))}function P(e){if(Array.isArray(e))return`[${e.map(P).join(",")}]`;if(e&&typeof e==="object")return`{${Object.entries(e).filter(([,r])=>r!==void 0).sort(([r],[s])=>r.localeCompare(s)).map(([r,s])=>`${JSON.stringify(r)}:${P(s)}`).join(",")}}`;return JSON.stringify(e)}function G(e,t){let r=Vn(e.expression);return r!==null&&r===Vn(t.expression)&&e.action===t.action&&e.description===t.description&&(e.enabled??!0)===(t.enabled??!0)&&P(e.action_parameters)===P(t.action_parameters)}function K(e,t){let r=new Set(t.flatMap((o)=>Vt(o.expression))),s=(o)=>(o.description||"").startsWith(Gt),i=[];for(let o of e){if(!s(o)){i.push(o);continue}let a=Vt(o.expression);if(a.length===0){if(r.size>0)i.push(o);continue}let c=a.filter((d)=>!r.has(d));if(c.length===a.length)i.push(o);else if(c.length>0)i.push({...o,expression:O(o.expression,c)})}for(let o of t){let a=Vt(o.expression),c=a.length>0?i.findIndex((g)=>s(g)&&G(g,o)):-1;if(c===-1){i.push(o);continue}let d=i[c],u=[...new Set([...Vt(d.expression),...a])];i[c]={...d,expression:O(d.expression,u)}}return i}function Vt(e){let t=[];for(let r of e.matchAll(/http\.host eq "([^"]+)"/g))t.push(r[1]);for(let r of e.matchAll(/http\.host in \{([^}]*)\}/g))for(let s of r[1].matchAll(/"([^"]+)"/g))t.push(s[1]);return t}function x(e,t){if(e===t)return!0;if(typeof e!==typeof t||e===null||t===null)return!1;if(typeof e!=="object")return!1;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;return e.every((i,o)=>x(i,t[o]))}let r=e,s=t;return Object.keys(s).every((i)=>x(r[i],s[i]))}function W(e){let t=(e.content||e.value||"").trim();if(e.weight!==void 0&&e.port!==void 0&&e.priority!==void 0&&t)return{priority:e.priority,weight:e.weight,port:e.port,target:M(t)};let r=t.split(/\s+/);if(r.length<4)return null;let[s,i,o]=r.slice(0,3).map(Number);if(![s,i,o].every(Number.isFinite))return null;return{priority:s,weight:i,port:o,target:M(r.slice(3).join(" "))}}function M(e){return e.replace(/\.$/,"")}var B=new Set(["A","AAAA","CNAME","ALIAS"]);function qt(e){let t=e.trim().replace(/^"|"$/g,"").toLowerCase();if(t.startsWith("v=spf1"))return"v=spf1";if(t.startsWith("v=dmarc1"))return"v=dmarc1";return}function R(e){return e.trim().replace(/^"(.*)"$/s,"$1")}function w(e){return e.replace(/\.$/,"").toLowerCase()}function qn(e,t){let r=w(t),s=(e??"@").trim();if(!s||s==="@")return r;let i=w(s);if(i===r||i.endsWith(`.${r}`))return i;return`${i}.${r}`}function Bs(e,t){return e.map((r)=>({...r,name:qn(r.name,t),proxied:r.proxied??!1}))}function X(e,t){if(e.type!==t.type)return!1;if(w(e.name)!==w(t.name))return!1;if(B.has(t.type))return!0;if(t.type==="TXT"){let r=qt(t.content);if(r)return qt(R(e.content))===r;return R(e.content)===R(t.content)}return R(e.content)===R(t.content)}function Y(e,t){if(R(e.content)!==R(t.content))return!1;if(t.priority!==void 0&&e.priority!==t.priority)return!1;if(t.proxied!==void 0&&e.proxied!==void 0&&e.proxied!==t.proxied)return!1;return!0}async function xs(e){let{provider:t,zone:r,records:s}=e,i={outcomes:[],warnings:[]};if(s.length===0)return i;let o=await t.listRecords(r);if(!o.success)return i.warnings.push(`could not list ${r}: ${o.message||"unknown provider error"} — records not reconciled`),i;let a=o.records;for(let c of s){let d=a.filter((p)=>X(p,c));if(d.length>0&&d.every((p)=>Y(p,c))){i.outcomes.push({record:c,action:"unchanged"});continue}let u={name:c.name,type:c.type,content:c.content,ttl:c.ttl??3600,...c.priority!==void 0?{priority:c.priority}:{},...c.proxied!==void 0?{proxied:c.proxied}:{}},g=c.type==="TXT"&&qt(c.content)!==void 0;if(g)for(let p of d){let y=await t.deleteRecord(r,{name:p.name,type:p.type,content:p.content});if(!y.success)i.warnings.push(`could not remove superseded ${p.type} at ${p.name}: ${y.message||"unknown error"}`)}let m=g||d.length===0?await t.createRecord(r,u):await t.upsertRecord(r,u);if(m.success)i.outcomes.push({record:c,action:d.length>0?"updated":"created"});else i.outcomes.push({record:c,action:"failed",message:m.message})}for(let c of["MX"]){let d=new Set(s.filter((u)=>u.type===c).map((u)=>w(u.name)));for(let u of d){let g=new Set(s.filter((p)=>p.type===c&&w(p.name)===u).map((p)=>R(p.content).toLowerCase())),m=a.filter((p)=>p.type===c&&w(p.name)===u&&!g.has(R(p.content).toLowerCase()));for(let p of m)i.warnings.push(`${u} has an undeclared ${c} record (${p.content}) alongside the declared one — mail will be split between them. Remove it at the provider if it is stale.`)}}return i}function Tr(e){if(!e||typeof e!=="object")return!1;let t=e;return typeof t.getNameServers==="function"&&typeof t.updateNameServers==="function"}function wr(e){return Boolean(e&&typeof e.createZone==="function")}var J=new Set(["NS"]);function D(e){return e.replace(/\.$/,"").toLowerCase()}function jn(e,t){if(e.length===0||t.length===0)return!1;let r=new Set(e.map(D)),s=new Set(t.map(D));if(r.size!==s.size)return!1;for(let i of r)if(!s.has(i))return!1;return!0}function Q(e){let t=e.content.trim(),r=t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t;return e.type==="TXT"?r:D(r)}var ee=new Set(["MX","SRV"]),te=new Set(["A","AAAA","CNAME"]);function S(e){let t=ee.has(e.type)&&e.priority!==void 0&&e.priority!==null?String(Number(e.priority)):"";return`${e.type}|${D(e.name)}|${Q(e)}|${t}`}function re(e,t){return S(e)===S(t)}async function Rr(e){let{domain:t,registrar:r,host:s,dryRun:i=!1}=e,o=new Set([...e.proxiedHosts??[]].map(D)),a=[],c=await s.createZone(t,{accountId:e.accountId,jumpStart:!1}),d=await r.getNameServers(t),u={status:"ready",domain:t,zoneId:c.id,targetNameservers:c.nameServers,currentNameservers:d,records:[],missing:[],warnings:a};if(jn(d,c.nameServers))return u.status="already-delegated",u;if(c.nameServers.length===0)return a.push(`${s.name} did not report nameservers for ${t}; cannot delegate.`),u.status="blocked",u;let g=await r.listRecords(t);if(!g.success)return a.push(`Could not read ${t} from ${r.name}: ${g.message??"unknown error"}`),u.status="blocked",u;let m=[];for(let l of g.records){if(J.has(l.type)){u.records.push({record:l,status:"skipped",reason:`${l.type} describes the delegation itself; ${s.name} owns it`});continue}let f=pt.has(l.type)&&o.has(D(l.name));m.push({name:l.name,type:l.type,content:l.content,ttl:l.ttl,priority:l.priority,...pt.has(l.type)?{proxied:f}:{}})}if(i){for(let l of m)u.records.push({record:l,status:"copied",reason:"dry run"});return u}let p=new Map;for(let l of m){let f=`${l.type}|${D(l.name)}`;p.set(f,(p.get(f)??0)+1)}let y=new Set;try{let l=await s.listRecords(t);for(let f of l.records??[])y.add(S(f))}catch{}for(let l of m){let f=te.has(l.type)&&p.get(`${l.type}|${D(l.name)}`)===1;if(!f&&y.has(S(l))){u.records.push({record:l,status:"present"});continue}let A;try{A=f?await s.upsertRecord(t,l):await s.createRecord(t,l)}catch(N){A={success:!1,message:N instanceof Error?N.message:String(N)}}if(A.success)y.add(S(l));u.records.push(A.success?{record:l,status:"copied"}:{record:l,status:"failed",reason:A.message})}let v=await s.listRecords(t);if(!v.success)return a.push(`Could not read back ${t} from ${s.name}: ${v.message??"unknown error"}`),u.status="blocked",u;for(let l of m)if(!v.records.some((f)=>re(l,f)))u.missing.push(l);if(u.missing.length>0)return a.push(`${u.missing.length} record(s) did not arrive at ${s.name}; leaving ${r.name}'s nameservers alone. Delegating now would take the domain off a complete zone and onto an incomplete one.`),u.status="blocked",u;if(!await r.updateNameServers(t,c.nameServers))return a.push(`${r.name} refused the nameserver update for ${t}.`),u.status="blocked",u;return u.status="delegated",u}var ne={add_visitor_location_headers:"visitorLocationHeaders"};function z(e){return{porkbunApiKey:e.PORKBUN_API_KEY,porkbunSecretKey:e.PORKBUN_SECRET_KEY,godaddyApiKey:e.GODADDY_API_KEY,godaddyApiSecret:e.GODADDY_API_SECRET,cloudflareApiToken:e.CLOUDFLARE_API_TOKEN,cloudflareAccountId:e.CLOUDFLARE_ACCOUNT_ID}}function se(e,t){if(e==="porkbun"){if(!t.porkbunApiKey||!t.porkbunSecretKey)return"PORKBUN_API_KEY / PORKBUN_SECRET_KEY are not set";return new he(t.porkbunApiKey,t.porkbunSecretKey)}if(!t.godaddyApiKey||!t.godaddyApiSecret)return"GODADDY_API_KEY / GODADDY_API_SECRET are not set";let r=new Ge(t.godaddyApiKey,t.godaddyApiSecret);if(!Tr(r))return"the GoDaddy provider cannot change nameservers";return r}async function Os(e,t={}){let r=e.registrar;if(!r)return{status:"skipped",reason:"no dns.registrar configured"};if(r.delegate===!1)return{status:"skipped",reason:"dns.registrar.delegate is false"};if(!e.domain)return{status:"skipped",reason:"no dns.domain configured"};if(!e.provider||e.provider===r.provider)return{status:"skipped",reason:`dns.provider is already ${r.provider}`};if(e.provider!=="cloudflare")return{status:"skipped",reason:`delegation to ${e.provider} is not supported yet`};let s=t.credentials??z(t.env??process.env);if(!s.cloudflareApiToken)return{status:"skipped",reason:"CLOUDFLARE_API_TOKEN is not set"};let i=se(r.provider,s);if(typeof i==="string")return{status:"skipped",reason:i};let o=new H(s.cloudflareApiToken,{accountId:s.cloudflareAccountId});if(!wr(o))return{status:"skipped",reason:"the Cloudflare provider cannot create zones"};return Rr({domain:e.domain,registrar:i,host:o,proxiedHosts:r.proxied,accountId:s.cloudflareAccountId,dryRun:r.dryRun})}function _s(e){if(e.status==="skipped")return[`dns: delegation skipped — ${e.reason}`];let t=[];switch(e.status){case"already-delegated":t.push(`dns: ${e.domain} already delegated to ${e.targetNameservers.join(", ")}`);break;case"delegated":t.push(`dns: ${e.domain} delegated to ${e.targetNameservers.join(", ")} (${e.records.filter((r)=>r.status==="copied").length} record(s) copied)`),t.push("dns: nameserver changes take up to 24h to propagate; the old zone answers until then");break;case"ready":t.push(`dns: ${e.domain} would delegate to ${e.targetNameservers.join(", ")} (dry run)`);break;case"blocked":t.push(`dns: ${e.domain} NOT delegated — nameservers left at ${e.currentNameservers.join(", ")}`);for(let r of e.missing)t.push(` missing at destination: ${r.type} ${r.name}`);break}for(let r of e.warnings)t.push(` ${r}`);return t}function oe(e){let t={};if(e.ssl!==void 0)t.ssl=e.ssl;if(e.alwaysUseHttps!==void 0)t.always_use_https=e.alwaysUseHttps?"on":"off";if(e.minTlsVersion!==void 0)t.min_tls_version=e.minTlsVersion;return t}function ae(e){let t={};for(let[r,s]of Object.entries(ne)){let i=e[s];if(typeof i==="boolean")t[r]=i}return t}async function Ls(e,t={}){if(!e.zone)return{status:"skipped",reason:"no dns.zone configured"};if(!e.domain)return{status:"skipped",reason:"no dns.domain configured"};if(e.provider!=="cloudflare")return{status:"skipped",reason:`zone settings are not supported for ${e.provider??"this provider"}`};let r=oe(e.zone),s=ae(e.zone);if(Object.keys(r).length===0&&Object.keys(s).length===0&&!e.zone.tieredCache)return{status:"skipped",reason:"dns.zone declares no settings"};let i=t.credentials??z(t.env??process.env);if(!i.cloudflareApiToken)return{status:"skipped",reason:"CLOUDFLARE_API_TOKEN is not set"};let o=new H(i.cloudflareApiToken,{accountId:i.cloudflareAccountId}),a=await o.applyZoneSettings(e.domain,r),c=Object.keys(s).length>0?await o.applyManagedRequestHeaders(e.domain,s):{changed:[],failed:[]},d=e.zone.tieredCache?await o.applyTieredCache(e.domain,e.zone.tieredCache):{changed:[],failed:[]},u=[...a.changed,...c.changed,...d.changed],g=[...a.failed,...c.failed,...d.failed];return{status:u.length>0?"applied":"unchanged",domain:e.domain,changed:u,failed:g}}function $s(e){if(e.status==="skipped")return[`dns: zone settings skipped — ${e.reason}`];let t=[];for(let r of e.changed)t.push(`dns: ${e.domain} ${r.id}: ${String(r.from)} → ${String(r.to)}`);if(e.status==="unchanged"&&e.failed.length===0)t.push(`dns: ${e.domain} zone settings already as declared`);for(let r of e.failed)t.push(`dns: ${e.domain} could not set ${r.id} — ${r.error}`);return t}class ie{name="route53";client;hostedZoneCache=new Map;providedHostedZoneId;constructor(e="us-east-1",t){this.client=new I(e),this.providedHostedZoneId=t}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}async getHostedZoneId(e){if(this.providedHostedZoneId)return this.providedHostedZoneId;let t=this.getRootDomain(e),r=this.hostedZoneCache.get(t);if(r)return r;let s=await this.client.findHostedZoneForDomain(e);if(s){let i=s.Id.replace("/hostedzone/","");return this.hostedZoneCache.set(t,i),i}return null}normalizeName(e,t){let r=e.replace(/\.$/,""),s=t.replace(/\.$/,"");if(!s||s==="@")return`${r}.`;if(s===r||s.endsWith(`.${r}`))return`${s}.`;return`${s}.${r}.`}formatValue(e){let t=e.content;if(e.type==="TXT"&&!t.startsWith('"'))t=ce(t);if(e.type==="MX"&&e.priority!==void 0)t=`${e.priority} ${t}`;return t}sameValue(e,t,r){return e==="TXT"?_(t)===_(r):t===r}async currentSet(e,t,r){let i=(await this.client.listResourceRecordSets({HostedZoneId:e,StartRecordName:t,StartRecordType:r,MaxItems:"1"})).ResourceRecordSets?.[0];if(!i||i.Name.toLowerCase()!==t.toLowerCase()||i.Type!==r||i.AliasTarget||i.SetIdentifier)return null;return{ttl:i.TTL??300,values:(i.ResourceRecords??[]).map((o)=>o.Value)}}async createRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let s=this.normalizeName(e,t.name),i=this.formatValue(t),o=await this.currentSet(r,s,t.type);if(o?.values.some((d)=>this.sameValue(t.type,d,i)))return{success:!0,message:"Record already present"};let a=[...o?.values??[],i];return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Created by ts-cloud DNS provider",Changes:[{Action:o?"UPSERT":"CREATE",ResourceRecordSet:{Name:s,Type:t.type,TTL:o?.ttl??t.ttl??300,ResourceRecords:a.map((d)=>({Value:d}))}}]}})).ChangeInfo?.Id,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let s=this.normalizeName(e,t.name),i=this.formatValue(t);return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Upserted by ts-cloud DNS provider",Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:s,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:i}]}}]}})).ChangeInfo?.Id,message:"Record upserted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async deleteRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let s=this.normalizeName(e,t.name),i=this.formatValue(t),o=await this.currentSet(r,s,t.type);if(!o||!o.values.some((c)=>this.sameValue(t.type,c,i)))return{success:!0,message:"Record already absent"};let a=o.values.filter((c)=>!this.sameValue(t.type,c,i));return await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Deleted by ts-cloud DNS provider",Changes:[{Action:a.length>0?"UPSERT":"DELETE",ResourceRecordSet:{Name:s,Type:t.type,TTL:o.ttl,ResourceRecords:(a.length>0?a:o.values).map((c)=>({Value:c}))}}]}}),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,records:[],message:`No hosted zone found for domain: ${e}`};let s=await this.client.listResourceRecordSets({HostedZoneId:r,StartRecordType:t}),i=[];for(let o of s.ResourceRecordSets){if(t&&o.Type!==t)continue;if(o.AliasTarget)continue;for(let a of o.ResourceRecords||[]){let c=a.Value,d;if(o.Type==="MX"){let u=c.split(" ");if(u.length>=2)d=Number.parseInt(u[0],10),c=u.slice(1).join(" ")}if(o.Type==="TXT"&&c.startsWith('"'))c=_(c);i.push({name:o.Name.replace(/\.$/,""),type:o.Type,content:c,ttl:o.TTL,priority:d})}}return{success:!0,records:i}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){return await this.getHostedZoneId(e)!==null}async listDomains(){try{return(await this.client.listHostedZones()).HostedZones.map((t)=>t.Name.replace(/\.$/,""))}catch{return[]}}getRoute53Client(){return this.client}async createAliasRecord(e){try{let t=await this.getHostedZoneId(e.domain);if(!t)return{success:!1,message:`No hosted zone found for domain: ${e.domain}`};return{success:!0,id:(await this.client.createAliasRecord({HostedZoneId:t,Name:this.normalizeName(e.domain,e.name),TargetHostedZoneId:e.targetHostedZoneId,TargetDNSName:e.targetDnsName,EvaluateTargetHealth:e.evaluateTargetHealth,Type:e.type})).ChangeInfo?.Id,message:"Alias record created successfully"}}catch(t){return{success:!1,message:t instanceof Error?t.message:"Unknown error"}}}async createCloudFrontAlias(e){return this.createAliasRecord({domain:e.domain,name:e.name,targetHostedZoneId:I.CloudFrontHostedZoneId,targetDnsName:e.cloudFrontDomainName,evaluateTargetHealth:!1})}async createAlbAlias(e){let t=I.ALBHostedZoneIds[e.region];if(!t)return{success:!1,message:`Unknown region for ALB: ${e.region}`};return this.createAliasRecord({domain:e.domain,name:e.name,targetHostedZoneId:t,targetDnsName:e.albDnsName,evaluateTargetHealth:!0})}}var q=255;function ce(e){let t=[];for(let r=0;r<e.length;r+=q)t.push(e.slice(r,r+q));if(t.length===0)t.push("");return t.map((r)=>`"${r.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`).join(" ")}function _(e){if(!e.startsWith('"'))return e;let t="",r=!1;for(let s=0;s<e.length;s++){let i=e[s];if(!r){if(i==='"')r=!0;continue}if(i==="\\"&&s+1<e.length){t+=e[++s];continue}if(i==='"'){r=!1;continue}t+=i}return t}async function Ms(e,t){let r=[],s,i;for(;;){let o=await e.listResourceRecordSets({HostedZoneId:t,StartRecordName:s,StartRecordType:i,MaxItems:"100"});if(r.push(...o.ResourceRecordSets),!o.IsTruncated)break;if(s=o.NextRecordName,i=o.NextRecordType,!s)break}return r}function h(e){return e.replace(/\.$/,"").toLowerCase()}function L(e){return e.replace(/\.$/,"")}function T(e){if(e.type==="SRV"&&e.weight!==void 0&&e.port!==void 0)return`${e.weight} ${e.port} ${L(e.content)}`;return L(e.content)}function de(e){let t=e.match(/"(?:[^"\\]|\\.)*"/g);if(!t)return e;return t.map((r)=>r.slice(1,-1).replace(/\\(.)/g,"$1")).join("")}function Fs(e,t){let r=h(t),s=[],i=[],o=[],a=new Set;for(let c of e){let d=h(c.Name),u=c.Type;if(u==="SOA"||u==="NS"&&d===r){i.push({name:d,type:u,reason:"owned by the destination provider"});continue}if(c.SetIdentifier){i.push({name:d,type:u,reason:`routing policy record (SetIdentifier=${c.SetIdentifier}) has no equivalent — recreate by hand`}),o.push(`${u} ${d} is part of a Route53 routing policy and was NOT migrated`);continue}if(c.AliasTarget){if(a.has(d))continue;a.add(d);let g=h(c.AliasTarget.DNSName);if(s.push({name:d,type:"CNAME",content:g,ttl:300,translatedFrom:`${u} ALIAS → ${g}`}),c.AliasTarget.EvaluateTargetHealth)o.push(`${d} was an ALIAS with health evaluation enabled; the CNAME that replaces it has no health check`);continue}for(let g of c.ResourceRecords||[]){let m=ue(d,u,g.Value,c.TTL);if("reason"in m){i.push({name:d,type:u,reason:m.reason}),o.push(`${u} ${d}: ${m.reason}`);continue}s.push(m)}}return{zone:r,records:s,skipped:i,warnings:o}}function ue(e,t,r,s){let i={name:e,ttl:s};switch(t){case"A":case"AAAA":case"CNAME":case"PTR":return{...i,type:t==="PTR"?"CNAME":t,content:h(r)};case"TXT":return{...i,type:"TXT",content:de(r)};case"MX":{let[o,...a]=r.trim().split(/\s+/);if(!a.length)return{reason:`malformed MX value "${r}"`};return{...i,type:"MX",content:h(a.join(" ")),priority:Number(o)}}case"SRV":{let o=r.trim().split(/\s+/);if(o.length<4)return{reason:`malformed SRV value "${r}"`};let[a,c,d]=o.slice(0,3).map(Number);return{...i,type:"SRV",content:h(o.slice(3).join(" ")),priority:a,weight:c,port:d}}case"NS":return{...i,type:"NS",content:h(r)};case"CAA":return{...i,type:"CAA",content:r.trim()};default:return{reason:`unsupported record type ${t}`}}}var le=new Set(["TXT","MX","SRV","NS","CAA"]);async function Us(e,t){let r=[],s=[],i=new Set;try{let o=await e.listRecords(t.zone);for(let a of o.records||[])i.add(`${h(a.name)}|${a.type}|${T(a)}`)}catch{}for(let o of t.records){let a={...o,proxied:!1},c=`${h(o.name)}|${o.type}|${T(o)}`;if(!le.has(o.type)){let u=await e.upsertRecord(t.zone,a);if(u.success)r.push(o);else s.push({record:o,message:u.message||"unknown provider error"});continue}if(i.has(c)){r.push(o);continue}let d=await e.createRecord(t.zone,a);if(d.success)i.add(c),r.push(o);else s.push({record:o,message:d.message||"unknown provider error"})}return{applied:r,failed:s}}async function Qs(e,t){let r=await e.listRecords(t.zone),s=[],i=[],o=new Map;for(let a of r.records||[]){let c=`${h(a.name)}|${a.type}`,d=o.get(c)??[];d.push(T(a)),o.set(c,d)}for(let a of t.records){let c=o.get(`${h(a.name)}|${a.type}`),d=T(a);if(c?.some((u)=>u===d))s.push(a);else i.push({record:a,found:c?.join(", ")})}return{matched:s,missing:i,ok:i.length===0}}class Ae{acm;dnsProvider;constructor(e,t="us-east-1"){if(this.acm=new ye(t),"provider"in e)this.dnsProvider=k(e);else this.dnsProvider=e}getProvider(){return this.dnsProvider}async requestAndValidate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:s=!1,maxWaitMinutes:i=30}=e,{CertificateArn:o}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:r.length>0?[t,...r]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(o);let a=await this.acm.getDnsValidationRecords(o);for(let d of a){let u=await this.dnsProvider.upsertRecord(t,{name:d.recordName,type:d.recordType,content:d.recordValue,ttl:300});if(!u.success)console.warn(`Failed to create validation record for ${d.domainName}: ${u.message}`)}let c="pending";if(s)c=(await this.acm.waitForCertificateValidation(o,i*2,30000))?.Status==="ISSUED"?"issued":"failed";return{certificateArn:o,validationRecords:a.map((d)=>({domainName:d.domainName,recordName:d.recordName,recordType:d.recordType,recordValue:d.recordValue})),isNew:!0,status:c}}async createValidationRecords(e){let{certificateArn:t,domain:r}=e,s=[],i=await this.acm.getDnsValidationRecords(t);for(let o of i){let a=await this.dnsProvider.upsertRecord(r,{name:o.recordName,type:o.recordType,content:o.recordValue,ttl:300});if(!a.success)s.push(`Failed to create record for ${o.domainName}: ${a.message}`)}return{success:s.length===0,records:i.map((o)=>({domainName:o.domainName,recordName:o.recordName,recordType:o.recordType,recordValue:o.recordValue})),errors:s}}async deleteValidationRecords(e){let{certificateArn:t,domain:r}=e,s=[],i=await this.acm.getDnsValidationRecords(t);for(let o of i){let a=await this.dnsProvider.deleteRecord(r,{name:o.recordName,type:o.recordType,content:o.recordValue});if(!a.success)s.push(`Failed to delete record for ${o.domainName}: ${a.message}`)}return{success:s.length===0,errors:s}}async findOrCreateCertificate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:s=!0,maxWaitMinutes:i}=e,o=await this.acm.findCertificateByDomain(t);if(o&&o.Status==="ISSUED"){let a=o.SubjectAlternativeNames||[o.DomainName],c=a.some((u)=>u===`*.${t}`);if(r.every((u)=>a.includes(u)||c))return{certificateArn:o.CertificateArn,validationRecords:[],isNew:!1,status:"issued"};console.log("Existing certificate doesn't cover all required SANs, requesting new certificate...")}return this.requestAndValidate({domainName:t,subjectAlternativeNames:r,waitForValidation:s,maxWaitMinutes:i})}async requestCertificateWithCommonSans(e){let{domainName:t,includeWww:r=!0,includeWildcard:s=!1,additionalSans:i=[],waitForValidation:o=!1}=e,a=[];if(r)a.push(`www.${t}`);if(s)a.push(`*.${t}`);return a.push(...i),this.requestAndValidate({domainName:t,subjectAlternativeNames:a,waitForValidation:o})}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let s=await this.acm.describeCertificate({CertificateArn:e});if(s.DomainValidationOptions&&s.DomainValidationOptions.length>0&&s.DomainValidationOptions[0].ResourceRecord)return;await new Promise((i)=>setTimeout(i,2000))}throw Error("Timeout waiting for DNS validation options")}async getCertificateStatus(e){let t=await this.acm.describeCertificate({CertificateArn:e});return{status:t.Status,domainValidations:(t.DomainValidationOptions||[]).map((r)=>({domain:r.DomainName,status:r.ValidationStatus||"UNKNOWN"}))}}}function Hs(e,t,r){return new Ae({provider:"porkbun",apiKey:e,secretKey:t},r)}function Gs(e,t,r,s){return new Ae({provider:"godaddy",apiKey:e,apiSecret:t,environment:s},r)}function Vs(e,t,r){return new Ae({provider:"route53",region:e,hostedZoneId:t},r||e)}function k(e){switch(e.provider){case"route53":return new ie(e.region,e.hostedZoneId);case"porkbun":return new he(e.apiKey,e.secretKey);case"godaddy":return new Ge(e.apiKey,e.apiSecret,e.environment);case"cloudflare":return new H(e.apiToken,{zoneId:e.zoneId,accountId:e.accountId});default:throw Error(`Unknown DNS provider: ${e.provider}`)}}async function Cc(e,t){for(let r of t){let s=k(r);if(await s.canManageDomain(e))return s}return null}class zn{providers=new Map;configs=[];addConfig(e){return this.configs.push(e),this}addRoute53(e,t){return this.configs.push({provider:"route53",region:e,hostedZoneId:t}),this}addPorkbun(e,t){return this.configs.push({provider:"porkbun",apiKey:e,secretKey:t}),this}addGoDaddy(e,t,r){return this.configs.push({provider:"godaddy",apiKey:e,apiSecret:t,environment:r}),this}addCloudflare(e,t={}){return this.configs.push({provider:"cloudflare",apiToken:e,zoneId:t.zoneId,accountId:t.accountId}),this}loadFromEnv(){if(process.env.AWS_ACCESS_KEY_ID||process.env.AWS_PROFILE||process.env.AWS_REGION)this.addRoute53(process.env.AWS_REGION);let e=process.env.PORKBUN_API_KEY,t=process.env.PORKBUN_SECRET_KEY;if(e&&t)this.addPorkbun(e,t);let r=process.env.GODADDY_API_KEY,s=process.env.GODADDY_API_SECRET;if(r&&s){let o=process.env.GODADDY_ENVIRONMENT;this.addGoDaddy(r,s,o)}let i=process.env.CLOUDFLARE_API_TOKEN;if(i)this.addCloudflare(i,{zoneId:process.env.CLOUDFLARE_ZONE_ID,accountId:process.env.CLOUDFLARE_ACCOUNT_ID});return this}getProvider(e){let t=this.providers.get(e);if(t)return t;let r=this.configs.find((i)=>i.provider===e);if(!r)return null;let s=k(r);return this.providers.set(e,s),s}async getProviderForDomain(e){for(let t of this.configs){let r=k(t);if(await r.canManageDomain(e))return r}return null}getAllProviders(){return this.configs.map((e)=>k(e))}}var Ec=new zn;class ye{client;region;constructor(e="us-east-1"){this.client=new n,this.region=e}async requestCertificate(e){let t={DomainName:e.DomainName,ValidationMethod:e.ValidationMethod||"DNS"};if(e.SubjectAlternativeNames)t.SubjectAlternativeNames=e.SubjectAlternativeNames;return{CertificateArn:(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.RequestCertificate"},body:JSON.stringify(t)})).CertificateArn||""}}async describeCertificate(e){let r=(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.DescribeCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})).Certificate||{};return{CertificateArn:r.CertificateArn||"",DomainName:r.DomainName||"",SubjectAlternativeNames:r.SubjectAlternativeNames,Status:r.Status||"PENDING_VALIDATION",Type:r.Type,DomainValidationOptions:r.DomainValidationOptions?.map((s)=>({DomainName:s.DomainName,ValidationDomain:s.ValidationDomain,ValidationStatus:s.ValidationStatus,ResourceRecord:s.ResourceRecord?{Name:s.ResourceRecord.Name,Type:s.ResourceRecord.Type,Value:s.ResourceRecord.Value}:void 0,ValidationMethod:s.ValidationMethod})),CreatedAt:r.CreatedAt,IssuedAt:r.IssuedAt,NotBefore:r.NotBefore,NotAfter:r.NotAfter}}async listCertificates(e){let t={};if(e?.CertificateStatuses)t.CertificateStatuses=e.CertificateStatuses;if(e?.MaxItems)t.MaxItems=e.MaxItems;if(e?.NextToken)t.NextToken=e.NextToken;let r=await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ListCertificates"},body:JSON.stringify(t)});return{CertificateSummaryList:(r.CertificateSummaryList||[]).map((s)=>({CertificateArn:s.CertificateArn,DomainName:s.DomainName})),NextToken:r.NextToken}}async deleteCertificate(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.DeleteCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})}async listTagsForCertificate(e){return{Tags:(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ListTagsForCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})).Tags||[]}}async addTagsToCertificate(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.AddTagsToCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn,Tags:e.Tags})})}async resendValidationEmail(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ResendValidationEmail"},body:JSON.stringify({CertificateArn:e.CertificateArn,Domain:e.Domain,ValidationDomain:e.ValidationDomain})})}async findCertificateByDomain(e){let r=(await this.listCertificates({CertificateStatuses:["ISSUED"]})).CertificateSummaryList.find((s)=>s.DomainName===e||s.DomainName===`*.${e.split(".").slice(1).join(".")}`);if(!r)return null;return this.describeCertificate({CertificateArn:r.CertificateArn})}async waitForCertificateValidation(e,t=60,r=30000){for(let s=0;s<t;s++){let i=await this.describeCertificate({CertificateArn:e});if(i.Status==="ISSUED")return i;if(i.Status==="FAILED"||i.Status==="VALIDATION_TIMED_OUT")return null;await new Promise((o)=>setTimeout(o,r))}return null}async getDnsValidationRecords(e){let t=await this.describeCertificate({CertificateArn:e});if(!t.DomainValidationOptions)return[];return t.DomainValidationOptions.filter((r)=>r.ResourceRecord&&r.ValidationMethod==="DNS").map((r)=>({domainName:r.DomainName,recordName:r.ResourceRecord.Name,recordType:r.ResourceRecord.Type,recordValue:r.ResourceRecord.Value}))}async requestCertificateWithSans(e){let t=new Set;if(t.add(e.DomainName),e.IncludeWww!==!1)t.add(`www.${e.DomainName}`);if(e.IncludeWildcard)t.add(`*.${e.DomainName}`);if(e.AdditionalSans)for(let r of e.AdditionalSans)t.add(r);return this.requestCertificate({DomainName:e.DomainName,SubjectAlternativeNames:Array.from(t),ValidationMethod:"DNS"})}async isCertificateValidForDomain(e,t){let r=await this.describeCertificate({CertificateArn:e});if(r.Status!=="ISSUED")return!1;if(r.DomainName===t)return!0;if(r.DomainName?.startsWith("*.")){let s=r.DomainName.slice(2),i=t.split("."),o=s.split(".");if(i.slice(-o.length).join(".")===s)return!0}if(r.SubjectAlternativeNames)for(let s of r.SubjectAlternativeNames){if(s===t)return!0;if(s.startsWith("*.")){let i=s.slice(2),o=t.split("."),a=i.split(".");if(o.slice(-a.length).join(".")===i)return!0}}return!1}}class Dr{acm;route53;dnsProvider;constructor(e="us-east-1",t){if(this.acm=new ye(e),this.route53=new I,t&&t.provider!=="route53")this.dnsProvider=k(t)}async requestAndValidate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:s=[],waitForValidation:i=!1,maxWaitMinutes:o=30}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let{CertificateArn:a}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:s.length>0?[t,...s]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(a);let c=await this.acm.getDnsValidationRecords(a);if(this.dnsProvider)for(let d of c){let u=await this.dnsProvider.upsertRecord(t,{name:d.recordName,type:d.recordType,content:d.recordValue,ttl:300});if(!u.success)console.warn(`Failed to create validation record for ${d.domainName}: ${u.message}`)}else if(r)for(let d of c)await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${d.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:d.recordName,Type:d.recordType,TTL:300,ResourceRecords:[{Value:d.recordValue}]}}]}});if(i){if(!await this.acm.waitForCertificateValidation(a,o*2,30000))throw Error(`Certificate validation timed out after ${o} minutes`)}return{certificateArn:a,validationRecords:c}}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let s=await this.acm.describeCertificate({CertificateArn:e});if(s.DomainValidationOptions&&s.DomainValidationOptions.length>0&&s.DomainValidationOptions[0].ResourceRecord)return;await new Promise((i)=>setTimeout(i,2000))}throw Error("Timeout waiting for DNS validation options")}async createValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:s}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let i=await this.acm.getDnsValidationRecords(t),o=[];if(this.dnsProvider){let a=s||i[0]?.domainName;for(let c of i){let d=await this.dnsProvider.upsertRecord(a,{name:c.recordName,type:c.recordType,content:c.recordValue,ttl:300});o.push({...c,changeId:d.success?d.id:void 0})}}else if(r)for(let a of i){let c=await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${a.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:a.recordName,Type:a.recordType,TTL:300,ResourceRecords:[{Value:a.recordValue}]}}]}});o.push({...a,changeId:c.ChangeInfo?.Id})}return o}async deleteValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:s}=e,i=await this.acm.getDnsValidationRecords(t);if(this.dnsProvider){let o=s||i[0]?.domainName;for(let a of i)try{await this.dnsProvider.deleteRecord(o,{name:a.recordName,type:a.recordType,content:a.recordValue})}catch{}}else if(r)for(let o of i)try{await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`Cleanup ACM DNS validation for ${o.domainName}`,Changes:[{Action:"DELETE",ResourceRecordSet:{Name:o.recordName,Type:o.recordType,TTL:300,ResourceRecords:[{Value:o.recordValue}]}}]}})}catch{}}async findOrCreateCertificate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:s,waitForValidation:i=!0}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let o=await this.acm.findCertificateByDomain(t);if(o&&o.Status==="ISSUED")return{certificateArn:o.CertificateArn,isNew:!1};let{certificateArn:a}=await this.requestAndValidate({domainName:t,hostedZoneId:r,subjectAlternativeNames:s,waitForValidation:i});return{certificateArn:a,isNew:!0}}hasExternalDnsProvider(){return this.dnsProvider!==void 0}getDnsProviderName(){return this.dnsProvider?.name||"route53"}}
2
- export{pt,he,Ge,yg,Ht,Ic,bc,Gt,H,Vn,Vt,qt,qn,Bs,xs,Tr,wr,jn,Rr,Os,_s,Ls,$s,ie,Ms,Fs,Us,Qs,Ae,Hs,Gs,Vs,k,Cc,zn,Ec,ye,Dr};
1
+ import{n}from"./chunk-e42gpavb.js";import{I}from"./chunk-y7k5872m.js";var pt=new Set(["A","AAAA","CNAME"]);function V(e,t=""){return e===408||e===409||e===425||e===429||e>=500||/rate limit|temporar|timed? ?out|try again/i.test(t)}async function E(e,t){let r=t?.headers.get("retry-after"),s=r===null||r===void 0?void 0:Number(r)*1000,i=Number.isFinite(s)?Math.max(0,s):Math.min(1000*2**(e-1),30000);await new Promise((o)=>setTimeout(o,i))}class he{name="porkbun";apiKey;secretKey;requestTimeoutMs;constructor(e,t,r=15000){this.apiKey=e,this.secretKey=t,this.requestTimeoutMs=r}async request(e,t={}){let r;for(let s=1;s<=8;s+=1){let i,o=new AbortController,a=setTimeout(()=>{o.abort(Error(`Porkbun API request timed out after ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);try{i=await fetch(`https://api.porkbun.com/api/json/v3${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apikey:this.apiKey,secretapikey:this.secretKey,...t}),signal:o.signal})}catch(d){if(r=d,s===8)throw d;await E(s);continue}finally{clearTimeout(a)}if(!i.ok){let d=await i.clone().json().then((u)=>u?.message).catch(()=>{return});if(r=Error(`Porkbun API error: ${i.status} ${i.statusText}${d?`: ${d}`:""}`),!V(i.status)||s===8)throw r;await E(s,i);continue}let c=await i.json();if(c.status==="ERROR"){if(r=Error(`Porkbun API error: ${c.message||"Unknown error"}`),!V(0,c.message)||s===8)throw r;await E(s,i);continue}return c}throw r}getSubdomain(e,t){let r=e.replace(/\.$/,""),s=t.replace(/\.$/,"");if(r===s)return"";if(r.endsWith(`.${s}`))return r.slice(0,-(s.length+1));return r}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}static ADDRESS_TYPES=new Set(["A","AAAA"]);async clearConflictingAliases(e,t){if(!he.ADDRESS_TYPES.has(t.type))return[];let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),i=await this.listRecords(e);if(!i.success)return[`could not list records to clear ALIAS/CNAME conflicts: ${i.message??"unknown provider error"}`];let o=[];for(let a of i.records){if(a.type!=="ALIAS"&&a.type!=="CNAME")continue;if(this.getSubdomain(a.name,r)!==s)continue;let c=await this.deleteRecord(e,a);if(!c.success)o.push(`could not remove conflicting ${a.type} on ${a.name}: ${c.message??"unknown provider error"}`)}return o}async addressRecordExists(e,t){let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),i=await this.listRecords(e);if(!i.success)return!0;return i.records.some((o)=>o.type===t.type&&this.getSubdomain(o.name,r)===s&&o.content===t.content)}async createRecord(e,t){try{let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),i={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(s)i.name=s;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)i.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)i.content=`${t.weight} ${t.port} ${t.content}`;let o=await this.clearConflictingAliases(e,t),a=await this.request(`/dns/create/${r}`,i);if(he.ADDRESS_TYPES.has(t.type)&&!await this.addressRecordExists(e,t))return{success:!1,message:`Porkbun reported success but no ${t.type} record for ${t.name} exists${o.length>0?` (${o.join("; ")})`:""}. A conflicting ALIAS/CNAME on the same name silently voids the write.`};return{success:!0,id:a.id?.toString(),message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),i=await this.listRecords(e);if(i.success){let o=i.records.find((a)=>this.getSubdomain(a.name,r)===s&&a.type===t.type);if(o?.id&&o.content===t.content&&(t.ttl===void 0||o.ttl===t.ttl)&&(t.type!=="MX"&&t.type!=="SRV"||t.priority===void 0||o.priority===t.priority))return{success:!0,id:o.id,message:"Record already up to date"};if(o?.id){let a={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(s)a.name=s;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)a.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)a.content=`${t.weight} ${t.port} ${t.content}`;return await this.request(`/dns/edit/${r}/${o.id}`,a),{success:!0,id:o.id,message:"Record updated successfully"}}}return this.createRecord(e,t)}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=this.getRootDomain(e);if("id"in t&&t.id)return await this.request(`/dns/delete/${r}/${t.id}`),{success:!0,message:"Record deleted successfully"};let s=this.getSubdomain(t.name,r),i=await this.listRecords(e);if(!i.success)return{success:!1,message:"Failed to list records"};let o=i.records.find((a)=>this.getSubdomain(a.name,r)===s&&a.type===t.type&&a.content===t.content);if(!o?.id)return{success:!1,message:"Record not found"};return await this.request(`/dns/delete/${r}/${o.id}`),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=this.getRootDomain(e),s=`/dns/retrieve/${r}`;if(t)s=`/dns/retrieveByNameType/${r}/${t}`;return{success:!0,records:((await this.request(s)).records||[]).map((a)=>({id:a.id,name:a.name||r,type:a.type,content:a.content,ttl:Number.parseInt(a.ttl,10),priority:a.prio?Number.parseInt(a.prio,10):void 0}))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{let t=this.getRootDomain(e);return await this.request(`/dns/retrieve/${t}`),!0}catch{return!1}}async listDomains(){try{return((await this.request("/domain/listAll")).domains||[]).map((t)=>t.domain)}catch{return[]}}async getNameServers(e){try{let t=this.getRootDomain(e);return(await this.request(`/domain/getNs/${t}`)).ns||[]}catch{return[]}}async updateNameServers(e,t){try{let r=this.getRootDomain(e);return await this.request(`/domain/updateNs/${r}`,{ns:t}),!0}catch{return!1}}}class Ge{name="godaddy";apiKey;apiSecret;baseUrl;constructor(e,t="",r="production"){this.apiKey=e,this.apiSecret=t,this.baseUrl=r==="ote"?"https://api.ote-godaddy.com":"https://api.godaddy.com"}authorization(){if(!this.apiSecret||this.apiKey.startsWith("gd_pat_"))return`Bearer ${this.apiKey}`;return`sso-key ${this.apiKey}:${this.apiSecret}`}async request(e,t,r){let s=`${this.baseUrl}${t}`,i={Authorization:this.authorization(),"Content-Type":"application/json",Accept:"application/json"},o={method:e,headers:i};if(r)o.body=JSON.stringify(r);let a=await fetch(s,o);if(a.status===204)return{};if(a.ok){let d=await a.text();if(d)return JSON.parse(d);return{}}let c=`GoDaddy API error: ${a.status} ${a.statusText}`;try{let d=await a.json();if(d.message)c=`GoDaddy API error: ${d.message}`;if(d.fields)c+=` - Fields: ${JSON.stringify(d.fields)}`}catch{}throw Error(c)}getSubdomain(e,t){let r=e.replace(/\.$/,""),s=t.replace(/\.$/,"");if(r===s)return"@";if(r.endsWith(`.${s}`))return r.slice(0,-(s.length+1));return r}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}toGoDaddyRecord(e,t){let r=this.getRootDomain(t),s=this.getSubdomain(e.name,r),i={type:e.type,name:s,data:e.content,ttl:e.ttl||600};if(e.type==="MX"&&e.priority!==void 0)i.priority=e.priority;return i}fromGoDaddyRecord(e,t){let r=this.getRootDomain(t),s=e.name;if(s==="@")s=r;else if(!s.endsWith(r))s=`${s}.${r}`;return{name:s,type:e.type,content:e.data,ttl:e.ttl,priority:e.priority}}async createRecord(e,t){try{let r=this.getRootDomain(e),s=this.toGoDaddyRecord(t,e);return await this.request("PATCH",`/v1/domains/${r}/records`,[s]),{success:!0,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=this.getRootDomain(e),s=this.toGoDaddyRecord(t,e);return await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${s.name}`,[s]),{success:!0,message:"Record upserted successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=this.getRootDomain(e),s=this.getSubdomain(t.name,r),i=await this.request("GET",`/v1/domains/${r}/records/${t.type}/${s}`),o=i.filter((a)=>a.data!==t.content);if(o.length===i.length)return{success:!1,message:"Record not found"};if(o.length===0)try{await this.request("DELETE",`/v1/domains/${r}/records/${t.type}/${s}`)}catch{}else await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${s}`,o);return{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=this.getRootDomain(e),s=`/v1/domains/${r}/records`;if(t)s=`/v1/domains/${r}/records/${t}`;return{success:!0,records:(await this.request("GET",s)).map((o)=>this.fromGoDaddyRecord(o,e))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{let t=this.getRootDomain(e);return await this.request("GET",`/v1/domains/${t}`),!0}catch{return!1}}async listDomains(){try{return(await this.request("GET","/v1/domains")).map((t)=>t.domain)}catch{return[]}}async getDomainDetails(e){try{let t=this.getRootDomain(e),r=await this.request("GET",`/v1/domains/${t}`);return{domain:r.domain,status:r.status,nameServers:r.nameServers,expires:r.expires}}catch{return null}}async getNameServers(e){return(await this.getDomainDetails(e))?.nameServers??[]}async updateNameServers(e,t){try{let r=this.getRootDomain(e);return await this.request("PATCH",`/v1/domains/${r}`,{nameServers:t}),!0}catch{return!1}}async checkDomainAvailability(e){try{let t=await this.request("GET",`/v1/domains/available?domain=${encodeURIComponent(e)}`);return{available:t.available,price:t.price,currency:t.currency}}catch{return{available:!1}}}}var Rg=["js","mjs","cjs","css","map","woff","woff2","ttf","otf","eot","png","jpg","jpeg","gif","webp","avif","svg","ico","mp4","webm","ogg","mp3","wav","pdf","wasm"],U=[{name:"x-stx-router",value:"true"}];function C(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function Z(e){return`{${e.map(C).join(" ")}}`}function j(e){let t=`http.request.headers[${C(e.name.toLowerCase())}]`;return e.value===void 0?`len(${t}) > 0`:`any(${t}[*] == ${C(e.value)})`}function Ht(e){if(e.length===1)return`http.host eq ${C(e[0])}`;return`http.host in ${Z(e)}`}function wc(e,t={}){if(t.enabled===!1||e.length===0)return[];let r=Ht(e),s=[],o=(t.bypassPaths??[]).map((v)=>`starts_with(http.request.uri.path, ${C(v)})`),c=(t.negotiatedRequestHeaders??U).map(j),d=[...o,...c],u=d.length>0?`(${d.join(" or ")})`:void 0;if(u)s.push({action:"set_cache_settings",description:"bypass cache",expression:`(${r} and ${u})`,enabled:!0,action_parameters:{cache:!1}});let g=u?`${r} and not ${u}`:r,m=t.assetExtensions??Rg,p=m.length>0?`lower(http.request.uri.path.extension) in ${Z([...m])}`:void 0;if(p)s.push({action:"set_cache_settings",description:"cache fingerprinted assets",expression:`(${g} and ${p})`,enabled:!0,action_parameters:{cache:!0,edge_ttl:{mode:"override_origin",default:t.assetEdgeTtl??2592000},browser_ttl:{mode:"override_origin",default:t.assetBrowserTtl??31536000}}});let y=p?`(${g} and not ${p})`:`(${g})`;if(t.documentEdgeTtl===0)return s.push({action:"set_cache_settings",description:"bypass documents",expression:y,enabled:!0,action_parameters:{cache:!1}}),s;return s.push({action:"set_cache_settings",description:"cache documents",expression:y,enabled:!0,action_parameters:{cache:!0,edge_ttl:{mode:"override_origin",default:t.documentEdgeTtl??3600},browser_ttl:{mode:"override_origin",default:t.documentBrowserTtl??0}}}),s}function Rc(e,t,r){if(e.length===0||!t||!r)return[];return[{action:"rewrite",description:"origin guard header",expression:`(${Ht(e)})`,enabled:!0,action_parameters:{headers:{[t]:{operation:"set",value:r}}}}]}var F="https://api.cloudflare.com/client/v4",Gt="[ts-cloud]";class H{name="cloudflare";apiToken;zoneCache=new Map;configuredZoneId;accountId;configuredZoneName;constructor(e,t={}){this.apiToken=e,this.configuredZoneId=t.zoneId,this.accountId=t.accountId}async request(e,t,r){let s=`${F}${t}`,i={Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},o={method:e,headers:i};if(r)o.body=JSON.stringify(r);let c=await(await fetch(s,o)).json();if(!c.success){let d=c.errors.map((u)=>u.message).join(", ");throw Error(`Cloudflare API error: ${d}`)}return c}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}async resolveZone(e){let t=e.replace(/\.$/,"").toLowerCase();if(this.configuredZoneId){let a=await this.resolveConfiguredZoneName();if(a&&(t===a||t.endsWith(`.${a}`)))return{id:this.configuredZoneId,name:a}}let r=this.getRootDomain(t),s=this.zoneCache.get(r);if(s)return{id:s,name:r};let i=await this.request("GET",`/zones?name=${encodeURIComponent(r)}`);if(!i.result||i.result.length===0)throw Error(`Zone not found for domain: ${r}. `+"If the API token is scoped to a single zone, set its zone id (CLOUDFLARE_ZONE_ID) — "+"zone lookup by name needs account-wide Zone:Read.");let o=i.result[0].id;return this.zoneCache.set(r,o),{id:o,name:i.result[0].name||r}}async resolveConfiguredZoneName(){if(!this.configuredZoneId)return;if(this.configuredZoneName)return this.configuredZoneName;try{let t=(await this.request("GET",`/zones/${this.configuredZoneId}`)).result?.name?.toLowerCase();if(!t)return;return this.configuredZoneName=t,this.zoneCache.set(t,this.configuredZoneId),t}catch{return}}async getZoneId(e){return(await this.resolveZone(e)).id}getFullRecordName(e,t){let r=e.replace(/\.$/,"");if(!r||r===t||r==="@")return t;if(r.endsWith(`.${t}`))return r;return`${r}.${t}`}toCloudflareRecord(e,t,r){let s={type:e.type,name:this.getFullRecordName(e.name,t),content:e.content||e.value||"",ttl:e.ttl||1},i=r??e.proxied;if(i!==void 0&&pt.has(e.type)){if(s.proxied=i,i)s.ttl=1}if(e.type==="MX"&&e.priority!==void 0)s.priority=e.priority;if(e.type==="SRV"){let o=W(e);if(o)s.data=o,delete s.content,delete s.priority;else if(e.priority!==void 0)s.priority=e.priority}return s}fromCloudflareRecord(e){return{id:e.id,name:e.name,type:e.type,content:e.content,ttl:e.ttl,priority:e.priority,proxied:e.proxied}}async createRecord(e,t){try{let r=await this.resolveZone(e),s=this.toCloudflareRecord(t,r.name);return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,s)).result.id,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=await this.resolveZone(e),s=this.getFullRecordName(t.name,r.name),o=(await this.request("GET",`/zones/${r.id}/dns_records?type=${t.type}&name=${encodeURIComponent(s)}`)).result?.[0],a=t.proxied??o?.proxied,c=this.toCloudflareRecord(t,r.name,a);if(o)return{success:!0,id:(await this.request("PUT",`/zones/${r.id}/dns_records/${o.id}`,c)).result.id,message:"Record updated successfully"};return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,c)).result.id,message:"Record created successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=await this.resolveZone(e),s=r.id,i=this.getFullRecordName(t.name,r.name),o=await this.request("GET",`/zones/${s}/dns_records?type=${t.type}&name=${encodeURIComponent(i)}`);if(!o.result||o.result.length===0)return{success:!1,message:"Record not found"};let a=o.result.find((c)=>c.content===t.content);if(!a)return{success:!1,message:"Record with matching content not found"};return await this.request("DELETE",`/zones/${s}/dns_records/${a.id}`),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let s=`/zones/${await this.getZoneId(e)}/dns_records?per_page=100`;if(t)s+=`&type=${t}`;let i=[],o=1,a=!0;while(a){let c=await this.request("GET",`${s}&page=${o}`);if(i.push(...c.result||[]),c.result_info)a=o<c.result_info.total_pages,o++;else a=!1}return{success:!0,records:i.map((c)=>this.fromCloudflareRecord(c))}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){try{return await this.getZoneId(e),!0}catch{return!1}}async listDomains(){try{let e=[],t=1,r=!0;while(r){let s=await this.request("GET",`/zones?per_page=50&page=${t}`);if(e.push(...s.result||[]),s.result_info)r=t<s.result_info.total_pages,t++;else r=!1}return e.map((s)=>s.name)}catch{return[]}}async createZone(e,t={}){let r=e.replace(/\.$/,"").toLowerCase(),s=t.accountId??this.accountId;if(!s)throw Error(`Cannot create zone ${r}: no Cloudflare account id. Set CLOUDFLARE_ACCOUNT_ID, or pass accountId.`);let i=await this.getZoneDetails(r);if(i)return{...i,created:!1};try{let a=(await this.request("POST","/zones",{name:r,account:{id:s},jump_start:t.jumpStart??!1})).result;return this.zoneCache.set(a.name,a.id),{id:a.id,name:a.name,status:a.status,nameServers:a.name_servers??[],created:!0}}catch(o){let a=o instanceof Error?o.message:String(o);if(!/already exists|1061/i.test(a))throw o;let c=await this.getZoneDetails(r);if(!c)throw o;return{...c,created:!1}}}async getZoneDetails(e){try{let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}`);return{id:r.result.id,name:r.result.name,status:r.result.status,nameServers:r.result.name_servers,paused:r.result.paused}}catch{return null}}async listEdgeCertificateHosts(e){try{let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/ssl/certificate_packs?per_page=50`),s=new Set;for(let i of r.result||[]){if(i.status!=="active")continue;for(let o of i.hosts||[])s.add(o.toLowerCase())}return[...s]}catch{return null}}async purgeCache(e,t){try{let r=await this.getZoneId(e),s={};if(t?.purgeEverything)s.purge_everything=!0;else{if(t?.files)s.files=t.files;if(t?.tags)s.tags=t.tags;if(t?.hosts)s.hosts=t.hosts}if(Object.keys(s).length===0)s.purge_everything=!0;return await this.request("POST",`/zones/${r}/purge_cache`,s),!0}catch{return!1}}async getRecordProxyStatus(e,t){try{let r=await this.resolveZone(e),s=r.id,i=this.getFullRecordName(t.name,r.name),o=await this.request("GET",`/zones/${s}/dns_records?type=${t.type}&name=${encodeURIComponent(i)}`);if(o.result&&o.result.length>0)return o.result.find((c)=>c.content===t.content)?.proxied??null;return null}catch{return null}}async setRecordProxyStatus(e,t,r){try{let s=await this.resolveZone(e),i=s.id,o=this.getFullRecordName(t.name,s.name),a=await this.request("GET",`/zones/${i}/dns_records?type=${t.type}&name=${encodeURIComponent(o)}`);if(!a.result||a.result.length===0)return!1;let c=a.result.find((d)=>d.content===t.content);if(!c)return!1;return await this.request("PATCH",`/zones/${i}/dns_records/${c.id}`,{proxied:r}),!0}catch{return!1}}async zoneIdFor(e){return this.getZoneId(e)}get account(){return this.accountId}async getZoneSettings(e){let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/settings`),s={};for(let i of r.result||[])s[i.id]=i.value;return s}async applyZoneSettings(e,t){let r=await this.getZoneId(e),s=await this.getZoneSettings(e).catch(()=>({})),i=[],o=[];for(let[a,c]of Object.entries(t)){if(c===void 0)continue;let d=s[a];if(d!==void 0&&_(d,c))continue;try{await this.request("PATCH",`/zones/${r}/settings/${a}`,{value:c}),i.push({id:a,from:d,to:c})}catch(u){o.push({id:a,error:u instanceof Error?u.message:String(u)})}}return{changed:i,failed:o}}async getManagedRequestHeaders(e){let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/managed_headers`),s={};for(let i of r.result?.managed_request_headers||[])s[i.id]=i.enabled===!0;return s}async applyTieredCache(e,t){let r=[],s=[],i=await this.getZoneId(e),o=[["tiered_caching",`/zones/${i}/argo/tiered_caching`,t==="off"?"off":"on"],["tiered_cache_smart_topology_enable",`/zones/${i}/cache/tiered_cache_smart_topology_enable`,t==="smart"?"on":"off"]];if(t==="off")o.reverse();for(let[a,c,d]of o)try{let g=(await this.request("GET",c)).result?.value;if(g===d)continue;await this.request("PATCH",c,{value:d}),r.push({id:a,from:g,to:d})}catch(u){s.push({id:a,error:u instanceof Error?u.message:String(u)})}return{changed:r,failed:s}}async applyManagedRequestHeaders(e,t){let r=[],s=[],i=Object.entries(t).filter(([,d])=>d!==void 0);if(i.length===0)return{changed:r,failed:s};let o=await this.getZoneId(e),a;try{a=await this.getManagedRequestHeaders(e)}catch(d){let u=d instanceof Error?d.message:String(d);for(let[g]of i)s.push({id:g,error:`could not read managed headers — ${u}`});return{changed:r,failed:s}}let c=[];for(let[d,u]of i){if(!(d in a)){s.push({id:d,error:"not a managed request header transform on this zone"});continue}if(a[d]!==u)c.push([d,u])}if(c.length===0)return{changed:r,failed:s};try{await this.request("PATCH",`/zones/${o}/managed_headers`,{managed_request_headers:c.map(([d,u])=>({id:d,enabled:u})),managed_response_headers:[]});for(let[d,u]of c)r.push({id:d,from:a[d],to:u})}catch(d){let u=d instanceof Error?d.message:String(d);for(let[g]of c)s.push({id:g,error:u})}return{changed:r,failed:s}}async getPhaseRules(e,t){let r=await this.getZoneId(e);try{return(await this.request("GET",`/zones/${r}/rulesets/phases/${t}/entrypoint`)).result?.rules||[]}catch{return[]}}async putManagedPhaseRules(e,t,r){try{let s=await this.getZoneId(e),i=await this.getPhaseRules(e,t),o=r.map((d)=>({...d,description:d.description?.startsWith(Gt)?d.description:`${Gt} ${d.description||t}`})),c=K(i,o).map(({id:d,...u})=>u);return await this.request("PUT",`/zones/${s}/rulesets/phases/${t}/entrypoint`,{rules:c}),{success:!0}}catch(s){return{success:!1,message:s instanceof Error?s.message:String(s)}}}}var x=/http\.host (?:eq "[^"]+"|in \{[^}]*\})/;function qn(e){return x.test(e)?e.replace(x,"\x00hosts\x00"):null}function O(e,t){return e.replace(x,Ht(t))}function P(e){if(Array.isArray(e))return`[${e.map(P).join(",")}]`;if(e&&typeof e==="object")return`{${Object.entries(e).filter(([,r])=>r!==void 0).sort(([r],[s])=>r.localeCompare(s)).map(([r,s])=>`${JSON.stringify(r)}:${P(s)}`).join(",")}}`;return JSON.stringify(e)}function G(e,t){let r=qn(e.expression);return r!==null&&r===qn(t.expression)&&e.action===t.action&&e.description===t.description&&(e.enabled??!0)===(t.enabled??!0)&&P(e.action_parameters)===P(t.action_parameters)}function K(e,t){let r=new Set(t.flatMap((o)=>Vt(o.expression))),s=(o)=>(o.description||"").startsWith(Gt),i=[];for(let o of e){if(!s(o)){i.push(o);continue}let a=Vt(o.expression);if(a.length===0){if(r.size>0)i.push(o);continue}let c=a.filter((d)=>!r.has(d));if(c.length===a.length)i.push(o);else if(c.length>0)i.push({...o,expression:O(o.expression,c)})}for(let o of t){let a=Vt(o.expression),c=a.length>0?i.findIndex((g)=>s(g)&&G(g,o)):-1;if(c===-1){i.push(o);continue}let d=i[c],u=[...new Set([...Vt(d.expression),...a])];i[c]={...d,expression:O(d.expression,u)}}return i}function Vt(e){let t=[];for(let r of e.matchAll(/http\.host eq "([^"]+)"/g))t.push(r[1]);for(let r of e.matchAll(/http\.host in \{([^}]*)\}/g))for(let s of r[1].matchAll(/"([^"]+)"/g))t.push(s[1]);return t}function _(e,t){if(e===t)return!0;if(typeof e!==typeof t||e===null||t===null)return!1;if(typeof e!=="object")return!1;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;return e.every((i,o)=>_(i,t[o]))}let r=e,s=t;return Object.keys(s).every((i)=>_(r[i],s[i]))}function W(e){let t=(e.content||e.value||"").trim();if(e.weight!==void 0&&e.port!==void 0&&e.priority!==void 0&&t)return{priority:e.priority,weight:e.weight,port:e.port,target:M(t)};let r=t.split(/\s+/);if(r.length<4)return null;let[s,i,o]=r.slice(0,3).map(Number);if(![s,i,o].every(Number.isFinite))return null;return{priority:s,weight:i,port:o,target:M(r.slice(3).join(" "))}}function M(e){return e.replace(/\.$/,"")}var B=new Set(["A","AAAA","CNAME","ALIAS"]);function qt(e){let t=e.trim().replace(/^"|"$/g,"").toLowerCase();if(t.startsWith("v=spf1"))return"v=spf1";if(t.startsWith("v=dmarc1"))return"v=dmarc1";return}function R(e){return e.trim().replace(/^"(.*)"$/s,"$1")}function w(e){return e.replace(/\.$/,"").toLowerCase()}function jn(e,t){let r=w(t),s=(e??"@").trim();if(!s||s==="@")return r;let i=w(s);if(i===r||i.endsWith(`.${r}`))return i;return`${i}.${r}`}function $s(e,t){return e.map((r)=>({...r,name:jn(r.name,t),proxied:r.proxied??!1}))}function X(e,t){if(e.type!==t.type)return!1;if(w(e.name)!==w(t.name))return!1;if(B.has(t.type))return!0;if(t.type==="TXT"){let r=qt(t.content);if(r)return qt(R(e.content))===r;return R(e.content)===R(t.content)}return R(e.content)===R(t.content)}function Y(e,t){if(R(e.content)!==R(t.content))return!1;if(t.priority!==void 0&&e.priority!==t.priority)return!1;if(t.proxied!==void 0&&e.proxied!==void 0&&e.proxied!==t.proxied)return!1;return!0}async function Ms(e){let{provider:t,zone:r,records:s}=e,i={outcomes:[],warnings:[]};if(s.length===0)return i;let o=await t.listRecords(r);if(!o.success)return i.warnings.push(`could not list ${r}: ${o.message||"unknown provider error"} — records not reconciled`),i;let a=o.records;for(let c of s){let d=a.filter((p)=>X(p,c));if(d.length>0&&d.every((p)=>Y(p,c))){i.outcomes.push({record:c,action:"unchanged"});continue}let u={name:c.name,type:c.type,content:c.content,ttl:c.ttl??3600,...c.priority!==void 0?{priority:c.priority}:{},...c.proxied!==void 0?{proxied:c.proxied}:{}},g=c.type==="TXT"&&qt(c.content)!==void 0;if(g)for(let p of d){let y=await t.deleteRecord(r,{name:p.name,type:p.type,content:p.content});if(!y.success)i.warnings.push(`could not remove superseded ${p.type} at ${p.name}: ${y.message||"unknown error"}`)}let m=g||d.length===0?await t.createRecord(r,u):await t.upsertRecord(r,u);if(m.success)i.outcomes.push({record:c,action:d.length>0?"updated":"created"});else i.outcomes.push({record:c,action:"failed",message:m.message})}for(let c of["MX"]){let d=new Set(s.filter((u)=>u.type===c).map((u)=>w(u.name)));for(let u of d){let g=new Set(s.filter((p)=>p.type===c&&w(p.name)===u).map((p)=>R(p.content).toLowerCase())),m=a.filter((p)=>p.type===c&&w(p.name)===u&&!g.has(R(p.content).toLowerCase()));for(let p of m)i.warnings.push(`${u} has an undeclared ${c} record (${p.content}) alongside the declared one — mail will be split between them. Remove it at the provider if it is stale.`)}}return i}function Tr(e){if(!e||typeof e!=="object")return!1;let t=e;return typeof t.getNameServers==="function"&&typeof t.updateNameServers==="function"}function wr(e){return Boolean(e&&typeof e.createZone==="function")}var J=new Set(["NS"]);function D(e){return e.replace(/\.$/,"").toLowerCase()}function zn(e,t){if(e.length===0||t.length===0)return!1;let r=new Set(e.map(D)),s=new Set(t.map(D));if(r.size!==s.size)return!1;for(let i of r)if(!s.has(i))return!1;return!0}function Q(e){let t=e.content.trim(),r=t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t;return e.type==="TXT"?r:D(r)}var ee=new Set(["MX","SRV"]),te=new Set(["A","AAAA","CNAME"]);function S(e){let t=ee.has(e.type)&&e.priority!==void 0&&e.priority!==null?String(Number(e.priority)):"";return`${e.type}|${D(e.name)}|${Q(e)}|${t}`}function re(e,t){return S(e)===S(t)}async function Rr(e){let{domain:t,registrar:r,host:s,dryRun:i=!1}=e,o=new Set([...e.proxiedHosts??[]].map(D)),a=[],c=await s.createZone(t,{accountId:e.accountId,jumpStart:!1}),d=await r.getNameServers(t),u={status:"ready",domain:t,zoneId:c.id,targetNameservers:c.nameServers,currentNameservers:d,records:[],missing:[],warnings:a};if(zn(d,c.nameServers))return u.status="already-delegated",u;if(c.nameServers.length===0)return a.push(`${s.name} did not report nameservers for ${t}; cannot delegate.`),u.status="blocked",u;let g=await r.listRecords(t);if(!g.success)return a.push(`Could not read ${t} from ${r.name}: ${g.message??"unknown error"}`),u.status="blocked",u;let m=[];for(let l of g.records){if(J.has(l.type)){u.records.push({record:l,status:"skipped",reason:`${l.type} describes the delegation itself; ${s.name} owns it`});continue}let f=pt.has(l.type)&&o.has(D(l.name));m.push({name:l.name,type:l.type,content:l.content,ttl:l.ttl,priority:l.priority,...pt.has(l.type)?{proxied:f}:{}})}if(i){for(let l of m)u.records.push({record:l,status:"copied",reason:"dry run"});return u}let p=new Map;for(let l of m){let f=`${l.type}|${D(l.name)}`;p.set(f,(p.get(f)??0)+1)}let y=new Set;try{let l=await s.listRecords(t);for(let f of l.records??[])y.add(S(f))}catch{}for(let l of m){let f=te.has(l.type)&&p.get(`${l.type}|${D(l.name)}`)===1;if(!f&&y.has(S(l))){u.records.push({record:l,status:"present"});continue}let A;try{A=f?await s.upsertRecord(t,l):await s.createRecord(t,l)}catch(b){A={success:!1,message:b instanceof Error?b.message:String(b)}}if(A.success)y.add(S(l));u.records.push(A.success?{record:l,status:"copied"}:{record:l,status:"failed",reason:A.message})}let v=await s.listRecords(t);if(!v.success)return a.push(`Could not read back ${t} from ${s.name}: ${v.message??"unknown error"}`),u.status="blocked",u;for(let l of m)if(!v.records.some((f)=>re(l,f)))u.missing.push(l);if(u.missing.length>0)return a.push(`${u.missing.length} record(s) did not arrive at ${s.name}; leaving ${r.name}'s nameservers alone. Delegating now would take the domain off a complete zone and onto an incomplete one.`),u.status="blocked",u;if(!await r.updateNameServers(t,c.nameServers))return a.push(`${r.name} refused the nameserver update for ${t}.`),u.status="blocked",u;return u.status="delegated",u}var ne={add_visitor_location_headers:"visitorLocationHeaders"};function z(e){return{porkbunApiKey:e.PORKBUN_API_KEY,porkbunSecretKey:e.PORKBUN_SECRET_KEY,godaddyApiKey:e.GODADDY_API_KEY,godaddyApiSecret:e.GODADDY_API_SECRET,cloudflareApiToken:e.CLOUDFLARE_API_TOKEN,cloudflareAccountId:e.CLOUDFLARE_ACCOUNT_ID}}function se(e,t){if(e==="porkbun"){if(!t.porkbunApiKey||!t.porkbunSecretKey)return"PORKBUN_API_KEY / PORKBUN_SECRET_KEY are not set";return new he(t.porkbunApiKey,t.porkbunSecretKey)}if(!t.godaddyApiKey||!t.godaddyApiSecret)return"GODADDY_API_KEY / GODADDY_API_SECRET are not set";let r=new Ge(t.godaddyApiKey,t.godaddyApiSecret);if(!Tr(r))return"the GoDaddy provider cannot change nameservers";return r}async function Fs(e,t={}){let r=e.registrar;if(!r)return{status:"skipped",reason:"no dns.registrar configured"};if(r.delegate===!1)return{status:"skipped",reason:"dns.registrar.delegate is false"};if(!e.domain)return{status:"skipped",reason:"no dns.domain configured"};if(!e.provider||e.provider===r.provider)return{status:"skipped",reason:`dns.provider is already ${r.provider}`};if(e.provider!=="cloudflare")return{status:"skipped",reason:`delegation to ${e.provider} is not supported yet`};let s=t.credentials??z(t.env??process.env);if(!s.cloudflareApiToken)return{status:"skipped",reason:"CLOUDFLARE_API_TOKEN is not set"};let i=se(r.provider,s);if(typeof i==="string")return{status:"skipped",reason:i};let o=new H(s.cloudflareApiToken,{accountId:s.cloudflareAccountId});if(!wr(o))return{status:"skipped",reason:"the Cloudflare provider cannot create zones"};return Rr({domain:e.domain,registrar:i,host:o,proxiedHosts:r.proxied,accountId:s.cloudflareAccountId,dryRun:r.dryRun})}function Us(e){if(e.status==="skipped")return[`dns: delegation skipped — ${e.reason}`];let t=[];switch(e.status){case"already-delegated":t.push(`dns: ${e.domain} already delegated to ${e.targetNameservers.join(", ")}`);break;case"delegated":t.push(`dns: ${e.domain} delegated to ${e.targetNameservers.join(", ")} (${e.records.filter((r)=>r.status==="copied").length} record(s) copied)`),t.push("dns: nameserver changes take up to 24h to propagate; the old zone answers until then");break;case"ready":t.push(`dns: ${e.domain} would delegate to ${e.targetNameservers.join(", ")} (dry run)`);break;case"blocked":t.push(`dns: ${e.domain} NOT delegated — nameservers left at ${e.currentNameservers.join(", ")}`);for(let r of e.missing)t.push(` missing at destination: ${r.type} ${r.name}`);break}for(let r of e.warnings)t.push(` ${r}`);return t}function oe(e){let t={};if(e.ssl!==void 0)t.ssl=e.ssl;if(e.alwaysUseHttps!==void 0)t.always_use_https=e.alwaysUseHttps?"on":"off";if(e.minTlsVersion!==void 0)t.min_tls_version=e.minTlsVersion;return t}function ae(e){let t={};for(let[r,s]of Object.entries(ne)){let i=e[s];if(typeof i==="boolean")t[r]=i}return t}async function Qs(e,t={}){if(!e.zone)return{status:"skipped",reason:"no dns.zone configured"};if(!e.domain)return{status:"skipped",reason:"no dns.domain configured"};if(e.provider!=="cloudflare")return{status:"skipped",reason:`zone settings are not supported for ${e.provider??"this provider"}`};let r=oe(e.zone),s=ae(e.zone);if(Object.keys(r).length===0&&Object.keys(s).length===0&&!e.zone.tieredCache)return{status:"skipped",reason:"dns.zone declares no settings"};let i=t.credentials??z(t.env??process.env);if(!i.cloudflareApiToken)return{status:"skipped",reason:"CLOUDFLARE_API_TOKEN is not set"};let o=new H(i.cloudflareApiToken,{accountId:i.cloudflareAccountId}),a=await o.applyZoneSettings(e.domain,r),c=Object.keys(s).length>0?await o.applyManagedRequestHeaders(e.domain,s):{changed:[],failed:[]},d=e.zone.tieredCache?await o.applyTieredCache(e.domain,e.zone.tieredCache):{changed:[],failed:[]},u=[...a.changed,...c.changed,...d.changed],g=[...a.failed,...c.failed,...d.failed];return{status:u.length>0?"applied":"unchanged",domain:e.domain,changed:u,failed:g}}function Hs(e){if(e.status==="skipped")return[`dns: zone settings skipped — ${e.reason}`];let t=[];for(let r of e.changed)t.push(`dns: ${e.domain} ${r.id}: ${String(r.from)} → ${String(r.to)}`);if(e.status==="unchanged"&&e.failed.length===0)t.push(`dns: ${e.domain} zone settings already as declared`);for(let r of e.failed)t.push(`dns: ${e.domain} could not set ${r.id} — ${r.error}`);return t}class ie{name="route53";client;hostedZoneCache=new Map;providedHostedZoneId;constructor(e="us-east-1",t){this.client=new I(e),this.providedHostedZoneId=t}getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length>=2)return t.slice(-2).join(".");return e}async getHostedZoneId(e){if(this.providedHostedZoneId)return this.providedHostedZoneId;let t=this.getRootDomain(e),r=this.hostedZoneCache.get(t);if(r)return r;let s=await this.client.findHostedZoneForDomain(e);if(s){let i=s.Id.replace("/hostedzone/","");return this.hostedZoneCache.set(t,i),i}return null}normalizeName(e,t){let r=e.replace(/\.$/,""),s=t.replace(/\.$/,"");if(!s||s==="@")return`${r}.`;if(s===r||s.endsWith(`.${r}`))return`${s}.`;return`${s}.${r}.`}formatValue(e){let t=e.content;if(e.type==="TXT"&&!t.startsWith('"'))t=ce(t);if(e.type==="MX"&&e.priority!==void 0)t=`${e.priority} ${t}`;return t}sameValue(e,t,r){return e==="TXT"?k(t)===k(r):t===r}async currentSet(e,t,r){let i=(await this.client.listResourceRecordSets({HostedZoneId:e,StartRecordName:t,StartRecordType:r,MaxItems:"1"})).ResourceRecordSets?.[0];if(!i||i.Name.toLowerCase()!==t.toLowerCase()||i.Type!==r||i.AliasTarget||i.SetIdentifier)return null;return{ttl:i.TTL??300,values:(i.ResourceRecords??[]).map((o)=>o.Value)}}async createRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let s=this.normalizeName(e,t.name),i=this.formatValue(t),o=await this.currentSet(r,s,t.type);if(o?.values.some((d)=>this.sameValue(t.type,d,i)))return{success:!0,message:"Record already present"};let a=[...o?.values??[],i];return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Created by ts-cloud DNS provider",Changes:[{Action:o?"UPSERT":"CREATE",ResourceRecordSet:{Name:s,Type:t.type,TTL:o?.ttl??t.ttl??300,ResourceRecords:a.map((d)=>({Value:d}))}}]}})).ChangeInfo?.Id,message:"Record created successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async upsertRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let s=this.normalizeName(e,t.name),i=this.formatValue(t);return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Upserted by ts-cloud DNS provider",Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:s,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:i}]}}]}})).ChangeInfo?.Id,message:"Record upserted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async deleteRecord(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,message:`No hosted zone found for domain: ${e}`};let s=this.normalizeName(e,t.name),i=this.formatValue(t),o=await this.currentSet(r,s,t.type);if(!o||!o.values.some((c)=>this.sameValue(t.type,c,i)))return{success:!0,message:"Record already absent"};let a=o.values.filter((c)=>!this.sameValue(t.type,c,i));return await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Deleted by ts-cloud DNS provider",Changes:[{Action:a.length>0?"UPSERT":"DELETE",ResourceRecordSet:{Name:s,Type:t.type,TTL:o.ttl,ResourceRecords:(a.length>0?a:o.values).map((c)=>({Value:c}))}}]}}),{success:!0,message:"Record deleted successfully"}}catch(r){return{success:!1,message:r instanceof Error?r.message:"Unknown error"}}}async listRecords(e,t){try{let r=await this.getHostedZoneId(e);if(!r)return{success:!1,records:[],message:`No hosted zone found for domain: ${e}`};let s=await this.client.listResourceRecordSets({HostedZoneId:r,StartRecordType:t}),i=[];for(let o of s.ResourceRecordSets){if(t&&o.Type!==t)continue;if(o.AliasTarget)continue;for(let a of o.ResourceRecords||[]){let c=a.Value,d;if(o.Type==="MX"){let u=c.split(" ");if(u.length>=2)d=Number.parseInt(u[0],10),c=u.slice(1).join(" ")}if(o.Type==="TXT"&&c.startsWith('"'))c=k(c);i.push({name:o.Name.replace(/\.$/,""),type:o.Type,content:c,ttl:o.TTL,priority:d})}}return{success:!0,records:i}}catch(r){return{success:!1,records:[],message:r instanceof Error?r.message:"Unknown error"}}}async canManageDomain(e){return await this.getHostedZoneId(e)!==null}async listDomains(){try{return(await this.client.listHostedZones()).HostedZones.map((t)=>t.Name.replace(/\.$/,""))}catch{return[]}}getRoute53Client(){return this.client}async createAliasRecord(e){try{let t=await this.getHostedZoneId(e.domain);if(!t)return{success:!1,message:`No hosted zone found for domain: ${e.domain}`};return{success:!0,id:(await this.client.createAliasRecord({HostedZoneId:t,Name:this.normalizeName(e.domain,e.name),TargetHostedZoneId:e.targetHostedZoneId,TargetDNSName:e.targetDnsName,EvaluateTargetHealth:e.evaluateTargetHealth,Type:e.type})).ChangeInfo?.Id,message:"Alias record created successfully"}}catch(t){return{success:!1,message:t instanceof Error?t.message:"Unknown error"}}}async createCloudFrontAlias(e){return this.createAliasRecord({domain:e.domain,name:e.name,targetHostedZoneId:I.CloudFrontHostedZoneId,targetDnsName:e.cloudFrontDomainName,evaluateTargetHealth:!1})}async createAlbAlias(e){let t=I.ALBHostedZoneIds[e.region];if(!t)return{success:!1,message:`Unknown region for ALB: ${e.region}`};return this.createAliasRecord({domain:e.domain,name:e.name,targetHostedZoneId:t,targetDnsName:e.albDnsName,evaluateTargetHealth:!0})}}var q=255;function ce(e){let t=[];for(let r=0;r<e.length;r+=q)t.push(e.slice(r,r+q));if(t.length===0)t.push("");return t.map((r)=>`"${r.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`).join(" ")}function k(e){if(!e.startsWith('"'))return e;let t="",r=!1;for(let s=0;s<e.length;s++){let i=e[s];if(!r){if(i==='"')r=!0;continue}if(i==="\\"&&s+1<e.length){t+=e[++s];continue}if(i==='"'){r=!1;continue}t+=i}return t}async function Gs(e,t){let r=[],s,i;for(;;){let o=await e.listResourceRecordSets({HostedZoneId:t,StartRecordName:s,StartRecordType:i,MaxItems:"100"});if(r.push(...o.ResourceRecordSets),!o.IsTruncated)break;if(s=o.NextRecordName,i=o.NextRecordType,!s)break}return r}function h(e){return e.replace(/\.$/,"").toLowerCase()}function L(e){return e.replace(/\.$/,"")}function T(e){if(e.type==="SRV"&&e.weight!==void 0&&e.port!==void 0)return`${e.weight} ${e.port} ${L(e.content)}`;return L(e.content)}function de(e){let t=e.match(/"(?:[^"\\]|\\.)*"/g);if(!t)return e;return t.map((r)=>r.slice(1,-1).replace(/\\(.)/g,"$1")).join("")}function Vs(e,t){let r=h(t),s=[],i=[],o=[],a=new Set;for(let c of e){let d=h(c.Name),u=c.Type;if(u==="SOA"||u==="NS"&&d===r){i.push({name:d,type:u,reason:"owned by the destination provider"});continue}if(c.SetIdentifier){i.push({name:d,type:u,reason:`routing policy record (SetIdentifier=${c.SetIdentifier}) has no equivalent — recreate by hand`}),o.push(`${u} ${d} is part of a Route53 routing policy and was NOT migrated`);continue}if(c.AliasTarget){if(a.has(d))continue;a.add(d);let g=h(c.AliasTarget.DNSName);if(s.push({name:d,type:"CNAME",content:g,ttl:300,translatedFrom:`${u} ALIAS → ${g}`}),c.AliasTarget.EvaluateTargetHealth)o.push(`${d} was an ALIAS with health evaluation enabled; the CNAME that replaces it has no health check`);continue}for(let g of c.ResourceRecords||[]){let m=ue(d,u,g.Value,c.TTL);if("reason"in m){i.push({name:d,type:u,reason:m.reason}),o.push(`${u} ${d}: ${m.reason}`);continue}s.push(m)}}return{zone:r,records:s,skipped:i,warnings:o}}function ue(e,t,r,s){let i={name:e,ttl:s};switch(t){case"A":case"AAAA":case"CNAME":case"PTR":return{...i,type:t==="PTR"?"CNAME":t,content:h(r)};case"TXT":return{...i,type:"TXT",content:de(r)};case"MX":{let[o,...a]=r.trim().split(/\s+/);if(!a.length)return{reason:`malformed MX value "${r}"`};return{...i,type:"MX",content:h(a.join(" ")),priority:Number(o)}}case"SRV":{let o=r.trim().split(/\s+/);if(o.length<4)return{reason:`malformed SRV value "${r}"`};let[a,c,d]=o.slice(0,3).map(Number);return{...i,type:"SRV",content:h(o.slice(3).join(" ")),priority:a,weight:c,port:d}}case"NS":return{...i,type:"NS",content:h(r)};case"CAA":return{...i,type:"CAA",content:r.trim()};default:return{reason:`unsupported record type ${t}`}}}var le=new Set(["TXT","MX","SRV","NS","CAA"]);async function qs(e,t){let r=[],s=[],i=new Set;try{let o=await e.listRecords(t.zone);for(let a of o.records||[])i.add(`${h(a.name)}|${a.type}|${T(a)}`)}catch{}for(let o of t.records){let a={...o,proxied:!1},c=`${h(o.name)}|${o.type}|${T(o)}`;if(!le.has(o.type)){let u=await e.upsertRecord(t.zone,a);if(u.success)r.push(o);else s.push({record:o,message:u.message||"unknown provider error"});continue}if(i.has(c)){r.push(o);continue}let d=await e.createRecord(t.zone,a);if(d.success)i.add(c),r.push(o);else s.push({record:o,message:d.message||"unknown provider error"})}return{applied:r,failed:s}}async function js(e,t){let r=await e.listRecords(t.zone),s=[],i=[],o=new Map;for(let a of r.records||[]){let c=`${h(a.name)}|${a.type}`,d=o.get(c)??[];d.push(T(a)),o.set(c,d)}for(let a of t.records){let c=o.get(`${h(a.name)}|${a.type}`),d=T(a);if(c?.some((u)=>u===d))s.push(a);else i.push({record:a,found:c?.join(", ")})}return{matched:s,missing:i,ok:i.length===0}}class Ae{acm;dnsProvider;constructor(e,t="us-east-1"){if(this.acm=new ye(t),"provider"in e)this.dnsProvider=N(e);else this.dnsProvider=e}getProvider(){return this.dnsProvider}async requestAndValidate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:s=!1,maxWaitMinutes:i=30}=e,{CertificateArn:o}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:r.length>0?[t,...r]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(o);let a=await this.acm.getDnsValidationRecords(o);for(let d of a){let u=await this.dnsProvider.upsertRecord(t,{name:d.recordName,type:d.recordType,content:d.recordValue,ttl:300});if(!u.success)console.warn(`Failed to create validation record for ${d.domainName}: ${u.message}`)}let c="pending";if(s)c=(await this.acm.waitForCertificateValidation(o,i*2,30000))?.Status==="ISSUED"?"issued":"failed";return{certificateArn:o,validationRecords:a.map((d)=>({domainName:d.domainName,recordName:d.recordName,recordType:d.recordType,recordValue:d.recordValue})),isNew:!0,status:c}}async createValidationRecords(e){let{certificateArn:t,domain:r}=e,s=[],i=await this.acm.getDnsValidationRecords(t);for(let o of i){let a=await this.dnsProvider.upsertRecord(r,{name:o.recordName,type:o.recordType,content:o.recordValue,ttl:300});if(!a.success)s.push(`Failed to create record for ${o.domainName}: ${a.message}`)}return{success:s.length===0,records:i.map((o)=>({domainName:o.domainName,recordName:o.recordName,recordType:o.recordType,recordValue:o.recordValue})),errors:s}}async deleteValidationRecords(e){let{certificateArn:t,domain:r}=e,s=[],i=await this.acm.getDnsValidationRecords(t);for(let o of i){let a=await this.dnsProvider.deleteRecord(r,{name:o.recordName,type:o.recordType,content:o.recordValue});if(!a.success)s.push(`Failed to delete record for ${o.domainName}: ${a.message}`)}return{success:s.length===0,errors:s}}async findOrCreateCertificate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:s=!0,maxWaitMinutes:i}=e,o=await this.acm.findCertificateByDomain(t);if(o&&o.Status==="ISSUED"){let a=o.SubjectAlternativeNames||[o.DomainName],c=a.some((u)=>u===`*.${t}`);if(r.every((u)=>a.includes(u)||c))return{certificateArn:o.CertificateArn,validationRecords:[],isNew:!1,status:"issued"};console.log("Existing certificate doesn't cover all required SANs, requesting new certificate...")}return this.requestAndValidate({domainName:t,subjectAlternativeNames:r,waitForValidation:s,maxWaitMinutes:i})}async requestCertificateWithCommonSans(e){let{domainName:t,includeWww:r=!0,includeWildcard:s=!1,additionalSans:i=[],waitForValidation:o=!1}=e,a=[];if(r)a.push(`www.${t}`);if(s)a.push(`*.${t}`);return a.push(...i),this.requestAndValidate({domainName:t,subjectAlternativeNames:a,waitForValidation:o})}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let s=await this.acm.describeCertificate({CertificateArn:e});if(s.DomainValidationOptions&&s.DomainValidationOptions.length>0&&s.DomainValidationOptions[0].ResourceRecord)return;await new Promise((i)=>setTimeout(i,2000))}throw Error("Timeout waiting for DNS validation options")}async getCertificateStatus(e){let t=await this.acm.describeCertificate({CertificateArn:e});return{status:t.Status,domainValidations:(t.DomainValidationOptions||[]).map((r)=>({domain:r.DomainName,status:r.ValidationStatus||"UNKNOWN"}))}}}function zs(e,t,r){return new Ae({provider:"porkbun",apiKey:e,secretKey:t},r)}function Ks(e,t,r,s){return new Ae({provider:"godaddy",apiKey:e,apiSecret:t,environment:s},r)}function Ws(e,t,r){return new Ae({provider:"route53",region:e,hostedZoneId:t},r||e)}function N(e){switch(e.provider){case"route53":return new ie(e.region,e.hostedZoneId);case"porkbun":return new he(e.apiKey,e.secretKey);case"godaddy":return new Ge(e.apiKey,e.apiSecret,e.environment);case"cloudflare":return new H(e.apiToken,{zoneId:e.zoneId,accountId:e.accountId});default:throw Error(`Unknown DNS provider: ${e.provider}`)}}async function Dc(e,t){for(let r of t){let s=N(r);if(await s.canManageDomain(e))return s}return null}class Kn{providers=new Map;configs=[];addConfig(e){return this.configs.push(e),this}addRoute53(e,t){return this.configs.push({provider:"route53",region:e,hostedZoneId:t}),this}addPorkbun(e,t){return this.configs.push({provider:"porkbun",apiKey:e,secretKey:t}),this}addGoDaddy(e,t,r){return this.configs.push({provider:"godaddy",apiKey:e,apiSecret:t,environment:r}),this}addCloudflare(e,t={}){return this.configs.push({provider:"cloudflare",apiToken:e,zoneId:t.zoneId,accountId:t.accountId}),this}loadFromEnv(){if(process.env.AWS_ACCESS_KEY_ID||process.env.AWS_PROFILE||process.env.AWS_REGION)this.addRoute53(process.env.AWS_REGION);let e=process.env.PORKBUN_API_KEY,t=process.env.PORKBUN_SECRET_KEY;if(e&&t)this.addPorkbun(e,t);let r=process.env.GODADDY_API_KEY,s=process.env.GODADDY_API_SECRET;if(r&&s){let o=process.env.GODADDY_ENVIRONMENT;this.addGoDaddy(r,s,o)}let i=process.env.CLOUDFLARE_API_TOKEN;if(i)this.addCloudflare(i,{zoneId:process.env.CLOUDFLARE_ZONE_ID,accountId:process.env.CLOUDFLARE_ACCOUNT_ID});return this}getProvider(e){let t=this.providers.get(e);if(t)return t;let r=this.configs.find((i)=>i.provider===e);if(!r)return null;let s=N(r);return this.providers.set(e,s),s}async getProviderForDomain(e){for(let t of this.configs){let r=N(t);if(await r.canManageDomain(e))return r}return null}getAllProviders(){return this.configs.map((e)=>N(e))}}var Pc=new Kn;class ye{client;region;constructor(e="us-east-1"){this.client=new n,this.region=e}async requestCertificate(e){let t={DomainName:e.DomainName,ValidationMethod:e.ValidationMethod||"DNS"};if(e.SubjectAlternativeNames)t.SubjectAlternativeNames=e.SubjectAlternativeNames;return{CertificateArn:(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.RequestCertificate"},body:JSON.stringify(t)})).CertificateArn||""}}async describeCertificate(e){let r=(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.DescribeCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})).Certificate||{};return{CertificateArn:r.CertificateArn||"",DomainName:r.DomainName||"",SubjectAlternativeNames:r.SubjectAlternativeNames,Status:r.Status||"PENDING_VALIDATION",Type:r.Type,DomainValidationOptions:r.DomainValidationOptions?.map((s)=>({DomainName:s.DomainName,ValidationDomain:s.ValidationDomain,ValidationStatus:s.ValidationStatus,ResourceRecord:s.ResourceRecord?{Name:s.ResourceRecord.Name,Type:s.ResourceRecord.Type,Value:s.ResourceRecord.Value}:void 0,ValidationMethod:s.ValidationMethod})),CreatedAt:r.CreatedAt,IssuedAt:r.IssuedAt,NotBefore:r.NotBefore,NotAfter:r.NotAfter}}async listCertificates(e){let t={};if(e?.CertificateStatuses)t.CertificateStatuses=e.CertificateStatuses;if(e?.MaxItems)t.MaxItems=e.MaxItems;if(e?.NextToken)t.NextToken=e.NextToken;let r=await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ListCertificates"},body:JSON.stringify(t)});return{CertificateSummaryList:(r.CertificateSummaryList||[]).map((s)=>({CertificateArn:s.CertificateArn,DomainName:s.DomainName})),NextToken:r.NextToken}}async deleteCertificate(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.DeleteCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})}async listTagsForCertificate(e){return{Tags:(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ListTagsForCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn})})).Tags||[]}}async addTagsToCertificate(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.AddTagsToCertificate"},body:JSON.stringify({CertificateArn:e.CertificateArn,Tags:e.Tags})})}async resendValidationEmail(e){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ResendValidationEmail"},body:JSON.stringify({CertificateArn:e.CertificateArn,Domain:e.Domain,ValidationDomain:e.ValidationDomain})})}async findCertificateByDomain(e){let r=(await this.listCertificates({CertificateStatuses:["ISSUED"]})).CertificateSummaryList.find((s)=>s.DomainName===e||s.DomainName===`*.${e.split(".").slice(1).join(".")}`);if(!r)return null;return this.describeCertificate({CertificateArn:r.CertificateArn})}async waitForCertificateValidation(e,t=60,r=30000){for(let s=0;s<t;s++){let i=await this.describeCertificate({CertificateArn:e});if(i.Status==="ISSUED")return i;if(i.Status==="FAILED"||i.Status==="VALIDATION_TIMED_OUT")return null;await new Promise((o)=>setTimeout(o,r))}return null}async getDnsValidationRecords(e){let t=await this.describeCertificate({CertificateArn:e});if(!t.DomainValidationOptions)return[];return t.DomainValidationOptions.filter((r)=>r.ResourceRecord&&r.ValidationMethod==="DNS").map((r)=>({domainName:r.DomainName,recordName:r.ResourceRecord.Name,recordType:r.ResourceRecord.Type,recordValue:r.ResourceRecord.Value}))}async requestCertificateWithSans(e){let t=new Set;if(t.add(e.DomainName),e.IncludeWww!==!1)t.add(`www.${e.DomainName}`);if(e.IncludeWildcard)t.add(`*.${e.DomainName}`);if(e.AdditionalSans)for(let r of e.AdditionalSans)t.add(r);return this.requestCertificate({DomainName:e.DomainName,SubjectAlternativeNames:Array.from(t),ValidationMethod:"DNS"})}async isCertificateValidForDomain(e,t){let r=await this.describeCertificate({CertificateArn:e});if(r.Status!=="ISSUED")return!1;if(r.DomainName===t)return!0;if(r.DomainName?.startsWith("*.")){let s=r.DomainName.slice(2),i=t.split("."),o=s.split(".");if(i.slice(-o.length).join(".")===s)return!0}if(r.SubjectAlternativeNames)for(let s of r.SubjectAlternativeNames){if(s===t)return!0;if(s.startsWith("*.")){let i=s.slice(2),o=t.split("."),a=i.split(".");if(o.slice(-a.length).join(".")===i)return!0}}return!1}}class Dr{acm;route53;dnsProvider;constructor(e="us-east-1",t){if(this.acm=new ye(e),this.route53=new I,t&&t.provider!=="route53")this.dnsProvider=N(t)}async requestAndValidate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:s=[],waitForValidation:i=!1,maxWaitMinutes:o=30}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let{CertificateArn:a}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:s.length>0?[t,...s]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(a);let c=await this.acm.getDnsValidationRecords(a);if(this.dnsProvider)for(let d of c){let u=await this.dnsProvider.upsertRecord(t,{name:d.recordName,type:d.recordType,content:d.recordValue,ttl:300});if(!u.success)console.warn(`Failed to create validation record for ${d.domainName}: ${u.message}`)}else if(r)for(let d of c)await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${d.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:d.recordName,Type:d.recordType,TTL:300,ResourceRecords:[{Value:d.recordValue}]}}]}});if(i){if(!await this.acm.waitForCertificateValidation(a,o*2,30000))throw Error(`Certificate validation timed out after ${o} minutes`)}return{certificateArn:a,validationRecords:c}}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let s=await this.acm.describeCertificate({CertificateArn:e});if(s.DomainValidationOptions&&s.DomainValidationOptions.length>0&&s.DomainValidationOptions[0].ResourceRecord)return;await new Promise((i)=>setTimeout(i,2000))}throw Error("Timeout waiting for DNS validation options")}async createValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:s}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let i=await this.acm.getDnsValidationRecords(t),o=[];if(this.dnsProvider){let a=s||i[0]?.domainName;for(let c of i){let d=await this.dnsProvider.upsertRecord(a,{name:c.recordName,type:c.recordType,content:c.recordValue,ttl:300});o.push({...c,changeId:d.success?d.id:void 0})}}else if(r)for(let a of i){let c=await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${a.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:a.recordName,Type:a.recordType,TTL:300,ResourceRecords:[{Value:a.recordValue}]}}]}});o.push({...a,changeId:c.ChangeInfo?.Id})}return o}async deleteValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:s}=e,i=await this.acm.getDnsValidationRecords(t);if(this.dnsProvider){let o=s||i[0]?.domainName;for(let a of i)try{await this.dnsProvider.deleteRecord(o,{name:a.recordName,type:a.recordType,content:a.recordValue})}catch{}}else if(r)for(let o of i)try{await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`Cleanup ACM DNS validation for ${o.domainName}`,Changes:[{Action:"DELETE",ResourceRecordSet:{Name:o.recordName,Type:o.recordType,TTL:300,ResourceRecords:[{Value:o.recordValue}]}}]}})}catch{}}async findOrCreateCertificate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:s,waitForValidation:i=!0}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let o=await this.acm.findCertificateByDomain(t);if(o&&o.Status==="ISSUED")return{certificateArn:o.CertificateArn,isNew:!1};let{certificateArn:a}=await this.requestAndValidate({domainName:t,hostedZoneId:r,subjectAlternativeNames:s,waitForValidation:i});return{certificateArn:a,isNew:!0}}hasExternalDnsProvider(){return this.dnsProvider!==void 0}getDnsProviderName(){return this.dnsProvider?.name||"route53"}}
2
+ export{pt,he,Ge,Rg,Ht,wc,Rc,Gt,H,qn,Vt,qt,jn,$s,Ms,Tr,wr,zn,Rr,Fs,Us,Qs,Hs,ie,Gs,Vs,qs,js,Ae,zs,Ks,Ws,N,Dc,Kn,Pc,ye,Dr};