@stacksjs/ts-cloud 0.16.74 → 0.16.75

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 (180) hide show
  1. package/dist/aws/index.js +1 -1
  2. package/dist/bin/chunk-00j7xxxg.js +1 -0
  3. package/dist/bin/{chunk-10z6s9nj.js → chunk-06hwds44.js} +2 -2
  4. package/dist/bin/{chunk-xhe84hg1.js → chunk-0e7y7q0t.js} +1 -1
  5. package/dist/bin/{chunk-cs2a075v.js → chunk-0r8k7qth.js} +2 -2
  6. package/dist/bin/{chunk-jh4ajbt1.js → chunk-0v5q5sh0.js} +3 -3
  7. package/dist/bin/{chunk-fwcd0ef4.js → chunk-0zydd9s4.js} +3 -3
  8. package/dist/bin/chunk-1xfn93bc.js +1 -0
  9. package/dist/bin/{chunk-11xdxrp3.js → chunk-26vbw2m6.js} +70 -70
  10. package/dist/bin/{chunk-7v68hpgc.js → chunk-2h1q758c.js} +2 -2
  11. package/dist/bin/{chunk-bgjvxdds.js → chunk-33shhgye.js} +2 -2
  12. package/dist/bin/chunk-413nb697.js +1 -0
  13. package/dist/bin/{chunk-c99xvba1.js → chunk-4m2k5mvd.js} +4 -4
  14. package/dist/bin/{chunk-rg6r03q3.js → chunk-4vtyjj7c.js} +1 -1
  15. package/dist/bin/{chunk-9cj1fm00.js → chunk-540wkkhs.js} +3 -3
  16. package/dist/bin/{chunk-6wvgwn9q.js → chunk-6xx24qev.js} +1 -1
  17. package/dist/bin/chunk-72kpcqps.js +1 -0
  18. package/dist/bin/chunk-8esaawk6.js +1 -0
  19. package/dist/bin/chunk-8zc4kx6k.js +1 -0
  20. package/dist/bin/{chunk-whryzwb7.js → chunk-9ktyfegk.js} +1 -1
  21. package/dist/bin/chunk-9t6wztvn.js +1 -0
  22. package/dist/bin/{chunk-613m8vf9.js → chunk-b77qsk6r.js} +1 -1
  23. package/dist/bin/{chunk-ae9epvrr.js → chunk-by7dtwtj.js} +1 -1
  24. package/dist/bin/{chunk-6gspchrt.js → chunk-c1znyyca.js} +1 -1
  25. package/dist/bin/{chunk-9xs1fh7q.js → chunk-d73xkm0k.js} +1 -1
  26. package/dist/bin/{chunk-yjmydj1w.js → chunk-dmj5xv74.js} +1 -1
  27. package/dist/bin/chunk-dnswjyen.js +1 -0
  28. package/dist/bin/{chunk-bj94s3a7.js → chunk-e12679p1.js} +1 -1
  29. package/dist/bin/{chunk-zcq82zv1.js → chunk-eyzdhtp4.js} +3 -3
  30. package/dist/bin/{chunk-69j7md80.js → chunk-fhqjr3ba.js} +4 -4
  31. package/dist/bin/{chunk-eevqxagd.js → chunk-gndp57b6.js} +44 -44
  32. package/dist/bin/{chunk-648xb030.js → chunk-gq4htm3f.js} +2 -2
  33. package/dist/bin/{chunk-zph18vv6.js → chunk-gqstb8zn.js} +3 -3
  34. package/dist/bin/{chunk-7xd2tnjb.js → chunk-hhbmtgkq.js} +2 -2
  35. package/dist/bin/{chunk-8fspkmer.js → chunk-jcehsvnm.js} +10 -10
  36. package/dist/bin/chunk-k1bdndgj.js +1 -0
  37. package/dist/bin/{chunk-r5cpsqqk.js → chunk-k3cyh23p.js} +3 -3
  38. package/dist/bin/chunk-kkrp8100.js +1 -0
  39. package/dist/bin/{chunk-tvd5w8xq.js → chunk-kq526rgc.js} +1 -1
  40. package/dist/bin/{chunk-1g3gvxy2.js → chunk-ma0d990n.js} +2 -2
  41. package/dist/bin/{chunk-1n1s649d.js → chunk-nbffypj8.js} +1 -1
  42. package/dist/bin/chunk-nwcpck34.js +1 -0
  43. package/dist/bin/chunk-nzky7rgv.js +1 -0
  44. package/dist/bin/{chunk-qw5ch629.js → chunk-p35e4j11.js} +1 -1
  45. package/dist/bin/chunk-p96975b7.js +1 -0
  46. package/dist/bin/{chunk-sfv47z62.js → chunk-ps0pzqm0.js} +7 -7
  47. package/dist/bin/chunk-rgwwr6x2.js +1 -0
  48. package/dist/bin/{chunk-ekr2rzf6.js → chunk-s076q9sj.js} +2 -2
  49. package/dist/bin/chunk-sky689gw.js +1 -0
  50. package/dist/bin/{chunk-a8fqqd62.js → chunk-tf5tf414.js} +1 -1
  51. package/dist/bin/{chunk-47yznk07.js → chunk-th05q1gs.js} +1 -1
  52. package/dist/bin/chunk-tx56y5qk.js +1 -0
  53. package/dist/bin/{chunk-28a6yey5.js → chunk-v0fkhtgq.js} +1 -1
  54. package/dist/bin/chunk-v7dk21w9.js +1 -0
  55. package/dist/bin/{chunk-w244mfsx.js → chunk-vgcscxh1.js} +2 -2
  56. package/dist/bin/{chunk-gghy8mb4.js → chunk-wayhpmn7.js} +38 -38
  57. package/dist/bin/chunk-ww4r3r7x.js +1 -0
  58. package/dist/bin/{chunk-swbb39hj.js → chunk-y5gx3dq2.js} +1 -1
  59. package/dist/bin/chunk-y5hsmt17.js +1 -0
  60. package/dist/bin/{chunk-t6njpv8j.js → chunk-zfy6f6ph.js} +1 -1
  61. package/dist/bin/cli.js +82 -82
  62. package/dist/bin/dashboard-server.js +1 -1
  63. package/dist/{chunk-fd6gsz34.js → chunk-0cgrk9g3.js} +2 -2
  64. package/dist/{chunk-zthcwfbg.js → chunk-4ccv5c4m.js} +1 -1
  65. package/dist/{chunk-207hnnpp.js → chunk-84z2a1xn.js} +3 -3
  66. package/dist/chunk-86qwnp25.js +1 -0
  67. package/dist/{chunk-1ktv8jxf.js → chunk-8k44kaz0.js} +2 -2
  68. package/dist/{chunk-tdhm38cg.js → chunk-9pwvnh3f.js} +2 -2
  69. package/dist/{chunk-mqr6s8wa.js → chunk-b6wsc7jp.js} +22 -22
  70. package/dist/{chunk-49rt1jbe.js → chunk-c8kf2268.js} +3 -3
  71. package/dist/chunk-crpbs450.js +1 -0
  72. package/dist/{chunk-dq9g7cg9.js → chunk-dvma06m5.js} +3 -3
  73. package/dist/{chunk-qcs3qkdf.js → chunk-etv0rcjd.js} +3 -3
  74. package/dist/chunk-f4fggc5f.js +1 -0
  75. package/dist/{chunk-ebb7j388.js → chunk-fdf181e6.js} +1 -1
  76. package/dist/chunk-fmhqz3eg.js +1 -0
  77. package/dist/{chunk-yqzc3a9m.js → chunk-fnc88v79.js} +89 -89
  78. package/dist/{chunk-c2hvf1h5.js → chunk-hg93a2g9.js} +1 -1
  79. package/dist/{chunk-k05g8vy5.js → chunk-jx1zz1pw.js} +1 -1
  80. package/dist/{chunk-z90dv6jx.js → chunk-m9szynnf.js} +3 -3
  81. package/dist/{chunk-s7gv665w.js → chunk-ne8btf6v.js} +86 -86
  82. package/dist/{chunk-ssywr12y.js → chunk-nftqsker.js} +1 -1
  83. package/dist/{chunk-2r334egt.js → chunk-nxj8pwa7.js} +2 -2
  84. package/dist/chunk-pev4cpbd.js +1 -0
  85. package/dist/{chunk-277enqjc.js → chunk-t7qgvz8z.js} +27 -27
  86. package/dist/{chunk-7qhcfnqf.js → chunk-tmp2ym80.js} +1 -1
  87. package/dist/{chunk-65fwpzeg.js → chunk-tp37gyhc.js} +5 -5
  88. package/dist/{chunk-8ynkxbj6.js → chunk-v6s9k1mp.js} +3 -3
  89. package/dist/{chunk-cfyn21gd.js → chunk-vq8bejep.js} +2 -2
  90. package/dist/{chunk-49raybtd.js → chunk-w8sctn7m.js} +7 -7
  91. package/dist/{chunk-ggqxjcbe.js → chunk-z56sccfh.js} +1 -1
  92. package/dist/{chunk-f4qv0c6w.js → chunk-z5c5amm1.js} +5 -5
  93. package/dist/deploy/index.js +1 -1
  94. package/dist/dns/index.js +1 -1
  95. package/dist/drivers/index.js +1 -1
  96. package/dist/drivers/shared/db-provision.d.ts +3 -3
  97. package/dist/index.js +10 -10
  98. package/dist/mail/index.js +2 -2
  99. package/dist/operations/index.js +1 -1
  100. package/dist/protection/index.js +1 -1
  101. package/dist/spend/index.js +1 -1
  102. package/dist/ui/404.html +1 -1
  103. package/dist/ui/accept-invitation.html +1 -1
  104. package/dist/ui/access-denied.html +1 -1
  105. package/dist/ui/account/automation.html +6 -6
  106. package/dist/ui/account/security.html +2 -2
  107. package/dist/ui/applications/compose.html +6 -6
  108. package/dist/ui/applications/new.html +2 -2
  109. package/dist/ui/data/backups.html +6 -6
  110. package/dist/ui/data/services.html +6 -6
  111. package/dist/ui/data/volumes.html +6 -6
  112. package/dist/ui/index.html +5 -5
  113. package/dist/ui/infrastructure/topology.html +6 -6
  114. package/dist/ui/integrations.html +2 -2
  115. package/dist/ui/operations/alerts.html +6 -6
  116. package/dist/ui/operations/configuration.html +6 -6
  117. package/dist/ui/operations/jobs.html +6 -6
  118. package/dist/ui/operations/maintenance.html +5 -5
  119. package/dist/ui/operations/observability.html +6 -6
  120. package/dist/ui/operations/previews.html +6 -6
  121. package/dist/ui/operations/queue.html +6 -6
  122. package/dist/ui/operations/regions.html +5 -5
  123. package/dist/ui/operations/releases.html +6 -6
  124. package/dist/ui/operations/spend.html +6 -6
  125. package/dist/ui/operations/workloads.html +6 -6
  126. package/dist/ui/security.html +2 -2
  127. package/dist/ui/server/actions.html +6 -6
  128. package/dist/ui/server/activity.html +1 -1
  129. package/dist/ui/server/capacity.html +6 -6
  130. package/dist/ui/server/database.html +5 -5
  131. package/dist/ui/server/deployments.html +6 -6
  132. package/dist/ui/server/diagnostics.html +2 -2
  133. package/dist/ui/server/firewall.html +5 -5
  134. package/dist/ui/server/fleet.html +6 -6
  135. package/dist/ui/server/logs.html +6 -6
  136. package/dist/ui/server/metrics.html +6 -6
  137. package/dist/ui/server/security.html +1 -1
  138. package/dist/ui/server/services.html +1 -1
  139. package/dist/ui/server/sites.html +5 -5
  140. package/dist/ui/server/ssh-keys.html +5 -5
  141. package/dist/ui/server/team.html +5 -5
  142. package/dist/ui/server/terminal.html +2 -2
  143. package/dist/ui/serverless/alarms.html +5 -5
  144. package/dist/ui/serverless/assets.html +2 -2
  145. package/dist/ui/serverless/cost.html +2 -2
  146. package/dist/ui/serverless/data.html +5 -5
  147. package/dist/ui/serverless/deployments.html +1 -1
  148. package/dist/ui/serverless/firewall.html +1 -1
  149. package/dist/ui/serverless/functions.html +5 -5
  150. package/dist/ui/serverless/logs.html +6 -6
  151. package/dist/ui/serverless/metrics.html +2 -2
  152. package/dist/ui/serverless/queues.html +6 -6
  153. package/dist/ui/serverless/secrets.html +6 -6
  154. package/dist/ui/serverless/traces.html +6 -6
  155. package/dist/ui/serverless.html +5 -5
  156. package/package.json +3 -3
  157. package/dist/bin/chunk-0pptjpck.js +0 -1
  158. package/dist/bin/chunk-0sswdcvq.js +0 -1
  159. package/dist/bin/chunk-1pj60edk.js +0 -1
  160. package/dist/bin/chunk-1qcztara.js +0 -1
  161. package/dist/bin/chunk-6bnxvtvy.js +0 -1
  162. package/dist/bin/chunk-7x4vs33k.js +0 -1
  163. package/dist/bin/chunk-8bs3m2x7.js +0 -1
  164. package/dist/bin/chunk-8cxdvpzy.js +0 -1
  165. package/dist/bin/chunk-9twr514q.js +0 -1
  166. package/dist/bin/chunk-9zbfadg4.js +0 -1
  167. package/dist/bin/chunk-bgm9p3x6.js +0 -1
  168. package/dist/bin/chunk-cmraxfxd.js +0 -1
  169. package/dist/bin/chunk-cvet8kjp.js +0 -1
  170. package/dist/bin/chunk-d5n4d3pj.js +0 -1
  171. package/dist/bin/chunk-e6kfkaxc.js +0 -1
  172. package/dist/bin/chunk-f80asgbh.js +0 -1
  173. package/dist/bin/chunk-wkwcskhg.js +0 -1
  174. package/dist/bin/chunk-yqqx644v.js +0 -1
  175. package/dist/bin/chunk-ywpkvdfg.js +0 -1
  176. package/dist/chunk-c5pq3x7x.js +0 -1
  177. package/dist/chunk-fvad4wm8.js +0 -1
  178. package/dist/chunk-gc8r2gvd.js +0 -1
  179. package/dist/chunk-k0scshn2.js +0 -1
  180. package/dist/chunk-sacbxd79.js +0 -1
@@ -1,9 +1,9 @@
1
- import{H,Fr}from"./chunk-gghy8mb4.js";function W(e,t){return`/var/www/${e}-${t}`}var me=new Set(["laravel","php","statamic","wordpress"]);function Di(e){return e.type!=null&&me.has(e.type)}function Us(e){let t=e.proxyTo;if(t==null)return[];return(Array.isArray(t)?t:[t]).map((n)=>String(n).trim()).filter((n)=>n.length>0)}function fe(e){return Us(e).length>0}function te(e){if(e.deploy)return e.deploy;if(Di(e))return"server";if(e.start)return"server";return"bucket"}function w(e){if(e.redirect)return"redirect";if(fe(e))return"proxy";if(Di(e))return"server-php";if(te(e)==="bucket")return"bucket";return e.start?"server-app":"server-static"}function Ro(e){return e.infrastructure?.compute!=null||Boolean(e.cloud?.attachTo?.trim())}function Bs(e,t={}){let r=[],n=[],o=e.sites||{},s=Ro(e),c=Fr(e);if(c)r.push(c);let p=new Map;for(let[l,i]of Object.entries(o)){if(!i)continue;let f=te(i),C=w(i);if(C==="redirect"){if(!i.domain)r.push(`Site '${l}' is a redirect site but has no \`domain\` to redirect from.`);if(!(typeof i.redirect==="string"?i.redirect:i.redirect?.to))r.push(`Site '${l}' is a redirect site but has no redirect target (\`redirect\` / \`redirect.to\`).`);if(!s)r.push(`Site '${l}' is a redirect site but no \`infrastructure.compute\` is configured to host the gateway that serves the redirect.`);let a=[];if(i.start)a.push("start");if(i.root)a.push("root");if(i.proxyTo)a.push("proxyTo");if(a.length>0)n.push(`Site '${l}' is a redirect site but also sets ${a.join(", ")}. These are ignored.`);continue}if(C==="proxy"){if(!i.domain)r.push(`Site '${l}' is a proxy site but has no \`domain\` to route from.`);if(!s)r.push(`Site '${l}' is a proxy site but no \`infrastructure.compute\` is configured to host the gateway that forwards it.`);let u=[];if(i.start)u.push("start");if(i.root)u.push("root");if(typeof i.port==="number")u.push("port");if(i.build)u.push("build");if(i.preStart&&i.preStart.length>0)u.push("preStart");if(u.length>0)n.push(`Site '${l}' sets \`proxyTo\`, so ts-cloud ships and supervises nothing for it. ${u.join(", ")} ${u.length===1?"is":"are"} ignored — remove ${u.length===1?"it":"them"}, or drop \`proxyTo\` to let ts-cloud own the service.`);continue}if(f==="server"&&!i.start&&!i.root){r.push(`Site '${l}' sets deploy:'server' but declares neither \`start\` (dynamic app) nor \`root\` (static site to serve). Add one.`);continue}if(C==="server-php"){if(!s)r.push(`Site '${l}' is a PHP site (type:'${i.type}') but no \`infrastructure.compute\` is configured. Add a server (infrastructure.compute) with PHP provisioning.`);if(!i.repository?.url)r.push(`Site '${l}' is a PHP site (type:'${i.type}') but has no \`repository.url\` to clone. PHP sites deploy via git.`)}else if(C==="server-app"){if(!s)r.push(`Site '${l}' deploys to a server (deploy:'server'${i.deploy?"":" inferred from `start`"}) but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`);if(typeof i.port==="number"){let u=t.occupiedPorts?.get(i.port);if(u)r.push(`Site '${l}' wants port ${i.port}, which project '${u}' already serves on this box. Attached projects share one port namespace. Give '${l}' a free port, or let the attach allocate one.`);let a=p.get(i.port);if(a)r.push(`Sites '${a}' and '${l}' both use port ${i.port}. Server apps sharing a box must use distinct ports.`);else p.set(i.port,l)}}else if(C==="server-static"){if(!i.root)r.push(`Site '${l}' is a server static site (deploy:'server', no \`start\`) but has no \`root\` directory to serve.`);if(!s)r.push(`Site '${l}' deploys to a server (deploy:'server') but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`)}else{if(!i.root)r.push(`Site '${l}' deploys to a bucket but has no \`root\` directory to upload.`);let u=[];if(i.start)u.push("start");if(typeof i.port==="number")u.push("port");if(i.preStart&&i.preStart.length>0)u.push("preStart");if(u.length>0)n.push(`Site '${l}' deploys to a bucket but sets server-only field(s): ${u.join(", ")}. These are ignored. Set deploy:'server' to use them.`)}}return{errors:r,warnings:n}}function Fs(e){let t=w(e);return t!=="bucket"&&t!=="redirect"&&t!=="proxy"}function qc(e){return w(e)==="bucket"}function Wc(e,t){if(H(e)==="serverless")return!0;let r=Object.entries(e.sites??{}).filter(([,o])=>o!=null),n=t?r.filter(([o])=>o===t):r;if(n.length===0)return!0;return!n.every(([,o])=>{let s=w(o);return s==="redirect"||s==="proxy"})}var L={php:"php.net",nginx:"nginx.org",composer:"getcomposer.org",mysql:"mysql.com",mariadb:"mariadb.com/server",postgres:"postgresql.org",vitess:"vitess.io",etcd:"etcd.io",redis:"redis.io",memcached:"memcached.org",meilisearch:"meilisearch.com",mail:"github.com/mail-os/mail",git:"git-scm.com",certbot:"certbot.eff.org",bun:"bun.sh",node:"nodejs.org",deno:"deno.land"};var R="/opt/pantry";function M(e){return`'${e.split("'").join("'\\''")}'`}function Tt(e={}){let t=e.installDir??"/usr/local/bin",r=e.version?`export PANTRY_VERSION=${M(e.version)}`:'export PANTRY_VERSION="${PANTRY_VERSION:-latest}"';return["export DEBIAN_FRONTEND=noninteractive","export PANTRY_SERVICE_SCOPE=system",`export PANTRY_INSTALL_DIR=${t}`,r,"command -v curl >/dev/null 2>&1 || (apt-get update -y && apt-get install -y curl ca-certificates)","command -v unzip >/dev/null 2>&1 || (apt-get update -y && apt-get install -y unzip)",`OS=$(uname -s | tr '[:upper:]' '[:lower:]'); ARCH=$(uname -m); case "$ARCH" in x86_64|amd64) ARCH=x64 ;; arm64|aarch64) ARCH=arm64 ;; esac; ZIP="pantry-\${OS}-\${ARCH}.zip"; if [ "\${PANTRY_VERSION:-latest}" = latest ]; then REL='latest/download'; else REL="download/v\${PANTRY_VERSION}"; fi; TMP=$(mktemp -d); curl -fsSL -o "\${TMP}/\${ZIP}" "https://github.com/pantry-pm/pantry/releases/\${REL}/\${ZIP}"; mkdir -p ${t}; unzip -o "\${TMP}/\${ZIP}" -d ${t}; chmod +x ${t}/pantry; rm -rf "\${TMP}"`,`export PATH="${t}:$PATH"`,"mkdir -p /opt/pantry"]}function Ve(){return'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true'}function it(e){if(e.length===0)return[];return[`(cd /opt/pantry && pantry install ${[...new Set(e)].map(M).join(" ")})`]}function Io(e){return[...new Set(e)].flatMap((t)=>[`(cd /opt/pantry && pantry start ${M(t)})`,`(cd /opt/pantry && pantry enable ${M(t)})`])}var m="/etc/mail",T="mail-server",q="mail",F=`${R}/pantry/.bin`;function h(e){return`'${String(e).split("'").join("'\\''")}'`}function P(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function ge(e){return[e.version?`${L.mail}@${e.version}`:L.mail]}function Y(e,t){return`${m}/dkim/${t}.${e.dkim.selector}.pem`}function re(e){return`${e.storagePath}/smtp.db`}function Te(e){let t=["# Generated by ts-cloud. Edits are overwritten on the next deploy —","# change `services.mail` in the cloud config instead.","","[server]",`host = ${P(e.bindAddress)}`,`port = ${e.ports.smtp}`,`hostname = ${P(e.hostname)}`];if(e.domains.length>0)t.push(`local_domains = ${P(e.domains.join(", "))}`);if(e.mode==="catcher")t.push("catch_all = true");if(t.push(`max_message_size = ${e.maxMessageSize}`,"","[tls]",`enabled = ${e.tls.enabled}`),e.tls.certPath)t.push(`cert_path = ${P(e.tls.certPath)}`);if(e.tls.keyPath)t.push(`key_path = ${P(e.tls.keyPath)}`);if(t.push("","[auth]",`enabled = ${e.mode==="server"}`,"","[antispam]",`dnsbl = ${e.spam.dnsbl}`,`dnsbl_reject = ${e.spam.dnsblReject}`,`greylist = ${e.spam.greylist}`,`spam_filter = ${e.spam.enabled}`,`junk_score = ${e.spam.junkScore}`,`reject_score = ${e.spam.rejectScore}`,"","[dkim]",`rotation_enabled = ${e.dkim.enabled&&e.dkim.rotate}`,`rotation_interval_days = ${e.dkim.rotateIntervalDays}`,"","[acme]",`enabled = ${e.tls.acme}`),e.tls.acmeEmail)t.push(`email = ${P(e.tls.acmeEmail)}`);if(t.push("","[webhook]",`enabled = ${!!e.webhookUrl}`),e.webhookUrl)t.push(`url = ${P(e.webhookUrl)}`);return t.push(""),t.join(`
1
+ import{H,Fr}from"./chunk-wayhpmn7.js";function W(e,t){return`/var/www/${e}-${t}`}var me=new Set(["laravel","php","statamic","wordpress"]);function ki(e){return e.type!=null&&me.has(e.type)}function Us(e){let t=e.proxyTo;if(t==null)return[];return(Array.isArray(t)?t:[t]).map((n)=>String(n).trim()).filter((n)=>n.length>0)}function fe(e){return Us(e).length>0}function te(e){if(e.deploy)return e.deploy;if(ki(e))return"server";if(e.start)return"server";return"bucket"}function w(e){if(e.redirect)return"redirect";if(fe(e))return"proxy";if(ki(e))return"server-php";if(te(e)==="bucket")return"bucket";return e.start?"server-app":"server-static"}function Ro(e){return e.infrastructure?.compute!=null||Boolean(e.cloud?.attachTo?.trim())}function Bs(e,t={}){let r=[],n=[],o=e.sites||{},s=Ro(e),c=Fr(e);if(c)r.push(c);let p=new Map;for(let[l,i]of Object.entries(o)){if(!i)continue;let f=te(i),P=w(i);if(P==="redirect"){if(!i.domain)r.push(`Site '${l}' is a redirect site but has no \`domain\` to redirect from.`);if(!(typeof i.redirect==="string"?i.redirect:i.redirect?.to))r.push(`Site '${l}' is a redirect site but has no redirect target (\`redirect\` / \`redirect.to\`).`);if(!s)r.push(`Site '${l}' is a redirect site but no \`infrastructure.compute\` is configured to host the gateway that serves the redirect.`);let a=[];if(i.start)a.push("start");if(i.root)a.push("root");if(i.proxyTo)a.push("proxyTo");if(a.length>0)n.push(`Site '${l}' is a redirect site but also sets ${a.join(", ")}. These are ignored.`);continue}if(P==="proxy"){if(!i.domain)r.push(`Site '${l}' is a proxy site but has no \`domain\` to route from.`);if(!s)r.push(`Site '${l}' is a proxy site but no \`infrastructure.compute\` is configured to host the gateway that forwards it.`);let u=[];if(i.start)u.push("start");if(i.root)u.push("root");if(typeof i.port==="number")u.push("port");if(i.build)u.push("build");if(i.preStart&&i.preStart.length>0)u.push("preStart");if(u.length>0)n.push(`Site '${l}' sets \`proxyTo\`, so ts-cloud ships and supervises nothing for it. ${u.join(", ")} ${u.length===1?"is":"are"} ignored — remove ${u.length===1?"it":"them"}, or drop \`proxyTo\` to let ts-cloud own the service.`);continue}if(f==="server"&&!i.start&&!i.root){r.push(`Site '${l}' sets deploy:'server' but declares neither \`start\` (dynamic app) nor \`root\` (static site to serve). Add one.`);continue}if(P==="server-php"){if(!s)r.push(`Site '${l}' is a PHP site (type:'${i.type}') but no \`infrastructure.compute\` is configured. Add a server (infrastructure.compute) with PHP provisioning.`);if(!i.repository?.url)r.push(`Site '${l}' is a PHP site (type:'${i.type}') but has no \`repository.url\` to clone. PHP sites deploy via git.`)}else if(P==="server-app"){if(!s)r.push(`Site '${l}' deploys to a server (deploy:'server'${i.deploy?"":" inferred from `start`"}) but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`);if(typeof i.port==="number"){let u=t.occupiedPorts?.get(i.port);if(u)r.push(`Site '${l}' wants port ${i.port}, which project '${u}' already serves on this box. Attached projects share one port namespace. Give '${l}' a free port, or let the attach allocate one.`);let a=p.get(i.port);if(a)r.push(`Sites '${a}' and '${l}' both use port ${i.port}. Server apps sharing a box must use distinct ports.`);else p.set(i.port,l)}}else if(P==="server-static"){if(!i.root)r.push(`Site '${l}' is a server static site (deploy:'server', no \`start\`) but has no \`root\` directory to serve.`);if(!s)r.push(`Site '${l}' deploys to a server (deploy:'server') but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`)}else{if(!i.root)r.push(`Site '${l}' deploys to a bucket but has no \`root\` directory to upload.`);let u=[];if(i.start)u.push("start");if(typeof i.port==="number")u.push("port");if(i.preStart&&i.preStart.length>0)u.push("preStart");if(u.length>0)n.push(`Site '${l}' deploys to a bucket but sets server-only field(s): ${u.join(", ")}. These are ignored. Set deploy:'server' to use them.`)}}return{errors:r,warnings:n}}function Fs(e){let t=w(e);return t!=="bucket"&&t!=="redirect"&&t!=="proxy"}function qc(e){return w(e)==="bucket"}function Wc(e,t){if(H(e)==="serverless")return!0;let r=Object.entries(e.sites??{}).filter(([,o])=>o!=null),n=t?r.filter(([o])=>o===t):r;if(n.length===0)return!0;return!n.every(([,o])=>{let s=w(o);return s==="redirect"||s==="proxy"})}var b={php:"php.net",nginx:"nginx.org",composer:"getcomposer.org",mysql:"mysql.com",mariadb:"mariadb.com/server",postgres:"postgresql.org",vitess:"vitess.io",etcd:"etcd.io",redis:"redis.io",memcached:"memcached.org",meilisearch:"meilisearch.com",mail:"github.com/mail-os/mail",git:"git-scm.com",certbot:"certbot.eff.org",bun:"bun.sh",node:"nodejs.org",deno:"deno.land"};var R="/opt/pantry";function M(e){return`'${e.split("'").join("'\\''")}'`}function Tt(e={}){let t=e.installDir??"/usr/local/bin",r=e.version?`export PANTRY_VERSION=${M(e.version)}`:'export PANTRY_VERSION="${PANTRY_VERSION:-latest}"';return["export DEBIAN_FRONTEND=noninteractive","export PANTRY_SERVICE_SCOPE=system",`export PANTRY_INSTALL_DIR=${t}`,r,"command -v curl >/dev/null 2>&1 || (apt-get update -y && apt-get install -y curl ca-certificates)","command -v unzip >/dev/null 2>&1 || (apt-get update -y && apt-get install -y unzip)",`OS=$(uname -s | tr '[:upper:]' '[:lower:]'); ARCH=$(uname -m); case "$ARCH" in x86_64|amd64) ARCH=x64 ;; arm64|aarch64) ARCH=arm64 ;; esac; ZIP="pantry-\${OS}-\${ARCH}.zip"; if [ "\${PANTRY_VERSION:-latest}" = latest ]; then REL='latest/download'; else REL="download/v\${PANTRY_VERSION}"; fi; TMP=$(mktemp -d); curl -fsSL -o "\${TMP}/\${ZIP}" "https://github.com/pantry-pm/pantry/releases/\${REL}/\${ZIP}"; mkdir -p ${t}; unzip -o "\${TMP}/\${ZIP}" -d ${t}; chmod +x ${t}/pantry; rm -rf "\${TMP}"`,`export PATH="${t}:$PATH"`,"mkdir -p /opt/pantry"]}function Ve(){return'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true'}function it(e){if(e.length===0)return[];return[`(cd /opt/pantry && pantry install ${[...new Set(e)].map(M).join(" ")})`]}function Io(e){return[...new Set(e)].flatMap((t)=>[`(cd /opt/pantry && pantry start ${M(t)})`,`(cd /opt/pantry && pantry enable ${M(t)})`])}var m="/etc/mail",g="mail-server",q="mail",F=`${R}/pantry/.bin`;function h(e){return`'${String(e).split("'").join("'\\''")}'`}function C(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function Te(e){return[e.version?`${b.mail}@${e.version}`:b.mail]}function Y(e,t){return`${m}/dkim/${t}.${e.dkim.selector}.pem`}function re(e){return`${e.storagePath}/smtp.db`}function ge(e){let t=["# Generated by ts-cloud. Edits are overwritten on the next deploy —","# change `services.mail` in the cloud config instead.","","[server]",`host = ${C(e.bindAddress)}`,`port = ${e.ports.smtp}`,`hostname = ${C(e.hostname)}`];if(e.domains.length>0)t.push(`local_domains = ${C(e.domains.join(", "))}`);if(e.mode==="catcher")t.push("catch_all = true");if(t.push(`max_message_size = ${e.maxMessageSize}`,"","[tls]",`enabled = ${e.tls.enabled}`),e.tls.certPath)t.push(`cert_path = ${C(e.tls.certPath)}`);if(e.tls.keyPath)t.push(`key_path = ${C(e.tls.keyPath)}`);if(t.push("","[auth]",`enabled = ${e.mode==="server"}`,"","[antispam]",`dnsbl = ${e.spam.dnsbl}`,`dnsbl_reject = ${e.spam.dnsblReject}`,`greylist = ${e.spam.greylist}`,`spam_filter = ${e.spam.enabled}`,`junk_score = ${e.spam.junkScore}`,`reject_score = ${e.spam.rejectScore}`,"","[dkim]",`rotation_enabled = ${e.dkim.enabled&&e.dkim.rotate}`,`rotation_interval_days = ${e.dkim.rotateIntervalDays}`,"","[acme]",`enabled = ${e.tls.acme}`),e.tls.acmeEmail)t.push(`email = ${C(e.tls.acmeEmail)}`);if(t.push("","[webhook]",`enabled = ${!!e.webhookUrl}`),e.webhookUrl)t.push(`url = ${C(e.webhookUrl)}`);return t.push(""),t.join(`
2
2
  `)}function he(e){let t=["# Generated by ts-cloud. See /etc/mail/config.toml for the rest.",`SMTP_DB_PATH=${re(e)}`,`SMTP_DNSBL_REJECT=${e.spam.dnsblReject}`,`SMTP_DELIVERY_METHOD=${e.delivery==="ses"?"ses":"direct"}`];if(e.delivery==="ses")t.push(`SMTP_SES_REGION=${e.sesRegion}`);if(e.ports.submission)t.push(`SUBMISSION_PORT=${e.ports.submission}`);if(e.ports.submissions)t.push(`SMTPS_PORT=${e.ports.submissions}`);if(e.ports.imap)t.push("IMAP_ENABLED=1",`IMAP_PORT=${e.ports.imap}`);if(e.webmail.enabled)t.push("SMTP_ENABLE_WEBMAIL=true",`SMTP_WEBMAIL_PORT=${e.webmail.port}`,`SMTP_WEBMAIL_TLS=${e.webmail.tls}`,`SMTP_WEBMAIL_SECURE_COOKIES=${e.webmail.secureCookies}`,`SMTP_WEBMAIL_ATTACHMENT_MAX_FILE=${e.webmail.attachmentMaxFileBytes}`,`SMTP_WEBMAIL_ATTACHMENT_MAX_TOTAL=${e.webmail.attachmentMaxTotalBytes}`,`SMTP_WEBMAIL_ATTACHMENT_MAX_COUNT=${e.webmail.attachmentMaxCount}`,`SMTP_WEBMAIL_UNDO_SEND_SECONDS=${e.webmail.undoSendSeconds}`);if(e.tls.requireForAuth)t.push("SMTP_REQUIRE_TLS_FOR_AUTH=true");if(e.dkim.enabled&&e.domains.length>0){let[r,...n]=e.domains;if(t.push(`DKIM_DOMAIN=${r}`,`DKIM_SELECTOR=${e.dkim.selector}`,`DKIM_PRIVATE_KEY_PATH=${Y(e,r)}`),n.length>0){let o=n.map((s)=>`${s}:${e.dkim.selector}:${Y(e,s)}`);t.push(`DKIM_EXTRA_KEYS=${o.join(",")}`)}}return t.push(""),t.join(`
3
- `)}function Ee(e){let t=[e.ports.smtp,e.ports.submission,e.ports.submissions,e.ports.imap,e.ports.imaps].some((r)=>typeof r==="number"&&r<1024);return["[Unit]","Description=Mail server (SMTP/IMAP + webmail)","After=network-online.target","Wants=network-online.target","","[Service]","Type=simple",`User=${T}`,`Group=${T}`,`WorkingDirectory=${e.storagePath}`,`EnvironmentFile=${m}/mail.env`,`Environment="PATH=${F}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"`,`ExecStart=${F}/mail serve --config ${m}/config.toml`,"Restart=always","RestartSec=5","LimitNOFILE=65536",...t?["AmbientCapabilities=CAP_NET_BIND_SERVICE","CapabilityBoundingSet=CAP_NET_BIND_SERVICE"]:[],"NoNewPrivileges=true","PrivateTmp=true","ProtectSystem=strict","ProtectHome=true","ProtectKernelTunables=true","ProtectKernelModules=true","ProtectControlGroups=true",`ReadWritePaths=${e.storagePath} ${m}`,"","[Install]","WantedBy=multi-user.target",""].join(`
4
- `)}function ye(e){if(!e.dkim.enabled||e.domains.length===0)return[];let t=[`mkdir -p ${m}/dkim`];for(let r of e.domains){let n=Y(e,r);t.push(`if [ ! -f ${h(n)} ]; then openssl genrsa -out ${h(n)} 2048; fi`,`chmod 0600 ${h(n)}`,`echo "DKIM ${e.dkim.selector}._domainkey.${r} IN TXT v=DKIM1; k=rsa; p=$(openssl rsa -in ${h(n)} -pubout -outform PEM 2>/dev/null | grep -v '^-----' | tr -d '\\n')"`)}return t.push(`chown -R ${T}:${T} ${m}/dkim`),t}function ve(e){if(e.accounts.length===0)return[];let t=(r)=>`runuser -u ${T} -- env SMTP_DB_PATH="$TS_CLOUD_MAIL_DB" ${F}/mail user:local ${r}`;return e.accounts.flatMap((r)=>[t(`create ${h(r.address)} ${h(r.password)} ${h(r.address)}`),...r.passwordPolicy==="managed"?[t(`change-password ${h(r.address)} ${h(r.password)}`)]:[]])}function ne(e){if(!e.enabled)return[];return[...it(ge(e)),`id -u ${T} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin ${T}`,`mkdir -p ${e.storagePath} ${m}`,`chown -R ${T}:${T} ${e.storagePath}`,`TS_CLOUD_MAIL_DB="$(grep -sE '^SMTP_DB_PATH=' ${m}/mail.env | head -1 | cut -d= -f2- || true)"`,`[ -n "$TS_CLOUD_MAIL_DB" ] || TS_CLOUD_MAIL_DB=${h(re(e))}`,`cat > ${m}/config.toml <<'TS_CLOUD_MAIL_CONF_EOF'`,Te(e),"TS_CLOUD_MAIL_CONF_EOF",`cat > ${m}/mail.env <<'TS_CLOUD_MAIL_ENV_EOF'`,he(e),"TS_CLOUD_MAIL_ENV_EOF",`sed -i "s|^SMTP_DB_PATH=.*|SMTP_DB_PATH=$TS_CLOUD_MAIL_DB|" ${m}/mail.env`,`chmod 0640 ${m}/mail.env`,`chown root:${T} ${m}/mail.env`,...ye(e),`cat > /etc/systemd/system/${q}.service <<'TS_CLOUD_MAIL_UNIT_EOF'`,Ee(e),"TS_CLOUD_MAIL_UNIT_EOF","systemctl daemon-reload",`systemctl enable ${q}`,`systemctl restart ${q}`,...ve(e)]}var g=`${R}/pantry/.bin`,X=15306,K=15991,N=15999,se=16101,B=2379,E="/var/lib/vitess",z=100;function ki(e){return e===!0||typeof e==="object"&&e!==null}function Ce(e){return typeof e==="object"&&e!==null?e:{}}function _(e){return`'${String(e).split("'").join("'\\''")}'`}function Re(e){let r=[e.version?`vitess.io@${e.version}`:"vitess.io"];if(e.mode!=="combo"&&!e.etcdEndpoint)r.push("etcd.io");return r.push("mysql.com@8.0.43"),r}var S="vitess",Pe=`${g}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`,ce="/usr/local/lib/vitess",Q=new Map;function j(e){return`${ce}/${e}.sh`}function D(e,t){return Q.set(e,be(t)),`/bin/sh ${j(e)}`}function oe(){let e=[`mkdir -p ${ce}`];for(let[t,r]of Q)e.push(`cat > ${j(t)} <<'TS_CLOUD_VITESS_LAUNCHER_EOF'`,r,"TS_CLOUD_VITESS_LAUNCHER_EOF",`chmod 0755 ${j(t)}`);return e}function be(e){return["#!/bin/sh","set -e",`cd ${R}`,`PANTRY_ENV="$(pantry env 2>/dev/null | grep -E '^(export [A-Za-z_]|[A-Za-z_][A-Za-z0-9_]*=)' || true)"`,'if [ -n "$PANTRY_ENV" ]; then eval "$PANTRY_ENV"; fi',`VT_MYSQL_ROOT="$(dirname "$(dirname "$(readlink -f ${g}/mysqld 2>/dev/null)")")"`,`VTROOT="$(dirname "$(dirname "$(readlink -f ${g}/mysqlctld 2>/dev/null)")")"`,"export VT_MYSQL_ROOT VTROOT",'LD_LIBRARY_PATH="$VT_MYSQL_ROOT/lib:$VTROOT/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"',"export LD_LIBRARY_PATH",`exec ${e.join(" ")}`].join(`
5
- `)}function A(e){let t=["[Unit]",`Description=${e.description}`,`After=network.target${e.after?.length?` ${e.after.join(" ")}`:""}`];if(e.requires?.length)t.push(`Requires=${e.requires.join(" ")}`);return t.push("","[Service]","Type=simple",`User=${S}`,`Group=${S}`,`Environment="PATH=${Pe}"`,`Environment="VTDATAROOT=${E}"`,...Object.entries(e.environment??{}).map(([r,n])=>`Environment="${r}=${n}"`),...(e.execStartPre??[]).map((r)=>`ExecStartPre=${r}`),`ExecStart=${e.execStart}`,"Restart=always","RestartSec=5","LimitNOFILE=65535","","[Install]","WantedBy=multi-user.target"),t.join(`
6
- `)}function ie(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_VITESS_UNIT_EOF'`,t,"TS_CLOUD_VITESS_UNIT_EOF"]}function De(e){let t=e.cell??"zone1",r=e.vtgatePort??X,o=`${((e.keyspaces?.length)?e.keyspaces:[{name:"app"}]).map((s)=>{let c=(s.sharded?["-80","80-"]:["0"]).map((p)=>`shards:{name:"${p}"}`).join(" ");return`keyspaces:{name:"${s.name}" ${c}}`}).join(" ")} cells:"${t}"`;return A({description:"Vitess (vtcombo, single-process development stack)",execStart:D("vtcombo",[`${g}/vtcombo`,`--cell ${t}`,`--proto-topo ${_(o)}`,`--mysql-server-port ${r}`,"--mysql-server-bind-address 127.0.0.1","--mysql-auth-server-impl none","--start-mysql",`--port ${K}`,`--grpc-port ${N}`])})}function Ae(){return A({description:"etcd (Vitess topology store)",execStart:D("etcd",[`${g}/etcd`,`--data-dir ${E}/etcd`,`--listen-client-urls http://127.0.0.1:${B}`,`--advertise-client-urls http://127.0.0.1:${B}`]),execStartPre:[`+/bin/mkdir -p ${E}/etcd`,`+/bin/chown ${S}:${S} ${E}/etcd`]})}function J(e){return["--topo-implementation etcd2",`--topo-global-server-address ${e.etcdEndpoint??`http://127.0.0.1:${B}`}`,"--topo-global-root /vitess/global"]}function Oe(e){let t=!e.etcdEndpoint;return A({description:"Vitess vtctld (control plane)",after:t?["vitess-etcd.service"]:[],requires:t?["vitess-etcd.service"]:[],execStart:D("vtctld",[`${g}/vtctld`,...J(e),`--cell ${e.cell??"zone1"}`,"--service-map grpc-vtctl,grpc-vtctld",`--grpc-port ${N}`,`--port ${N+1}`])})}function Le(e,t,r){let n=e.cell??"zone1";return A({description:`Vitess vttablet (${t}/${r})`,after:["vitess-vtctld.service","vitess-mysqlctld.service"],requires:["vitess-mysqlctld.service"],execStart:D("vttablet",[`${g}/vttablet`,...J(e),`--tablet-path ${n}-${String(z).padStart(10,"0")}`,`--init-keyspace ${t}`,`--init-shard ${r}`,"--init-tablet-type replica",`--service-map ${_("grpc-queryservice,grpc-tabletmanager,grpc-updatestream")}`,`--port ${se}`,`--grpc-port ${se+1}`,`--db-port ${e.mysqlPort??3306}`,`--mycnf-mysql-port ${e.mysqlPort??3306}`])})}function Ue(e){return A({description:"Vitess mysqlctld (managed mysqld)",execStart:D("mysqlctld",[`${g}/mysqlctld`,`--tablet-uid ${z}`,`--mysql-port ${e.mysqlPort??3306}`,'--init-db-sql-file "$VTROOT/config/init_db.sql"',"--wait-time 2m"]),execStartPre:[`+/bin/mkdir -p ${E}`,`+/bin/chown ${S}:${S} ${E}`]})}var le="/etc/vitess/auth.json",U="/var/lib/vitess/vtgate-auth.sha256";function xe(e){let t=e.username??"vitess",r=e.password??"";return["mkdir -p /etc/vitess",'VTESS_AUTH_TMP="$(mktemp)"',`cat > "$VTESS_AUTH_TMP" <<'TS_CLOUD_VITESS_AUTH_EOF'`,JSON.stringify({[t]:[{Password:r,UserData:t}]}),"TS_CLOUD_VITESS_AUTH_EOF",`VTESS_VTGATE_AUTH_SHA="$(sha256sum "$VTESS_AUTH_TMP" | awk '{print $1}')"`,"VTESS_VTGATE_AUTH_CHANGED=1",`if [ -f ${U} ] && [ "$(cat ${U})" = "$VTESS_VTGATE_AUTH_SHA" ]; then VTESS_VTGATE_AUTH_CHANGED=0; fi`,`install -o ${S} -g ${S} -m 0600 "$VTESS_AUTH_TMP" ${le}`,'rm -f "$VTESS_AUTH_TMP"']}function Ie(e){let t=e.cell??"zone1";return A({description:"Vitess vtgate (query router)",after:["vitess-vtctld.service"],execStart:D("vtgate",[`${g}/vtgate`,...J(e),`--cell ${t}`,`--cells-to-watch ${t}`,"--tablet-types-to-wait PRIMARY,REPLICA",`--service-map ${_("grpc-vtgateservice")}`,`--mysql-server-port ${e.vtgatePort??X}`,`--mysql-server-bind-address ${e.bindAddress??"127.0.0.1"}`,"--mysql-auth-server-impl static",`--mysql-auth-server-static-file ${le}`,`--port ${K}`,`--grpc-port ${K+1}`])})}function ke(e){let t=e.cell??"zone1",r=e.etcdEndpoint??`http://127.0.0.1:${B}`,n=`${g}/vtctldclient --server 127.0.0.1:${N}`,o=[`for i in $(seq 1 30); do ${n} GetCellInfoNames >/dev/null 2>&1 && break; sleep 2; done`,`if ! ${n} GetCellInfoNames 2>/dev/null | grep -qx ${_(t)}; then`,` ${n} AddCellInfo --root ${_(`/vitess/${t}`)} --server-address ${_(r)} ${_(t)}`,"fi"];for(let s of e.keyspaces??[]){let c=s.sharded?" --sharded":"";o.push(`if ! ${n} GetKeyspace ${_(s.name)} >/dev/null 2>&1; then`,` ${n} CreateKeyspace${c} ${_(s.name)}`,"fi");let p=`${t}-${String(z).padStart(10,"0")}`;for(let l of s.sharded?["-80","80-"]:["0"]){let i=`${s.name}/${l}`;o.push("for i in $(seq 1 90); do",` if ${n} GetShard ${_(i)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then break; fi`,` ${n} PlannedReparentShard ${_(i)} --new-primary ${_(p)} >/dev/null 2>&1 && break`,` ${n} InitShardPrimary --force ${_(i)} ${_(p)} >/dev/null 2>&1 && break`," sleep 2","done",`if ! ${n} GetShard ${_(i)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then`,` echo "no primary could be elected for ${i}" >&2; exit 1`,"fi")}o.push(`${n} RebuildKeyspaceGraph ${_(s.name)} >/dev/null`)}return o}function ae(e){let t=e.vtgatePort??X;return["for i in $(seq 1 60); do",` if (cd ${R} && eval "$(pantry env 2>/dev/null)"; MYSQL_PWD=${_(e.password??"")} ${g}/mysql -h 127.0.0.1 -P ${t} -u ${_(e.username??"vitess")} --connect-timeout=2 -e 'SHOW KEYSPACES') >/dev/null 2>&1; then`,` echo "vtgate is serving on ${t}"; exit 0`," fi"," sleep 2","done",`echo "vtgate did not become ready on port ${t}" >&2`,"exit 1"]}function Po(e){if(!ki(e))return[];let t=Ce(e),r=t.mode==="combo";Q.clear();let n=['if [ "$(uname -m)" != "x86_64" ]; then',' echo "vitess: Vitess publishes only x86_64 release tarballs; this box is $(uname -m). Drop managedServices.vitess or use an x86_64 host." >&2'," exit 1","fi",...it(Re(t)),`VT_MYSQL_LIB="$(dirname "$(dirname "$(readlink -f ${g}/mysqld)")")/lib"`,'if [ -d "$VT_MYSQL_LIB" ]; then',` printf '%s\\n' "$VT_MYSQL_LIB" > /etc/ld.so.conf.d/vitess-mysql.conf`," ldconfig","else",' echo "mysqld library directory not found under $VT_MYSQL_LIB" >&2; exit 1',"fi",`id -u ${S} >/dev/null 2>&1 || useradd --system --home-dir ${E} --shell /usr/sbin/nologin ${S}`,`mkdir -p ${E}`,`chown -R ${S}:${S} ${E}`];if(r)return n.push(...ie("vitess-vtcombo",De(t)),...oe(),"systemctl daemon-reload","systemctl enable --now vitess-vtcombo.service",...ae(t)),n;n.push(...xe(t));let o=[];if(!t.etcdEndpoint)o.push(["vitess-etcd",Ae()]);o.push(["vitess-vtctld",Oe(t)],["vitess-mysqlctld",Ue(t)],["vitess-vtgate",Ie(t)]);for(let s of t.keyspaces??[])for(let c of s.sharded?["-80","80-"]:["0"])o.push([`vitess-vttablet-${s.name}-${c.replace(/-/g,"x")}`,Le(t,s.name,c)]);for(let[s,c]of o)n.push(...ie(s,c));n.push(...oe()),n.push("systemctl daemon-reload");for(let[s]of o)n.push(`systemctl enable --now ${s}.service`);return n.push(`if [ "$VTESS_VTGATE_AUTH_CHANGED" = 1 ]; then systemctl restart vitess-vtgate.service; printf '%s\\n' "$VTESS_VTGATE_AUTH_SHA" > ${U}; chown ${S}:${S} ${U}; chmod 0600 ${U}; fi`,...ke(t),...ae(t)),n}var Me=new Set(["singlestore","vitess"]);function Ni(e){if(e?.engine&&Me.has(e.engine))return!1;return!e?.host||e.host==="127.0.0.1"||e.host==="localhost"}function Pr(e,t="psql"){let r=e?.port??5432;if(Ni(e))return`${t} -p ${r} -U postgres`;let n=e?.username||"postgres";return`${e?.password?`PGPASSWORD='${e.password.replace(/'/g,"'\\''")}' `:""}${t} -h ${e.host} -p ${r} -U ${n} -w`}function y(e){return e===!0||typeof e==="object"&&e!=null}function Ne(e){let t=[],r=[];if(y(e.mysql))t.push(typeof e.mysql==="object"&&e.mysql.version?`mysql.com@${e.mysql.version}`:"mysql.com@8.0.43"),r.push("mysql");else if(y(e.mariadb))t.push(L.mariadb),r.push("mariadb");if(y(e.postgres))t.push("postgresql.org"),r.push("postgres");if(y(e.redis))t.push("redis.io"),r.push("redis");if(y(e.memcached))t.push("memcached.org"),r.push("memcached");if(y(e.meilisearch))t.push("meilisearch.com"),r.push("meilisearch");return{packages:t,services:r}}function Do(e={},t={}){let r=Ne(e),n=Po(e.vitess),o=t.mail?ne(t.mail):[];if(r.packages.length===0)return[...n,...o];return[...it(r.packages),...Io(r.services),...n,...o]}function Et(e,t={}){if(!e?.name)return[];if(!Ni(e))return[];let r=e.name,n=e.username||r,o=e.password||"",s=y(t.postgres)||e.engine==="postgres",c=y(t.mariadb)||e.engine==="mariadb",p=y(t.mysql)||e.engine==="mysql";if(s&&!p&&!c){let a=(d)=>`"${d.replace(/"/g,'""')}"`,b=(d)=>`'${d.replace(/'/g,"''")}'`,O=(d,k)=>["DO $$ BEGIN",` IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${b(d)}) THEN`,` CREATE ROLE ${a(d)} LOGIN PASSWORD ${b(k)};`," ELSE",` ALTER ROLE ${a(d)} LOGIN PASSWORD ${b(k)};`," END IF;","END $$;"],x=(d)=>{let k=d.databases&&d.databases.length>0?d.databases:[r],V=[];for(let G of k)if(d.access==="readonly")V.push(`GRANT CONNECT ON DATABASE ${a(G)} TO ${a(d.username)};`,`\\connect ${a(G)}`,`GRANT USAGE ON SCHEMA public TO ${a(d.username)};`,`GRANT SELECT ON ALL TABLES IN SCHEMA public TO ${a(d.username)};`,`ALTER DEFAULT PRIVILEGES FOR ROLE ${a(n)} IN SCHEMA public GRANT SELECT ON TABLES TO ${a(d.username)};`,"\\connect postgres");else V.push(`GRANT ALL PRIVILEGES ON DATABASE ${a(G)} TO ${a(d.username)};`);return V},I=e.users||[],Se=e.port??5432;return[Ve(),`for i in $(seq 1 30); do pg_isready -p ${Se} -q && break; sleep 2; done`,`${Pr(e)} <<'TS_CLOUD_PG_EOF'`,...O(n,o),`SELECT 'CREATE DATABASE ${a(r)} OWNER ${a(n)}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = ${b(r)})\\gexec`,...I.flatMap((d)=>[...O(d.username,d.password),...x(d)]),"TS_CLOUD_PG_EOF",...Be(e)]}let l=c?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock",i=(a)=>a.replace(/`/g,"``"),f=(a)=>a.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),C=(a)=>{let b=a.databases&&a.databases.length>0?a.databases:[r],O=a.access==="readonly"?"SELECT":"ALL PRIVILEGES",x=[`CREATE USER IF NOT EXISTS '${f(a.username)}'@'%' IDENTIFIED BY '${f(a.password)}';`,`CREATE USER IF NOT EXISTS '${f(a.username)}'@'localhost' IDENTIFIED BY '${f(a.password)}';`,`ALTER USER '${f(a.username)}'@'%' IDENTIFIED BY '${f(a.password)}';`,`ALTER USER '${f(a.username)}'@'localhost' IDENTIFIED BY '${f(a.password)}';`];for(let I of b)x.push(`GRANT ${O} ON \`${i(I)}\`.* TO '${f(a.username)}'@'%';`,`GRANT ${O} ON \`${i(I)}\`.* TO '${f(a.username)}'@'localhost';`);return x},u=e.users||[];return[Ve(),`for i in $(seq 1 30); do mysqladmin --socket=${l} -u root ping 2>/dev/null | grep -q alive && break; sleep 2; done`,`mysql --socket=${l} -u root <<'TS_CLOUD_SQL_EOF'`,`CREATE DATABASE IF NOT EXISTS \`${i(r)}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`,...C({username:n,password:o}),...u.flatMap(C),"FLUSH PRIVILEGES;","TS_CLOUD_SQL_EOF"]}function Be(e){return[`${Pr(e)} -tA <<'TS_CLOUD_PG_CAP_EOF' || true`,"\\set QUIET on","SELECT CASE WHEN used::float / NULLIF(cap, 0) >= 0.8"," THEN '[ts-cloud] postgres is at ' || used || '/' || cap || ' connections on this server.'"," || ' Raise max_connections (ALTER SYSTEM SET max_connections = ...; then restart) or'"," || ' set idle_session_timeout so abandoned pools are reclaimed.'"," ELSE NULL END","FROM (SELECT (SELECT count(*) FROM pg_stat_activity) AS used,"," (SELECT setting::int FROM pg_settings WHERE name = 'max_connections') AS cap) c","WHERE CASE WHEN used::float / NULLIF(cap, 0) >= 0.8 THEN true ELSE false END;","SELECT '[ts-cloud] ' || coalesce(datname, '(background)') || ': ' || count(*) || ' connection(s), oldest idle ' ||"," coalesce(round(extract(epoch from max(now() - state_change)) / 60)::text || 'm', 'n/a')","FROM pg_stat_activity","WHERE (SELECT count(*)::float / NULLIF((SELECT setting::int FROM pg_settings WHERE name = 'max_connections'), 0) FROM pg_stat_activity) >= 0.8","GROUP BY datname ORDER BY count(*) DESC;","TS_CLOUD_PG_CAP_EOF"]}function Kc(e){if(!e?.name)return{};let t=e.engine==="singlestore",r=e.engine==="vitess",n=e.engine==="postgres"?"pgsql":t?"singlestore":r?"vitess":"mysql",o=e.port??(e.engine==="postgres"?5432:r?15306:3306),s={DB_CONNECTION:n,DB_HOST:e.host||"127.0.0.1",DB_PORT:String(o),DB_DATABASE:e.name};if(e.username)s.DB_USERNAME=e.username;if(e.password)s.DB_PASSWORD=e.password;if((t||r)&&e.ssl!==!1)s.DB_SSL="true";return s}var Z="/var/backups/ts-cloud",we="/etc/ts-cloud/backups.config.ts",pe="/etc/cron.d/ts-cloud-backups",gn="/usr/local/bin/ts-cloud-backup.sh";function He(e){if(!e.name)return null;let t=e.host||"127.0.0.1",r=e.engine==="postgres",n=r?"postgresql":"mysql",o=e.port??(r?5432:3306),s=(c)=>c.replace(/\\/g,"\\\\").replace(/'/g,"\\'");return[" {",` type: '${n}',`,` name: '${s(e.name)}',`," connection: {",` hostname: '${s(t)}',`,` port: ${o},`,` database: '${s(e.name)}',`,` username: '${s(e.username||e.name)}',`,` password: '${s(e.password||"")}',`," ssl: false,"," },"," includeSchema: true,"," includeData: true,"," },"].join(`
3
+ `)}function Ee(e){let t=[e.ports.smtp,e.ports.submission,e.ports.submissions,e.ports.imap,e.ports.imaps].some((r)=>typeof r==="number"&&r<1024);return["[Unit]","Description=Mail server (SMTP/IMAP + webmail)","After=network-online.target","Wants=network-online.target","","[Service]","Type=simple",`User=${g}`,`Group=${g}`,`WorkingDirectory=${e.storagePath}`,`EnvironmentFile=${m}/mail.env`,`Environment="PATH=${F}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"`,`ExecStart=${F}/mail serve --config ${m}/config.toml`,"Restart=always","RestartSec=5","LimitNOFILE=65536",...t?["AmbientCapabilities=CAP_NET_BIND_SERVICE","CapabilityBoundingSet=CAP_NET_BIND_SERVICE"]:[],"NoNewPrivileges=true","PrivateTmp=true","ProtectSystem=strict","ProtectHome=true","ProtectKernelTunables=true","ProtectKernelModules=true","ProtectControlGroups=true",`ReadWritePaths=${e.storagePath} ${m}`,"","[Install]","WantedBy=multi-user.target",""].join(`
4
+ `)}function ye(e){if(!e.dkim.enabled||e.domains.length===0)return[];let t=[`mkdir -p ${m}/dkim`];for(let r of e.domains){let n=Y(e,r);t.push(`if [ ! -f ${h(n)} ]; then openssl genrsa -out ${h(n)} 2048; fi`,`chmod 0600 ${h(n)}`,`echo "DKIM ${e.dkim.selector}._domainkey.${r} IN TXT v=DKIM1; k=rsa; p=$(openssl rsa -in ${h(n)} -pubout -outform PEM 2>/dev/null | grep -v '^-----' | tr -d '\\n')"`)}return t.push(`chown -R ${g}:${g} ${m}/dkim`),t}function ve(e){if(e.accounts.length===0)return[];let t=(r)=>`runuser -u ${g} -- env SMTP_DB_PATH="$TS_CLOUD_MAIL_DB" ${F}/mail user:local ${r}`;return e.accounts.flatMap((r)=>[t(`create ${h(r.address)} ${h(r.password)} ${h(r.address)}`),...r.passwordPolicy==="managed"?[t(`change-password ${h(r.address)} ${h(r.password)}`)]:[]])}function ne(e){if(!e.enabled)return[];return[...it(Te(e)),`id -u ${g} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin ${g}`,`mkdir -p ${e.storagePath} ${m}`,`chown -R ${g}:${g} ${e.storagePath}`,`TS_CLOUD_MAIL_DB="$(grep -sE '^SMTP_DB_PATH=' ${m}/mail.env | head -1 | cut -d= -f2- || true)"`,`[ -n "$TS_CLOUD_MAIL_DB" ] || TS_CLOUD_MAIL_DB=${h(re(e))}`,`cat > ${m}/config.toml <<'TS_CLOUD_MAIL_CONF_EOF'`,ge(e),"TS_CLOUD_MAIL_CONF_EOF",`cat > ${m}/mail.env <<'TS_CLOUD_MAIL_ENV_EOF'`,he(e),"TS_CLOUD_MAIL_ENV_EOF",`sed -i "s|^SMTP_DB_PATH=.*|SMTP_DB_PATH=$TS_CLOUD_MAIL_DB|" ${m}/mail.env`,`chmod 0640 ${m}/mail.env`,`chown root:${g} ${m}/mail.env`,...ye(e),`cat > /etc/systemd/system/${q}.service <<'TS_CLOUD_MAIL_UNIT_EOF'`,Ee(e),"TS_CLOUD_MAIL_UNIT_EOF","systemctl daemon-reload",`systemctl enable ${q}`,`systemctl restart ${q}`,...ve(e)]}var T=`${R}/pantry/.bin`,X=15306,K=15991,N=15999,se=16101,B=2379,E="/var/lib/vitess",z=100;function Ni(e){return e===!0||typeof e==="object"&&e!==null}function Pe(e){return typeof e==="object"&&e!==null?e:{}}function _(e){return`'${String(e).split("'").join("'\\''")}'`}function Ce(e){let r=[e.version?`vitess.io@${e.version}`:"vitess.io"];if(e.mode!=="combo"&&!e.etcdEndpoint)r.push("etcd.io");return r.push("mysql.com@8.0.43"),r}var S="vitess",Re=`${T}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`,ce="/usr/local/lib/vitess",Q=new Map;function j(e){return`${ce}/${e}.sh`}function A(e,t){return Q.set(e,De(t)),`/bin/sh ${j(e)}`}function oe(){let e=[`mkdir -p ${ce}`];for(let[t,r]of Q)e.push(`cat > ${j(t)} <<'TS_CLOUD_VITESS_LAUNCHER_EOF'`,r,"TS_CLOUD_VITESS_LAUNCHER_EOF",`chmod 0755 ${j(t)}`);return e}function De(e){return["#!/bin/sh","set -e",`cd ${R}`,`PANTRY_ENV="$(pantry env 2>/dev/null | grep -E '^(export [A-Za-z_]|[A-Za-z_][A-Za-z0-9_]*=)' || true)"`,'if [ -n "$PANTRY_ENV" ]; then eval "$PANTRY_ENV"; fi',`VT_MYSQL_ROOT="$(dirname "$(dirname "$(readlink -f ${T}/mysqld 2>/dev/null)")")"`,`VTROOT="$(dirname "$(dirname "$(readlink -f ${T}/mysqlctld 2>/dev/null)")")"`,"export VT_MYSQL_ROOT VTROOT",'LD_LIBRARY_PATH="$VT_MYSQL_ROOT/lib:$VTROOT/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"',"export LD_LIBRARY_PATH",`exec ${e.join(" ")}`].join(`
5
+ `)}function O(e){let t=["[Unit]",`Description=${e.description}`,`After=network.target${e.after?.length?` ${e.after.join(" ")}`:""}`];if(e.requires?.length)t.push(`Requires=${e.requires.join(" ")}`);return t.push("","[Service]","Type=simple",`User=${S}`,`Group=${S}`,`Environment="PATH=${Re}"`,`Environment="VTDATAROOT=${E}"`,...Object.entries(e.environment??{}).map(([r,n])=>`Environment="${r}=${n}"`),...(e.execStartPre??[]).map((r)=>`ExecStartPre=${r}`),`ExecStart=${e.execStart}`,"Restart=always","RestartSec=5","LimitNOFILE=65535","","[Install]","WantedBy=multi-user.target"),t.join(`
6
+ `)}function ie(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_VITESS_UNIT_EOF'`,t,"TS_CLOUD_VITESS_UNIT_EOF"]}function Ae(e){let t=e.cell??"zone1",r=e.vtgatePort??X,o=`${((e.keyspaces?.length)?e.keyspaces:[{name:"app"}]).map((s)=>{let c=(s.sharded?["-80","80-"]:["0"]).map((p)=>`shards:{name:"${p}"}`).join(" ");return`keyspaces:{name:"${s.name}" ${c}}`}).join(" ")} cells:"${t}"`;return O({description:"Vitess (vtcombo, single-process development stack)",execStart:A("vtcombo",[`${T}/vtcombo`,`--cell ${t}`,`--proto-topo ${_(o)}`,`--mysql-server-port ${r}`,"--mysql-server-bind-address 127.0.0.1","--mysql-auth-server-impl none","--start-mysql",`--port ${K}`,`--grpc-port ${N}`])})}function Oe(){return O({description:"etcd (Vitess topology store)",execStart:A("etcd",[`${T}/etcd`,`--data-dir ${E}/etcd`,`--listen-client-urls http://127.0.0.1:${B}`,`--advertise-client-urls http://127.0.0.1:${B}`]),execStartPre:[`+/bin/mkdir -p ${E}/etcd`,`+/bin/chown ${S}:${S} ${E}/etcd`]})}function J(e){return["--topo-implementation etcd2",`--topo-global-server-address ${e.etcdEndpoint??`http://127.0.0.1:${B}`}`,"--topo-global-root /vitess/global"]}function Le(e){let t=!e.etcdEndpoint;return O({description:"Vitess vtctld (control plane)",after:t?["vitess-etcd.service"]:[],requires:t?["vitess-etcd.service"]:[],execStart:A("vtctld",[`${T}/vtctld`,...J(e),`--cell ${e.cell??"zone1"}`,"--service-map grpc-vtctl,grpc-vtctld",`--grpc-port ${N}`,`--port ${N+1}`])})}function be(e,t,r){let n=e.cell??"zone1";return O({description:`Vitess vttablet (${t}/${r})`,after:["vitess-vtctld.service","vitess-mysqlctld.service"],requires:["vitess-mysqlctld.service"],execStart:A("vttablet",[`${T}/vttablet`,...J(e),`--tablet-path ${n}-${String(z).padStart(10,"0")}`,`--init-keyspace ${t}`,`--init-shard ${r}`,"--init-tablet-type replica",`--service-map ${_("grpc-queryservice,grpc-tabletmanager,grpc-updatestream")}`,`--port ${se}`,`--grpc-port ${se+1}`,`--db-port ${e.mysqlPort??3306}`,`--mycnf-mysql-port ${e.mysqlPort??3306}`])})}function Ue(e){return O({description:"Vitess mysqlctld (managed mysqld)",execStart:A("mysqlctld",[`${T}/mysqlctld`,`--tablet-uid ${z}`,`--mysql-port ${e.mysqlPort??3306}`,'--init-db-sql-file "$VTROOT/config/init_db.sql"',"--wait-time 2m"]),execStartPre:[`+/bin/mkdir -p ${E}`,`+/bin/chown ${S}:${S} ${E}`]})}var le="/etc/vitess/auth.json",U="/var/lib/vitess/vtgate-auth.sha256";function xe(e){let t=e.username??"vitess",r=e.password??"";return["mkdir -p /etc/vitess",'VTESS_AUTH_TMP="$(mktemp)"',`cat > "$VTESS_AUTH_TMP" <<'TS_CLOUD_VITESS_AUTH_EOF'`,JSON.stringify({[t]:[{Password:r,UserData:t}]}),"TS_CLOUD_VITESS_AUTH_EOF",`VTESS_VTGATE_AUTH_SHA="$(sha256sum "$VTESS_AUTH_TMP" | awk '{print $1}')"`,"VTESS_VTGATE_AUTH_CHANGED=1",`if [ -f ${U} ] && [ "$(cat ${U})" = "$VTESS_VTGATE_AUTH_SHA" ]; then VTESS_VTGATE_AUTH_CHANGED=0; fi`,`install -o ${S} -g ${S} -m 0600 "$VTESS_AUTH_TMP" ${le}`,'rm -f "$VTESS_AUTH_TMP"']}function Ie(e){let t=e.cell??"zone1";return O({description:"Vitess vtgate (query router)",after:["vitess-vtctld.service"],execStart:A("vtgate",[`${T}/vtgate`,...J(e),`--cell ${t}`,`--cells-to-watch ${t}`,"--tablet-types-to-wait PRIMARY,REPLICA",`--service-map ${_("grpc-vtgateservice")}`,`--mysql-server-port ${e.vtgatePort??X}`,`--mysql-server-bind-address ${e.bindAddress??"127.0.0.1"}`,"--mysql-auth-server-impl static",`--mysql-auth-server-static-file ${le}`,`--port ${K}`,`--grpc-port ${K+1}`])})}function ke(e){let t=e.cell??"zone1",r=e.etcdEndpoint??`http://127.0.0.1:${B}`,n=`${T}/vtctldclient --server 127.0.0.1:${N}`,o=[`for i in $(seq 1 30); do ${n} GetCellInfoNames >/dev/null 2>&1 && break; sleep 2; done`,`if ! ${n} GetCellInfoNames 2>/dev/null | grep -qx ${_(t)}; then`,` ${n} AddCellInfo --root ${_(`/vitess/${t}`)} --server-address ${_(r)} ${_(t)}`,"fi"];for(let s of e.keyspaces??[]){let c=s.sharded?" --sharded":"";o.push(`if ! ${n} GetKeyspace ${_(s.name)} >/dev/null 2>&1; then`,` ${n} CreateKeyspace${c} ${_(s.name)}`,"fi");let p=`${t}-${String(z).padStart(10,"0")}`;for(let l of s.sharded?["-80","80-"]:["0"]){let i=`${s.name}/${l}`;o.push("for i in $(seq 1 90); do",` if ${n} GetShard ${_(i)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then break; fi`,` ${n} PlannedReparentShard ${_(i)} --new-primary ${_(p)} >/dev/null 2>&1 && break`,` ${n} InitShardPrimary --force ${_(i)} ${_(p)} >/dev/null 2>&1 && break`," sleep 2","done",`if ! ${n} GetShard ${_(i)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then`,` echo "no primary could be elected for ${i}" >&2; exit 1`,"fi")}o.push(`${n} RebuildKeyspaceGraph ${_(s.name)} >/dev/null`)}return o}function ae(e){let t=e.vtgatePort??X;return["for i in $(seq 1 60); do",` if (cd ${R} && eval "$(pantry env 2>/dev/null)"; MYSQL_PWD=${_(e.password??"")} ${T}/mysql -h 127.0.0.1 -P ${t} -u ${_(e.username??"vitess")} --connect-timeout=2 -e 'SHOW KEYSPACES') >/dev/null 2>&1; then`,` echo "vtgate is serving on ${t}"; exit 0`," fi"," sleep 2","done",`echo "vtgate did not become ready on port ${t}" >&2`,"exit 1"]}function Po(e){if(!Ni(e))return[];let t=Pe(e),r=t.mode==="combo";Q.clear();let n=['if [ "$(uname -m)" != "x86_64" ]; then',' echo "vitess: Vitess publishes only x86_64 release tarballs; this box is $(uname -m). Drop managedServices.vitess or use an x86_64 host." >&2'," exit 1","fi",...it(Ce(t)),`VT_MYSQL_LIB="$(dirname "$(dirname "$(readlink -f ${T}/mysqld)")")/lib"`,'if [ -d "$VT_MYSQL_LIB" ]; then',` printf '%s\\n' "$VT_MYSQL_LIB" > /etc/ld.so.conf.d/vitess-mysql.conf`," ldconfig","else",' echo "mysqld library directory not found under $VT_MYSQL_LIB" >&2; exit 1',"fi",`id -u ${S} >/dev/null 2>&1 || useradd --system --home-dir ${E} --shell /usr/sbin/nologin ${S}`,`mkdir -p ${E}`,`chown -R ${S}:${S} ${E}`];if(r)return n.push(...ie("vitess-vtcombo",Ae(t)),...oe(),"systemctl daemon-reload","systemctl enable --now vitess-vtcombo.service",...ae(t)),n;n.push(...xe(t));let o=[];if(!t.etcdEndpoint)o.push(["vitess-etcd",Oe()]);o.push(["vitess-vtctld",Le(t)],["vitess-mysqlctld",Ue(t)],["vitess-vtgate",Ie(t)]);for(let s of t.keyspaces??[])for(let c of s.sharded?["-80","80-"]:["0"])o.push([`vitess-vttablet-${s.name}-${c.replace(/-/g,"x")}`,be(t,s.name,c)]);for(let[s,c]of o)n.push(...ie(s,c));n.push(...oe()),n.push("systemctl daemon-reload");for(let[s]of o)n.push(`systemctl enable --now ${s}.service`);return n.push(`if [ "$VTESS_VTGATE_AUTH_CHANGED" = 1 ]; then systemctl restart vitess-vtgate.service; printf '%s\\n' "$VTESS_VTGATE_AUTH_SHA" > ${U}; chown ${S}:${S} ${U}; chmod 0600 ${U}; fi`,...ke(t),...ae(t)),n}var Me=new Set(["singlestore","vitess"]);function gn(e){if(e?.engine&&Me.has(e.engine))return!1;return!e?.host||e.host==="127.0.0.1"||e.host==="localhost"}function Et(e,t="psql"){let r=e?.port??5432;if(gn(e))return`${t} -p ${r} -U postgres`;let n=e?.username||"postgres";return`${e?.password?`PGPASSWORD='${e.password.replace(/'/g,"'\\''")}' `:""}${t} -h ${e.host} -p ${r} -U ${n} -w`}function y(e){return e===!0||typeof e==="object"&&e!=null}function Ne(e){let t=[],r=[];if(y(e.mysql))t.push(typeof e.mysql==="object"&&e.mysql.version?`mysql.com@${e.mysql.version}`:"mysql.com@8.0.43"),r.push("mysql");else if(y(e.mariadb))t.push(b.mariadb),r.push("mariadb");if(y(e.postgres))t.push("postgresql.org"),r.push("postgres");if(y(e.redis))t.push("redis.io"),r.push("redis");if(y(e.memcached))t.push("memcached.org"),r.push("memcached");if(y(e.meilisearch))t.push("meilisearch.com"),r.push("meilisearch");return{packages:t,services:r}}function Do(e={},t={}){let r=Ne(e),n=Po(e.vitess),o=t.mail?ne(t.mail):[];if(r.packages.length===0)return[...n,...o];return[...it(r.packages),...Io(r.services),...n,...o]}function wt(e,t={}){if(e?.requireLocalPasswordAuth&&(e.engine!=="postgres"||!gn(e)||!e.name||!e.username||!e.password||e.users?.some((a)=>!a.password)))throw Error("Password authentication requires a named local PostgreSQL database and nonempty login passwords");if(!e?.name)return[];if(!gn(e))return[];let r=e.name,n=e.username||r,o=e.password||"",s=y(t.postgres)||e.engine==="postgres",c=y(t.mariadb)||e.engine==="mariadb",p=y(t.mysql)||e.engine==="mysql";if(s&&!p&&!c){let a=(d)=>`"${d.replace(/"/g,'""')}"`,D=(d)=>`'${d.replace(/'/g,"''")}'`,L=(d,k)=>[...e.requireLocalPasswordAuth?["SET password_encryption = 'scram-sha-256';"]:[],"DO $$ BEGIN",` IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${D(d)}) THEN`,` CREATE ROLE ${a(d)} LOGIN PASSWORD ${D(k)};`," ELSE",` ALTER ROLE ${a(d)} LOGIN PASSWORD ${D(k)};`," END IF;","END $$;"],x=(d)=>{let k=d.databases&&d.databases.length>0?d.databases:[r],V=[];for(let G of k)if(d.access==="readonly")V.push(`GRANT CONNECT ON DATABASE ${a(G)} TO ${a(d.username)};`,`\\connect ${a(G)}`,`GRANT USAGE ON SCHEMA public TO ${a(d.username)};`,`GRANT SELECT ON ALL TABLES IN SCHEMA public TO ${a(d.username)};`,`ALTER DEFAULT PRIVILEGES FOR ROLE ${a(n)} IN SCHEMA public GRANT SELECT ON TABLES TO ${a(d.username)};`,"\\connect postgres");else V.push(`GRANT ALL PRIVILEGES ON DATABASE ${a(G)} TO ${a(d.username)};`);return V},I=e.users||[],Se=e.port??5432;return[Ve(),`for i in $(seq 1 30); do pg_isready -p ${Se} -q && break; sleep 2; done`,`${Et(e)}${e.requireLocalPasswordAuth?" -v ON_ERROR_STOP=1":""} <<'TS_CLOUD_PG_EOF'`,...L(n,o),`SELECT 'CREATE DATABASE ${a(r)} OWNER ${a(n)}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = ${D(r)})\\gexec`,...I.flatMap((d)=>[...L(d.username,d.password),...x(d)]),"TS_CLOUD_PG_EOF",...e.requireLocalPasswordAuth?[`TS_CLOUD_PG_HBA=$(${Et(e)} -Atc 'SHOW hba_file')`,'case "$TS_CLOUD_PG_HBA" in /*) ;; *) echo "Invalid PostgreSQL authentication path" >&2; exit 1 ;; esac','[ -f "$TS_CLOUD_PG_HBA.before-ts-cloud-password-auth" ] || cp -p "$TS_CLOUD_PG_HBA" "$TS_CLOUD_PG_HBA.before-ts-cloud-password-auth"','TS_CLOUD_PG_AUTH=$(mktemp "$TS_CLOUD_PG_HBA.ts-cloud.XXXXXXXX")',"{"," printf '%s\\n' '# BEGIN ts-cloud password authentication' 'host all all 127.0.0.1/32 scram-sha-256' 'host all all ::1/128 scram-sha-256' 'host replication all 127.0.0.1/32 scram-sha-256' 'host replication all ::1/128 scram-sha-256' '# END ts-cloud password authentication'",` sed '/^# BEGIN ts-cloud password authentication$/,/^# END ts-cloud password authentication$/d' "$TS_CLOUD_PG_HBA"`,'} > "$TS_CLOUD_PG_AUTH"','chown --reference="$TS_CLOUD_PG_HBA" "$TS_CLOUD_PG_AUTH"','chmod --reference="$TS_CLOUD_PG_HBA" "$TS_CLOUD_PG_AUTH"','mv -f "$TS_CLOUD_PG_AUTH" "$TS_CLOUD_PG_HBA"',`${Et(e)} -v ON_ERROR_STOP=1 -c 'SELECT pg_reload_conf()'`]:[],...Be(e)]}let l=c?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock",i=(a)=>a.replace(/`/g,"``"),f=(a)=>a.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),P=(a)=>{let D=a.databases&&a.databases.length>0?a.databases:[r],L=a.access==="readonly"?"SELECT":"ALL PRIVILEGES",x=[`CREATE USER IF NOT EXISTS '${f(a.username)}'@'%' IDENTIFIED BY '${f(a.password)}';`,`CREATE USER IF NOT EXISTS '${f(a.username)}'@'localhost' IDENTIFIED BY '${f(a.password)}';`,`ALTER USER '${f(a.username)}'@'%' IDENTIFIED BY '${f(a.password)}';`,`ALTER USER '${f(a.username)}'@'localhost' IDENTIFIED BY '${f(a.password)}';`];for(let I of D)x.push(`GRANT ${L} ON \`${i(I)}\`.* TO '${f(a.username)}'@'%';`,`GRANT ${L} ON \`${i(I)}\`.* TO '${f(a.username)}'@'localhost';`);return x},u=e.users||[];return[Ve(),`for i in $(seq 1 30); do mysqladmin --socket=${l} -u root ping 2>/dev/null | grep -q alive && break; sleep 2; done`,`mysql --socket=${l} -u root <<'TS_CLOUD_SQL_EOF'`,`CREATE DATABASE IF NOT EXISTS \`${i(r)}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`,...P({username:n,password:o}),...u.flatMap(P),"FLUSH PRIVILEGES;","TS_CLOUD_SQL_EOF"]}function Be(e){return[`${Et(e)} -tA <<'TS_CLOUD_PG_CAP_EOF' || true`,"\\set QUIET on","SELECT CASE WHEN used::float / NULLIF(cap, 0) >= 0.8"," THEN '[ts-cloud] postgres is at ' || used || '/' || cap || ' connections on this server.'"," || ' Raise max_connections (ALTER SYSTEM SET max_connections = ...; then restart) or'"," || ' set idle_session_timeout so abandoned pools are reclaimed.'"," ELSE NULL END","FROM (SELECT (SELECT count(*) FROM pg_stat_activity) AS used,"," (SELECT setting::int FROM pg_settings WHERE name = 'max_connections') AS cap) c","WHERE CASE WHEN used::float / NULLIF(cap, 0) >= 0.8 THEN true ELSE false END;","SELECT '[ts-cloud] ' || coalesce(datname, '(background)') || ': ' || count(*) || ' connection(s), oldest idle ' ||"," coalesce(round(extract(epoch from max(now() - state_change)) / 60)::text || 'm', 'n/a')","FROM pg_stat_activity","WHERE (SELECT count(*)::float / NULLIF((SELECT setting::int FROM pg_settings WHERE name = 'max_connections'), 0) FROM pg_stat_activity) >= 0.8","GROUP BY datname ORDER BY count(*) DESC;","TS_CLOUD_PG_CAP_EOF"]}function Kc(e){if(!e?.name)return{};let t=e.engine==="singlestore",r=e.engine==="vitess",n=e.engine==="postgres"?"pgsql":t?"singlestore":r?"vitess":"mysql",o=e.port??(e.engine==="postgres"?5432:r?15306:3306),s={DB_CONNECTION:n,DB_HOST:e.host||"127.0.0.1",DB_PORT:String(o),DB_DATABASE:e.name};if(e.username)s.DB_USERNAME=e.username;if(e.password)s.DB_PASSWORD=e.password;if((t||r)&&e.ssl!==!1)s.DB_SSL="true";return s}var Z="/var/backups/ts-cloud",we="/etc/ts-cloud/backups.config.ts",pe="/etc/cron.d/ts-cloud-backups",fn="/usr/local/bin/ts-cloud-backup.sh";function He(e){if(!e.name)return null;let t=e.host||"127.0.0.1",r=e.engine==="postgres",n=r?"postgresql":"mysql",o=e.port??(r?5432:3306),s=(c)=>c.replace(/\\/g,"\\\\").replace(/'/g,"\\'");return[" {",` type: '${n}',`,` name: '${s(e.name)}',`," connection: {",` hostname: '${s(t)}',`,` port: ${o},`,` database: '${s(e.name)}',`,` username: '${s(e.username||e.name)}',`,` password: '${s(e.password||"")}',`," ssl: false,"," },"," includeSchema: true,"," includeData: true,"," },"].join(`
7
7
  `)}function Ge(e,t){let r=e?He(e):null,n=t.bucket?[" destinations: ["," {"," type: 's3',",` bucket: '${t.bucket}',`," prefix: 'db-backups',",...t.endpoint?[` endpoint: '${t.endpoint}',`]:[]," optional: false,"," },"," ],"]:[];return["import type { BackupConfig } from 'ts-backups'","","const config: BackupConfig = {"," verbose: true,",` outputPath: '${Z}',`," retention: {",` count: ${t.retentionCount??5},`,` maxAge: ${t.retentionDays??30},`," },"," databases: [",...r?[r]:[]," ],",...n,"}","","export default config",""].join(`
8
- `)}function ko(e){let{database:t,backups:r}=e;if(!r.enabled)return[];let n=r.schedule||"0 2 * * *",o=Ge(t,r);return["export DEBIAN_FRONTEND=noninteractive",`mkdir -p /etc/ts-cloud ${Z}`,"command -v bun >/dev/null 2>&1 || (curl -fsSL https://bun.sh/install | bash && ln -sf /root/.bun/bin/bun /usr/local/bin/bun)","bun add -g ts-backups || true",`cat > ${we} <<'TS_CLOUD_BACKUP_CFG_EOF'`,o.replace(/\n$/,""),"TS_CLOUD_BACKUP_CFG_EOF",`cat > ${gn} <<'TS_CLOUD_BACKUP_RUN_EOF'`,"#!/bin/bash","set -uo pipefail",'export PATH="/root/.bun/bin:/usr/local/bin:$PATH"','notify() { [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "$1" || true; }',"cd /etc/ts-cloud",'if ! ts-backups start --config /etc/ts-cloud/backups.config.ts; then notify "❌ ts-cloud backup failed"; exit 1; fi',"TS_CLOUD_BACKUP_RUN_EOF",`chmod +x ${gn}`,`cat > ${pe} <<'TS_CLOUD_BACKUP_CRON_EOF'`,`${n} root ${gn} >> /var/log/ts-cloud-backup.log 2>&1`,"TS_CLOUD_BACKUP_CRON_EOF",`chmod 644 ${pe}`]}function qe(e){return e==="mariadb"?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock"}function xi(e,t={}){if(!e?.name)return[];let r=e.name,n=e.engine==="postgres",o=t.from?`TS_CLOUD_DUMP="${t.from}"`:`TS_CLOUD_DUMP="$(find ${Z} -type f -name '*${r}*.sql' -o -type f -name '*${r}*.sql.gz' 2>/dev/null | xargs -r ls -1t 2>/dev/null | head -1)"`,s=n?`${Pr(e)} -d "${r}"`:`mysql --socket=${qe(e.engine)} -u root "${r}"`;return["set -uo pipefail",'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true',o,'[ -n "$TS_CLOUD_DUMP" ] && [ -f "$TS_CLOUD_DUMP" ] || { echo "no backup dump found to restore" >&2; exit 1; }','echo "[ts-cloud] restoring '+r+' from $TS_CLOUD_DUMP"',`case "$TS_CLOUD_DUMP" in *.gz) gunzip -c "$TS_CLOUD_DUMP" ;; *) cat "$TS_CLOUD_DUMP" ;; esac | ${s}`,'echo "restore complete"']}var No=["storage",".env"],_i=4;function v(e){return`${e.replace(/\/+$/,"")}/.ts-cloud`}function js(e){return`${v(e)}/deploy-history.log`}function Fe(e,t){return`${v(e)}/deploys/${t}.log`}function ue(e){return`${v(e)}/shared-paths`}function xo(e){return`${e.shared}/stx-images`}function Oi(e){return`${e.shared}/stx-bundles`}function zt(e,t){let r=e.replace(/\/+$/,"");return{base:r,releases:`${r}/releases`,shared:`${r}/shared`,current:`${r}/current`,release:`${r}/releases/${t}`}}function de(e){let t=e.split("/").pop()||e;if(t===".env"||t.startsWith(".env."))return!0;return/\.[a-z0-9]+$/i.test(t)}function Vs(e){return typeof e==="string"?e:e.path}function Jc(e){let t=new Map;for(let r of e)t.set(Vs(r),r);return[...t.values()]}function $e(e,t){if(typeof t==="string")return{path:t,target:`${e.shared}/${t}`,seed:!0};return{path:t.path,target:t.target??`${e.shared}/${t.path}`,seed:t.seed!==!1}}function Ye(e){return["ts_cloud_adopt_shared() {",' TS_CLOUD_SP="$1"',' TS_CLOUD_DST="$2"',` TS_CLOUD_SRC="${e.current}/$TS_CLOUD_SP"`,' if [ -e "$TS_CLOUD_DST" ]; then return 0; fi',' if [ -L "$TS_CLOUD_SRC" ] || [ ! -e "$TS_CLOUD_SRC" ]; then return 0; fi',' mkdir -p "$(dirname "$TS_CLOUD_DST")"',' cp -a "$TS_CLOUD_SRC" "$TS_CLOUD_DST"'," for TS_CLOUD_SIDECAR in -wal -shm; do",' if [ -f "$TS_CLOUD_SRC$TS_CLOUD_SIDECAR" ]; then cp -a "$TS_CLOUD_SRC$TS_CLOUD_SIDECAR" "$TS_CLOUD_DST$TS_CLOUD_SIDECAR"; fi'," done",' echo "[ts-cloud] adopted $TS_CLOUD_SP from the live release into shared/ — it now survives deploys"'," return 0","}"]}function $i(e,t=No){let r=[`mkdir -p ${e.releases} ${e.shared} ${xo(e)} ${Oi(e)}`,...Ye(e)],n=t.map((s)=>$e(e,s));for(let{path:s,target:c,seed:p}of n){if(!p)continue;if(r.push(`ts_cloud_adopt_shared '${s}' '${c}'`),de(s))r.push(`mkdir -p "$(dirname ${c})"`,`touch ${c}`);else if(s==="storage")r.push(`mkdir -p ${c}/app/public`,`mkdir -p ${c}/framework/cache/data`,`mkdir -p ${c}/framework/sessions`,`mkdir -p ${c}/framework/testing`,`mkdir -p ${c}/framework/views`,`mkdir -p ${c}/logs`);else r.push(`mkdir -p ${c}`)}let o=ue(e.base);return r.push(`mkdir -p ${v(e.base)}`,`cat > ${o} <<'TS_CLOUD_SHARED_PATHS_EOF'`,...n.map((s)=>`${s.path} ${s.target}`),"TS_CLOUD_SHARED_PATHS_EOF"),r}function zs(e,t=900){let r=`${v(e.base)}/deploy.lock`;return[`mkdir -p "$(dirname ${r})"`,`exec 9>${r}`,`flock -w ${t} 9 || { echo "[ts-cloud] another deploy of this site has held the lock for ${t}s — refusing to race it" >&2; exit 1; }`]}function Hs(e){let t=`${e.release}.incoming`;return[`rm -rf ${t}`,`mkdir -p ${t}`,...Ke(e),'if [ "$TS_CLOUD_IS_LIVE" = "yes" ]; then',` TS_CLOUD_STAGED=${t}`,"else",` rm -rf ${e.release}`,` mkdir -p ${e.release}`,` rmdir ${t}`,` TS_CLOUD_STAGED=${e.release}`,"fi"]}function Gs(e){let t=`TS_CLOUD_TRAP_LIVE="$(readlink -f ${e.current} 2>/dev/null || true)"`,r=`TS_CLOUD_TRAP_TARGET="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`;return`trap '${`if [ $? -ne 0 ]; then ${t}; ${r}; [ "$TS_CLOUD_TRAP_LIVE" = "$TS_CLOUD_TRAP_TARGET" ] || rm -rf ${e.release}; fi`}' EXIT`}function Ke(e){return[`TS_CLOUD_LIVE_PATH="$(readlink -f ${e.current} 2>/dev/null || true)"`,`TS_CLOUD_RELEASE_PATH="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`,'if [ -n "$TS_CLOUD_LIVE_PATH" ] && [ "$TS_CLOUD_LIVE_PATH" = "$TS_CLOUD_RELEASE_PATH" ]; then TS_CLOUD_IS_LIVE=yes; else TS_CLOUD_IS_LIVE=no; fi']}function qs(e){let t=`${e.release}.incoming`;return[`if [ "$TS_CLOUD_STAGED" = "${t}" ]; then`,` rm -rf ${e.release}.previous`,` mv ${e.release} ${e.release}.previous`,` mv ${t} ${e.release}`,` rm -rf ${e.release}.previous`,"fi"]}function je(e,t){return[`if [ -f ${e} ] && [ ! -L ${e} ] && [ -s ${e} ] && [ ! -s ${t} ]; then`,` cp -a ${e} ${t}`,` echo "[ts-cloud] seeded shared/ from the release's own copy of the file"`,"fi"]}function _o(e,t=No){let r=[];for(let n of t){let{path:o,target:s,seed:c}=$e(e,n),p=`${e.release}/${o}`,l=[`rm -rf ${p}`,`mkdir -p "$(dirname ${p})"`,`ln -sfn ${s} ${p}`];if(c){if(o!==".env"&&de(o))r.push(...je(p,s));r.push(...l);continue}r.push(`if [ -e ${s} ]; then`,...l.map((i)=>` ${i}`),"fi")}return r}function We(e,t){let r=ue(e.base);return[`if [ -f ${r} ]; then`,' while IFS="\t" read -r TS_CLOUD_SP TS_CLOUD_TGT; do',' [ -n "$TS_CLOUD_SP" ] || continue',` [ -n "$TS_CLOUD_TGT" ] || TS_CLOUD_TGT="${e.shared}/$TS_CLOUD_SP"`,' [ -e "$TS_CLOUD_TGT" ] || continue',` rm -rf ${t}/"$TS_CLOUD_SP"`,` mkdir -p "$(dirname ${t}/"$TS_CLOUD_SP")"`,` ln -sfn "$TS_CLOUD_TGT" ${t}/"$TS_CLOUD_SP"`,` done < ${r}`,"fi"]}function fn(e){return[`ln -sfn ${e.release} ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`]}function ee(e){return`${v(e)}/previous-release`}function Ws(e,t="TS_CLOUD_PREV_CURRENT"){let r=ee(e.base);return[`if [ -n "\${${t}:-}" ] && [ -d "$${t}" ] && [ "$(readlink -f "$${t}")" != "$(readlink -f ${e.release})" ]; then mkdir -p ${v(e.base)}; basename "$${t}" > ${r}; fi`]}function _e(e,t){let r=ee(e.base);return[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,...t?[`TS_CLOUD_RB_TARGET=${e.releases}/${t}`]:["TS_CLOUD_RB_TARGET=",`if [ -f ${r} ]; then TS_CLOUD_REC="${e.releases}/$(cat ${r})"; if [ -d "$TS_CLOUD_REC" ] && [ "$(readlink -f "$TS_CLOUD_REC")" != "$TS_CLOUD_CURRENT" ]; then TS_CLOUD_RB_TARGET="$TS_CLOUD_REC"; fi; fi`,`[ -n "$TS_CLOUD_RB_TARGET" ] || TS_CLOUD_RB_TARGET=$(ls -1dt ${e.releases}/*/ 2>/dev/null | sed 's#/$##' | while read -r r; do [ "$(readlink -f "$r")" != "$TS_CLOUD_CURRENT" ] && { echo "$r"; break; }; done)`],'[ -n "$TS_CLOUD_RB_TARGET" ] && [ -d "$TS_CLOUD_RB_TARGET" ] || { echo "no release to roll back to (looked for ${TS_CLOUD_RB_TARGET:-a previous release})" >&2; exit 1; }','[ "$(readlink -f "$TS_CLOUD_RB_TARGET")" != "$TS_CLOUD_CURRENT" ] || { echo "$(basename "$TS_CLOUD_RB_TARGET") is already the live release" >&2; exit 1; }','TS_CLOUD_RB_ID=$(basename "$TS_CLOUD_RB_TARGET")']}function Xc(e,t={}){return[..._e(e,t.to),'echo "would roll back from $(basename "${TS_CLOUD_CURRENT:-none}") to $TS_CLOUD_RB_ID (dry run: nothing changed)"']}function Qc(e,t={}){let r=Math.max(1,t.gateSeconds??5),n=t.systemdDir??"/etc/systemd/system",o=[`ln -sfn "$TS_CLOUD_RB_TARGET" ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`,`rm -f ${ee(e.base)}`,'echo "rolled back to $TS_CLOUD_RB_ID"'],s=[..._e(e,t.to),...We(e,'"$TS_CLOUD_RB_TARGET"')];if(!t.unitBase)return[...s,...o];let c=t.unitBase,p=`${c}@\${TS_CLOUD_RB_ID}.service`;return[...s,`if [ -f ${n}/${c}@.service ]; then`,` systemctl start "${p}"`,` for TS_CLOUD_I in $(seq 1 ${r}); do sleep 1; systemctl is-active --quiet "${p}" || { echo "the release rolled back to, $TS_CLOUD_RB_ID, did not stay up; the current release keeps serving" >&2; journalctl -u "${p}" -n 30 --no-pager >&2 || true; systemctl stop "${p}" 2>/dev/null || true; exit 1; }; done`,...o.map((l)=>` ${l}`),` systemctl enable "${p}" 2>/dev/null || true`,` systemctl list-units --plain --no-legend --type=service "${c}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v "^${c}@\${TS_CLOUD_RB_ID}.service$" || true; } | while read -r TS_CLOUD_U; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done`,`elif [ -f ${n}/${c}.service ]; then`,...o.map((l)=>` ${l}`),` systemctl restart ${c}.service`,"else",...o.map((l)=>` ${l}`),"fi"]}function hn(e,t=4){let r=Math.max(1,t);return[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,`ls -1dt ${e.releases}/*/ 2>/dev/null | sed 's#/$##' | tail -n +${r+1} | while read -r TS_CLOUD_OLD; do`,' [ "$(readlink -f "$TS_CLOUD_OLD")" = "$TS_CLOUD_CURRENT" ] || rm -rf "$TS_CLOUD_OLD"',"done"]}function Xe(e){return`${v(e)}/owner`}function Ks(e,t){let r=Xe(e);return[`if [ -f "${r}" ]; then`,` TS_CLOUD_OWNER=$(cat "${r}")`,` if [ "$TS_CLOUD_OWNER" != "${t}" ]; then`,` echo "[ts-cloud] REFUSING deploy: ${e} belongs to project '$TS_CLOUD_OWNER', not '${t}'. Another project on this box derives the same site key — give one of them a distinct site name/domain, or remove ${r} to transfer ownership." >&2`," exit 1"," fi","else",` mkdir -p "$(dirname "${r}")"`,` printf '%s\\n' "${t}" > "${r}"`,"fi"]}function Oo(e,t){let r=v(e),n=Fe(e,t.releaseId),o=js(e),s=Math.max(1,t.keepLogs??20),c=t.commit||"",p=t.branch||"";return[`mkdir -p ${r}/deploys`,`exec > >(tee -a ${n}) 2>&1`,`echo "[ts-cloud] deploy ${t.releaseId} commit=${c} branch=${p} starting $(date -u +%Y-%m-%dT%H:%M:%SZ)"`,"ts_cloud_record_deploy() {"," TS_CLOUD_RC=$?",' if [ "$TS_CLOUD_RC" -eq 0 ]; then TS_CLOUD_ST=success; else TS_CLOUD_ST=failed; fi',` printf '%s\\t%s\\t%s\\t%s\\trc=%s\\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "${t.releaseId}" "${c}" "$TS_CLOUD_ST" "$TS_CLOUD_RC" >> ${o}`,"}","trap ts_cloud_record_deploy EXIT",`ls -1t ${r}/deploys/*.log 2>/dev/null | tail -n +${s+1} | while read -r TS_CLOUD_OLDLOG; do rm -f "$TS_CLOUD_OLDLOG"; done`]}
9
- export{W,Di,Us,w,Ro,Bs,Fs,qc,Wc,R,Tt,Ve,it,Io,ki,Po,Ni,Pr,Do,Et,Kc,gn,ko,xi,No,_i,js,xo,Oi,zt,Vs,Jc,$i,zs,Hs,Gs,qs,_o,fn,Ws,Xc,Qc,hn,Ks,Oo};
8
+ `)}function ko(e){let{database:t,backups:r}=e;if(!r.enabled)return[];let n=r.schedule||"0 2 * * *",o=Ge(t,r);return["export DEBIAN_FRONTEND=noninteractive",`mkdir -p /etc/ts-cloud ${Z}`,"command -v bun >/dev/null 2>&1 || (curl -fsSL https://bun.sh/install | bash && ln -sf /root/.bun/bin/bun /usr/local/bin/bun)","bun add -g ts-backups || true",`cat > ${we} <<'TS_CLOUD_BACKUP_CFG_EOF'`,o.replace(/\n$/,""),"TS_CLOUD_BACKUP_CFG_EOF",`cat > ${fn} <<'TS_CLOUD_BACKUP_RUN_EOF'`,"#!/bin/bash","set -uo pipefail",'export PATH="/root/.bun/bin:/usr/local/bin:$PATH"','notify() { [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "$1" || true; }',"cd /etc/ts-cloud",'if ! ts-backups start --config /etc/ts-cloud/backups.config.ts; then notify "❌ ts-cloud backup failed"; exit 1; fi',"TS_CLOUD_BACKUP_RUN_EOF",`chmod +x ${fn}`,`cat > ${pe} <<'TS_CLOUD_BACKUP_CRON_EOF'`,`${n} root ${fn} >> /var/log/ts-cloud-backup.log 2>&1`,"TS_CLOUD_BACKUP_CRON_EOF",`chmod 644 ${pe}`]}function qe(e){return e==="mariadb"?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock"}function xi(e,t={}){if(!e?.name)return[];let r=e.name,n=e.engine==="postgres",o=t.from?`TS_CLOUD_DUMP="${t.from}"`:`TS_CLOUD_DUMP="$(find ${Z} -type f -name '*${r}*.sql' -o -type f -name '*${r}*.sql.gz' 2>/dev/null | xargs -r ls -1t 2>/dev/null | head -1)"`,s=n?`${Et(e)} -d "${r}"`:`mysql --socket=${qe(e.engine)} -u root "${r}"`;return["set -uo pipefail",'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true',o,'[ -n "$TS_CLOUD_DUMP" ] && [ -f "$TS_CLOUD_DUMP" ] || { echo "no backup dump found to restore" >&2; exit 1; }','echo "[ts-cloud] restoring '+r+' from $TS_CLOUD_DUMP"',`case "$TS_CLOUD_DUMP" in *.gz) gunzip -c "$TS_CLOUD_DUMP" ;; *) cat "$TS_CLOUD_DUMP" ;; esac | ${s}`,'echo "restore complete"']}var No=["storage",".env"],_i=4;function v(e){return`${e.replace(/\/+$/,"")}/.ts-cloud`}function js(e){return`${v(e)}/deploy-history.log`}function Fe(e,t){return`${v(e)}/deploys/${t}.log`}function ue(e){return`${v(e)}/shared-paths`}function xo(e){return`${e.shared}/stx-images`}function Oi(e){return`${e.shared}/stx-bundles`}function Ht(e,t){let r=e.replace(/\/+$/,"");return{base:r,releases:`${r}/releases`,shared:`${r}/shared`,current:`${r}/current`,release:`${r}/releases/${t}`}}function de(e){let t=e.split("/").pop()||e;if(t===".env"||t.startsWith(".env."))return!0;return/\.[a-z0-9]+$/i.test(t)}function Vs(e){return typeof e==="string"?e:e.path}function Jc(e){let t=new Map;for(let r of e)t.set(Vs(r),r);return[...t.values()]}function $e(e,t){if(typeof t==="string")return{path:t,target:`${e.shared}/${t}`,seed:!0};return{path:t.path,target:t.target??`${e.shared}/${t.path}`,seed:t.seed!==!1}}function Ye(e){return["ts_cloud_adopt_shared() {",' TS_CLOUD_SP="$1"',' TS_CLOUD_DST="$2"',` TS_CLOUD_SRC="${e.current}/$TS_CLOUD_SP"`,' if [ -e "$TS_CLOUD_DST" ]; then return 0; fi',' if [ -L "$TS_CLOUD_SRC" ] || [ ! -e "$TS_CLOUD_SRC" ]; then return 0; fi',' mkdir -p "$(dirname "$TS_CLOUD_DST")"',' cp -a "$TS_CLOUD_SRC" "$TS_CLOUD_DST"'," for TS_CLOUD_SIDECAR in -wal -shm; do",' if [ -f "$TS_CLOUD_SRC$TS_CLOUD_SIDECAR" ]; then cp -a "$TS_CLOUD_SRC$TS_CLOUD_SIDECAR" "$TS_CLOUD_DST$TS_CLOUD_SIDECAR"; fi'," done",' echo "[ts-cloud] adopted $TS_CLOUD_SP from the live release into shared/ — it now survives deploys"'," return 0","}"]}function $i(e,t=No){let r=[`mkdir -p ${e.releases} ${e.shared} ${xo(e)} ${Oi(e)}`,...Ye(e)],n=t.map((s)=>$e(e,s));for(let{path:s,target:c,seed:p}of n){if(!p)continue;if(r.push(`ts_cloud_adopt_shared '${s}' '${c}'`),de(s))r.push(`mkdir -p "$(dirname ${c})"`,`touch ${c}`);else if(s==="storage")r.push(`mkdir -p ${c}/app/public`,`mkdir -p ${c}/framework/cache/data`,`mkdir -p ${c}/framework/sessions`,`mkdir -p ${c}/framework/testing`,`mkdir -p ${c}/framework/views`,`mkdir -p ${c}/logs`);else r.push(`mkdir -p ${c}`)}let o=ue(e.base);return r.push(`mkdir -p ${v(e.base)}`,`cat > ${o} <<'TS_CLOUD_SHARED_PATHS_EOF'`,...n.map((s)=>`${s.path} ${s.target}`),"TS_CLOUD_SHARED_PATHS_EOF"),r}function zs(e,t=900){let r=`${v(e.base)}/deploy.lock`;return[`mkdir -p "$(dirname ${r})"`,`exec 9>${r}`,`flock -w ${t} 9 || { echo "[ts-cloud] another deploy of this site has held the lock for ${t}s — refusing to race it" >&2; exit 1; }`]}function Hs(e){let t=`${e.release}.incoming`;return[`rm -rf ${t}`,`mkdir -p ${t}`,...Ke(e),'if [ "$TS_CLOUD_IS_LIVE" = "yes" ]; then',` TS_CLOUD_STAGED=${t}`,"else",` rm -rf ${e.release}`,` mkdir -p ${e.release}`,` rmdir ${t}`,` TS_CLOUD_STAGED=${e.release}`,"fi"]}function Gs(e){let t=`TS_CLOUD_TRAP_LIVE="$(readlink -f ${e.current} 2>/dev/null || true)"`,r=`TS_CLOUD_TRAP_TARGET="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`;return`trap '${`if [ $? -ne 0 ]; then ${t}; ${r}; [ "$TS_CLOUD_TRAP_LIVE" = "$TS_CLOUD_TRAP_TARGET" ] || rm -rf ${e.release}; fi`}' EXIT`}function Ke(e){return[`TS_CLOUD_LIVE_PATH="$(readlink -f ${e.current} 2>/dev/null || true)"`,`TS_CLOUD_RELEASE_PATH="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`,'if [ -n "$TS_CLOUD_LIVE_PATH" ] && [ "$TS_CLOUD_LIVE_PATH" = "$TS_CLOUD_RELEASE_PATH" ]; then TS_CLOUD_IS_LIVE=yes; else TS_CLOUD_IS_LIVE=no; fi']}function qs(e){let t=`${e.release}.incoming`;return[`if [ "$TS_CLOUD_STAGED" = "${t}" ]; then`,` rm -rf ${e.release}.previous`,` mv ${e.release} ${e.release}.previous`,` mv ${t} ${e.release}`,` rm -rf ${e.release}.previous`,"fi"]}function je(e,t){return[`if [ -f ${e} ] && [ ! -L ${e} ] && [ -s ${e} ] && [ ! -s ${t} ]; then`,` cp -a ${e} ${t}`,` echo "[ts-cloud] seeded shared/ from the release's own copy of the file"`,"fi"]}function _o(e,t=No){let r=[];for(let n of t){let{path:o,target:s,seed:c}=$e(e,n),p=`${e.release}/${o}`,l=[`rm -rf ${p}`,`mkdir -p "$(dirname ${p})"`,`ln -sfn ${s} ${p}`];if(c){if(o!==".env"&&de(o))r.push(...je(p,s));r.push(...l);continue}r.push(`if [ -e ${s} ]; then`,...l.map((i)=>` ${i}`),"fi")}return r}function We(e,t){let r=ue(e.base);return[`if [ -f ${r} ]; then`,' while IFS="\t" read -r TS_CLOUD_SP TS_CLOUD_TGT; do',' [ -n "$TS_CLOUD_SP" ] || continue',` [ -n "$TS_CLOUD_TGT" ] || TS_CLOUD_TGT="${e.shared}/$TS_CLOUD_SP"`,' [ -e "$TS_CLOUD_TGT" ] || continue',` rm -rf ${t}/"$TS_CLOUD_SP"`,` mkdir -p "$(dirname ${t}/"$TS_CLOUD_SP")"`,` ln -sfn "$TS_CLOUD_TGT" ${t}/"$TS_CLOUD_SP"`,` done < ${r}`,"fi"]}function hn(e){return[`ln -sfn ${e.release} ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`]}function ee(e){return`${v(e)}/previous-release`}function Ws(e,t="TS_CLOUD_PREV_CURRENT"){let r=ee(e.base);return[`if [ -n "\${${t}:-}" ] && [ -d "$${t}" ] && [ "$(readlink -f "$${t}")" != "$(readlink -f ${e.release})" ]; then mkdir -p ${v(e.base)}; basename "$${t}" > ${r}; fi`]}function _e(e,t){let r=ee(e.base);return[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,...t?[`TS_CLOUD_RB_TARGET=${e.releases}/${t}`]:["TS_CLOUD_RB_TARGET=",`if [ -f ${r} ]; then TS_CLOUD_REC="${e.releases}/$(cat ${r})"; if [ -d "$TS_CLOUD_REC" ] && [ "$(readlink -f "$TS_CLOUD_REC")" != "$TS_CLOUD_CURRENT" ]; then TS_CLOUD_RB_TARGET="$TS_CLOUD_REC"; fi; fi`,`[ -n "$TS_CLOUD_RB_TARGET" ] || TS_CLOUD_RB_TARGET=$(ls -1dt ${e.releases}/*/ 2>/dev/null | sed 's#/$##' | while read -r r; do [ "$(readlink -f "$r")" != "$TS_CLOUD_CURRENT" ] && { echo "$r"; break; }; done)`],'[ -n "$TS_CLOUD_RB_TARGET" ] && [ -d "$TS_CLOUD_RB_TARGET" ] || { echo "no release to roll back to (looked for ${TS_CLOUD_RB_TARGET:-a previous release})" >&2; exit 1; }','[ "$(readlink -f "$TS_CLOUD_RB_TARGET")" != "$TS_CLOUD_CURRENT" ] || { echo "$(basename "$TS_CLOUD_RB_TARGET") is already the live release" >&2; exit 1; }','TS_CLOUD_RB_ID=$(basename "$TS_CLOUD_RB_TARGET")']}function Xc(e,t={}){return[..._e(e,t.to),'echo "would roll back from $(basename "${TS_CLOUD_CURRENT:-none}") to $TS_CLOUD_RB_ID (dry run: nothing changed)"']}function Qc(e,t={}){let r=Math.max(1,t.gateSeconds??5),n=t.systemdDir??"/etc/systemd/system",o=[`ln -sfn "$TS_CLOUD_RB_TARGET" ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`,`rm -f ${ee(e.base)}`,'echo "rolled back to $TS_CLOUD_RB_ID"'],s=[..._e(e,t.to),...We(e,'"$TS_CLOUD_RB_TARGET"')];if(!t.unitBase)return[...s,...o];let c=t.unitBase,p=`${c}@\${TS_CLOUD_RB_ID}.service`;return[...s,`if [ -f ${n}/${c}@.service ]; then`,` systemctl start "${p}"`,` for TS_CLOUD_I in $(seq 1 ${r}); do sleep 1; systemctl is-active --quiet "${p}" || { echo "the release rolled back to, $TS_CLOUD_RB_ID, did not stay up; the current release keeps serving" >&2; journalctl -u "${p}" -n 30 --no-pager >&2 || true; systemctl stop "${p}" 2>/dev/null || true; exit 1; }; done`,...o.map((l)=>` ${l}`),` systemctl enable "${p}" 2>/dev/null || true`,` systemctl list-units --plain --no-legend --type=service "${c}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v "^${c}@\${TS_CLOUD_RB_ID}.service$" || true; } | while read -r TS_CLOUD_U; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done`,`elif [ -f ${n}/${c}.service ]; then`,...o.map((l)=>` ${l}`),` systemctl restart ${c}.service`,"else",...o.map((l)=>` ${l}`),"fi"]}function yn(e,t=4){let r=Math.max(1,t);return[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,`ls -1dt ${e.releases}/*/ 2>/dev/null | sed 's#/$##' | tail -n +${r+1} | while read -r TS_CLOUD_OLD; do`,' [ "$(readlink -f "$TS_CLOUD_OLD")" = "$TS_CLOUD_CURRENT" ] || rm -rf "$TS_CLOUD_OLD"',"done"]}function Xe(e){return`${v(e)}/owner`}function Ks(e,t){let r=Xe(e);return[`if [ -f "${r}" ]; then`,` TS_CLOUD_OWNER=$(cat "${r}")`,` if [ "$TS_CLOUD_OWNER" != "${t}" ]; then`,` echo "[ts-cloud] REFUSING deploy: ${e} belongs to project '$TS_CLOUD_OWNER', not '${t}'. Another project on this box derives the same site key — give one of them a distinct site name/domain, or remove ${r} to transfer ownership." >&2`," exit 1"," fi","else",` mkdir -p "$(dirname "${r}")"`,` printf '%s\\n' "${t}" > "${r}"`,"fi"]}function Oo(e,t){let r=v(e),n=Fe(e,t.releaseId),o=js(e),s=Math.max(1,t.keepLogs??20),c=t.commit||"",p=t.branch||"";return[`mkdir -p ${r}/deploys`,`exec > >(tee -a ${n}) 2>&1`,`echo "[ts-cloud] deploy ${t.releaseId} commit=${c} branch=${p} starting $(date -u +%Y-%m-%dT%H:%M:%SZ)"`,"ts_cloud_record_deploy() {"," TS_CLOUD_RC=$?",' if [ "$TS_CLOUD_RC" -eq 0 ]; then TS_CLOUD_ST=success; else TS_CLOUD_ST=failed; fi',` printf '%s\\t%s\\t%s\\t%s\\trc=%s\\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "${t.releaseId}" "${c}" "$TS_CLOUD_ST" "$TS_CLOUD_RC" >> ${o}`,"}","trap ts_cloud_record_deploy EXIT",`ls -1t ${r}/deploys/*.log 2>/dev/null | tail -n +${s+1} | while read -r TS_CLOUD_OLDLOG; do rm -f "$TS_CLOUD_OLDLOG"; done`]}
9
+ export{W,ki,Us,w,Ro,Bs,Fs,qc,Wc,R,Tt,Ve,it,Io,Ni,Po,gn,Et,Do,wt,Kc,fn,ko,xi,No,_i,js,xo,Oi,Ht,Vs,Jc,$i,zs,Hs,Gs,qs,_o,hn,Ws,Xc,Qc,yn,Ks,Oo};
@@ -0,0 +1 @@
1
+ import{V}from"./chunk-y5gx3dq2.js";import"./chunk-540wkkhs.js";export{V as SQSClient};
@@ -1,2 +1,2 @@
1
- import{p}from"./chunk-9cj1fm00.js";import{F}from"./chunk-bj94s3a7.js";var A=new Set(["A","AAAA","CNAME"]);function N(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 C(e,t){let r=t?.headers.get("retry-after"),n=r===null||r===void 0?void 0:Number(r)*1000,o=Number.isFinite(n)?Math.max(0,n):Math.min(1000*2**(e-1),30000);await new Promise((s)=>setTimeout(s,o))}class ot{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 n=1;n<=8;n+=1){let o,s=new AbortController,i=setTimeout(()=>{s.abort(Error(`Porkbun API request timed out after ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);try{o=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:s.signal})}catch(c){if(r=c,n===8)throw c;await C(n);continue}finally{clearTimeout(i)}if(!o.ok){let c=await o.clone().json().then((d)=>d?.message).catch(()=>{return});if(r=Error(`Porkbun API error: ${o.status} ${o.statusText}${c?`: ${c}`:""}`),!N(o.status)||n===8)throw r;await C(n,o);continue}let a=await o.json();if(a.status==="ERROR"){if(r=Error(`Porkbun API error: ${a.message||"Unknown error"}`),!N(0,a.message)||n===8)throw r;await C(n,o);continue}return a}throw r}getSubdomain(e,t){let r=e.replace(/\.$/,""),n=t.replace(/\.$/,"");if(r===n)return"";if(r.endsWith(`.${n}`))return r.slice(0,-(n.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(!ot.ADDRESS_TYPES.has(t.type))return[];let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(!o.success)return[`could not list records to clear ALIAS/CNAME conflicts: ${o.message??"unknown provider error"}`];let s=[];for(let i of o.records){if(i.type!=="ALIAS"&&i.type!=="CNAME")continue;if(this.getSubdomain(i.name,r)!==n)continue;let a=await this.deleteRecord(e,i);if(!a.success)s.push(`could not remove conflicting ${i.type} on ${i.name}: ${a.message??"unknown provider error"}`)}return s}async addressRecordExists(e,t){let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(!o.success)return!0;return o.records.some((s)=>s.type===t.type&&this.getSubdomain(s.name,r)===n&&s.content===t.content)}async createRecord(e,t){try{let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),o={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(n)o.name=n;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)o.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)o.content=`${t.weight} ${t.port} ${t.content}`;let s=await this.clearConflictingAliases(e,t),i=await this.request(`/dns/create/${r}`,o);if(ot.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${s.length>0?` (${s.join("; ")})`:""}. A conflicting ALIAS/CNAME on the same name silently voids the write.`};return{success:!0,id:i.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),n=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(o.success){let s=o.records.find((i)=>this.getSubdomain(i.name,r)===n&&i.type===t.type);if(s?.id&&s.content===t.content&&(t.ttl===void 0||s.ttl===t.ttl)&&(t.type!=="MX"&&t.type!=="SRV"||t.priority===void 0||s.priority===t.priority))return{success:!0,id:s.id,message:"Record already up to date"};if(s?.id){let i={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(n)i.name=n;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}`;return await this.request(`/dns/edit/${r}/${s.id}`,i),{success:!0,id:s.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 n=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(!o.success)return{success:!1,message:"Failed to list records"};let s=o.records.find((i)=>this.getSubdomain(i.name,r)===n&&i.type===t.type&&i.content===t.content);if(!s?.id)return{success:!1,message:"Record not found"};return await this.request(`/dns/delete/${r}/${s.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),n=`/dns/retrieve/${r}`;if(t)n=`/dns/retrieveByNameType/${r}/${t}`;return{success:!0,records:((await this.request(n)).records||[]).map((i)=>({id:i.id,name:i.name||r,type:i.type,content:i.content,ttl:Number.parseInt(i.ttl,10),priority:i.prio?Number.parseInt(i.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 Ht{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 n=`${this.baseUrl}${t}`,o={Authorization:this.authorization(),"Content-Type":"application/json",Accept:"application/json"},s={method:e,headers:o};if(r)s.body=JSON.stringify(r);let i=await fetch(n,s);if(i.status===204)return{};if(i.ok){let c=await i.text();if(c)return JSON.parse(c);return{}}let a=`GoDaddy API error: ${i.status} ${i.statusText}`;try{let c=await i.json();if(c.message)a=`GoDaddy API error: ${c.message}`;if(c.fields)a+=` - Fields: ${JSON.stringify(c.fields)}`}catch{}throw Error(a)}getSubdomain(e,t){let r=e.replace(/\.$/,""),n=t.replace(/\.$/,"");if(r===n)return"@";if(r.endsWith(`.${n}`))return r.slice(0,-(n.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),n=this.getSubdomain(e.name,r),o={type:e.type,name:n,data:e.content,ttl:e.ttl||600};if(e.type==="MX"&&e.priority!==void 0)o.priority=e.priority;return o}fromGoDaddyRecord(e,t){let r=this.getRootDomain(t),n=e.name;if(n==="@")n=r;else if(!n.endsWith(r))n=`${n}.${r}`;return{name:n,type:e.type,content:e.data,ttl:e.ttl,priority:e.priority}}async createRecord(e,t){try{let r=this.getRootDomain(e),n=this.toGoDaddyRecord(t,e);return await this.request("PATCH",`/v1/domains/${r}/records`,[n]),{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),n=this.toGoDaddyRecord(t,e);return await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${n.name}`,[n]),{success:!0,message:"Record upserted successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),o=await this.request("GET",`/v1/domains/${r}/records/${t.type}/${n}`),s=o.filter((i)=>i.data!==t.content);if(s.length===o.length)return{success:!1,message:"Record not found"};if(s.length===0)try{await this.request("DELETE",`/v1/domains/${r}/records/${t.type}/${n}`)}catch{}else await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${n}`,s);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),n=`/v1/domains/${r}/records`;if(t)n=`/v1/domains/${r}/records/${t}`;return{success:!0,records:(await this.request("GET",n)).map((s)=>this.fromGoDaddyRecord(s,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 Z=["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"],O=[{name:"x-stx-router",value:"true"}];function R(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function b(e){return`{${e.map(R).join(" ")}}`}function M(e){let t=`http.request.headers[${R(e.name.toLowerCase())}]`;return e.value===void 0?`len(${t}) > 0`:`any(${t}[*] == ${R(e.value)})`}function Dr(e){if(e.length===1)return`http.host eq ${R(e[0])}`;return`http.host in ${b(e)}`}function Xs(e,t={}){if(t.enabled===!1||e.length===0)return[];let r=Dr(e),n=[],s=(t.bypassPaths??[]).map((V)=>`starts_with(http.request.uri.path, ${R(V)})`),a=(t.negotiatedRequestHeaders??O).map(M),c=[...s,...a],d=c.length>0?`(${c.join(" or ")})`:void 0;if(d)n.push({action:"set_cache_settings",description:"bypass cache",expression:`(${r} and ${d})`,enabled:!0,action_parameters:{cache:!1}});let l=d?`${r} and not ${d}`:r,g=t.assetExtensions??Z,u=g.length>0?`lower(http.request.uri.path.extension) in ${b([...g])}`:void 0;if(u)n.push({action:"set_cache_settings",description:"cache fingerprinted assets",expression:`(${l} and ${u})`,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=u?`(${l} and not ${u})`:`(${l})`;if(t.documentEdgeTtl===0)return n.push({action:"set_cache_settings",description:"bypass documents",expression:y,enabled:!0,action_parameters:{cache:!1}}),n;return n.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}}}),n}function Qs(e,t,r){if(e.length===0||!t||!r)return[];return[{action:"rewrite",description:"origin guard header",expression:`(${Dr(e)})`,enabled:!0,action_parameters:{headers:{[t]:{operation:"set",value:r}}}}]}var z="https://api.cloudflare.com/client/v4",kr="[ts-cloud]";class he{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 n=`${z}${t}`,o={Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},s={method:e,headers:o};if(r)s.body=JSON.stringify(r);let a=await(await fetch(n,s)).json();if(!a.success){let c=a.errors.map((d)=>d.message).join(", ");throw Error(`Cloudflare API error: ${c}`)}return a}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 i=await this.resolveConfiguredZoneName();if(i&&(t===i||t.endsWith(`.${i}`)))return{id:this.configuredZoneId,name:i}}let r=this.getRootDomain(t),n=this.zoneCache.get(r);if(n)return{id:n,name:r};let o=await this.request("GET",`/zones?name=${encodeURIComponent(r)}`);if(!o.result||o.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 s=o.result[0].id;return this.zoneCache.set(r,s),{id:s,name:o.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 n={type:e.type,name:this.getFullRecordName(e.name,t),content:e.content||e.value||"",ttl:e.ttl||1},o=r??e.proxied;if(o!==void 0&&A.has(e.type)){if(n.proxied=o,o)n.ttl=1}if(e.type==="MX"&&e.priority!==void 0)n.priority=e.priority;if(e.type==="SRV"){let s=U(e);if(s)n.data=s,delete n.content,delete n.priority;else if(e.priority!==void 0)n.priority=e.priority}return n}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),n=this.toCloudflareRecord(t,r.name);return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,n)).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),n=this.getFullRecordName(t.name,r.name),s=(await this.request("GET",`/zones/${r.id}/dns_records?type=${t.type}&name=${encodeURIComponent(n)}`)).result?.[0],i=t.proxied??s?.proxied,a=this.toCloudflareRecord(t,r.name,i);if(s)return{success:!0,id:(await this.request("PUT",`/zones/${r.id}/dns_records/${s.id}`,a)).result.id,message:"Record updated successfully"};return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,a)).result.id,message:"Record created successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=await this.resolveZone(e),n=r.id,o=this.getFullRecordName(t.name,r.name),s=await this.request("GET",`/zones/${n}/dns_records?type=${t.type}&name=${encodeURIComponent(o)}`);if(!s.result||s.result.length===0)return{success:!1,message:"Record not found"};let i=s.result.find((a)=>a.content===t.content);if(!i)return{success:!1,message:"Record with matching content not found"};return await this.request("DELETE",`/zones/${n}/dns_records/${i.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 n=`/zones/${await this.getZoneId(e)}/dns_records?per_page=100`;if(t)n+=`&type=${t}`;let o=[],s=1,i=!0;while(i){let a=await this.request("GET",`${n}&page=${s}`);if(o.push(...a.result||[]),a.result_info)i=s<a.result_info.total_pages,s++;else i=!1}return{success:!0,records:o.map((a)=>this.fromCloudflareRecord(a))}}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 n=await this.request("GET",`/zones?per_page=50&page=${t}`);if(e.push(...n.result||[]),n.result_info)r=t<n.result_info.total_pages,t++;else r=!1}return e.map((n)=>n.name)}catch{return[]}}async createZone(e,t={}){let r=e.replace(/\.$/,"").toLowerCase(),n=t.accountId??this.accountId;if(!n)throw Error(`Cannot create zone ${r}: no Cloudflare account id. Set CLOUDFLARE_ACCOUNT_ID, or pass accountId.`);let o=await this.getZoneDetails(r);if(o)return{...o,created:!1};try{let i=(await this.request("POST","/zones",{name:r,account:{id:n},jump_start:t.jumpStart??!1})).result;return this.zoneCache.set(i.name,i.id),{id:i.id,name:i.name,status:i.status,nameServers:i.name_servers??[],created:!0}}catch(s){let i=s instanceof Error?s.message:String(s);if(!/already exists|1061/i.test(i))throw s;let a=await this.getZoneDetails(r);if(!a)throw s;return{...a,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`),n=new Set;for(let o of r.result||[]){if(o.status!=="active")continue;for(let s of o.hosts||[])n.add(s.toLowerCase())}return[...n]}catch{return null}}async purgeCache(e,t){try{let r=await this.getZoneId(e),n={};if(t?.purgeEverything)n.purge_everything=!0;else{if(t?.files)n.files=t.files;if(t?.tags)n.tags=t.tags;if(t?.hosts)n.hosts=t.hosts}if(Object.keys(n).length===0)n.purge_everything=!0;return await this.request("POST",`/zones/${r}/purge_cache`,n),!0}catch{return!1}}async getRecordProxyStatus(e,t){try{let r=await this.resolveZone(e),n=r.id,o=this.getFullRecordName(t.name,r.name),s=await this.request("GET",`/zones/${n}/dns_records?type=${t.type}&name=${encodeURIComponent(o)}`);if(s.result&&s.result.length>0)return s.result.find((a)=>a.content===t.content)?.proxied??null;return null}catch{return null}}async setRecordProxyStatus(e,t,r){try{let n=await this.resolveZone(e),o=n.id,s=this.getFullRecordName(t.name,n.name),i=await this.request("GET",`/zones/${o}/dns_records?type=${t.type}&name=${encodeURIComponent(s)}`);if(!i.result||i.result.length===0)return!1;let a=i.result.find((c)=>c.content===t.content);if(!a)return!1;return await this.request("PATCH",`/zones/${o}/dns_records/${a.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`),n={};for(let o of r.result||[])n[o.id]=o.value;return n}async applyZoneSettings(e,t){let r=await this.getZoneId(e),n=await this.getZoneSettings(e).catch(()=>({})),o=[],s=[];for(let[i,a]of Object.entries(t)){if(a===void 0)continue;let c=n[i];if(c!==void 0&&P(c,a))continue;try{await this.request("PATCH",`/zones/${r}/settings/${i}`,{value:a}),o.push({id:i,from:c,to:a})}catch(d){s.push({id:i,error:d instanceof Error?d.message:String(d)})}}return{changed:o,failed:s}}async getManagedRequestHeaders(e){let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/managed_headers`),n={};for(let o of r.result?.managed_request_headers||[])n[o.id]=o.enabled===!0;return n}async applyTieredCache(e,t){let r=[],n=[],o=await this.getZoneId(e),s=[["tiered_caching",`/zones/${o}/argo/tiered_caching`,t==="off"?"off":"on"],["tiered_cache_smart_topology_enable",`/zones/${o}/cache/tiered_cache_smart_topology_enable`,t==="smart"?"on":"off"]];if(t==="off")s.reverse();for(let[i,a,c]of s)try{let l=(await this.request("GET",a)).result?.value;if(l===c)continue;await this.request("PATCH",a,{value:c}),r.push({id:i,from:l,to:c})}catch(d){n.push({id:i,error:d instanceof Error?d.message:String(d)})}return{changed:r,failed:n}}async applyManagedRequestHeaders(e,t){let r=[],n=[],o=Object.entries(t).filter(([,c])=>c!==void 0);if(o.length===0)return{changed:r,failed:n};let s=await this.getZoneId(e),i;try{i=await this.getManagedRequestHeaders(e)}catch(c){let d=c instanceof Error?c.message:String(c);for(let[l]of o)n.push({id:l,error:`could not read managed headers — ${d}`});return{changed:r,failed:n}}let a=[];for(let[c,d]of o){if(!(c in i)){n.push({id:c,error:"not a managed request header transform on this zone"});continue}if(i[c]!==d)a.push([c,d])}if(a.length===0)return{changed:r,failed:n};try{await this.request("PATCH",`/zones/${s}/managed_headers`,{managed_request_headers:a.map(([c,d])=>({id:c,enabled:d})),managed_response_headers:[]});for(let[c,d]of a)r.push({id:c,from:i[c],to:d})}catch(c){let d=c instanceof Error?c.message:String(c);for(let[l]of a)n.push({id:l,error:d})}return{changed:r,failed:n}}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 n=await this.getZoneId(e),o=await this.getPhaseRules(e,t),s=r.map((c)=>({...c,description:c.description?.startsWith(kr)?c.description:`${kr} ${c.description||t}`})),a=L(o,s).map(({id:c,...d})=>d);return await this.request("PUT",`/zones/${n}/rulesets/phases/${t}/entrypoint`,{rules:a}),{success:!0}}catch(n){return{success:!1,message:n instanceof Error?n.message:String(n)}}}}var S=/http\.host (?:eq "[^"]+"|in \{[^}]*\})/;function Li(e){return S.test(e)?e.replace(S,"\x00hosts\x00"):null}function I(e,t){return e.replace(S,Dr(t))}function D(e){if(Array.isArray(e))return`[${e.map(D).join(",")}]`;if(e&&typeof e==="object")return`{${Object.entries(e).filter(([,r])=>r!==void 0).sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>`${JSON.stringify(r)}:${D(n)}`).join(",")}}`;return JSON.stringify(e)}function q(e,t){let r=Li(e.expression);return r!==null&&r===Li(t.expression)&&e.action===t.action&&e.description===t.description&&(e.enabled??!0)===(t.enabled??!0)&&D(e.action_parameters)===D(t.action_parameters)}function L(e,t){let r=new Set(t.flatMap((s)=>Nr(s.expression))),n=(s)=>(s.description||"").startsWith(kr),o=[];for(let s of e){if(!n(s)){o.push(s);continue}let i=Nr(s.expression);if(i.length===0){if(r.size>0)o.push(s);continue}let a=i.filter((c)=>!r.has(c));if(a.length===i.length)o.push(s);else if(a.length>0)o.push({...s,expression:I(s.expression,a)})}for(let s of t){let i=Nr(s.expression),a=i.length>0?o.findIndex((l)=>n(l)&&q(l,s)):-1;if(a===-1){o.push(s);continue}let c=o[a],d=[...new Set([...Nr(c.expression),...i])];o[a]={...c,expression:I(c.expression,d)}}return o}function Nr(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 n of r[1].matchAll(/"([^"]+)"/g))t.push(n[1]);return t}function P(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((o,s)=>P(o,t[s]))}let r=e,n=t;return Object.keys(n).every((o)=>P(r[o],n[o]))}function U(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:E(t)};let r=t.split(/\s+/);if(r.length<4)return null;let[n,o,s]=r.slice(0,3).map(Number);if(![n,o,s].every(Number.isFinite))return null;return{priority:n,weight:o,port:s,target:E(r.slice(3).join(" "))}}function E(e){return e.replace(/\.$/,"")}var j=new Set(["A","AAAA","CNAME","ALIAS"]);function w(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 f(e){return e.trim().replace(/^"(.*)"$/s,"$1")}function h(e){return e.replace(/\.$/,"").toLowerCase()}function x(e,t){let r=h(t),n=(e??"@").trim();if(!n||n==="@")return r;let o=h(n);if(o===r||o.endsWith(`.${r}`))return o;return`${o}.${r}`}function $o(e,t){return e.map((r)=>({...r,name:x(r.name,t),proxied:r.proxied??!1}))}function H(e,t){if(e.type!==t.type)return!1;if(h(e.name)!==h(t.name))return!1;if(j.has(t.type))return!0;if(t.type==="TXT"){let r=w(t.content);if(r)return w(f(e.content))===r;return f(e.content)===f(t.content)}return f(e.content)===f(t.content)}function G(e,t){if(f(e.content)!==f(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 Lo(e){let{provider:t,zone:r,records:n}=e,o={outcomes:[],warnings:[]};if(n.length===0)return o;let s=await t.listRecords(r);if(!s.success)return o.warnings.push(`could not list ${r}: ${s.message||"unknown provider error"} — records not reconciled`),o;let i=s.records;for(let a of n){let c=i.filter((u)=>H(u,a));if(c.length>0&&c.every((u)=>G(u,a))){o.outcomes.push({record:a,action:"unchanged"});continue}let d={name:a.name,type:a.type,content:a.content,ttl:a.ttl??3600,...a.priority!==void 0?{priority:a.priority}:{},...a.proxied!==void 0?{proxied:a.proxied}:{}},l=a.type==="TXT"&&w(a.content)!==void 0;if(l)for(let u of c){let y=await t.deleteRecord(r,{name:u.name,type:u.type,content:u.content});if(!y.success)o.warnings.push(`could not remove superseded ${u.type} at ${u.name}: ${y.message||"unknown error"}`)}let g=l||c.length===0?await t.createRecord(r,d):await t.upsertRecord(r,d);if(g.success)o.outcomes.push({record:a,action:c.length>0?"updated":"created"});else o.outcomes.push({record:a,action:"failed",message:g.message})}for(let a of["MX"]){let c=new Set(n.filter((d)=>d.type===a).map((d)=>h(d.name)));for(let d of c){let l=new Set(n.filter((u)=>u.type===a&&h(u.name)===d).map((u)=>f(u.content).toLowerCase())),g=i.filter((u)=>u.type===a&&h(u.name)===d&&!l.has(f(u.content).toLowerCase()));for(let u of g)o.warnings.push(`${d} has an undeclared ${a} record (${u.content}) alongside the declared one — mail will be split between them. Remove it at the provider if it is stale.`)}}return o}class bn{name="route53";client;hostedZoneCache=new Map;providedHostedZoneId;constructor(e="us-east-1",t){this.client=new F(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 n=await this.client.findHostedZoneForDomain(e);if(n){let o=n.Id.replace("/hostedzone/","");return this.hostedZoneCache.set(t,o),o}return null}normalizeName(e,t){let r=e.replace(/\.$/,""),n=t.replace(/\.$/,"");if(!n||n==="@")return`${r}.`;if(n===r||n.endsWith(`.${r}`))return`${n}.`;return`${n}.${r}.`}formatValue(e){let t=e.content;if(e.type==="TXT"&&!t.startsWith('"'))t=J(t);if(e.type==="MX"&&e.priority!==void 0)t=`${e.priority} ${t}`;return t}sameValue(e,t,r){return e==="TXT"?T(t)===T(r):t===r}async currentSet(e,t,r){let o=(await this.client.listResourceRecordSets({HostedZoneId:e,StartRecordName:t,StartRecordType:r,MaxItems:"1"})).ResourceRecordSets?.[0];if(!o||o.Name.toLowerCase()!==t.toLowerCase()||o.Type!==r||o.AliasTarget||o.SetIdentifier)return null;return{ttl:o.TTL??300,values:(o.ResourceRecords??[]).map((s)=>s.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 n=this.normalizeName(e,t.name),o=this.formatValue(t),s=await this.currentSet(r,n,t.type);if(s?.values.some((c)=>this.sameValue(t.type,c,o)))return{success:!0,message:"Record already present"};let i=[...s?.values??[],o];return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Created by ts-cloud DNS provider",Changes:[{Action:s?"UPSERT":"CREATE",ResourceRecordSet:{Name:n,Type:t.type,TTL:s?.ttl??t.ttl??300,ResourceRecords:i.map((c)=>({Value:c}))}}]}})).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 n=this.normalizeName(e,t.name),o=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:n,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:o}]}}]}})).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 n=this.normalizeName(e,t.name),o=this.formatValue(t),s=await this.currentSet(r,n,t.type);if(!s||!s.values.some((a)=>this.sameValue(t.type,a,o)))return{success:!0,message:"Record already absent"};let i=s.values.filter((a)=>!this.sameValue(t.type,a,o));return await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Deleted by ts-cloud DNS provider",Changes:[{Action:i.length>0?"UPSERT":"DELETE",ResourceRecordSet:{Name:n,Type:t.type,TTL:s.ttl,ResourceRecords:(i.length>0?i:s.values).map((a)=>({Value:a}))}}]}}),{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 n=await this.client.listResourceRecordSets({HostedZoneId:r,StartRecordType:t}),o=[];for(let s of n.ResourceRecordSets){if(t&&s.Type!==t)continue;if(s.AliasTarget)continue;for(let i of s.ResourceRecords||[]){let a=i.Value,c;if(s.Type==="MX"){let d=a.split(" ");if(d.length>=2)c=Number.parseInt(d[0],10),a=d.slice(1).join(" ")}if(s.Type==="TXT"&&a.startsWith('"'))a=T(a);o.push({name:s.Name.replace(/\.$/,""),type:s.Type,content:a,ttl:s.TTL,priority:c})}}return{success:!0,records:o}}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:F.CloudFrontHostedZoneId,targetDnsName:e.cloudFrontDomainName,evaluateTargetHealth:!1})}async createAlbAlias(e){let t=F.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 _=255;function J(e){let t=[];for(let r=0;r<e.length;r+=_)t.push(e.slice(r,r+_));if(t.length===0)t.push("");return t.map((r)=>`"${r.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`).join(" ")}function T(e){if(!e.startsWith('"'))return e;let t="",r=!1;for(let n=0;n<e.length;n++){let o=e[n];if(!r){if(o==='"')r=!0;continue}if(o==="\\"&&n+1<e.length){t+=e[++n];continue}if(o==='"'){r=!1;continue}t+=o}return t}async function Mo(e,t){let r=[],n,o;for(;;){let s=await e.listResourceRecordSets({HostedZoneId:t,StartRecordName:n,StartRecordType:o,MaxItems:"100"});if(r.push(...s.ResourceRecordSets),!s.IsTruncated)break;if(n=s.NextRecordName,o=s.NextRecordType,!n)break}return r}function m(e){return e.replace(/\.$/,"").toLowerCase()}function k(e){return e.replace(/\.$/,"")}function v(e){if(e.type==="SRV"&&e.weight!==void 0&&e.port!==void 0)return`${e.weight} ${e.port} ${k(e.content)}`;return k(e.content)}function Q(e){let t=e.match(/"(?:[^"\\]|\\.)*"/g);if(!t)return e;return t.map((r)=>r.slice(1,-1).replace(/\\(.)/g,"$1")).join("")}function Uo(e,t){let r=m(t),n=[],o=[],s=[],i=new Set;for(let a of e){let c=m(a.Name),d=a.Type;if(d==="SOA"||d==="NS"&&c===r){o.push({name:c,type:d,reason:"owned by the destination provider"});continue}if(a.SetIdentifier){o.push({name:c,type:d,reason:`routing policy record (SetIdentifier=${a.SetIdentifier}) has no equivalent — recreate by hand`}),s.push(`${d} ${c} is part of a Route53 routing policy and was NOT migrated`);continue}if(a.AliasTarget){if(i.has(c))continue;i.add(c);let l=m(a.AliasTarget.DNSName);if(n.push({name:c,type:"CNAME",content:l,ttl:300,translatedFrom:`${d} ALIAS → ${l}`}),a.AliasTarget.EvaluateTargetHealth)s.push(`${c} was an ALIAS with health evaluation enabled; the CNAME that replaces it has no health check`);continue}for(let l of a.ResourceRecords||[]){let g=ee(c,d,l.Value,a.TTL);if("reason"in g){o.push({name:c,type:d,reason:g.reason}),s.push(`${d} ${c}: ${g.reason}`);continue}n.push(g)}}return{zone:r,records:n,skipped:o,warnings:s}}function ee(e,t,r,n){let o={name:e,ttl:n};switch(t){case"A":case"AAAA":case"CNAME":case"PTR":return{...o,type:t==="PTR"?"CNAME":t,content:m(r)};case"TXT":return{...o,type:"TXT",content:Q(r)};case"MX":{let[s,...i]=r.trim().split(/\s+/);if(!i.length)return{reason:`malformed MX value "${r}"`};return{...o,type:"MX",content:m(i.join(" ")),priority:Number(s)}}case"SRV":{let s=r.trim().split(/\s+/);if(s.length<4)return{reason:`malformed SRV value "${r}"`};let[i,a,c]=s.slice(0,3).map(Number);return{...o,type:"SRV",content:m(s.slice(3).join(" ")),priority:i,weight:a,port:c}}case"NS":return{...o,type:"NS",content:m(r)};case"CAA":return{...o,type:"CAA",content:r.trim()};default:return{reason:`unsupported record type ${t}`}}}var te=new Set(["TXT","MX","SRV","NS","CAA"]);async function Bo(e,t){let r=[],n=[],o=new Set;try{let s=await e.listRecords(t.zone);for(let i of s.records||[])o.add(`${m(i.name)}|${i.type}|${v(i)}`)}catch{}for(let s of t.records){let i={...s,proxied:!1},a=`${m(s.name)}|${s.type}|${v(s)}`;if(!te.has(s.type)){let d=await e.upsertRecord(t.zone,i);if(d.success)r.push(s);else n.push({record:s,message:d.message||"unknown provider error"});continue}if(o.has(a)){r.push(s);continue}let c=await e.createRecord(t.zone,i);if(c.success)o.add(a),r.push(s);else n.push({record:s,message:c.message||"unknown provider error"})}return{applied:r,failed:n}}async function Fo(e,t){let r=await e.listRecords(t.zone),n=[],o=[],s=new Map;for(let i of r.records||[]){let a=`${m(i.name)}|${i.type}`,c=s.get(a)??[];c.push(v(i)),s.set(a,c)}for(let i of t.records){let a=s.get(`${m(i.name)}|${i.type}`),c=v(i);if(a?.some((d)=>d===c))n.push(i);else o.push({record:i,found:a?.join(", ")})}return{matched:n,missing:o,ok:o.length===0}}class K{client;region;constructor(e="us-east-1"){this.client=new p,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((n)=>({DomainName:n.DomainName,ValidationDomain:n.ValidationDomain,ValidationStatus:n.ValidationStatus,ResourceRecord:n.ResourceRecord?{Name:n.ResourceRecord.Name,Type:n.ResourceRecord.Type,Value:n.ResourceRecord.Value}:void 0,ValidationMethod:n.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((n)=>({CertificateArn:n.CertificateArn,DomainName:n.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((n)=>n.DomainName===e||n.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 n=0;n<t;n++){let o=await this.describeCertificate({CertificateArn:e});if(o.Status==="ISSUED")return o;if(o.Status==="FAILED"||o.Status==="VALIDATION_TIMED_OUT")return null;await new Promise((s)=>setTimeout(s,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 n=r.DomainName.slice(2),o=t.split("."),s=n.split(".");if(o.slice(-s.length).join(".")===n)return!0}if(r.SubjectAlternativeNames)for(let n of r.SubjectAlternativeNames){if(n===t)return!0;if(n.startsWith("*.")){let o=n.slice(2),s=t.split("."),i=o.split(".");if(s.slice(-i.length).join(".")===o)return!0}}return!1}}class jo{acm;route53;dnsProvider;constructor(e="us-east-1",t){if(this.acm=new K(e),this.route53=new F,t&&t.provider!=="route53")this.dnsProvider=B(t)}async requestAndValidate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:n=[],waitForValidation:o=!1,maxWaitMinutes:s=30}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let{CertificateArn:i}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:n.length>0?[t,...n]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(i);let a=await this.acm.getDnsValidationRecords(i);if(this.dnsProvider)for(let c of a){let d=await this.dnsProvider.upsertRecord(t,{name:c.recordName,type:c.recordType,content:c.recordValue,ttl:300});if(!d.success)console.warn(`Failed to create validation record for ${c.domainName}: ${d.message}`)}else if(r)for(let c of a)await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${c.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:c.recordName,Type:c.recordType,TTL:300,ResourceRecords:[{Value:c.recordValue}]}}]}});if(o){if(!await this.acm.waitForCertificateValidation(i,s*2,30000))throw Error(`Certificate validation timed out after ${s} minutes`)}return{certificateArn:i,validationRecords:a}}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let n=await this.acm.describeCertificate({CertificateArn:e});if(n.DomainValidationOptions&&n.DomainValidationOptions.length>0&&n.DomainValidationOptions[0].ResourceRecord)return;await new Promise((o)=>setTimeout(o,2000))}throw Error("Timeout waiting for DNS validation options")}async createValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:n}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let o=await this.acm.getDnsValidationRecords(t),s=[];if(this.dnsProvider){let i=n||o[0]?.domainName;for(let a of o){let c=await this.dnsProvider.upsertRecord(i,{name:a.recordName,type:a.recordType,content:a.recordValue,ttl:300});s.push({...a,changeId:c.success?c.id:void 0})}}else if(r)for(let i of o){let a=await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${i.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:i.recordName,Type:i.recordType,TTL:300,ResourceRecords:[{Value:i.recordValue}]}}]}});s.push({...i,changeId:a.ChangeInfo?.Id})}return s}async deleteValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:n}=e,o=await this.acm.getDnsValidationRecords(t);if(this.dnsProvider){let s=n||o[0]?.domainName;for(let i of o)try{await this.dnsProvider.deleteRecord(s,{name:i.recordName,type:i.recordType,content:i.recordValue})}catch{}}else if(r)for(let s of o)try{await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`Cleanup ACM DNS validation for ${s.domainName}`,Changes:[{Action:"DELETE",ResourceRecordSet:{Name:s.recordName,Type:s.recordType,TTL:300,ResourceRecords:[{Value:s.recordValue}]}}]}})}catch{}}async findOrCreateCertificate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:n,waitForValidation:o=!0}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let s=await this.acm.findCertificateByDomain(t);if(s&&s.Status==="ISSUED")return{certificateArn:s.CertificateArn,isNew:!1};let{certificateArn:i}=await this.requestAndValidate({domainName:t,hostedZoneId:r,subjectAlternativeNames:n,waitForValidation:o});return{certificateArn:i,isNew:!0}}hasExternalDnsProvider(){return this.dnsProvider!==void 0}getDnsProviderName(){return this.dnsProvider?.name||"route53"}}class Gt{acm;dnsProvider;constructor(e,t="us-east-1"){if(this.acm=new K(t),"provider"in e)this.dnsProvider=B(e);else this.dnsProvider=e}getProvider(){return this.dnsProvider}async requestAndValidate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:n=!1,maxWaitMinutes:o=30}=e,{CertificateArn:s}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:r.length>0?[t,...r]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(s);let i=await this.acm.getDnsValidationRecords(s);for(let c of i){let d=await this.dnsProvider.upsertRecord(t,{name:c.recordName,type:c.recordType,content:c.recordValue,ttl:300});if(!d.success)console.warn(`Failed to create validation record for ${c.domainName}: ${d.message}`)}let a="pending";if(n)a=(await this.acm.waitForCertificateValidation(s,o*2,30000))?.Status==="ISSUED"?"issued":"failed";return{certificateArn:s,validationRecords:i.map((c)=>({domainName:c.domainName,recordName:c.recordName,recordType:c.recordType,recordValue:c.recordValue})),isNew:!0,status:a}}async createValidationRecords(e){let{certificateArn:t,domain:r}=e,n=[],o=await this.acm.getDnsValidationRecords(t);for(let s of o){let i=await this.dnsProvider.upsertRecord(r,{name:s.recordName,type:s.recordType,content:s.recordValue,ttl:300});if(!i.success)n.push(`Failed to create record for ${s.domainName}: ${i.message}`)}return{success:n.length===0,records:o.map((s)=>({domainName:s.domainName,recordName:s.recordName,recordType:s.recordType,recordValue:s.recordValue})),errors:n}}async deleteValidationRecords(e){let{certificateArn:t,domain:r}=e,n=[],o=await this.acm.getDnsValidationRecords(t);for(let s of o){let i=await this.dnsProvider.deleteRecord(r,{name:s.recordName,type:s.recordType,content:s.recordValue});if(!i.success)n.push(`Failed to delete record for ${s.domainName}: ${i.message}`)}return{success:n.length===0,errors:n}}async findOrCreateCertificate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:n=!0,maxWaitMinutes:o}=e,s=await this.acm.findCertificateByDomain(t);if(s&&s.Status==="ISSUED"){let i=s.SubjectAlternativeNames||[s.DomainName],a=i.some((d)=>d===`*.${t}`);if(r.every((d)=>i.includes(d)||a))return{certificateArn:s.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:n,maxWaitMinutes:o})}async requestCertificateWithCommonSans(e){let{domainName:t,includeWww:r=!0,includeWildcard:n=!1,additionalSans:o=[],waitForValidation:s=!1}=e,i=[];if(r)i.push(`www.${t}`);if(n)i.push(`*.${t}`);return i.push(...o),this.requestAndValidate({domainName:t,subjectAlternativeNames:i,waitForValidation:s})}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let n=await this.acm.describeCertificate({CertificateArn:e});if(n.DomainValidationOptions&&n.DomainValidationOptions.length>0&&n.DomainValidationOptions[0].ResourceRecord)return;await new Promise((o)=>setTimeout(o,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 B(e){switch(e.provider){case"route53":return new bn(e.region,e.hostedZoneId);case"porkbun":return new ot(e.apiKey,e.secretKey);case"godaddy":return new Ht(e.apiKey,e.apiSecret,e.environment);case"cloudflare":return new he(e.apiToken,{zoneId:e.zoneId,accountId:e.accountId});default:throw Error(`Unknown DNS provider: ${e.provider}`)}}class Mi{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,n=process.env.GODADDY_API_SECRET;if(r&&n){let s=process.env.GODADDY_ENVIRONMENT;this.addGoDaddy(r,n,s)}let o=process.env.CLOUDFLARE_API_TOKEN;if(o)this.addCloudflare(o,{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((o)=>o.provider===e);if(!r)return null;let n=B(r);return this.providers.set(e,n),n}async getProviderForDomain(e){for(let t of this.configs){let r=B(t);if(await r.canManageDomain(e))return r}return null}getAllProviders(){return this.configs.map((e)=>B(e))}}var qe=new Mi;
2
- export{ot,Ht,Dr,Xs,Qs,kr,he,Li,Nr,$o,Lo,bn,Mo,Uo,Bo,Fo,K,jo,Gt,B,Mi};
1
+ import{p}from"./chunk-540wkkhs.js";import{F}from"./chunk-e12679p1.js";var A=new Set(["A","AAAA","CNAME"]);function N(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 C(e,t){let r=t?.headers.get("retry-after"),n=r===null||r===void 0?void 0:Number(r)*1000,o=Number.isFinite(n)?Math.max(0,n):Math.min(1000*2**(e-1),30000);await new Promise((s)=>setTimeout(s,o))}class ot{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 n=1;n<=8;n+=1){let o,s=new AbortController,i=setTimeout(()=>{s.abort(Error(`Porkbun API request timed out after ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);try{o=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:s.signal})}catch(c){if(r=c,n===8)throw c;await C(n);continue}finally{clearTimeout(i)}if(!o.ok){let c=await o.clone().json().then((d)=>d?.message).catch(()=>{return});if(r=Error(`Porkbun API error: ${o.status} ${o.statusText}${c?`: ${c}`:""}`),!N(o.status)||n===8)throw r;await C(n,o);continue}let a=await o.json();if(a.status==="ERROR"){if(r=Error(`Porkbun API error: ${a.message||"Unknown error"}`),!N(0,a.message)||n===8)throw r;await C(n,o);continue}return a}throw r}getSubdomain(e,t){let r=e.replace(/\.$/,""),n=t.replace(/\.$/,"");if(r===n)return"";if(r.endsWith(`.${n}`))return r.slice(0,-(n.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(!ot.ADDRESS_TYPES.has(t.type))return[];let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(!o.success)return[`could not list records to clear ALIAS/CNAME conflicts: ${o.message??"unknown provider error"}`];let s=[];for(let i of o.records){if(i.type!=="ALIAS"&&i.type!=="CNAME")continue;if(this.getSubdomain(i.name,r)!==n)continue;let a=await this.deleteRecord(e,i);if(!a.success)s.push(`could not remove conflicting ${i.type} on ${i.name}: ${a.message??"unknown provider error"}`)}return s}async addressRecordExists(e,t){let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(!o.success)return!0;return o.records.some((s)=>s.type===t.type&&this.getSubdomain(s.name,r)===n&&s.content===t.content)}async createRecord(e,t){try{let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),o={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(n)o.name=n;if((t.type==="MX"||t.type==="SRV")&&t.priority!==void 0)o.prio=String(t.priority);if(t.type==="SRV"&&t.weight!==void 0&&t.port!==void 0)o.content=`${t.weight} ${t.port} ${t.content}`;let s=await this.clearConflictingAliases(e,t),i=await this.request(`/dns/create/${r}`,o);if(ot.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${s.length>0?` (${s.join("; ")})`:""}. A conflicting ALIAS/CNAME on the same name silently voids the write.`};return{success:!0,id:i.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),n=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(o.success){let s=o.records.find((i)=>this.getSubdomain(i.name,r)===n&&i.type===t.type);if(s?.id&&s.content===t.content&&(t.ttl===void 0||s.ttl===t.ttl)&&(t.type!=="MX"&&t.type!=="SRV"||t.priority===void 0||s.priority===t.priority))return{success:!0,id:s.id,message:"Record already up to date"};if(s?.id){let i={type:t.type,content:t.content,ttl:String(t.ttl||600)};if(n)i.name=n;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}`;return await this.request(`/dns/edit/${r}/${s.id}`,i),{success:!0,id:s.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 n=this.getSubdomain(t.name,r),o=await this.listRecords(e);if(!o.success)return{success:!1,message:"Failed to list records"};let s=o.records.find((i)=>this.getSubdomain(i.name,r)===n&&i.type===t.type&&i.content===t.content);if(!s?.id)return{success:!1,message:"Record not found"};return await this.request(`/dns/delete/${r}/${s.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),n=`/dns/retrieve/${r}`;if(t)n=`/dns/retrieveByNameType/${r}/${t}`;return{success:!0,records:((await this.request(n)).records||[]).map((i)=>({id:i.id,name:i.name||r,type:i.type,content:i.content,ttl:Number.parseInt(i.ttl,10),priority:i.prio?Number.parseInt(i.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 Gt{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 n=`${this.baseUrl}${t}`,o={Authorization:this.authorization(),"Content-Type":"application/json",Accept:"application/json"},s={method:e,headers:o};if(r)s.body=JSON.stringify(r);let i=await fetch(n,s);if(i.status===204)return{};if(i.ok){let c=await i.text();if(c)return JSON.parse(c);return{}}let a=`GoDaddy API error: ${i.status} ${i.statusText}`;try{let c=await i.json();if(c.message)a=`GoDaddy API error: ${c.message}`;if(c.fields)a+=` - Fields: ${JSON.stringify(c.fields)}`}catch{}throw Error(a)}getSubdomain(e,t){let r=e.replace(/\.$/,""),n=t.replace(/\.$/,"");if(r===n)return"@";if(r.endsWith(`.${n}`))return r.slice(0,-(n.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),n=this.getSubdomain(e.name,r),o={type:e.type,name:n,data:e.content,ttl:e.ttl||600};if(e.type==="MX"&&e.priority!==void 0)o.priority=e.priority;return o}fromGoDaddyRecord(e,t){let r=this.getRootDomain(t),n=e.name;if(n==="@")n=r;else if(!n.endsWith(r))n=`${n}.${r}`;return{name:n,type:e.type,content:e.data,ttl:e.ttl,priority:e.priority}}async createRecord(e,t){try{let r=this.getRootDomain(e),n=this.toGoDaddyRecord(t,e);return await this.request("PATCH",`/v1/domains/${r}/records`,[n]),{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),n=this.toGoDaddyRecord(t,e);return await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${n.name}`,[n]),{success:!0,message:"Record upserted successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=this.getRootDomain(e),n=this.getSubdomain(t.name,r),o=await this.request("GET",`/v1/domains/${r}/records/${t.type}/${n}`),s=o.filter((i)=>i.data!==t.content);if(s.length===o.length)return{success:!1,message:"Record not found"};if(s.length===0)try{await this.request("DELETE",`/v1/domains/${r}/records/${t.type}/${n}`)}catch{}else await this.request("PUT",`/v1/domains/${r}/records/${t.type}/${n}`,s);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),n=`/v1/domains/${r}/records`;if(t)n=`/v1/domains/${r}/records/${t}`;return{success:!0,records:(await this.request("GET",n)).map((s)=>this.fromGoDaddyRecord(s,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 Z=["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"],O=[{name:"x-stx-router",value:"true"}];function R(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function b(e){return`{${e.map(R).join(" ")}}`}function M(e){let t=`http.request.headers[${R(e.name.toLowerCase())}]`;return e.value===void 0?`len(${t}) > 0`:`any(${t}[*] == ${R(e.value)})`}function Dr(e){if(e.length===1)return`http.host eq ${R(e[0])}`;return`http.host in ${b(e)}`}function Xs(e,t={}){if(t.enabled===!1||e.length===0)return[];let r=Dr(e),n=[],s=(t.bypassPaths??[]).map((V)=>`starts_with(http.request.uri.path, ${R(V)})`),a=(t.negotiatedRequestHeaders??O).map(M),c=[...s,...a],d=c.length>0?`(${c.join(" or ")})`:void 0;if(d)n.push({action:"set_cache_settings",description:"bypass cache",expression:`(${r} and ${d})`,enabled:!0,action_parameters:{cache:!1}});let l=d?`${r} and not ${d}`:r,g=t.assetExtensions??Z,u=g.length>0?`lower(http.request.uri.path.extension) in ${b([...g])}`:void 0;if(u)n.push({action:"set_cache_settings",description:"cache fingerprinted assets",expression:`(${l} and ${u})`,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=u?`(${l} and not ${u})`:`(${l})`;if(t.documentEdgeTtl===0)return n.push({action:"set_cache_settings",description:"bypass documents",expression:y,enabled:!0,action_parameters:{cache:!1}}),n;return n.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}}}),n}function Qs(e,t,r){if(e.length===0||!t||!r)return[];return[{action:"rewrite",description:"origin guard header",expression:`(${Dr(e)})`,enabled:!0,action_parameters:{headers:{[t]:{operation:"set",value:r}}}}]}var z="https://api.cloudflare.com/client/v4",kr="[ts-cloud]";class he{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 n=`${z}${t}`,o={Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},s={method:e,headers:o};if(r)s.body=JSON.stringify(r);let a=await(await fetch(n,s)).json();if(!a.success){let c=a.errors.map((d)=>d.message).join(", ");throw Error(`Cloudflare API error: ${c}`)}return a}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 i=await this.resolveConfiguredZoneName();if(i&&(t===i||t.endsWith(`.${i}`)))return{id:this.configuredZoneId,name:i}}let r=this.getRootDomain(t),n=this.zoneCache.get(r);if(n)return{id:n,name:r};let o=await this.request("GET",`/zones?name=${encodeURIComponent(r)}`);if(!o.result||o.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 s=o.result[0].id;return this.zoneCache.set(r,s),{id:s,name:o.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 n={type:e.type,name:this.getFullRecordName(e.name,t),content:e.content||e.value||"",ttl:e.ttl||1},o=r??e.proxied;if(o!==void 0&&A.has(e.type)){if(n.proxied=o,o)n.ttl=1}if(e.type==="MX"&&e.priority!==void 0)n.priority=e.priority;if(e.type==="SRV"){let s=U(e);if(s)n.data=s,delete n.content,delete n.priority;else if(e.priority!==void 0)n.priority=e.priority}return n}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),n=this.toCloudflareRecord(t,r.name);return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,n)).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),n=this.getFullRecordName(t.name,r.name),s=(await this.request("GET",`/zones/${r.id}/dns_records?type=${t.type}&name=${encodeURIComponent(n)}`)).result?.[0],i=t.proxied??s?.proxied,a=this.toCloudflareRecord(t,r.name,i);if(s)return{success:!0,id:(await this.request("PUT",`/zones/${r.id}/dns_records/${s.id}`,a)).result.id,message:"Record updated successfully"};return{success:!0,id:(await this.request("POST",`/zones/${r.id}/dns_records`,a)).result.id,message:"Record created successfully"}}catch(r){return this.createRecord(e,t)}}async deleteRecord(e,t){try{let r=await this.resolveZone(e),n=r.id,o=this.getFullRecordName(t.name,r.name),s=await this.request("GET",`/zones/${n}/dns_records?type=${t.type}&name=${encodeURIComponent(o)}`);if(!s.result||s.result.length===0)return{success:!1,message:"Record not found"};let i=s.result.find((a)=>a.content===t.content);if(!i)return{success:!1,message:"Record with matching content not found"};return await this.request("DELETE",`/zones/${n}/dns_records/${i.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 n=`/zones/${await this.getZoneId(e)}/dns_records?per_page=100`;if(t)n+=`&type=${t}`;let o=[],s=1,i=!0;while(i){let a=await this.request("GET",`${n}&page=${s}`);if(o.push(...a.result||[]),a.result_info)i=s<a.result_info.total_pages,s++;else i=!1}return{success:!0,records:o.map((a)=>this.fromCloudflareRecord(a))}}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 n=await this.request("GET",`/zones?per_page=50&page=${t}`);if(e.push(...n.result||[]),n.result_info)r=t<n.result_info.total_pages,t++;else r=!1}return e.map((n)=>n.name)}catch{return[]}}async createZone(e,t={}){let r=e.replace(/\.$/,"").toLowerCase(),n=t.accountId??this.accountId;if(!n)throw Error(`Cannot create zone ${r}: no Cloudflare account id. Set CLOUDFLARE_ACCOUNT_ID, or pass accountId.`);let o=await this.getZoneDetails(r);if(o)return{...o,created:!1};try{let i=(await this.request("POST","/zones",{name:r,account:{id:n},jump_start:t.jumpStart??!1})).result;return this.zoneCache.set(i.name,i.id),{id:i.id,name:i.name,status:i.status,nameServers:i.name_servers??[],created:!0}}catch(s){let i=s instanceof Error?s.message:String(s);if(!/already exists|1061/i.test(i))throw s;let a=await this.getZoneDetails(r);if(!a)throw s;return{...a,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`),n=new Set;for(let o of r.result||[]){if(o.status!=="active")continue;for(let s of o.hosts||[])n.add(s.toLowerCase())}return[...n]}catch{return null}}async purgeCache(e,t){try{let r=await this.getZoneId(e),n={};if(t?.purgeEverything)n.purge_everything=!0;else{if(t?.files)n.files=t.files;if(t?.tags)n.tags=t.tags;if(t?.hosts)n.hosts=t.hosts}if(Object.keys(n).length===0)n.purge_everything=!0;return await this.request("POST",`/zones/${r}/purge_cache`,n),!0}catch{return!1}}async getRecordProxyStatus(e,t){try{let r=await this.resolveZone(e),n=r.id,o=this.getFullRecordName(t.name,r.name),s=await this.request("GET",`/zones/${n}/dns_records?type=${t.type}&name=${encodeURIComponent(o)}`);if(s.result&&s.result.length>0)return s.result.find((a)=>a.content===t.content)?.proxied??null;return null}catch{return null}}async setRecordProxyStatus(e,t,r){try{let n=await this.resolveZone(e),o=n.id,s=this.getFullRecordName(t.name,n.name),i=await this.request("GET",`/zones/${o}/dns_records?type=${t.type}&name=${encodeURIComponent(s)}`);if(!i.result||i.result.length===0)return!1;let a=i.result.find((c)=>c.content===t.content);if(!a)return!1;return await this.request("PATCH",`/zones/${o}/dns_records/${a.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`),n={};for(let o of r.result||[])n[o.id]=o.value;return n}async applyZoneSettings(e,t){let r=await this.getZoneId(e),n=await this.getZoneSettings(e).catch(()=>({})),o=[],s=[];for(let[i,a]of Object.entries(t)){if(a===void 0)continue;let c=n[i];if(c!==void 0&&P(c,a))continue;try{await this.request("PATCH",`/zones/${r}/settings/${i}`,{value:a}),o.push({id:i,from:c,to:a})}catch(d){s.push({id:i,error:d instanceof Error?d.message:String(d)})}}return{changed:o,failed:s}}async getManagedRequestHeaders(e){let t=await this.getZoneId(e),r=await this.request("GET",`/zones/${t}/managed_headers`),n={};for(let o of r.result?.managed_request_headers||[])n[o.id]=o.enabled===!0;return n}async applyTieredCache(e,t){let r=[],n=[],o=await this.getZoneId(e),s=[["tiered_caching",`/zones/${o}/argo/tiered_caching`,t==="off"?"off":"on"],["tiered_cache_smart_topology_enable",`/zones/${o}/cache/tiered_cache_smart_topology_enable`,t==="smart"?"on":"off"]];if(t==="off")s.reverse();for(let[i,a,c]of s)try{let l=(await this.request("GET",a)).result?.value;if(l===c)continue;await this.request("PATCH",a,{value:c}),r.push({id:i,from:l,to:c})}catch(d){n.push({id:i,error:d instanceof Error?d.message:String(d)})}return{changed:r,failed:n}}async applyManagedRequestHeaders(e,t){let r=[],n=[],o=Object.entries(t).filter(([,c])=>c!==void 0);if(o.length===0)return{changed:r,failed:n};let s=await this.getZoneId(e),i;try{i=await this.getManagedRequestHeaders(e)}catch(c){let d=c instanceof Error?c.message:String(c);for(let[l]of o)n.push({id:l,error:`could not read managed headers — ${d}`});return{changed:r,failed:n}}let a=[];for(let[c,d]of o){if(!(c in i)){n.push({id:c,error:"not a managed request header transform on this zone"});continue}if(i[c]!==d)a.push([c,d])}if(a.length===0)return{changed:r,failed:n};try{await this.request("PATCH",`/zones/${s}/managed_headers`,{managed_request_headers:a.map(([c,d])=>({id:c,enabled:d})),managed_response_headers:[]});for(let[c,d]of a)r.push({id:c,from:i[c],to:d})}catch(c){let d=c instanceof Error?c.message:String(c);for(let[l]of a)n.push({id:l,error:d})}return{changed:r,failed:n}}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 n=await this.getZoneId(e),o=await this.getPhaseRules(e,t),s=r.map((c)=>({...c,description:c.description?.startsWith(kr)?c.description:`${kr} ${c.description||t}`})),a=L(o,s).map(({id:c,...d})=>d);return await this.request("PUT",`/zones/${n}/rulesets/phases/${t}/entrypoint`,{rules:a}),{success:!0}}catch(n){return{success:!1,message:n instanceof Error?n.message:String(n)}}}}var S=/http\.host (?:eq "[^"]+"|in \{[^}]*\})/;function Li(e){return S.test(e)?e.replace(S,"\x00hosts\x00"):null}function I(e,t){return e.replace(S,Dr(t))}function D(e){if(Array.isArray(e))return`[${e.map(D).join(",")}]`;if(e&&typeof e==="object")return`{${Object.entries(e).filter(([,r])=>r!==void 0).sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>`${JSON.stringify(r)}:${D(n)}`).join(",")}}`;return JSON.stringify(e)}function q(e,t){let r=Li(e.expression);return r!==null&&r===Li(t.expression)&&e.action===t.action&&e.description===t.description&&(e.enabled??!0)===(t.enabled??!0)&&D(e.action_parameters)===D(t.action_parameters)}function L(e,t){let r=new Set(t.flatMap((s)=>Nr(s.expression))),n=(s)=>(s.description||"").startsWith(kr),o=[];for(let s of e){if(!n(s)){o.push(s);continue}let i=Nr(s.expression);if(i.length===0){if(r.size>0)o.push(s);continue}let a=i.filter((c)=>!r.has(c));if(a.length===i.length)o.push(s);else if(a.length>0)o.push({...s,expression:I(s.expression,a)})}for(let s of t){let i=Nr(s.expression),a=i.length>0?o.findIndex((l)=>n(l)&&q(l,s)):-1;if(a===-1){o.push(s);continue}let c=o[a],d=[...new Set([...Nr(c.expression),...i])];o[a]={...c,expression:I(c.expression,d)}}return o}function Nr(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 n of r[1].matchAll(/"([^"]+)"/g))t.push(n[1]);return t}function P(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((o,s)=>P(o,t[s]))}let r=e,n=t;return Object.keys(n).every((o)=>P(r[o],n[o]))}function U(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:E(t)};let r=t.split(/\s+/);if(r.length<4)return null;let[n,o,s]=r.slice(0,3).map(Number);if(![n,o,s].every(Number.isFinite))return null;return{priority:n,weight:o,port:s,target:E(r.slice(3).join(" "))}}function E(e){return e.replace(/\.$/,"")}var j=new Set(["A","AAAA","CNAME","ALIAS"]);function w(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 f(e){return e.trim().replace(/^"(.*)"$/s,"$1")}function h(e){return e.replace(/\.$/,"").toLowerCase()}function x(e,t){let r=h(t),n=(e??"@").trim();if(!n||n==="@")return r;let o=h(n);if(o===r||o.endsWith(`.${r}`))return o;return`${o}.${r}`}function $o(e,t){return e.map((r)=>({...r,name:x(r.name,t),proxied:r.proxied??!1}))}function H(e,t){if(e.type!==t.type)return!1;if(h(e.name)!==h(t.name))return!1;if(j.has(t.type))return!0;if(t.type==="TXT"){let r=w(t.content);if(r)return w(f(e.content))===r;return f(e.content)===f(t.content)}return f(e.content)===f(t.content)}function G(e,t){if(f(e.content)!==f(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 Lo(e){let{provider:t,zone:r,records:n}=e,o={outcomes:[],warnings:[]};if(n.length===0)return o;let s=await t.listRecords(r);if(!s.success)return o.warnings.push(`could not list ${r}: ${s.message||"unknown provider error"} — records not reconciled`),o;let i=s.records;for(let a of n){let c=i.filter((u)=>H(u,a));if(c.length>0&&c.every((u)=>G(u,a))){o.outcomes.push({record:a,action:"unchanged"});continue}let d={name:a.name,type:a.type,content:a.content,ttl:a.ttl??3600,...a.priority!==void 0?{priority:a.priority}:{},...a.proxied!==void 0?{proxied:a.proxied}:{}},l=a.type==="TXT"&&w(a.content)!==void 0;if(l)for(let u of c){let y=await t.deleteRecord(r,{name:u.name,type:u.type,content:u.content});if(!y.success)o.warnings.push(`could not remove superseded ${u.type} at ${u.name}: ${y.message||"unknown error"}`)}let g=l||c.length===0?await t.createRecord(r,d):await t.upsertRecord(r,d);if(g.success)o.outcomes.push({record:a,action:c.length>0?"updated":"created"});else o.outcomes.push({record:a,action:"failed",message:g.message})}for(let a of["MX"]){let c=new Set(n.filter((d)=>d.type===a).map((d)=>h(d.name)));for(let d of c){let l=new Set(n.filter((u)=>u.type===a&&h(u.name)===d).map((u)=>f(u.content).toLowerCase())),g=i.filter((u)=>u.type===a&&h(u.name)===d&&!l.has(f(u.content).toLowerCase()));for(let u of g)o.warnings.push(`${d} has an undeclared ${a} record (${u.content}) alongside the declared one — mail will be split between them. Remove it at the provider if it is stale.`)}}return o}class Sn{name="route53";client;hostedZoneCache=new Map;providedHostedZoneId;constructor(e="us-east-1",t){this.client=new F(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 n=await this.client.findHostedZoneForDomain(e);if(n){let o=n.Id.replace("/hostedzone/","");return this.hostedZoneCache.set(t,o),o}return null}normalizeName(e,t){let r=e.replace(/\.$/,""),n=t.replace(/\.$/,"");if(!n||n==="@")return`${r}.`;if(n===r||n.endsWith(`.${r}`))return`${n}.`;return`${n}.${r}.`}formatValue(e){let t=e.content;if(e.type==="TXT"&&!t.startsWith('"'))t=J(t);if(e.type==="MX"&&e.priority!==void 0)t=`${e.priority} ${t}`;return t}sameValue(e,t,r){return e==="TXT"?T(t)===T(r):t===r}async currentSet(e,t,r){let o=(await this.client.listResourceRecordSets({HostedZoneId:e,StartRecordName:t,StartRecordType:r,MaxItems:"1"})).ResourceRecordSets?.[0];if(!o||o.Name.toLowerCase()!==t.toLowerCase()||o.Type!==r||o.AliasTarget||o.SetIdentifier)return null;return{ttl:o.TTL??300,values:(o.ResourceRecords??[]).map((s)=>s.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 n=this.normalizeName(e,t.name),o=this.formatValue(t),s=await this.currentSet(r,n,t.type);if(s?.values.some((c)=>this.sameValue(t.type,c,o)))return{success:!0,message:"Record already present"};let i=[...s?.values??[],o];return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Created by ts-cloud DNS provider",Changes:[{Action:s?"UPSERT":"CREATE",ResourceRecordSet:{Name:n,Type:t.type,TTL:s?.ttl??t.ttl??300,ResourceRecords:i.map((c)=>({Value:c}))}}]}})).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 n=this.normalizeName(e,t.name),o=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:n,Type:t.type,TTL:t.ttl||300,ResourceRecords:[{Value:o}]}}]}})).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 n=this.normalizeName(e,t.name),o=this.formatValue(t),s=await this.currentSet(r,n,t.type);if(!s||!s.values.some((a)=>this.sameValue(t.type,a,o)))return{success:!0,message:"Record already absent"};let i=s.values.filter((a)=>!this.sameValue(t.type,a,o));return await this.client.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:"Deleted by ts-cloud DNS provider",Changes:[{Action:i.length>0?"UPSERT":"DELETE",ResourceRecordSet:{Name:n,Type:t.type,TTL:s.ttl,ResourceRecords:(i.length>0?i:s.values).map((a)=>({Value:a}))}}]}}),{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 n=await this.client.listResourceRecordSets({HostedZoneId:r,StartRecordType:t}),o=[];for(let s of n.ResourceRecordSets){if(t&&s.Type!==t)continue;if(s.AliasTarget)continue;for(let i of s.ResourceRecords||[]){let a=i.Value,c;if(s.Type==="MX"){let d=a.split(" ");if(d.length>=2)c=Number.parseInt(d[0],10),a=d.slice(1).join(" ")}if(s.Type==="TXT"&&a.startsWith('"'))a=T(a);o.push({name:s.Name.replace(/\.$/,""),type:s.Type,content:a,ttl:s.TTL,priority:c})}}return{success:!0,records:o}}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:F.CloudFrontHostedZoneId,targetDnsName:e.cloudFrontDomainName,evaluateTargetHealth:!1})}async createAlbAlias(e){let t=F.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 _=255;function J(e){let t=[];for(let r=0;r<e.length;r+=_)t.push(e.slice(r,r+_));if(t.length===0)t.push("");return t.map((r)=>`"${r.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`).join(" ")}function T(e){if(!e.startsWith('"'))return e;let t="",r=!1;for(let n=0;n<e.length;n++){let o=e[n];if(!r){if(o==='"')r=!0;continue}if(o==="\\"&&n+1<e.length){t+=e[++n];continue}if(o==='"'){r=!1;continue}t+=o}return t}async function Mo(e,t){let r=[],n,o;for(;;){let s=await e.listResourceRecordSets({HostedZoneId:t,StartRecordName:n,StartRecordType:o,MaxItems:"100"});if(r.push(...s.ResourceRecordSets),!s.IsTruncated)break;if(n=s.NextRecordName,o=s.NextRecordType,!n)break}return r}function m(e){return e.replace(/\.$/,"").toLowerCase()}function k(e){return e.replace(/\.$/,"")}function v(e){if(e.type==="SRV"&&e.weight!==void 0&&e.port!==void 0)return`${e.weight} ${e.port} ${k(e.content)}`;return k(e.content)}function Q(e){let t=e.match(/"(?:[^"\\]|\\.)*"/g);if(!t)return e;return t.map((r)=>r.slice(1,-1).replace(/\\(.)/g,"$1")).join("")}function Uo(e,t){let r=m(t),n=[],o=[],s=[],i=new Set;for(let a of e){let c=m(a.Name),d=a.Type;if(d==="SOA"||d==="NS"&&c===r){o.push({name:c,type:d,reason:"owned by the destination provider"});continue}if(a.SetIdentifier){o.push({name:c,type:d,reason:`routing policy record (SetIdentifier=${a.SetIdentifier}) has no equivalent — recreate by hand`}),s.push(`${d} ${c} is part of a Route53 routing policy and was NOT migrated`);continue}if(a.AliasTarget){if(i.has(c))continue;i.add(c);let l=m(a.AliasTarget.DNSName);if(n.push({name:c,type:"CNAME",content:l,ttl:300,translatedFrom:`${d} ALIAS → ${l}`}),a.AliasTarget.EvaluateTargetHealth)s.push(`${c} was an ALIAS with health evaluation enabled; the CNAME that replaces it has no health check`);continue}for(let l of a.ResourceRecords||[]){let g=ee(c,d,l.Value,a.TTL);if("reason"in g){o.push({name:c,type:d,reason:g.reason}),s.push(`${d} ${c}: ${g.reason}`);continue}n.push(g)}}return{zone:r,records:n,skipped:o,warnings:s}}function ee(e,t,r,n){let o={name:e,ttl:n};switch(t){case"A":case"AAAA":case"CNAME":case"PTR":return{...o,type:t==="PTR"?"CNAME":t,content:m(r)};case"TXT":return{...o,type:"TXT",content:Q(r)};case"MX":{let[s,...i]=r.trim().split(/\s+/);if(!i.length)return{reason:`malformed MX value "${r}"`};return{...o,type:"MX",content:m(i.join(" ")),priority:Number(s)}}case"SRV":{let s=r.trim().split(/\s+/);if(s.length<4)return{reason:`malformed SRV value "${r}"`};let[i,a,c]=s.slice(0,3).map(Number);return{...o,type:"SRV",content:m(s.slice(3).join(" ")),priority:i,weight:a,port:c}}case"NS":return{...o,type:"NS",content:m(r)};case"CAA":return{...o,type:"CAA",content:r.trim()};default:return{reason:`unsupported record type ${t}`}}}var te=new Set(["TXT","MX","SRV","NS","CAA"]);async function Bo(e,t){let r=[],n=[],o=new Set;try{let s=await e.listRecords(t.zone);for(let i of s.records||[])o.add(`${m(i.name)}|${i.type}|${v(i)}`)}catch{}for(let s of t.records){let i={...s,proxied:!1},a=`${m(s.name)}|${s.type}|${v(s)}`;if(!te.has(s.type)){let d=await e.upsertRecord(t.zone,i);if(d.success)r.push(s);else n.push({record:s,message:d.message||"unknown provider error"});continue}if(o.has(a)){r.push(s);continue}let c=await e.createRecord(t.zone,i);if(c.success)o.add(a),r.push(s);else n.push({record:s,message:c.message||"unknown provider error"})}return{applied:r,failed:n}}async function Fo(e,t){let r=await e.listRecords(t.zone),n=[],o=[],s=new Map;for(let i of r.records||[]){let a=`${m(i.name)}|${i.type}`,c=s.get(a)??[];c.push(v(i)),s.set(a,c)}for(let i of t.records){let a=s.get(`${m(i.name)}|${i.type}`),c=v(i);if(a?.some((d)=>d===c))n.push(i);else o.push({record:i,found:a?.join(", ")})}return{matched:n,missing:o,ok:o.length===0}}class K{client;region;constructor(e="us-east-1"){this.client=new p,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((n)=>({DomainName:n.DomainName,ValidationDomain:n.ValidationDomain,ValidationStatus:n.ValidationStatus,ResourceRecord:n.ResourceRecord?{Name:n.ResourceRecord.Name,Type:n.ResourceRecord.Type,Value:n.ResourceRecord.Value}:void 0,ValidationMethod:n.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((n)=>({CertificateArn:n.CertificateArn,DomainName:n.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((n)=>n.DomainName===e||n.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 n=0;n<t;n++){let o=await this.describeCertificate({CertificateArn:e});if(o.Status==="ISSUED")return o;if(o.Status==="FAILED"||o.Status==="VALIDATION_TIMED_OUT")return null;await new Promise((s)=>setTimeout(s,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 n=r.DomainName.slice(2),o=t.split("."),s=n.split(".");if(o.slice(-s.length).join(".")===n)return!0}if(r.SubjectAlternativeNames)for(let n of r.SubjectAlternativeNames){if(n===t)return!0;if(n.startsWith("*.")){let o=n.slice(2),s=t.split("."),i=o.split(".");if(s.slice(-i.length).join(".")===o)return!0}}return!1}}class jo{acm;route53;dnsProvider;constructor(e="us-east-1",t){if(this.acm=new K(e),this.route53=new F,t&&t.provider!=="route53")this.dnsProvider=B(t)}async requestAndValidate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:n=[],waitForValidation:o=!1,maxWaitMinutes:s=30}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let{CertificateArn:i}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:n.length>0?[t,...n]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(i);let a=await this.acm.getDnsValidationRecords(i);if(this.dnsProvider)for(let c of a){let d=await this.dnsProvider.upsertRecord(t,{name:c.recordName,type:c.recordType,content:c.recordValue,ttl:300});if(!d.success)console.warn(`Failed to create validation record for ${c.domainName}: ${d.message}`)}else if(r)for(let c of a)await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${c.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:c.recordName,Type:c.recordType,TTL:300,ResourceRecords:[{Value:c.recordValue}]}}]}});if(o){if(!await this.acm.waitForCertificateValidation(i,s*2,30000))throw Error(`Certificate validation timed out after ${s} minutes`)}return{certificateArn:i,validationRecords:a}}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let n=await this.acm.describeCertificate({CertificateArn:e});if(n.DomainValidationOptions&&n.DomainValidationOptions.length>0&&n.DomainValidationOptions[0].ResourceRecord)return;await new Promise((o)=>setTimeout(o,2000))}throw Error("Timeout waiting for DNS validation options")}async createValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:n}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let o=await this.acm.getDnsValidationRecords(t),s=[];if(this.dnsProvider){let i=n||o[0]?.domainName;for(let a of o){let c=await this.dnsProvider.upsertRecord(i,{name:a.recordName,type:a.recordType,content:a.recordValue,ttl:300});s.push({...a,changeId:c.success?c.id:void 0})}}else if(r)for(let i of o){let a=await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`ACM DNS validation for ${i.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:i.recordName,Type:i.recordType,TTL:300,ResourceRecords:[{Value:i.recordValue}]}}]}});s.push({...i,changeId:a.ChangeInfo?.Id})}return s}async deleteValidationRecords(e){let{certificateArn:t,hostedZoneId:r,domain:n}=e,o=await this.acm.getDnsValidationRecords(t);if(this.dnsProvider){let s=n||o[0]?.domainName;for(let i of o)try{await this.dnsProvider.deleteRecord(s,{name:i.recordName,type:i.recordType,content:i.recordValue})}catch{}}else if(r)for(let s of o)try{await this.route53.changeResourceRecordSets({HostedZoneId:r,ChangeBatch:{Comment:`Cleanup ACM DNS validation for ${s.domainName}`,Changes:[{Action:"DELETE",ResourceRecordSet:{Name:s.recordName,Type:s.recordType,TTL:300,ResourceRecords:[{Value:s.recordValue}]}}]}})}catch{}}async findOrCreateCertificate(e){let{domainName:t,hostedZoneId:r,subjectAlternativeNames:n,waitForValidation:o=!0}=e;if(!this.dnsProvider&&!r)throw Error("Either hostedZoneId or external DNS provider configuration is required");let s=await this.acm.findCertificateByDomain(t);if(s&&s.Status==="ISSUED")return{certificateArn:s.CertificateArn,isNew:!1};let{certificateArn:i}=await this.requestAndValidate({domainName:t,hostedZoneId:r,subjectAlternativeNames:n,waitForValidation:o});return{certificateArn:i,isNew:!0}}hasExternalDnsProvider(){return this.dnsProvider!==void 0}getDnsProviderName(){return this.dnsProvider?.name||"route53"}}class qt{acm;dnsProvider;constructor(e,t="us-east-1"){if(this.acm=new K(t),"provider"in e)this.dnsProvider=B(e);else this.dnsProvider=e}getProvider(){return this.dnsProvider}async requestAndValidate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:n=!1,maxWaitMinutes:o=30}=e,{CertificateArn:s}=await this.acm.requestCertificate({DomainName:t,SubjectAlternativeNames:r.length>0?[t,...r]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(s);let i=await this.acm.getDnsValidationRecords(s);for(let c of i){let d=await this.dnsProvider.upsertRecord(t,{name:c.recordName,type:c.recordType,content:c.recordValue,ttl:300});if(!d.success)console.warn(`Failed to create validation record for ${c.domainName}: ${d.message}`)}let a="pending";if(n)a=(await this.acm.waitForCertificateValidation(s,o*2,30000))?.Status==="ISSUED"?"issued":"failed";return{certificateArn:s,validationRecords:i.map((c)=>({domainName:c.domainName,recordName:c.recordName,recordType:c.recordType,recordValue:c.recordValue})),isNew:!0,status:a}}async createValidationRecords(e){let{certificateArn:t,domain:r}=e,n=[],o=await this.acm.getDnsValidationRecords(t);for(let s of o){let i=await this.dnsProvider.upsertRecord(r,{name:s.recordName,type:s.recordType,content:s.recordValue,ttl:300});if(!i.success)n.push(`Failed to create record for ${s.domainName}: ${i.message}`)}return{success:n.length===0,records:o.map((s)=>({domainName:s.domainName,recordName:s.recordName,recordType:s.recordType,recordValue:s.recordValue})),errors:n}}async deleteValidationRecords(e){let{certificateArn:t,domain:r}=e,n=[],o=await this.acm.getDnsValidationRecords(t);for(let s of o){let i=await this.dnsProvider.deleteRecord(r,{name:s.recordName,type:s.recordType,content:s.recordValue});if(!i.success)n.push(`Failed to delete record for ${s.domainName}: ${i.message}`)}return{success:n.length===0,errors:n}}async findOrCreateCertificate(e){let{domainName:t,subjectAlternativeNames:r=[],waitForValidation:n=!0,maxWaitMinutes:o}=e,s=await this.acm.findCertificateByDomain(t);if(s&&s.Status==="ISSUED"){let i=s.SubjectAlternativeNames||[s.DomainName],a=i.some((d)=>d===`*.${t}`);if(r.every((d)=>i.includes(d)||a))return{certificateArn:s.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:n,maxWaitMinutes:o})}async requestCertificateWithCommonSans(e){let{domainName:t,includeWww:r=!0,includeWildcard:n=!1,additionalSans:o=[],waitForValidation:s=!1}=e,i=[];if(r)i.push(`www.${t}`);if(n)i.push(`*.${t}`);return i.push(...o),this.requestAndValidate({domainName:t,subjectAlternativeNames:i,waitForValidation:s})}async waitForValidationOptions(e,t=30){for(let r=0;r<t;r++){let n=await this.acm.describeCertificate({CertificateArn:e});if(n.DomainValidationOptions&&n.DomainValidationOptions.length>0&&n.DomainValidationOptions[0].ResourceRecord)return;await new Promise((o)=>setTimeout(o,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 B(e){switch(e.provider){case"route53":return new Sn(e.region,e.hostedZoneId);case"porkbun":return new ot(e.apiKey,e.secretKey);case"godaddy":return new Gt(e.apiKey,e.apiSecret,e.environment);case"cloudflare":return new he(e.apiToken,{zoneId:e.zoneId,accountId:e.accountId});default:throw Error(`Unknown DNS provider: ${e.provider}`)}}class Mi{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,n=process.env.GODADDY_API_SECRET;if(r&&n){let s=process.env.GODADDY_ENVIRONMENT;this.addGoDaddy(r,n,s)}let o=process.env.CLOUDFLARE_API_TOKEN;if(o)this.addCloudflare(o,{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((o)=>o.provider===e);if(!r)return null;let n=B(r);return this.providers.set(e,n),n}async getProviderForDomain(e){for(let t of this.configs){let r=B(t);if(await r.canManageDomain(e))return r}return null}getAllProviders(){return this.configs.map((e)=>B(e))}}var qe=new Mi;
2
+ export{ot,Gt,Dr,Xs,Qs,kr,he,Li,Nr,$o,Lo,Sn,Mo,Uo,Bo,Fo,K,jo,qt,B,Mi};
@@ -0,0 +1 @@
1
+ import{g}from"./chunk-gqstb8zn.js";import"./chunk-540wkkhs.js";export{g as S3Client};
@@ -1,4 +1,4 @@
1
- import{p}from"./chunk-9cj1fm00.js";import{x}from"./chunk-gbbcp2bw.js";function T(e){let i=Array.isArray(e?.Items)?e.Items:x(e?.Items?.CNAME);return{Quantity:i.length,Items:i.map(String)}}function Yd(e){return x(e?.Origins?.Items?.Origin)}function xr(e){for(let i of Yd(e)){let t=String(i.DomainName??"").match(/^(.+?)\.s3[.-]/)?.[1];if(t)return t}return}class E{client;constructor(e,i){this.client=i??new p(void 0,{profile:e})}collectionItems(e,i){let t=e?.Items??e?.[i];if(!t)return[];if(Array.isArray(t))return t;let n=t[i]??t.Item;if(n===void 0)return typeof t==="object"&&(t.Id||t.PathPattern)?[t]:[];return Array.isArray(n)?n:[n]}validateExistingOriginInput(e,i){if(!/^[A-Z0-9]{8,32}$/.test(e))throw Error("CloudFront distribution ID is invalid");if(!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(i.id))throw Error("CloudFront origin ID is invalid");if(!/^(?=.{1,253}$)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/.test(i.domainName))throw Error("CloudFront origin must be a hostname without a scheme or path");let t=i.pathPattern.startsWith("/")?i.pathPattern:`/${i.pathPattern}`;if(t==="/"||t==="/*"||!/^\/[A-Za-z0-9_.*?~!$&'()+,;=:@%/-]{1,255}$/.test(t))throw Error("CloudFront path pattern must be a non-default absolute pattern");if(i.originPath&&(!i.originPath.startsWith("/")||i.originPath.includes("..")))throw Error("CloudFront origin path must be absolute and traversal-free");if(Object.entries(i.customHeaders??{}).some(([n,r])=>!/^[A-Za-z0-9-]{1,64}$/.test(n)||!r||r.length>1024))throw Error("CloudFront custom origin headers are invalid");return{...i,pathPattern:t}}async upsertExistingDistributionOrigin(e,i){let t=this.validateExistingOriginInput(e,i),n=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${e}/config`,returnHeaders:!0}),r=n.headers?.etag||n.headers?.ETag||n.ETag||"",s=n.body?.DistributionConfig||n.DistributionConfig||n.body;if(!s||s.Enabled===void 0||!r)throw Error("Failed to read an ETag-protected CloudFront distribution config");let o=this.collectionItems(s.Origins,"Origin"),a=this.collectionItems(s.CacheBehaviors,"CacheBehavior"),c=o.find((h)=>String(h.Id)===t.id),g=a.find((h)=>String(h.PathPattern)===t.pathPattern);if(c&&String(c.DomainName)!==t.domainName&&!t.replaceExisting)throw Error(`Origin ${t.id} already targets ${c.DomainName}; pass replaceExisting only after reviewing the live config`);if(g&&String(g.TargetOriginId)!==t.id&&!t.replaceExisting)throw Error(`Path ${t.pathPattern} already targets ${g.TargetOriginId}; pass replaceExisting only after reviewing the live config`);let u={Id:t.id,DomainName:t.domainName,OriginPath:t.originPath??"",CustomHeaders:{Quantity:Object.keys(t.customHeaders??{}).length,...Object.keys(t.customHeaders??{}).length?{Items:{OriginCustomHeader:Object.entries(t.customHeaders).map(([h,P])=>({HeaderName:h,HeaderValue:P}))}}:{}},CustomOriginConfig:{HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:t.protocolPolicy??"https-only",OriginSslProtocols:{Quantity:1,Items:{SslProtocol:["TLSv1.2"]}},OriginReadTimeout:30,OriginKeepaliveTimeout:5},ConnectionAttempts:3,ConnectionTimeout:10,...t.originAccessControlId?{OriginAccessControlId:t.originAccessControlId}:{}},m=["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"],d={PathPattern:t.pathPattern,TargetOriginId:t.id,ViewerProtocolPolicy:"redirect-to-https",Compress:!0,CachePolicyId:"4135ea2d-6df8-44a3-9df3-4b5a84be39ad",OriginRequestPolicyId:"b689b0a8-53d0-40ab-baf2-68738e2966ac",AllowedMethods:{Quantity:m.length,Items:{Method:m},CachedMethods:{Quantity:2,Items:{Method:["GET","HEAD"]}}},SmoothStreaming:!1,FieldLevelEncryptionId:"",TrustedSigners:{Enabled:!1,Quantity:0},TrustedKeyGroups:{Enabled:!1,Quantity:0},LambdaFunctionAssociations:{Quantity:0},FunctionAssociations:{Quantity:0}},f=c?o.map((h)=>String(h.Id)===t.id?u:h):[...o,u],l=g?a.map((h)=>String(h.PathPattern)===t.pathPattern?d:h):[...a,d],b=JSON.stringify(o)!==JSON.stringify(f)||JSON.stringify(a)!==JSON.stringify(l);if(!b||t.dryRun)return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:b,applied:!1,etag:r};s.Origins={Quantity:f.length,Items:{Origin:f}},s.CacheBehaviors={Quantity:l.length,...l.length?{Items:{CacheBehavior:l}}:{}};let C=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${e}/config`,body:this.buildDistributionConfigXml(s),headers:{"Content-Type":"application/xml","If-Match":r},returnHeaders:!0});return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!0,applied:!0,etag:C.headers?.etag||C.headers?.ETag||""}}async removeExistingDistributionOrigin(e,i){let t=this.validateExistingOriginInput(e,i),n=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${e}/config`,returnHeaders:!0}),r=n.headers?.etag||n.headers?.ETag||n.ETag||"",s=n.body?.DistributionConfig||n.DistributionConfig||n.body;if(!s||s.Enabled===void 0||!r)throw Error("Failed to read an ETag-protected CloudFront distribution config");let o=this.collectionItems(s.Origins,"Origin"),a=this.collectionItems(s.CacheBehaviors,"CacheBehavior"),c=o.find((l)=>String(l.Id)===t.id),g=a.find((l)=>String(l.PathPattern)===t.pathPattern);if(c&&String(c.DomainName)!==t.domainName)throw Error(`Origin ${t.id} no longer targets ${t.domainName}; refusing ambiguous removal`);if(g&&String(g.TargetOriginId)!==t.id)throw Error(`Path ${t.pathPattern} no longer targets ${t.id}; refusing ambiguous removal`);if(!g)return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!1,applied:!1,originRemoved:!1,etag:r};let u=a.filter((l)=>String(l.PathPattern)!==t.pathPattern),m=String(s.DefaultCacheBehavior?.TargetOriginId)===t.id||u.some((l)=>String(l.TargetOriginId)===t.id),d=m?o:o.filter((l)=>String(l.Id)!==t.id);if(t.dryRun)return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!0,applied:!1,originRemoved:!m&&!!c,etag:r};s.Origins={Quantity:d.length,Items:{Origin:d}},s.CacheBehaviors={Quantity:u.length,...u.length?{Items:{CacheBehavior:u}}:{}};let f=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${e}/config`,body:this.buildDistributionConfigXml(s),headers:{"Content-Type":"application/xml","If-Match":r},returnHeaders:!0});return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!0,applied:!0,originRemoved:!m&&!!c,etag:f.headers?.etag||f.headers?.ETag||""}}async createInvalidation(e){let i=e.callerReference||Date.now().toString(),t=`<?xml version="1.0" encoding="UTF-8"?>
1
+ import{p}from"./chunk-540wkkhs.js";import{x}from"./chunk-gbbcp2bw.js";function T(e){let i=Array.isArray(e?.Items)?e.Items:x(e?.Items?.CNAME);return{Quantity:i.length,Items:i.map(String)}}function Yd(e){return x(e?.Origins?.Items?.Origin)}function xr(e){for(let i of Yd(e)){let t=String(i.DomainName??"").match(/^(.+?)\.s3[.-]/)?.[1];if(t)return t}return}class E{client;constructor(e,i){this.client=i??new p(void 0,{profile:e})}collectionItems(e,i){let t=e?.Items??e?.[i];if(!t)return[];if(Array.isArray(t))return t;let n=t[i]??t.Item;if(n===void 0)return typeof t==="object"&&(t.Id||t.PathPattern)?[t]:[];return Array.isArray(n)?n:[n]}validateExistingOriginInput(e,i){if(!/^[A-Z0-9]{8,32}$/.test(e))throw Error("CloudFront distribution ID is invalid");if(!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(i.id))throw Error("CloudFront origin ID is invalid");if(!/^(?=.{1,253}$)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/.test(i.domainName))throw Error("CloudFront origin must be a hostname without a scheme or path");let t=i.pathPattern.startsWith("/")?i.pathPattern:`/${i.pathPattern}`;if(t==="/"||t==="/*"||!/^\/[A-Za-z0-9_.*?~!$&'()+,;=:@%/-]{1,255}$/.test(t))throw Error("CloudFront path pattern must be a non-default absolute pattern");if(i.originPath&&(!i.originPath.startsWith("/")||i.originPath.includes("..")))throw Error("CloudFront origin path must be absolute and traversal-free");if(Object.entries(i.customHeaders??{}).some(([n,r])=>!/^[A-Za-z0-9-]{1,64}$/.test(n)||!r||r.length>1024))throw Error("CloudFront custom origin headers are invalid");return{...i,pathPattern:t}}async upsertExistingDistributionOrigin(e,i){let t=this.validateExistingOriginInput(e,i),n=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${e}/config`,returnHeaders:!0}),r=n.headers?.etag||n.headers?.ETag||n.ETag||"",s=n.body?.DistributionConfig||n.DistributionConfig||n.body;if(!s||s.Enabled===void 0||!r)throw Error("Failed to read an ETag-protected CloudFront distribution config");let o=this.collectionItems(s.Origins,"Origin"),a=this.collectionItems(s.CacheBehaviors,"CacheBehavior"),c=o.find((h)=>String(h.Id)===t.id),g=a.find((h)=>String(h.PathPattern)===t.pathPattern);if(c&&String(c.DomainName)!==t.domainName&&!t.replaceExisting)throw Error(`Origin ${t.id} already targets ${c.DomainName}; pass replaceExisting only after reviewing the live config`);if(g&&String(g.TargetOriginId)!==t.id&&!t.replaceExisting)throw Error(`Path ${t.pathPattern} already targets ${g.TargetOriginId}; pass replaceExisting only after reviewing the live config`);let u={Id:t.id,DomainName:t.domainName,OriginPath:t.originPath??"",CustomHeaders:{Quantity:Object.keys(t.customHeaders??{}).length,...Object.keys(t.customHeaders??{}).length?{Items:{OriginCustomHeader:Object.entries(t.customHeaders).map(([h,P])=>({HeaderName:h,HeaderValue:P}))}}:{}},CustomOriginConfig:{HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:t.protocolPolicy??"https-only",OriginSslProtocols:{Quantity:1,Items:{SslProtocol:["TLSv1.2"]}},OriginReadTimeout:30,OriginKeepaliveTimeout:5},ConnectionAttempts:3,ConnectionTimeout:10,...t.originAccessControlId?{OriginAccessControlId:t.originAccessControlId}:{}},m=["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"],d={PathPattern:t.pathPattern,TargetOriginId:t.id,ViewerProtocolPolicy:"redirect-to-https",Compress:!0,CachePolicyId:"4135ea2d-6df8-44a3-9df3-4b5a84be39ad",OriginRequestPolicyId:"b689b0a8-53d0-40ab-baf2-68738e2966ac",AllowedMethods:{Quantity:m.length,Items:{Method:m},CachedMethods:{Quantity:2,Items:{Method:["GET","HEAD"]}}},SmoothStreaming:!1,FieldLevelEncryptionId:"",TrustedSigners:{Enabled:!1,Quantity:0},TrustedKeyGroups:{Enabled:!1,Quantity:0},LambdaFunctionAssociations:{Quantity:0},FunctionAssociations:{Quantity:0}},f=c?o.map((h)=>String(h.Id)===t.id?u:h):[...o,u],l=g?a.map((h)=>String(h.PathPattern)===t.pathPattern?d:h):[...a,d],b=JSON.stringify(o)!==JSON.stringify(f)||JSON.stringify(a)!==JSON.stringify(l);if(!b||t.dryRun)return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:b,applied:!1,etag:r};s.Origins={Quantity:f.length,Items:{Origin:f}},s.CacheBehaviors={Quantity:l.length,...l.length?{Items:{CacheBehavior:l}}:{}};let C=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${e}/config`,body:this.buildDistributionConfigXml(s),headers:{"Content-Type":"application/xml","If-Match":r},returnHeaders:!0});return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!0,applied:!0,etag:C.headers?.etag||C.headers?.ETag||""}}async removeExistingDistributionOrigin(e,i){let t=this.validateExistingOriginInput(e,i),n=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${e}/config`,returnHeaders:!0}),r=n.headers?.etag||n.headers?.ETag||n.ETag||"",s=n.body?.DistributionConfig||n.DistributionConfig||n.body;if(!s||s.Enabled===void 0||!r)throw Error("Failed to read an ETag-protected CloudFront distribution config");let o=this.collectionItems(s.Origins,"Origin"),a=this.collectionItems(s.CacheBehaviors,"CacheBehavior"),c=o.find((l)=>String(l.Id)===t.id),g=a.find((l)=>String(l.PathPattern)===t.pathPattern);if(c&&String(c.DomainName)!==t.domainName)throw Error(`Origin ${t.id} no longer targets ${t.domainName}; refusing ambiguous removal`);if(g&&String(g.TargetOriginId)!==t.id)throw Error(`Path ${t.pathPattern} no longer targets ${t.id}; refusing ambiguous removal`);if(!g)return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!1,applied:!1,originRemoved:!1,etag:r};let u=a.filter((l)=>String(l.PathPattern)!==t.pathPattern),m=String(s.DefaultCacheBehavior?.TargetOriginId)===t.id||u.some((l)=>String(l.TargetOriginId)===t.id),d=m?o:o.filter((l)=>String(l.Id)!==t.id);if(t.dryRun)return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!0,applied:!1,originRemoved:!m&&!!c,etag:r};s.Origins={Quantity:d.length,Items:{Origin:d}},s.CacheBehaviors={Quantity:u.length,...u.length?{Items:{CacheBehavior:u}}:{}};let f=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${e}/config`,body:this.buildDistributionConfigXml(s),headers:{"Content-Type":"application/xml","If-Match":r},returnHeaders:!0});return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!0,applied:!0,originRemoved:!m&&!!c,etag:f.headers?.etag||f.headers?.ETag||""}}async createInvalidation(e){let i=e.callerReference||Date.now().toString(),t=`<?xml version="1.0" encoding="UTF-8"?>
2
2
  <InvalidationBatch>
3
3
  <Paths>
4
4
  <Quantity>${e.paths.length}</Quantity>
@@ -1,2 +1,2 @@
1
- import{es,Aa}from"./chunk-gghy8mb4.js";import{g}from"./chunk-zph18vv6.js";var l=()=>{};async function Kp(a,c=l){for(let e of a){let t=new g(e.replicaRegion),i;try{i=await t.headBucket(e.replicaBucket)}catch(r){if(r?.statusCode===301)throw Error(`Failover replica bucket ${e.replicaBucket} already exists outside ${e.replicaRegion}. Pick another failover.bucket or region for infrastructure.storage.${e.name}.`);if(r?.statusCode===403)throw Error(`Failover replica bucket ${e.replicaBucket} exists but this account cannot reach it (S3 names are global, so another account may own it). Set infrastructure.storage.${e.name}.failover.bucket to a name you own.`);throw r}if(i.exists&&i.region&&i.region!==e.replicaRegion)throw Error(`Failover replica bucket ${e.replicaBucket} is in ${i.region}, not ${e.replicaRegion}.`);if(!i.exists)c(`Creating failover replica bucket ${e.replicaBucket} in ${e.replicaRegion}`),await t.createBucket(e.replicaBucket);if(await t.putPublicAccessBlock(e.replicaBucket,{BlockPublicAcls:!0,IgnorePublicAcls:!0,BlockPublicPolicy:!0,RestrictPublicBuckets:!0}),await t.putBucketEncryption(e.replicaBucket,"AES256"),e.replicate){if((await t.getBucketVersioning(e.replicaBucket)).Status!=="Enabled")c(`Enabling versioning on ${e.replicaBucket} (S3 replication requires it)`),await t.putBucketVersioning(e.replicaBucket,"Enabled")}}}async function Jp(a,c,e=l){for(let t of a){let i=c[t.distributionArnOutput];if(!i)throw Error(`Stack output ${t.distributionArnOutput} is missing, so the failover replica ${t.replicaBucket} cannot be scoped to its distribution.`);let r=new g(t.replicaRegion),s={Version:"2012-10-17",Statement:[...((await r.getBucketPolicy(t.replicaBucket))?.Statement??[]).filter((n)=>n?.Sid!==es),Aa({replicaBucket:t.replicaBucket,distributionArn:i})]};e(`Granting ${i} read access to ${t.replicaBucket}`),await r.putBucketPolicy(t.replicaBucket,s)}}async function Xp(a,c=l){let e={};for(let t of a){let i=new g(t.primaryRegion),r=new g(t.replicaRegion),[u,p]=await Promise.all([i.listAllObjects({bucket:t.primaryBucket}),r.listAllObjects({bucket:t.replicaBucket})]),s=new Map(p.map((o)=>[o.Key,o.Size])),n=u.filter((o)=>s.get(o.Key)!==o.Size);for(let o of n)await r.copyObject({sourceBucket:t.primaryBucket,sourceKey:o.Key,destinationBucket:t.replicaBucket,destinationKey:o.Key});if(n.length>0)c(`Copied ${n.length} object(s) from ${t.primaryBucket} to ${t.replicaBucket}`);e[t.replicaBucket]=n.length}return e}async function Qp(a,c=l){for(let e of a){let t=new g(e.replicaRegion);if(!(await t.headBucket(e.replicaBucket)).exists)continue;await t.emptyBucket(e.replicaBucket),await t.deleteBucket(e.replicaBucket),c(`Deleted failover replica bucket ${e.replicaBucket}`)}}
1
+ import{es,Aa}from"./chunk-wayhpmn7.js";import{g}from"./chunk-gqstb8zn.js";var l=()=>{};async function Kp(a,c=l){for(let e of a){let t=new g(e.replicaRegion),i;try{i=await t.headBucket(e.replicaBucket)}catch(r){if(r?.statusCode===301)throw Error(`Failover replica bucket ${e.replicaBucket} already exists outside ${e.replicaRegion}. Pick another failover.bucket or region for infrastructure.storage.${e.name}.`);if(r?.statusCode===403)throw Error(`Failover replica bucket ${e.replicaBucket} exists but this account cannot reach it (S3 names are global, so another account may own it). Set infrastructure.storage.${e.name}.failover.bucket to a name you own.`);throw r}if(i.exists&&i.region&&i.region!==e.replicaRegion)throw Error(`Failover replica bucket ${e.replicaBucket} is in ${i.region}, not ${e.replicaRegion}.`);if(!i.exists)c(`Creating failover replica bucket ${e.replicaBucket} in ${e.replicaRegion}`),await t.createBucket(e.replicaBucket);if(await t.putPublicAccessBlock(e.replicaBucket,{BlockPublicAcls:!0,IgnorePublicAcls:!0,BlockPublicPolicy:!0,RestrictPublicBuckets:!0}),await t.putBucketEncryption(e.replicaBucket,"AES256"),e.replicate){if((await t.getBucketVersioning(e.replicaBucket)).Status!=="Enabled")c(`Enabling versioning on ${e.replicaBucket} (S3 replication requires it)`),await t.putBucketVersioning(e.replicaBucket,"Enabled")}}}async function Jp(a,c,e=l){for(let t of a){let i=c[t.distributionArnOutput];if(!i)throw Error(`Stack output ${t.distributionArnOutput} is missing, so the failover replica ${t.replicaBucket} cannot be scoped to its distribution.`);let r=new g(t.replicaRegion),s={Version:"2012-10-17",Statement:[...((await r.getBucketPolicy(t.replicaBucket))?.Statement??[]).filter((n)=>n?.Sid!==es),Aa({replicaBucket:t.replicaBucket,distributionArn:i})]};e(`Granting ${i} read access to ${t.replicaBucket}`),await r.putBucketPolicy(t.replicaBucket,s)}}async function Xp(a,c=l){let e={};for(let t of a){let i=new g(t.primaryRegion),r=new g(t.replicaRegion),[u,p]=await Promise.all([i.listAllObjects({bucket:t.primaryBucket}),r.listAllObjects({bucket:t.replicaBucket})]),s=new Map(p.map((o)=>[o.Key,o.Size])),n=u.filter((o)=>s.get(o.Key)!==o.Size);for(let o of n)await r.copyObject({sourceBucket:t.primaryBucket,sourceKey:o.Key,destinationBucket:t.replicaBucket,destinationKey:o.Key});if(n.length>0)c(`Copied ${n.length} object(s) from ${t.primaryBucket} to ${t.replicaBucket}`);e[t.replicaBucket]=n.length}return e}async function Qp(a,c=l){for(let e of a){let t=new g(e.replicaRegion);if(!(await t.headBucket(e.replicaBucket)).exists)continue;await t.emptyBucket(e.replicaBucket),await t.deleteBucket(e.replicaBucket),c(`Deleted failover replica bucket ${e.replicaBucket}`)}}
2
2
  export{Kp,Jp,Xp,Qp};
@@ -0,0 +1 @@
1
+ import{tl,Cm}from"./chunk-nbffypj8.js";import"./chunk-e12679p1.js";import"./chunk-gqstb8zn.js";import"./chunk-540wkkhs.js";export{tl as EmailClient,Cm as email};