@stacksjs/ts-cloud 0.16.18 → 0.16.20

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 (90) hide show
  1. package/dist/aws/index.js +1 -1
  2. package/dist/bin/{chunk-cnbvm43k.js → chunk-0f1qpmd6.js} +2 -2
  3. package/dist/bin/{chunk-dk9f6h0m.js → chunk-28ztnqjk.js} +1 -1
  4. package/dist/bin/{chunk-eyvxsaaz.js → chunk-48x0wc2g.js} +1 -1
  5. package/dist/bin/{chunk-acqj5mfq.js → chunk-7zfydgfz.js} +3 -3
  6. package/dist/bin/chunk-840arz58.js +34 -0
  7. package/dist/bin/{chunk-qxwkg8yg.js → chunk-apnhhfkj.js} +1 -1
  8. package/dist/bin/{chunk-gfnw9nhq.js → chunk-e55fdn0r.js} +35 -35
  9. package/dist/bin/{chunk-d9yzg97w.js → chunk-gf7yavs5.js} +1 -1
  10. package/dist/bin/{chunk-nrrprf04.js → chunk-gfr2215x.js} +2 -2
  11. package/dist/bin/chunk-gp5w7e4c.js +1 -0
  12. package/dist/bin/{chunk-nagvc7e4.js → chunk-gt7g41js.js} +1 -1
  13. package/dist/bin/{chunk-75ak501k.js → chunk-ndddd2ft.js} +1 -1
  14. package/dist/bin/{chunk-padk76ac.js → chunk-sh248v2y.js} +1 -1
  15. package/dist/bin/chunk-y286zhty.js +1 -0
  16. package/dist/bin/chunk-ysv52qcc.js +1 -0
  17. package/dist/bin/cli.js +15 -15
  18. package/dist/bin/dashboard-server.js +1 -1
  19. package/dist/{chunk-rtn4gj6y.js → chunk-07rjctzz.js} +1 -1
  20. package/dist/{chunk-2p71e3x7.js → chunk-0j2tpr8d.js} +3 -3
  21. package/dist/chunk-49vvjfrd.js +1 -0
  22. package/dist/{chunk-yd40pg8g.js → chunk-9asn5fpt.js} +36 -36
  23. package/dist/{chunk-s2ve9zxn.js → chunk-aw1tp3p3.js} +2 -2
  24. package/dist/chunk-d46p0h6t.js +34 -0
  25. package/dist/{chunk-9syc8s7r.js → chunk-hyeeqga9.js} +2 -2
  26. package/dist/{chunk-60nr1ehk.js → chunk-wgf1ndgq.js} +1 -1
  27. package/dist/deploy/index.js +1 -1
  28. package/dist/drivers/index.js +1 -1
  29. package/dist/index.js +1 -1
  30. package/dist/ui/404.html +1 -1
  31. package/dist/ui/accept-invitation.html +1 -1
  32. package/dist/ui/access-denied.html +1 -1
  33. package/dist/ui/account/automation.html +6 -6
  34. package/dist/ui/account/security.html +2 -2
  35. package/dist/ui/applications/compose.html +6 -6
  36. package/dist/ui/applications/new.html +2 -2
  37. package/dist/ui/data/backups.html +6 -6
  38. package/dist/ui/data/services.html +6 -6
  39. package/dist/ui/data/volumes.html +6 -6
  40. package/dist/ui/index.html +6 -6
  41. package/dist/ui/infrastructure/topology.html +6 -6
  42. package/dist/ui/integrations.html +2 -2
  43. package/dist/ui/operations/alerts.html +6 -6
  44. package/dist/ui/operations/configuration.html +6 -6
  45. package/dist/ui/operations/jobs.html +6 -6
  46. package/dist/ui/operations/maintenance.html +6 -6
  47. package/dist/ui/operations/observability.html +6 -6
  48. package/dist/ui/operations/previews.html +6 -6
  49. package/dist/ui/operations/queue.html +6 -6
  50. package/dist/ui/operations/regions.html +6 -6
  51. package/dist/ui/operations/releases.html +6 -6
  52. package/dist/ui/operations/spend.html +6 -6
  53. package/dist/ui/operations/workloads.html +6 -6
  54. package/dist/ui/security.html +2 -2
  55. package/dist/ui/server/actions.html +6 -6
  56. package/dist/ui/server/activity.html +2 -2
  57. package/dist/ui/server/capacity.html +6 -6
  58. package/dist/ui/server/database.html +6 -6
  59. package/dist/ui/server/deployments.html +5 -5
  60. package/dist/ui/server/diagnostics.html +2 -2
  61. package/dist/ui/server/firewall.html +6 -6
  62. package/dist/ui/server/fleet.html +6 -6
  63. package/dist/ui/server/logs.html +5 -5
  64. package/dist/ui/server/metrics.html +5 -5
  65. package/dist/ui/server/security.html +2 -2
  66. package/dist/ui/server/services.html +2 -2
  67. package/dist/ui/server/sites.html +5 -5
  68. package/dist/ui/server/ssh-keys.html +5 -5
  69. package/dist/ui/server/team.html +6 -6
  70. package/dist/ui/server/terminal.html +1 -1
  71. package/dist/ui/serverless/alarms.html +6 -6
  72. package/dist/ui/serverless/assets.html +1 -1
  73. package/dist/ui/serverless/cost.html +2 -2
  74. package/dist/ui/serverless/data.html +6 -6
  75. package/dist/ui/serverless/deployments.html +1 -1
  76. package/dist/ui/serverless/firewall.html +1 -1
  77. package/dist/ui/serverless/functions.html +6 -6
  78. package/dist/ui/serverless/logs.html +6 -6
  79. package/dist/ui/serverless/metrics.html +1 -1
  80. package/dist/ui/serverless/queues.html +6 -6
  81. package/dist/ui/serverless/secrets.html +6 -6
  82. package/dist/ui/serverless/traces.html +6 -6
  83. package/dist/ui/serverless.html +6 -6
  84. package/package.json +3 -3
  85. package/dist/bin/chunk-a7kmjq4y.js +0 -1
  86. package/dist/bin/chunk-ckk70zc9.js +0 -1
  87. package/dist/bin/chunk-ezhbcpw1.js +0 -34
  88. package/dist/bin/chunk-zww0xfdp.js +0 -1
  89. package/dist/chunk-c3f89ryr.js +0 -34
  90. package/dist/chunk-hjgjbkhk.js +0 -1
@@ -1,4 +1,4 @@
1
- import{fd,O,d,p,bi,Id,Sd,le,g,Te,Fr,Qt,Ht,Vt,Ur,Ti}from"./chunk-v2p7c7s4.js";import{o}from"./chunk-yd40pg8g.js";import{B,vr,Tr,u}from"./chunk-3m9ghthh.js";import{ii}from"./chunk-srrscggm.js";import{Er,be}from"./chunk-qcaqc5b8.js";import{h}from"./chunk-ptq9v346.js";import{Ei}from"./chunk-g6g33pt9.js";import{readFileSync as to}from"node:fs";import{join as Ma}from"node:path";function vu(e={}){let t=new Set;for(let r of Object.values(e)){if(!r.domain)continue;if(r.redirect||r.deploy==="server"||r.start)t.add(r.domain)}return t}function Hr(e){return e.replace(/\.$/,"").toLowerCase()}function Ci(e,t,r){let n=Hr(e.name),s=Hr(t),i=Hr(r),a=i===s?"@":i.endsWith(`.${s}`)?i.slice(0,-(s.length+1)):i;return n===i||n===a||a==="@"&&(n===""||n===s)}async function Xa(e,t,r,n,s="A"){let i=await e.listRecords(t);if(!i.success)return[`could not list ${s} records: ${i.message||"unknown provider error"}`];let a=i.records.filter((m)=>m.type===s&&Ci(m,t,r)),c=a.findIndex((m)=>m.content===n);if(a.length<=1||c===-1)return[];let l=[];for(let[m,S]of a.entries()){if(m===c)continue;let v=await e.deleteRecord(t,S);if(!v.success)l.push(`could not remove stale ${S.name} ${s} ${S.content}: ${v.message||"unknown provider error"}`)}return l}function ye(e){if(!e)return;let t=e.trim();if(!t)return;if(!t.includes("/"))return t;let[r]=t.split("/");if(!r.endsWith("::"))return r||void 0;return`${r}1`}var Ya=new Set(["mail","smtp","imap","mx"]);function Tn(e){return!Ya.has(e.split(".")[0]??"")}async function Tu(e){let{provider:t,zone:r,fqdn:n,ipv4:s,ipv6:i,ttl:a=600}=e,c={published:[],warnings:[]},l=[{type:"A",content:s}];if(i&&Tn(n))l.push({type:"AAAA",content:i});for(let{type:m,content:S}of l){let v=await t.upsertRecord(r,{name:n,type:m,content:S,ttl:a});if(v?.success===!1){c.warnings.push(`${n} → ${S} failed: ${v.error||v.message||"unknown error"}`);continue}if(c.warnings.push(...(await Xa(t,r,n,S,m)).map((_)=>`${n} cleanup: ${_}`)),await Za(t,r,n,S,m))c.published.push({fqdn:n,type:m,content:S});else c.warnings.push(`${n} → ${S} reported success at ${t.name} but no matching ${m} record exists — create it manually: ${m} ${n} → ${S}`)}return c}async function Za(e,t,r,n,s){try{if(typeof e?.listRecords!=="function")return!0;let i=await e.listRecords(t);if(!i?.success||!Array.isArray(i.records))return!0;return i.records.some((a)=>{let c=typeof a?.name==="string"?a.name.replace(/\.$/,""):"";return a?.type===s&&c===r&&a?.content===n})}catch{return!0}}function Nr(e){return(Buffer.isBuffer(e)?e.toString("utf8"):typeof e==="string"?e:"").replace(/(^|\n)(\s*(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*=).*$/gm,"$1$2[redacted]").replace(/encrypted:[A-Za-z0-9+/=]+/g,"encrypted:[redacted]").trim().slice(-8000)}function wn(e,t){let r=Nr(e?.stderr),n=/line (\d+): syntax error/.exec(r);if(!n)return"";let s=Number(n[1]),i=t.split(`
1
+ import{fd,O,d,p,bi,Id,Sd,le,g,Te,Fr,Qt,Ht,Vt,Ur,Ti}from"./chunk-v2p7c7s4.js";import{o}from"./chunk-9asn5fpt.js";import{B,vr,Tr,u}from"./chunk-3m9ghthh.js";import{ii}from"./chunk-srrscggm.js";import{Er,be}from"./chunk-qcaqc5b8.js";import{h}from"./chunk-ptq9v346.js";import{Ei}from"./chunk-g6g33pt9.js";import{readFileSync as to}from"node:fs";import{join as Ma}from"node:path";function vu(e={}){let t=new Set;for(let r of Object.values(e)){if(!r.domain)continue;if(r.redirect||r.deploy==="server"||r.start)t.add(r.domain)}return t}function Hr(e){return e.replace(/\.$/,"").toLowerCase()}function Ci(e,t,r){let n=Hr(e.name),s=Hr(t),i=Hr(r),a=i===s?"@":i.endsWith(`.${s}`)?i.slice(0,-(s.length+1)):i;return n===i||n===a||a==="@"&&(n===""||n===s)}async function Xa(e,t,r,n,s="A"){let i=await e.listRecords(t);if(!i.success)return[`could not list ${s} records: ${i.message||"unknown provider error"}`];let a=i.records.filter((m)=>m.type===s&&Ci(m,t,r)),c=a.findIndex((m)=>m.content===n);if(a.length<=1||c===-1)return[];let l=[];for(let[m,S]of a.entries()){if(m===c)continue;let v=await e.deleteRecord(t,S);if(!v.success)l.push(`could not remove stale ${S.name} ${s} ${S.content}: ${v.message||"unknown provider error"}`)}return l}function ye(e){if(!e)return;let t=e.trim();if(!t)return;if(!t.includes("/"))return t;let[r]=t.split("/");if(!r.endsWith("::"))return r||void 0;return`${r}1`}var Ya=new Set(["mail","smtp","imap","mx"]);function Tn(e){return!Ya.has(e.split(".")[0]??"")}async function Tu(e){let{provider:t,zone:r,fqdn:n,ipv4:s,ipv6:i,ttl:a=600}=e,c={published:[],warnings:[]},l=[{type:"A",content:s}];if(i&&Tn(n))l.push({type:"AAAA",content:i});for(let{type:m,content:S}of l){let v=await t.upsertRecord(r,{name:n,type:m,content:S,ttl:a});if(v?.success===!1){c.warnings.push(`${n} → ${S} failed: ${v.error||v.message||"unknown error"}`);continue}if(c.warnings.push(...(await Xa(t,r,n,S,m)).map((_)=>`${n} cleanup: ${_}`)),await Za(t,r,n,S,m))c.published.push({fqdn:n,type:m,content:S});else c.warnings.push(`${n} → ${S} reported success at ${t.name} but no matching ${m} record exists — create it manually: ${m} ${n} → ${S}`)}return c}async function Za(e,t,r,n,s){try{if(typeof e?.listRecords!=="function")return!0;let i=await e.listRecords(t);if(!i?.success||!Array.isArray(i.records))return!0;return i.records.some((a)=>{let c=typeof a?.name==="string"?a.name.replace(/\.$/,""):"";return a?.type===s&&c===r&&a?.content===n})}catch{return!0}}function Nr(e){return(Buffer.isBuffer(e)?e.toString("utf8"):typeof e==="string"?e:"").replace(/(^|\n)(\s*(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*=).*$/gm,"$1$2[redacted]").replace(/encrypted:[A-Za-z0-9+/=]+/g,"encrypted:[redacted]").trim().slice(-8000)}function wn(e,t){let r=Nr(e?.stderr),n=/line (\d+): syntax error/.exec(r);if(!n)return"";let s=Number(n[1]),i=t.split(`
2
2
  `),a=Math.max(1,s-12),c=Math.min(i.length,s+2),l=i.slice(a-1,c).map((m,S)=>{let v=a+S,_=/^[A-Z_][A-Z0-9_]*=/.test(m)?m.replace(/=.*/,"=<redacted>"):m;return` ${String(v).padStart(4)}${v===s?" >":" "} ${_}`});return["",`The deploy script bash rejected is ${i.length} lines; it stopped at ${s}.`,...l].join(`
3
3
  `)}function Rt(e){let t=e,r=typeof t?.status==="number"?` (exit ${t.status})`:"",n=t?.signal?` (signal ${t.signal})`:"",s=[Nr(t?.stderr),Nr(t?.stdout)].filter(Boolean).join(`
4
4
  `);return`Remote SSH command failed${r}${n}${s?`
@@ -22,7 +22,7 @@ EOF`,`DISK_PCT=$(df -P / | awk 'NR==2{gsub("%","",$5); print $5}')`,"UPTIME_SEC=
22
22
  `)}
23
23
  `}return`${["server {"," listen 80;"," listen [::]:80;",` server_name ${r};`,...n,"}"].join(`
24
24
  `)}
25
- `}function Xr(e){let t=`/etc/nginx/sites-available/${e.siteName}`,r=`/etc/nginx/sites-enabled/${e.siteName}`,n=ha(e),s=[...Jr()];if(e.auth){let i=xs(e.siteName),a=(m)=>m.split("'").join("'\\''"),c=a(e.auth.password),l=a(e.auth.username);s.push(`TS_CLOUD_HTPASS=$(openssl passwd -apr1 '${c}')`,`printf '%s:%s\\n' '${l}' "$TS_CLOUD_HTPASS" > ${i}`,`chmod 640 ${i}`,`chown root:www-data ${i} 2>/dev/null || true`)}return s.push(`cat > ${t} <<'TS_CLOUD_NGINX_EOF'`,n.replace(/\n$/,""),"TS_CLOUD_NGINX_EOF",`ln -sf ${t} ${r}`,"rm -f /etc/nginx/sites-enabled/default",`${He} -t`,"systemctl reload ts-cloud-nginx 2>/dev/null || systemctl restart ts-cloud-nginx 2>/dev/null || true"),s}var He="/usr/local/bin/ts-cloud-nginx";function Jr(e="/opt/pantry"){return[...ur(),...ge(["nginx.org"]),"mkdir -p /etc/nginx/sites-available /etc/nginx/sites-enabled /var/log/nginx /var/lib/nginx/body /var/lib/nginx/proxy /var/lib/nginx/fastcgi /var/lib/nginx/uwsgi /var/lib/nginx/scgi","getent passwd www-data >/dev/null || useradd --system --no-create-home --shell /usr/sbin/nologin www-data","chown -R www-data:www-data /var/lib/nginx /var/log/nginx",`cat > ${He} <<'TS_CLOUD_NGINXBIN_EOF'`,"#!/bin/sh",`eval "$(cd ${e} && pantry env 2>/dev/null)"`,"NGINX_BIN=/opt/pantry/pantry/.bin/nginx",'if [ ! -x "$NGINX_BIN" ]; then NGINX_BIN=$(command -v nginx || true); fi','if [ -z "$NGINX_BIN" ]; then echo "nginx binary not found; run pantry install nginx.org or install nginx explicitly" >&2; exit 1; fi','exec "$NGINX_BIN" -c /etc/nginx/nginx.conf "$@"',"TS_CLOUD_NGINXBIN_EOF",`chmod +x ${He}`,"cat > /etc/nginx/fastcgi_params <<'TS_CLOUD_FCGI_EOF'","fastcgi_param QUERY_STRING $query_string;","fastcgi_param REQUEST_METHOD $request_method;","fastcgi_param CONTENT_TYPE $content_type;","fastcgi_param CONTENT_LENGTH $content_length;","fastcgi_param SCRIPT_NAME $fastcgi_script_name;","fastcgi_param REQUEST_URI $request_uri;","fastcgi_param DOCUMENT_URI $document_uri;","fastcgi_param DOCUMENT_ROOT $document_root;","fastcgi_param SERVER_PROTOCOL $server_protocol;","fastcgi_param REQUEST_SCHEME $scheme;","fastcgi_param HTTPS $https if_not_empty;","fastcgi_param GATEWAY_INTERFACE CGI/1.1;","fastcgi_param SERVER_SOFTWARE nginx/$nginx_version;","fastcgi_param REMOTE_ADDR $remote_addr;","fastcgi_param REMOTE_PORT $remote_port;","fastcgi_param SERVER_ADDR $server_addr;","fastcgi_param SERVER_PORT $server_port;","fastcgi_param SERVER_NAME $server_name;","fastcgi_param REDIRECT_STATUS 200;","TS_CLOUD_FCGI_EOF","cat > /etc/nginx/nginx.conf <<'TS_CLOUD_NGINXCONF_EOF'","user www-data;","worker_processes auto;","pid /run/nginx.pid;","error_log /var/log/nginx/error.log;","events { worker_connections 1024; }","http {"," default_type application/octet-stream;"," types {"," text/html html htm;"," text/css css;"," application/javascript js;"," application/json json;"," image/svg+xml svg;"," image/png png;"," image/jpeg jpg jpeg;"," image/gif gif;"," image/x-icon ico;"," image/webp webp;"," font/woff2 woff2;"," font/woff woff;"," text/plain txt;"," }"," access_log /var/log/nginx/access.log;"," sendfile on;"," tcp_nopush on;"," keepalive_timeout 65;"," server_tokens off;"," client_max_body_size 100m;"," client_body_temp_path /var/lib/nginx/body;"," proxy_temp_path /var/lib/nginx/proxy;"," fastcgi_temp_path /var/lib/nginx/fastcgi;"," uwsgi_temp_path /var/lib/nginx/uwsgi;"," scgi_temp_path /var/lib/nginx/scgi;"," server {"," listen 80 default_server;"," listen [::]:80 default_server;"," server_name _;"," return 444;"," }"," include /etc/nginx/sites-enabled/*;","}","TS_CLOUD_NGINXCONF_EOF","cat > /etc/systemd/system/ts-cloud-nginx.service <<'TS_CLOUD_NGINXUNIT_EOF'","[Unit]","Description=ts-cloud nginx (pantry)","After=network.target","","[Service]","Type=simple",`ExecStartPre=${He} -t`,`ExecStart=${He} -g 'daemon off;'`,`ExecReload=${He} -s reload`,"Restart=always","RestartSec=3","","[Install]","WantedBy=multi-user.target","TS_CLOUD_NGINXUNIT_EOF","systemctl daemon-reload","systemctl enable ts-cloud-nginx","ls /etc/nginx/sites-enabled/* >/dev/null 2>&1 && systemctl restart ts-cloud-nginx || true"]}function bt(e,t){return!e.events||e.events.includes(t)}async function Qr(e,t,r,n={}){if(!e)return[];let s=n.fetchImpl??globalThis.fetch,i=[],a=[],c=(l,m)=>s(l,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m)}).catch(()=>{return});if(e.slack?.webhookUrl&&bt(e,t))i.push("slack"),a.push(c(e.slack.webhookUrl,{text:r}));if(e.discord?.webhookUrl&&bt(e,t))i.push("discord"),a.push(c(e.discord.webhookUrl,{content:r}));if(e.telegram?.botToken&&e.telegram.chatId&&bt(e,t)){i.push("telegram");let l=`https://api.telegram.org/bot${e.telegram.botToken}/sendMessage`;a.push(c(l,{chat_id:e.telegram.chatId,text:r}))}if(e.webhook?.url&&bt(e,t))if(i.push("webhook"),(e.webhook.method||"POST")==="GET"){let l=e.webhook.url.includes("?")?"&":"?",m=`${e.webhook.url}${l}event=${encodeURIComponent(t)}&message=${encodeURIComponent(r)}`;a.push(s(m,{method:"GET"}).catch(()=>{return}))}else a.push(c(e.webhook.url,{event:t,message:r}));if(e.email?.to&&bt(e,t))i.push("email"),a.push(Sa(e.email,t,r));return await Promise.all(a),i}async function Sa(e,t,r){try{let n=await import("./chunk-hjgjbkhk.js");await n.email.send({to:e.to,from:e.from,subject:`[ts-cloud] ${t}`,text:r})}catch{}}function Os(e,t){return t??e}function Ze(e){if(!e)return[];let t=[];if(e.slack?.webhookUrl)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"text\\":\\"$MSG\\"}" ${e.slack.webhookUrl} || true`);if(e.discord?.webhookUrl)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"content\\":\\"$MSG\\"}" ${e.discord.webhookUrl} || true`);if(e.telegram?.botToken&&e.telegram.chatId)t.push(`curl -fsS -X POST "https://api.telegram.org/bot${e.telegram.botToken}/sendMessage" --data-urlencode "chat_id=${e.telegram.chatId}" --data-urlencode "text=$MSG" || true`);if(e.webhook?.url)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"message\\":\\"$MSG\\"}" ${e.webhook.url} || true`);if(t.length===0)return[];return["cat > /usr/local/bin/ts-cloud-notify <<'TS_CLOUD_NOTIFY_EOF'","#!/bin/bash",'MSG="$1"',...t,"TS_CLOUD_NOTIFY_EOF","chmod +x /usr/local/bin/ts-cloud-notify"]}import{isIP as As}from"node:net";var Dn="/etc/rpx/certs",Ls="/etc/rpx/local-ca",_a="rpx-root-ca.crt";function Wt(e=Ls){return`${e.replace(/\/+$/,"")}/${_a}`}function Pn(e){if(e.toLowerCase().endsWith(".local"))return!1;return e.split(".").length===2}function Nn(e,t={}){let r=new Set;for(let n of Object.values(e)){if(!n?.domain)continue;if(u(n)==="bucket")continue;r.add(n.domain)}if(t.autoWww!==!1)for(let n of[...r]){if(!Pn(n))continue;r.add(`www.${n}`)}return[...r]}var va=["1.1.1.1","8.8.8.8"],ya="/var/www/acme-challenge";function $a(e){if(typeof e==="string")return{to:e};let t={to:e.to};if(e.status!=null)t.status=e.status;if(e.preservePath!=null)t.preservePath=e.preservePath;return t}function ba(e){let t=e.auth;if(!t||t.enabled===!1||!t.password)return;return{username:t.username||"admin",password:t.password,...t.realm?{realm:t.realm}:{}}}function en(e){if(!e)return;return e.tls??"local-ca"}function Us(e,t){if(e.cloud?.provider!=="ssh")return;let r=e.ssh?.lan;if(!r)return;return{...r.hostname?{hostname:r.hostname}:{},tls:r.tls??"local-ca",...t?{ip:t}:{}}}function Hs(e){if(e.cloud?.provider!=="ssh")return;return e.ssh?.profile}function Ta(e){let t=e.trim().toLowerCase();if(!t||t.startsWith("*")||t.includes(":")||t.includes("/")||t.includes(" "))return!1;if(As(t)!==0)return!1;return t.endsWith(".local")||!t.includes(".")}function wa(e,t,r){let n=[],s=new Set,i=(m,S)=>{let v=m.trim().toLowerCase();if(!v||s.has(v))return;s.add(v),n.push({host:v,source:S})},a=t.hostname?.trim(),c=(a||`${r}.local`).toLowerCase();if(i(c,a?"ssh.lan.hostname":`the ssh provider's default LAN name for project "${r}"`),Object.entries(e).some(([m,S])=>!!S&&Ur(m)))i(`dashboard.${c}`,"the management dashboard site");for(let[m,S]of Object.entries(e)){if(!S?.domain)continue;if(u(S)==="bucket")continue;if(!Ta(S.domain))continue;i(S.domain,`site "${m}"`)}return n}function Ca(e,t){if(!t?.length)return;return t.find((r)=>{let n=(r.startsWith(".")?r.slice(1):r).toLowerCase();return e===n||e.endsWith(`.${n}`)})}function Pa(e,t){if(!t?.enabled)return;for(let{host:r,source:n}of e){let s=Ca(r,t.allowedSuffixes);if(!s)continue;throw Error(`The LAN certificate authority and public on-demand TLS both claim "${r}". LAN source: ${n}. Public source: the on-demand TLS allowed suffix "${s}", which is derived from the site domains. A host is either LAN-only, with a certificate signed by the box's own CA, or public, with one issued by Let's Encrypt, never both. Give the LAN a name no site domain covers (ssh.lan.hostname), or take that domain out of the sites this deploy routes.`)}}function Pu(e){if(!e||e==="/")return;let t=`/${e}`.replace(/\/+/g,"/").replace(/\/+$/,"");if(!t.startsWith("/"))t=`/${t}`;return t===""||t==="/"?void 0:t}function ec(e,t){let n=(t?`${e}${t}`:e).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return n.length>0?n:"rpx"}function Ea(e,t){if(!t||t.length===0)return`localhost:${e}`;return t.map((r)=>`${r.privateIp??r.publicIp}:${e}`)}function Ms(e,t,r){let n=(t.wwwRoot??"/var/www").replace(/\/+$/,""),s=t.slug??"app",i=t.proxy.certsDir??Dn,a=t.proxy.loadBalancer,c=[],l=new Set;for(let[_,f]of Object.entries(e)){if(!f||!f.domain)continue;let y=u(f);if(y==="bucket")continue;let x=Pu(f.path),P=ec(f.domain,x),C=ba(f);if(y==="redirect"){c.push({to:f.domain,path:x,redirect:$a(f.redirect),id:P,...C?{auth:C}:{}}),l.add(f.domain);continue}if(y==="proxy"){let T=Tr(f);if(T.length===0)continue;let b=T.length===1?T[0]:T;c.push({to:f.domain,path:x,from:b,id:P,...C?{auth:C}:{},...Array.isArray(b)&&a?{loadBalancer:a}:{}}),l.add(f.domain);continue}if(y==="server-app"){if(typeof f.port!=="number")continue;let T=Ea(f.port,r);c.push({to:f.domain,path:x,from:T,id:P,...C?{auth:C}:{},...Array.isArray(T)&&a?{loadBalancer:a}:{}})}else c.push({to:f.domain,path:x,static:{dir:`${n}/${s}-${_}/current`,spa:f.spa??!1,pathRewriteStyle:f.pathRewriteStyle??"directory"},cleanUrls:f.pathRewriteStyle!=="flat",...C?{auth:C}:{},id:P});l.add(f.domain)}if(t.proxy.autoWww!==!1)for(let _ of[...l]){if(!Pn(_))continue;let f=`www.${_}`;if(l.has(f))continue;c.push({to:f,redirect:{to:`https://${_}`},id:ec(f)}),l.add(f)}c.sort((_,f)=>{if(_.to!==f.to)return _.to.localeCompare(f.to);return(f.path?.length??0)-(_.path?.length??0)});let m={proxies:c,productionCerts:{certsDir:i,certsDirServerNames:[...l]},https:!0,hostsManagement:!1,cleanup:{hosts:!1,certs:!1}};if(t.proxy.onDemandTls&&l.size>0)m.onDemandTls={enabled:!0,allowedSuffixes:[...l],email:t.proxy.onDemandTlsEmail,certsDir:i,staging:t.proxy.onDemandTlsStaging??!1};if(t.proxy.onDemandTls)m.acmeChallengeWebroot=t.proxy.acmeWebroot??ya;let S=t.proxy.cdn,v=S?.frontedHosts?.length?S.frontedHosts:[...l];if(S?.secret&&v.length>0)m.originGuard={header:S.secretHeader??"X-Origin-Verify",value:S.secret,hosts:v};if(t.lan)if(en(t.lan)==="off")m.https=!1;else{let _=wa(e,t.lan,s);Pa(_,m.onDemandTls);let f=t.lan.ip&&As(t.lan.ip)!==0?[t.lan.ip]:[];m.localCa={dir:Ls,hosts:_.map((y)=>y.host),...f.length>0?{ips:f}:{},installTrust:!0}}return m}function K(e,t){return Ms(e,t)}function gr(e,t,r){return Ms(e,r,t)}function Nh(e){return`// Generated by ts-cloud — rpx reverse-proxy gateway.
25
+ `}function Xr(e){let t=`/etc/nginx/sites-available/${e.siteName}`,r=`/etc/nginx/sites-enabled/${e.siteName}`,n=ha(e),s=[...Jr()];if(e.auth){let i=xs(e.siteName),a=(m)=>m.split("'").join("'\\''"),c=a(e.auth.password),l=a(e.auth.username);s.push(`TS_CLOUD_HTPASS=$(openssl passwd -apr1 '${c}')`,`printf '%s:%s\\n' '${l}' "$TS_CLOUD_HTPASS" > ${i}`,`chmod 640 ${i}`,`chown root:www-data ${i} 2>/dev/null || true`)}return s.push(`cat > ${t} <<'TS_CLOUD_NGINX_EOF'`,n.replace(/\n$/,""),"TS_CLOUD_NGINX_EOF",`ln -sf ${t} ${r}`,"rm -f /etc/nginx/sites-enabled/default",`${He} -t`,"systemctl reload ts-cloud-nginx 2>/dev/null || systemctl restart ts-cloud-nginx 2>/dev/null || true"),s}var He="/usr/local/bin/ts-cloud-nginx";function Jr(e="/opt/pantry"){return[...ur(),...ge(["nginx.org"]),"mkdir -p /etc/nginx/sites-available /etc/nginx/sites-enabled /var/log/nginx /var/lib/nginx/body /var/lib/nginx/proxy /var/lib/nginx/fastcgi /var/lib/nginx/uwsgi /var/lib/nginx/scgi","getent passwd www-data >/dev/null || useradd --system --no-create-home --shell /usr/sbin/nologin www-data","chown -R www-data:www-data /var/lib/nginx /var/log/nginx",`cat > ${He} <<'TS_CLOUD_NGINXBIN_EOF'`,"#!/bin/sh",`eval "$(cd ${e} && pantry env 2>/dev/null)"`,"NGINX_BIN=/opt/pantry/pantry/.bin/nginx",'if [ ! -x "$NGINX_BIN" ]; then NGINX_BIN=$(command -v nginx || true); fi','if [ -z "$NGINX_BIN" ]; then echo "nginx binary not found; run pantry install nginx.org or install nginx explicitly" >&2; exit 1; fi','exec "$NGINX_BIN" -c /etc/nginx/nginx.conf "$@"',"TS_CLOUD_NGINXBIN_EOF",`chmod +x ${He}`,"cat > /etc/nginx/fastcgi_params <<'TS_CLOUD_FCGI_EOF'","fastcgi_param QUERY_STRING $query_string;","fastcgi_param REQUEST_METHOD $request_method;","fastcgi_param CONTENT_TYPE $content_type;","fastcgi_param CONTENT_LENGTH $content_length;","fastcgi_param SCRIPT_NAME $fastcgi_script_name;","fastcgi_param REQUEST_URI $request_uri;","fastcgi_param DOCUMENT_URI $document_uri;","fastcgi_param DOCUMENT_ROOT $document_root;","fastcgi_param SERVER_PROTOCOL $server_protocol;","fastcgi_param REQUEST_SCHEME $scheme;","fastcgi_param HTTPS $https if_not_empty;","fastcgi_param GATEWAY_INTERFACE CGI/1.1;","fastcgi_param SERVER_SOFTWARE nginx/$nginx_version;","fastcgi_param REMOTE_ADDR $remote_addr;","fastcgi_param REMOTE_PORT $remote_port;","fastcgi_param SERVER_ADDR $server_addr;","fastcgi_param SERVER_PORT $server_port;","fastcgi_param SERVER_NAME $server_name;","fastcgi_param REDIRECT_STATUS 200;","TS_CLOUD_FCGI_EOF","cat > /etc/nginx/nginx.conf <<'TS_CLOUD_NGINXCONF_EOF'","user www-data;","worker_processes auto;","pid /run/nginx.pid;","error_log /var/log/nginx/error.log;","events { worker_connections 1024; }","http {"," default_type application/octet-stream;"," types {"," text/html html htm;"," text/css css;"," application/javascript js;"," application/json json;"," image/svg+xml svg;"," image/png png;"," image/jpeg jpg jpeg;"," image/gif gif;"," image/x-icon ico;"," image/webp webp;"," font/woff2 woff2;"," font/woff woff;"," text/plain txt;"," }"," access_log /var/log/nginx/access.log;"," sendfile on;"," tcp_nopush on;"," keepalive_timeout 65;"," server_tokens off;"," client_max_body_size 100m;"," client_body_temp_path /var/lib/nginx/body;"," proxy_temp_path /var/lib/nginx/proxy;"," fastcgi_temp_path /var/lib/nginx/fastcgi;"," uwsgi_temp_path /var/lib/nginx/uwsgi;"," scgi_temp_path /var/lib/nginx/scgi;"," server {"," listen 80 default_server;"," listen [::]:80 default_server;"," server_name _;"," return 444;"," }"," include /etc/nginx/sites-enabled/*;","}","TS_CLOUD_NGINXCONF_EOF","cat > /etc/systemd/system/ts-cloud-nginx.service <<'TS_CLOUD_NGINXUNIT_EOF'","[Unit]","Description=ts-cloud nginx (pantry)","After=network.target","","[Service]","Type=simple",`ExecStartPre=${He} -t`,`ExecStart=${He} -g 'daemon off;'`,`ExecReload=${He} -s reload`,"Restart=always","RestartSec=3","","[Install]","WantedBy=multi-user.target","TS_CLOUD_NGINXUNIT_EOF","systemctl daemon-reload","systemctl enable ts-cloud-nginx","ls /etc/nginx/sites-enabled/* >/dev/null 2>&1 && systemctl restart ts-cloud-nginx || true"]}function bt(e,t){return!e.events||e.events.includes(t)}async function Qr(e,t,r,n={}){if(!e)return[];let s=n.fetchImpl??globalThis.fetch,i=[],a=[],c=(l,m)=>s(l,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m)}).catch(()=>{return});if(e.slack?.webhookUrl&&bt(e,t))i.push("slack"),a.push(c(e.slack.webhookUrl,{text:r}));if(e.discord?.webhookUrl&&bt(e,t))i.push("discord"),a.push(c(e.discord.webhookUrl,{content:r}));if(e.telegram?.botToken&&e.telegram.chatId&&bt(e,t)){i.push("telegram");let l=`https://api.telegram.org/bot${e.telegram.botToken}/sendMessage`;a.push(c(l,{chat_id:e.telegram.chatId,text:r}))}if(e.webhook?.url&&bt(e,t))if(i.push("webhook"),(e.webhook.method||"POST")==="GET"){let l=e.webhook.url.includes("?")?"&":"?",m=`${e.webhook.url}${l}event=${encodeURIComponent(t)}&message=${encodeURIComponent(r)}`;a.push(s(m,{method:"GET"}).catch(()=>{return}))}else a.push(c(e.webhook.url,{event:t,message:r}));if(e.email?.to&&bt(e,t))i.push("email"),a.push(Sa(e.email,t,r));return await Promise.all(a),i}async function Sa(e,t,r){try{let n=await import("./chunk-49vvjfrd.js");await n.email.send({to:e.to,from:e.from,subject:`[ts-cloud] ${t}`,text:r})}catch{}}function Os(e,t){return t??e}function Ze(e){if(!e)return[];let t=[];if(e.slack?.webhookUrl)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"text\\":\\"$MSG\\"}" ${e.slack.webhookUrl} || true`);if(e.discord?.webhookUrl)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"content\\":\\"$MSG\\"}" ${e.discord.webhookUrl} || true`);if(e.telegram?.botToken&&e.telegram.chatId)t.push(`curl -fsS -X POST "https://api.telegram.org/bot${e.telegram.botToken}/sendMessage" --data-urlencode "chat_id=${e.telegram.chatId}" --data-urlencode "text=$MSG" || true`);if(e.webhook?.url)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"message\\":\\"$MSG\\"}" ${e.webhook.url} || true`);if(t.length===0)return[];return["cat > /usr/local/bin/ts-cloud-notify <<'TS_CLOUD_NOTIFY_EOF'","#!/bin/bash",'MSG="$1"',...t,"TS_CLOUD_NOTIFY_EOF","chmod +x /usr/local/bin/ts-cloud-notify"]}import{isIP as As}from"node:net";var Dn="/etc/rpx/certs",Ls="/etc/rpx/local-ca",_a="rpx-root-ca.crt";function Wt(e=Ls){return`${e.replace(/\/+$/,"")}/${_a}`}function Pn(e){if(e.toLowerCase().endsWith(".local"))return!1;return e.split(".").length===2}function Nn(e,t={}){let r=new Set;for(let n of Object.values(e)){if(!n?.domain)continue;if(u(n)==="bucket")continue;r.add(n.domain)}if(t.autoWww!==!1)for(let n of[...r]){if(!Pn(n))continue;r.add(`www.${n}`)}return[...r]}var va=["1.1.1.1","8.8.8.8"],ya="/var/www/acme-challenge";function $a(e){if(typeof e==="string")return{to:e};let t={to:e.to};if(e.status!=null)t.status=e.status;if(e.preservePath!=null)t.preservePath=e.preservePath;return t}function ba(e){let t=e.auth;if(!t||t.enabled===!1||!t.password)return;return{username:t.username||"admin",password:t.password,...t.realm?{realm:t.realm}:{}}}function en(e){if(!e)return;return e.tls??"local-ca"}function Us(e,t){if(e.cloud?.provider!=="ssh")return;let r=e.ssh?.lan;if(!r)return;return{...r.hostname?{hostname:r.hostname}:{},tls:r.tls??"local-ca",...t?{ip:t}:{}}}function Hs(e){if(e.cloud?.provider!=="ssh")return;return e.ssh?.profile}function Ta(e){let t=e.trim().toLowerCase();if(!t||t.startsWith("*")||t.includes(":")||t.includes("/")||t.includes(" "))return!1;if(As(t)!==0)return!1;return t.endsWith(".local")||!t.includes(".")}function wa(e,t,r){let n=[],s=new Set,i=(m,S)=>{let v=m.trim().toLowerCase();if(!v||s.has(v))return;s.add(v),n.push({host:v,source:S})},a=t.hostname?.trim(),c=(a||`${r}.local`).toLowerCase();if(i(c,a?"ssh.lan.hostname":`the ssh provider's default LAN name for project "${r}"`),Object.entries(e).some(([m,S])=>!!S&&Ur(m)))i(`dashboard.${c}`,"the management dashboard site");for(let[m,S]of Object.entries(e)){if(!S?.domain)continue;if(u(S)==="bucket")continue;if(!Ta(S.domain))continue;i(S.domain,`site "${m}"`)}return n}function Ca(e,t){if(!t?.length)return;return t.find((r)=>{let n=(r.startsWith(".")?r.slice(1):r).toLowerCase();return e===n||e.endsWith(`.${n}`)})}function Pa(e,t){if(!t?.enabled)return;for(let{host:r,source:n}of e){let s=Ca(r,t.allowedSuffixes);if(!s)continue;throw Error(`The LAN certificate authority and public on-demand TLS both claim "${r}". LAN source: ${n}. Public source: the on-demand TLS allowed suffix "${s}", which is derived from the site domains. A host is either LAN-only, with a certificate signed by the box's own CA, or public, with one issued by Let's Encrypt, never both. Give the LAN a name no site domain covers (ssh.lan.hostname), or take that domain out of the sites this deploy routes.`)}}function Pu(e){if(!e||e==="/")return;let t=`/${e}`.replace(/\/+/g,"/").replace(/\/+$/,"");if(!t.startsWith("/"))t=`/${t}`;return t===""||t==="/"?void 0:t}function ec(e,t){let n=(t?`${e}${t}`:e).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return n.length>0?n:"rpx"}function Ea(e,t){if(!t||t.length===0)return`localhost:${e}`;return t.map((r)=>`${r.privateIp??r.publicIp}:${e}`)}function Ms(e,t,r){let n=(t.wwwRoot??"/var/www").replace(/\/+$/,""),s=t.slug??"app",i=t.proxy.certsDir??Dn,a=t.proxy.loadBalancer,c=[],l=new Set;for(let[_,f]of Object.entries(e)){if(!f||!f.domain)continue;let y=u(f);if(y==="bucket")continue;let x=Pu(f.path),P=ec(f.domain,x),C=ba(f);if(y==="redirect"){c.push({to:f.domain,path:x,redirect:$a(f.redirect),id:P,...C?{auth:C}:{}}),l.add(f.domain);continue}if(y==="proxy"){let T=Tr(f);if(T.length===0)continue;let b=T.length===1?T[0]:T;c.push({to:f.domain,path:x,from:b,id:P,...C?{auth:C}:{},...Array.isArray(b)&&a?{loadBalancer:a}:{}}),l.add(f.domain);continue}if(y==="server-app"){if(typeof f.port!=="number")continue;let T=Ea(f.port,r);c.push({to:f.domain,path:x,from:T,id:P,...C?{auth:C}:{},...Array.isArray(T)&&a?{loadBalancer:a}:{}})}else c.push({to:f.domain,path:x,static:{dir:`${n}/${s}-${_}/current`,spa:f.spa??!1,pathRewriteStyle:f.pathRewriteStyle??"directory"},cleanUrls:f.pathRewriteStyle!=="flat",...C?{auth:C}:{},id:P});l.add(f.domain)}if(t.proxy.autoWww!==!1)for(let _ of[...l]){if(!Pn(_))continue;let f=`www.${_}`;if(l.has(f))continue;c.push({to:f,redirect:{to:`https://${_}`},id:ec(f)}),l.add(f)}c.sort((_,f)=>{if(_.to!==f.to)return _.to.localeCompare(f.to);return(f.path?.length??0)-(_.path?.length??0)});let m={proxies:c,productionCerts:{certsDir:i,certsDirServerNames:[...l]},https:!0,hostsManagement:!1,cleanup:{hosts:!1,certs:!1}};if(t.proxy.onDemandTls&&l.size>0)m.onDemandTls={enabled:!0,allowedSuffixes:[...l],email:t.proxy.onDemandTlsEmail,certsDir:i,staging:t.proxy.onDemandTlsStaging??!1};if(t.proxy.onDemandTls)m.acmeChallengeWebroot=t.proxy.acmeWebroot??ya;let S=t.proxy.cdn,v=S?.frontedHosts?.length?S.frontedHosts:[...l];if(S?.secret&&v.length>0)m.originGuard={header:S.secretHeader??"X-Origin-Verify",value:S.secret,hosts:v};if(t.lan)if(en(t.lan)==="off")m.https=!1;else{let _=wa(e,t.lan,s);Pa(_,m.onDemandTls);let f=t.lan.ip&&As(t.lan.ip)!==0?[t.lan.ip]:[];m.localCa={dir:Ls,hosts:_.map((y)=>y.host),...f.length>0?{ips:f}:{},installTrust:!0}}return m}function K(e,t){return Ms(e,t)}function gr(e,t,r){return Ms(e,r,t)}function Nh(e){return`// Generated by ts-cloud — rpx reverse-proxy gateway.
26
26
  // Routes are derived from the \`sites\` model on every \`buddy deploy\`.
27
27
  import { startProxies } from '@stacksjs/rpx'
28
28
 
@@ -0,0 +1,34 @@
1
+ import{n}from"./chunk-zx8ecz8b.js";import{o}from"./chunk-9asn5fpt.js";import{y}from"./chunk-9wmer0zx.js";import{Fe}from"./chunk-bxrzsth8.js";function f(e,t){let s=[`Action=${e}`,"Version=2010-05-08"];for(let[a,i]of Object.entries(t)){if(i===void 0||i===null)continue;if(Array.isArray(i))i.forEach((c,u)=>{if(typeof c==="object"&&c!==null)for(let[d,m]of Object.entries(c))s.push(`${a}.member.${u+1}.${d}=${encodeURIComponent(String(m))}`);else s.push(`${a}.member.${u+1}=${encodeURIComponent(String(c))}`)});else if(typeof i==="object"){for(let[c,u]of Object.entries(i))if(u!==void 0&&u!==null)s.push(`${a}.${c}=${encodeURIComponent(String(u))}`)}else s.push(`${a}=${encodeURIComponent(String(i))}`)}return s.join("&")}function r(e,t){let s=new RegExp(`<${t}>([^<]*)</${t}>`),a=e.match(s);return a?a[1]:void 0}function l(e,t,s){let a=new RegExp(`<${t}>([\\s\\S]*?)</${t}>`),i=e.match(a);if(!i)return[];let c=[],u=new RegExp(`<${s}>([\\s\\S]*?)</${s}>`,"g"),d;while((d=u.exec(i[1]))!==null)c.push(d[1]);return c}class fe{client;region;constructor(e="us-east-1",t){this.client=new n(void 0,{profile:t}),this.region=e}async request(e,t={}){let s=f(e,t);return await this.client.request({service:"iam",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s})}async createUser(e){let t=await this.request("CreateUser",e);return this.parseUser(t)}async getUser(e={}){let t=await this.request("GetUser",e);return this.parseUser(t)}async listUsers(e={}){let t=await this.request("ListUsers",e),s=this.parseUsers(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Users:s,IsTruncated:a,Marker:i}}async updateUser(e){await this.request("UpdateUser",e)}async deleteUser(e){await this.request("DeleteUser",e)}parseUser(e){return{UserName:r(e,"UserName")||"",UserId:r(e,"UserId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate"),PasswordLastUsed:r(e,"PasswordLastUsed")}}parseUsers(e){return l(e,"Users","member").map((s)=>({UserName:r(s,"UserName")||"",UserId:r(s,"UserId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate"),PasswordLastUsed:r(s,"PasswordLastUsed")}))}async createGroup(e){let t=await this.request("CreateGroup",e);return this.parseGroup(t)}async getGroup(e){let t=await this.request("GetGroup",e),s=this.parseGroup(t),a=this.parseUsers(t),i=r(t,"IsTruncated")==="true",c=r(t,"Marker");return{Group:s,Users:a,IsTruncated:i,Marker:c}}async listGroups(e={}){let t=await this.request("ListGroups",e),s=this.parseGroups(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Groups:s,IsTruncated:a,Marker:i}}async updateGroup(e){await this.request("UpdateGroup",e)}async deleteGroup(e){await this.request("DeleteGroup",e)}async addUserToGroup(e){await this.request("AddUserToGroup",e)}async removeUserFromGroup(e){await this.request("RemoveUserFromGroup",e)}async listGroupsForUser(e){let t=await this.request("ListGroupsForUser",e),s=this.parseGroups(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Groups:s,IsTruncated:a,Marker:i}}parseGroup(e){return{GroupName:r(e,"GroupName")||"",GroupId:r(e,"GroupId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate")}}parseGroups(e){return l(e,"Groups","member").map((s)=>({GroupName:r(s,"GroupName")||"",GroupId:r(s,"GroupId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate")}))}async createRole(e){let t=await this.request("CreateRole",e);return this.parseRole(t)}async getRole(e){let t=await this.request("GetRole",e);return this.parseRole(t)}async listRoles(e={}){let t=await this.request("ListRoles",e),s=this.parseRoles(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Roles:s,IsTruncated:a,Marker:i}}async updateRole(e){await this.request("UpdateRole",e)}async updateRoleDescription(e){let t=await this.request("UpdateRoleDescription",e);return this.parseRole(t)}async updateAssumeRolePolicy(e){await this.request("UpdateAssumeRolePolicy",e)}async deleteRole(e){await this.request("DeleteRole",e)}async tagRole(e){await this.request("TagRole",e)}async untagRole(e){await this.request("UntagRole",e)}async listRoleTags(e){let t=await this.request("ListRoleTags",e),s=this.parseTags(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Tags:s,IsTruncated:a,Marker:i}}parseRole(e){return{RoleName:r(e,"RoleName")||"",RoleId:r(e,"RoleId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate"),AssumeRolePolicyDocument:r(e,"AssumeRolePolicyDocument"),Description:r(e,"Description"),MaxSessionDuration:r(e,"MaxSessionDuration")?Number.parseInt(r(e,"MaxSessionDuration"),10):void 0}}parseRoles(e){return l(e,"Roles","member").map((s)=>({RoleName:r(s,"RoleName")||"",RoleId:r(s,"RoleId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate"),AssumeRolePolicyDocument:r(s,"AssumeRolePolicyDocument"),Description:r(s,"Description"),MaxSessionDuration:r(s,"MaxSessionDuration")?Number.parseInt(r(s,"MaxSessionDuration"),10):void 0}))}parseTags(e){return l(e,"Tags","member").map((s)=>({Key:r(s,"Key")||"",Value:r(s,"Value")||""}))}async createPolicy(e){let t=await this.request("CreatePolicy",e);return this.parsePolicy(t)}async getPolicy(e){let t=await this.request("GetPolicy",e);return this.parsePolicy(t)}async getPolicyVersion(e){let t=await this.request("GetPolicyVersion",e);return{VersionId:r(t,"VersionId")||"",IsDefaultVersion:r(t,"IsDefaultVersion")==="true",CreateDate:r(t,"CreateDate"),Document:r(t,"Document")}}async listPolicies(e={}){let t=await this.request("ListPolicies",e),s=this.parsePolicies(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Policies:s,IsTruncated:a,Marker:i}}async listPolicyVersions(e){let t=await this.request("ListPolicyVersions",e),s=this.parsePolicyVersions(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Versions:s,IsTruncated:a,Marker:i}}async createPolicyVersion(e){let t=await this.request("CreatePolicyVersion",e);return{VersionId:r(t,"VersionId")||"",IsDefaultVersion:r(t,"IsDefaultVersion")==="true",CreateDate:r(t,"CreateDate")}}async deletePolicyVersion(e){await this.request("DeletePolicyVersion",e)}async setDefaultPolicyVersion(e){await this.request("SetDefaultPolicyVersion",e)}async deletePolicy(e){await this.request("DeletePolicy",e)}async attachUserPolicy(e){await this.request("AttachUserPolicy",e)}async detachUserPolicy(e){await this.request("DetachUserPolicy",e)}async attachGroupPolicy(e){await this.request("AttachGroupPolicy",e)}async detachGroupPolicy(e){await this.request("DetachGroupPolicy",e)}async attachRolePolicy(e){await this.request("AttachRolePolicy",e)}async detachRolePolicy(e){await this.request("DetachRolePolicy",e)}async listAttachedUserPolicies(e){let t=await this.request("ListAttachedUserPolicies",e),s=this.parseAttachedPolicies(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:a,Marker:i}}async listAttachedGroupPolicies(e){let t=await this.request("ListAttachedGroupPolicies",e),s=this.parseAttachedPolicies(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:a,Marker:i}}async listAttachedRolePolicies(e){let t=await this.request("ListAttachedRolePolicies",e),s=this.parseAttachedPolicies(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:a,Marker:i}}parsePolicy(e){return{PolicyName:r(e,"PolicyName")||"",PolicyId:r(e,"PolicyId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),DefaultVersionId:r(e,"DefaultVersionId"),AttachmentCount:r(e,"AttachmentCount")?Number.parseInt(r(e,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:r(e,"PermissionsBoundaryUsageCount")?Number.parseInt(r(e,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:r(e,"IsAttachable")==="true",Description:r(e,"Description"),CreateDate:r(e,"CreateDate"),UpdateDate:r(e,"UpdateDate")}}parsePolicies(e){return l(e,"Policies","member").map((s)=>({PolicyName:r(s,"PolicyName")||"",PolicyId:r(s,"PolicyId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),DefaultVersionId:r(s,"DefaultVersionId"),AttachmentCount:r(s,"AttachmentCount")?Number.parseInt(r(s,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:r(s,"PermissionsBoundaryUsageCount")?Number.parseInt(r(s,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:r(s,"IsAttachable")==="true",Description:r(s,"Description"),CreateDate:r(s,"CreateDate"),UpdateDate:r(s,"UpdateDate")}))}parsePolicyVersions(e){return l(e,"Versions","member").map((s)=>({VersionId:r(s,"VersionId")||"",IsDefaultVersion:r(s,"IsDefaultVersion")==="true",CreateDate:r(s,"CreateDate")}))}parseAttachedPolicies(e){return l(e,"AttachedPolicies","member").map((s)=>({PolicyName:r(s,"PolicyName")||"",PolicyArn:r(s,"PolicyArn")||""}))}async putUserPolicy(e){await this.request("PutUserPolicy",e)}async getUserPolicy(e){let t=await this.request("GetUserPolicy",e);return{UserName:r(t,"UserName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteUserPolicy(e){await this.request("DeleteUserPolicy",e)}async listUserPolicies(e){let t=await this.request("ListUserPolicies",e),s=l(t,"PolicyNames","member"),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:a,Marker:i}}async putGroupPolicy(e){await this.request("PutGroupPolicy",e)}async getGroupPolicy(e){let t=await this.request("GetGroupPolicy",e);return{GroupName:r(t,"GroupName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteGroupPolicy(e){await this.request("DeleteGroupPolicy",e)}async listGroupPolicies(e){let t=await this.request("ListGroupPolicies",e),s=l(t,"PolicyNames","member"),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:a,Marker:i}}async putRolePolicy(e){await this.request("PutRolePolicy",e)}async getRolePolicy(e){let t=await this.request("GetRolePolicy",e);return{RoleName:r(t,"RoleName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteRolePolicy(e){await this.request("DeleteRolePolicy",e)}async listRolePolicies(e){let t=await this.request("ListRolePolicies",e),s=l(t,"PolicyNames","member"),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:a,Marker:i}}async createAccessKey(e={}){let t=await this.request("CreateAccessKey",e);if(typeof t==="object"){let s=t?.CreateAccessKeyResult?.AccessKey||t?.AccessKey;if(s)return{AccessKey:{UserName:s.UserName||"",AccessKeyId:s.AccessKeyId||"",Status:s.Status||"Active",SecretAccessKey:s.SecretAccessKey||"",CreateDate:s.CreateDate}}}return{AccessKey:{UserName:r(t,"UserName")||"",AccessKeyId:r(t,"AccessKeyId")||"",Status:r(t,"Status")||"Active",SecretAccessKey:r(t,"SecretAccessKey")||"",CreateDate:r(t,"CreateDate")}}}async listAccessKeys(e={}){let t=await this.request("ListAccessKeys",e),s=this.parseAccessKeys(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AccessKeyMetadata:s,IsTruncated:a,Marker:i}}async updateAccessKey(e){await this.request("UpdateAccessKey",e)}async deleteAccessKey(e){await this.request("DeleteAccessKey",e)}async getAccessKeyLastUsed(e){let t=await this.request("GetAccessKeyLastUsed",e);return{UserName:r(t,"UserName")||"",AccessKeyLastUsed:{LastUsedDate:r(t,"LastUsedDate"),ServiceName:r(t,"ServiceName"),Region:r(t,"Region")}}}parseAccessKeys(e){return l(e,"AccessKeyMetadata","member").map((s)=>({UserName:r(s,"UserName"),AccessKeyId:r(s,"AccessKeyId")||"",Status:r(s,"Status")||"Active",CreateDate:r(s,"CreateDate")}))}async createInstanceProfile(e){let t=await this.request("CreateInstanceProfile",e);return this.parseInstanceProfile(t)}async getInstanceProfile(e){let t=await this.request("GetInstanceProfile",e);return this.parseInstanceProfile(t)}async listInstanceProfiles(e={}){let t=await this.request("ListInstanceProfiles",e),s=this.parseInstanceProfiles(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{InstanceProfiles:s,IsTruncated:a,Marker:i}}async listInstanceProfilesForRole(e){let t=await this.request("ListInstanceProfilesForRole",e),s=this.parseInstanceProfiles(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{InstanceProfiles:s,IsTruncated:a,Marker:i}}async addRoleToInstanceProfile(e){await this.request("AddRoleToInstanceProfile",e)}async removeRoleFromInstanceProfile(e){await this.request("RemoveRoleFromInstanceProfile",e)}async deleteInstanceProfile(e){await this.request("DeleteInstanceProfile",e)}parseInstanceProfile(e){return{InstanceProfileName:r(e,"InstanceProfileName")||"",InstanceProfileId:r(e,"InstanceProfileId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate")}}parseInstanceProfiles(e){return l(e,"InstanceProfiles","member").map((s)=>({InstanceProfileName:r(s,"InstanceProfileName")||"",InstanceProfileId:r(s,"InstanceProfileId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate")}))}async getAccountPasswordPolicy(){let e=await this.request("GetAccountPasswordPolicy");return{MinimumPasswordLength:r(e,"MinimumPasswordLength")?Number.parseInt(r(e,"MinimumPasswordLength"),10):void 0,RequireSymbols:r(e,"RequireSymbols")==="true",RequireNumbers:r(e,"RequireNumbers")==="true",RequireUppercaseCharacters:r(e,"RequireUppercaseCharacters")==="true",RequireLowercaseCharacters:r(e,"RequireLowercaseCharacters")==="true",AllowUsersToChangePassword:r(e,"AllowUsersToChangePassword")==="true",ExpirePasswords:r(e,"ExpirePasswords")==="true",MaxPasswordAge:r(e,"MaxPasswordAge")?Number.parseInt(r(e,"MaxPasswordAge"),10):void 0,PasswordReusePrevention:r(e,"PasswordReusePrevention")?Number.parseInt(r(e,"PasswordReusePrevention"),10):void 0,HardExpiry:r(e,"HardExpiry")==="true"}}async updateAccountPasswordPolicy(e){await this.request("UpdateAccountPasswordPolicy",e)}async deleteAccountPasswordPolicy(){await this.request("DeleteAccountPasswordPolicy")}async getAccountSummary(){let e=await this.request("GetAccountSummary"),t={},s=l(e,"SummaryMap","entry");for(let a of s){let i=r(a,"key"),c=r(a,"value");if(i&&c)t[i]=Number.parseInt(c,10)}return t}async listAccountAliases(){let e=await this.request("ListAccountAliases"),t=l(e,"AccountAliases","member"),s=r(e,"IsTruncated")==="true",a=r(e,"Marker");return{AccountAliases:t,IsTruncated:s,Marker:a}}async createAccountAlias(e){await this.request("CreateAccountAlias",e)}async deleteAccountAlias(e){await this.request("DeleteAccountAlias",e)}async simulatePrincipalPolicy(e){let t=await this.request("SimulatePrincipalPolicy",e);return this.parseSimulationResults(t)}parseSimulationResults(e){let s=l(e,"EvaluationResults","member").map((c)=>{let d=l(c,"MatchedStatements","member").map((m)=>({SourcePolicyId:r(m,"SourcePolicyId"),SourcePolicyType:r(m,"SourcePolicyType")}));return{EvalActionName:r(c,"EvalActionName")||"",EvalResourceName:r(c,"EvalResourceName"),EvalDecision:r(c,"EvalDecision")||"",MatchedStatements:d.length>0?d:void 0}}),a=r(e,"IsTruncated")==="true",i=r(e,"Marker");return{EvaluationResults:s,IsTruncated:a,Marker:i}}}function p(e,t){return(e?.[`${t}Response`]??e)?.[`${t}Result`]}class tt{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new n(t)}async createEmailIdentity(e){return await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/identities",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async getEmailIdentity(e){let t=await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/identities/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}});return{IdentityType:t.IdentityType,IdentityName:e,SendingEnabled:t.VerifiedForSendingStatus,VerificationStatus:t.VerificationStatus,DkimAttributes:t.DkimAttributes,MailFromAttributes:t.MailFromAttributes}}async putEmailIdentityMailFromAttributes(e,t){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(e)}/mail-from`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async listEmailIdentities(e){let t="/v2/email/identities",s=[];if(e?.PageSize)s.push(`PageSize=${e.PageSize}`);if(e?.NextToken)s.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(s.length>0)t+=`?${s.join("&")}`;let a=await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}});return{EmailIdentities:a.EmailIdentities,NextToken:a.NextToken}}async deleteEmailIdentity(e){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/identities/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async putEmailIdentityDkimAttributes(e){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(e.EmailIdentity)}/dkim`,headers:{"Content-Type":"application/json"},body:JSON.stringify({SigningEnabled:e.SigningEnabled})})}async sendEmail(e){return{MessageId:(await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/outbound-emails",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).MessageId}}async sendBulkEmail(e){return{BulkEmailEntryResults:(await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/outbound-bulk-emails",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).BulkEmailEntryResults}}async createEmailTemplate(e){await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/templates",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async getEmailTemplate(e){return await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/templates/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async deleteEmailTemplate(e){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/templates/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async listEmailTemplates(e){let t="/v2/email/templates",s=[];if(e?.PageSize)s.push(`PageSize=${e.PageSize}`);if(e?.NextToken)s.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(s.length>0)t+=`?${s.join("&")}`;return await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}})}async getSendStatistics(){let e=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendStatistics&Version=2010-12-01"}),t=p(e,"GetSendStatistics")?.SendDataPoints?.member;return{SendDataPoints:t==null?[]:Array.isArray(t)?t:[t]}}async getSendQuota(){let e=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendQuota&Version=2010-12-01"}),t=p(e,"GetSendQuota"),s=(a)=>a==null||a===""?void 0:Number(a);return{Max24HourSend:s(t?.Max24HourSend),MaxSendRate:s(t?.MaxSendRate),SentLast24Hours:s(t?.SentLast24Hours)}}async verifyDomain(e){let t=await this.createEmailIdentity({EmailIdentity:e});return{dkimTokens:t.DkimAttributes?.Tokens,verificationStatus:t.DkimAttributes?.Status}}async sendSimpleEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],s=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0,a={};if(e.text)a.Text={Data:e.text};if(e.html)a.Html={Data:e.html};return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Simple:{Subject:{Data:e.subject},Body:a}},ReplyToAddresses:s})}async sendTemplatedEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],s=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0;return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Template:{TemplateName:e.templateName,TemplateData:JSON.stringify(e.templateData)}},ReplyToAddresses:s})}async getDkimRecords(e){let t=await this.getEmailIdentity(e);if(!t.DkimAttributes?.Tokens)return[];return t.DkimAttributes.Tokens.map((s)=>({name:`${s}._domainkey.${e}`,type:"CNAME",value:`${s}.dkim.amazonses.com`}))}async isDomainVerified(e){try{let t=await this.getEmailIdentity(e);return t.VerificationStatus==="SUCCESS"&&t.SendingEnabled===!0}catch{return!1}}async waitForDomainVerification(e,t=60,s=30000){for(let a=0;a<t;a++){if(await this.isDomainVerified(e))return!0;await new Promise((c)=>setTimeout(c,s))}return!1}buildFormBody(e){return Object.entries(e).filter(([,s])=>s!==void 0).map(([s,a])=>`${encodeURIComponent(s)}=${encodeURIComponent(a)}`).join("&")}async createReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"CreateReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async deleteReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async setActiveReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"SetActiveReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async listReceiptRuleSets(e){let t={Action:"ListReceiptRuleSets",Version:"2010-12-01"};if(e)t.NextToken=e;let s=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)}),a=s?.ListReceiptRuleSetsResponse?.ListReceiptRuleSetsResult||s?.ListReceiptRuleSetsResult,i=a?.RuleSets?.member;return{RuleSets:Array.isArray(i)?i:i?[i]:[],NextToken:a?.NextToken}}async describeReceiptRuleSet(e){let t=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DescribeReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})}),s=t?.DescribeReceiptRuleSetResponse?.DescribeReceiptRuleSetResult||t?.DescribeReceiptRuleSetResult,a=s?.Rules?.member;return{Metadata:s?.Metadata,Rules:Array.isArray(a)?a:a?[a]:[]}}async createReceiptRule(e){let t={Action:"CreateReceiptRule",Version:"2010-12-01",RuleSetName:e.RuleSetName,"Rule.Name":e.Rule.Name,"Rule.Enabled":e.Rule.Enabled!==!1?"true":"false"};if(e.Rule.TlsPolicy)t["Rule.TlsPolicy"]=e.Rule.TlsPolicy;if(e.Rule.ScanEnabled!==void 0)t["Rule.ScanEnabled"]=e.Rule.ScanEnabled?"true":"false";if(e.After)t.After=e.After;if(e.Rule.Recipients)e.Rule.Recipients.forEach((s,a)=>{t[`Rule.Recipients.member.${a+1}`]=s});e.Rule.Actions.forEach((s,a)=>{let i=a+1;if(s.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=s.S3Action.BucketName,s.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=s.S3Action.ObjectKeyPrefix;if(s.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=s.S3Action.KmsKeyArn}if(s.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=s.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=s.LambdaAction.InvocationType||"Event";if(s.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=s.SNSAction.TopicArn,s.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=s.SNSAction.Encoding}if(s.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=s.StopAction.Scope,s.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=s.StopAction.TopicArn}}),await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)})}async deleteReceiptRule(e,t){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteReceiptRule",Version:"2010-12-01",RuleSetName:e,RuleName:t})})}async receiptRuleSetExists(e){try{return await this.describeReceiptRuleSet(e),!0}catch(t){if(t.code==="RuleSetDoesNotExist"||t.statusCode===400)return!1;throw t}}async getActiveReceiptRuleSet(){let e=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DescribeActiveReceiptRuleSet",Version:"2010-12-01"})}),t=e?.DescribeActiveReceiptRuleSetResponse?.DescribeActiveReceiptRuleSetResult||e?.DescribeActiveReceiptRuleSetResult;if(!t?.Metadata)return null;let s=t?.Rules?.member;return{Metadata:t?.Metadata,Rules:Array.isArray(s)?s:s?[s]:[]}}async updateReceiptRule(e){let t={Action:"UpdateReceiptRule",Version:"2010-12-01",RuleSetName:e.RuleSetName,"Rule.Name":e.Rule.Name};if(e.Rule.Enabled!==void 0)t["Rule.Enabled"]=e.Rule.Enabled?"true":"false";if(e.Rule.TlsPolicy)t["Rule.TlsPolicy"]=e.Rule.TlsPolicy;if(e.Rule.ScanEnabled!==void 0)t["Rule.ScanEnabled"]=e.Rule.ScanEnabled?"true":"false";if(e.Rule.Recipients)e.Rule.Recipients.forEach((s,a)=>{t[`Rule.Recipients.member.${a+1}`]=s});e.Rule.Actions.forEach((s,a)=>{let i=a+1;if(s.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=s.S3Action.BucketName,s.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=s.S3Action.ObjectKeyPrefix;if(s.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=s.S3Action.KmsKeyArn}if(s.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=s.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=s.LambdaAction.InvocationType||"Event";if(s.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=s.SNSAction.TopicArn,s.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=s.SNSAction.Encoding}if(s.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=s.StopAction.Scope,s.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=s.StopAction.TopicArn}}),await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)})}async sendRawEmail(e){let t=Buffer.from(e.rawMessage).toString("base64"),s={Action:"SendRawEmail",Version:"2010-12-01",Source:e.source,"RawMessage.Data":t};e.destinations.forEach((c,u)=>{s[`Destinations.member.${u+1}`]=c});let a=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(s)});return{MessageId:(a?.SendRawEmailResponse?.SendRawEmailResult||a?.SendRawEmailResult)?.MessageId}}async getSuppressedDestination(e){try{return(await this.client.request({service:"ses",region:this.region,method:"GET",path:`/v2/email/suppression/addresses/${encodeURIComponent(e)}`}))?.SuppressedDestination||null}catch(t){if(t.message?.includes("404")||t.message?.includes("NotFoundException"))return null;throw t}}async deleteSuppressedDestination(e){await this.client.request({service:"ses",region:this.region,method:"DELETE",path:`/v2/email/suppression/addresses/${encodeURIComponent(e)}`})}}class Sn{ses;s3;iam;route53;region;domain;defaultFrom;constructor(e={}){this.region=e.region||"us-east-1",this.domain=e.domain,this.defaultFrom=e.defaultFrom,this.ses=new tt(this.region),this.s3=new o(this.region),this.iam=new fe(this.region),this.route53=new y(this.region)}async send(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required. Set defaultFrom in constructor or provide from in options.");let s=e.fromName?`${e.fromName} <${t}>`:t,a=Array.isArray(e.to)?e.to:[e.to];if(!e.attachments||e.attachments.length===0)return{messageId:(await this.ses.sendSimpleEmail({from:s,to:a,subject:e.subject,text:e.text,html:e.html,replyTo:e.replyTo})).MessageId||""};let i=this.buildRawEmail(e,s,a);return{messageId:(await this.ses.sendEmail({FromEmailAddress:s,Destination:{ToAddresses:a,CcAddresses:e.cc?Array.isArray(e.cc)?e.cc:[e.cc]:void 0,BccAddresses:e.bcc?Array.isArray(e.bcc)?e.bcc:[e.bcc]:void 0},Content:{Raw:{Data:Buffer.from(i).toString("base64")}}})).MessageId||""}}async sendTemplate(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required");let s=e.fromName?`${e.fromName} <${t}>`:t;return{messageId:(await this.ses.sendTemplatedEmail({from:s,to:e.to,templateName:e.templateName,templateData:e.templateData,replyTo:e.replyTo})).MessageId||""}}async sendBulk(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required");let s=e.recipients.map((i)=>({Destination:{ToAddresses:Array.isArray(i.to)?i.to:[i.to]},ReplacementEmailContent:i.templateData?{ReplacementTemplate:{ReplacementTemplateData:JSON.stringify(i.templateData)}}:void 0}));return{results:(await this.ses.sendBulkEmail({FromEmailAddress:t,BulkEmailEntries:s,DefaultContent:{Template:{TemplateName:e.templateName,TemplateData:JSON.stringify(e.defaultTemplateData)}}})).BulkEmailEntryResults?.map((i)=>({status:i.Status||"UNKNOWN",messageId:i.MessageId,error:i.Error}))||[]}}async setupDomain(e){let t;try{t=await this.ses.getEmailIdentity(e)}catch{let a=await this.ses.createEmailIdentity({EmailIdentity:e});t={VerificationStatus:a.DkimAttributes?.Status,DkimAttributes:a.DkimAttributes,SendingEnabled:a.VerifiedForSendingStatus}}try{await this.ses.putEmailIdentityDkimAttributes({EmailIdentity:e,SigningEnabled:!0})}catch{}try{await this.ses.putEmailIdentityMailFromAttributes(e,{MailFromDomain:`mail.${e}`,BehaviorOnMxFailure:"USE_DEFAULT_VALUE"})}catch{}let s=await this.ses.getDkimRecords(e);return{domainVerified:t.SendingEnabled===!0,dkimStatus:t.DkimAttributes?.Status||"UNKNOWN",dkimTokens:t.DkimAttributes?.Tokens,mailFromStatus:t.MailFromAttributes?.MailFromDomainStatus}}async getDnsRecords(e){let t=[],s=await this.ses.getDkimRecords(e);for(let a of s)t.push({type:a.type,name:a.name,value:a.value,ttl:1800});return t.push({type:"MX",name:e,value:`inbound-smtp.${this.region}.amazonaws.com`,priority:10,ttl:3600}),t.push({type:"MX",name:`mail.${e}`,value:`feedback-smtp.${this.region}.amazonses.com`,priority:10,ttl:3600}),t.push({type:"TXT",name:`mail.${e}`,value:"v=spf1 include:amazonses.com ~all",ttl:3600}),t.push({type:"TXT",name:`_dmarc.${e}`,value:`v=DMARC1;p=quarantine;pct=25;rua=mailto:dmarcreports@${e}`,ttl:3600}),t}async isDomainReady(e){try{let t=await this.ses.getEmailIdentity(e);return t.SendingEnabled===!0&&t.DkimAttributes?.Status==="SUCCESS"}catch{return!1}}async setupReceiving(e){let t={Version:"2012-10-17",Statement:[{Sid:"AllowSESPuts",Effect:"Allow",Principal:{Service:"ses.amazonaws.com"},Action:"s3:PutObject",Resource:`arn:aws:s3:::${e.bucketName}/*`,Condition:{StringEquals:{"AWS:SourceAccount":e.accountId}}}]};await this.s3.putBucketPolicy(e.bucketName,t);try{await this.ses.createReceiptRuleSet(e.ruleSetName)}catch(a){if(!a.message?.includes("already exists")&&a.code!=="AlreadyExists")throw a}let s=[{S3Action:{BucketName:e.bucketName,ObjectKeyPrefix:e.prefix||"inbox/"}}];if(e.lambdaArn)s.push({LambdaAction:{FunctionArn:e.lambdaArn,InvocationType:"Event"}});try{await this.ses.createReceiptRule({RuleSetName:e.ruleSetName,Rule:{Name:e.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:e.recipients||[e.domain],ScanEnabled:e.scanEnabled!==!1,Actions:s}})}catch(a){if(a.message?.includes("already exists"))await this.ses.deleteReceiptRule(e.ruleSetName,e.ruleName),await this.ses.createReceiptRule({RuleSetName:e.ruleSetName,Rule:{Name:e.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:e.recipients||[e.domain],ScanEnabled:e.scanEnabled!==!1,Actions:s}});else throw a}await this.ses.setActiveReceiptRuleSet(e.ruleSetName)}async getIncomingEmails(e){return(await this.s3.list({bucket:e.bucket,prefix:e.prefix||"incoming/",maxKeys:e.maxResults||100})).map((s)=>({key:s.Key||"",lastModified:s.LastModified||"",size:s.Size||0}))}async readEmail(e){return await this.s3.getObject(e.bucket,e.key)}async createSmtpCredentials(e){let t=`ses-smtp-${e.username.replace(/[^a-zA-Z0-9]/g,"-")}`,{AWSClient:s}=await import("./chunk-6kcmbymp.js"),a=new s,i=(g,A)=>{let h={Action:g,Version:"2010-05-08",...A};return Object.entries(h).map(([R,S])=>`${encodeURIComponent(R)}=${encodeURIComponent(S)}`).join("&")};try{await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateUser",{UserName:t})})}catch(g){if(!g.message?.includes("EntityAlreadyExists"))throw g}let c={Version:"2012-10-17",Statement:[{Effect:"Allow",Action:"ses:SendRawEmail",Resource:"*",Condition:{StringLike:{"ses:FromAddress":`*@${e.domain}`}}}]},u=`ses-smtp-policy-${e.domain.replace(/\./g,"-")}`;try{await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("PutUserPolicy",{UserName:t,PolicyName:u,PolicyDocument:JSON.stringify(c)})})}catch{}let m=(await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateAccessKey",{UserName:t})}))?.CreateAccessKeyResult?.AccessKey;if(!m?.AccessKeyId||!m?.SecretAccessKey)throw Error("Failed to create access key");let P=this.deriveSmtpPassword(m.SecretAccessKey);return{username:m.AccessKeyId,password:P,server:`email-smtp.${this.region}.amazonaws.com`,port:587}}deriveSmtpPassword(e){let t=Fe("node:crypto"),s="SendRawEmail",a=Buffer.from([4]),i=t.createHmac("sha256",`AWS4${e}`).update("11111111").digest();return i=t.createHmac("sha256",i).update(this.region).digest(),i=t.createHmac("sha256",i).update("ses").digest(),i=t.createHmac("sha256",i).update("aws4_request").digest(),i=t.createHmac("sha256",i).update("SendRawEmail").digest(),Buffer.concat([a,i]).toString("base64")}async createTemplate(e){await this.ses.createEmailTemplate({TemplateName:e.name,TemplateContent:{Subject:e.subject,Text:e.text,Html:e.html}})}async getTemplate(e){try{let t=await this.ses.getEmailTemplate(e);return{name:t.TemplateName||e,subject:t.TemplateContent?.Subject,text:t.TemplateContent?.Text,html:t.TemplateContent?.Html}}catch{return null}}async deleteTemplate(e){await this.ses.deleteEmailTemplate(e)}async listTemplates(){return(await this.ses.listEmailTemplates()).TemplatesMetadata?.map((t)=>({name:t.TemplateName||"",createdAt:t.CreatedTimestamp}))||[]}async deploy(e){let t=`${e.appName}-${e.environment}-email-rules`,s=`${e.appName}-inbound-email`,a=e.storage?.bucketName||`${e.appName}-${e.environment}-email`,i=await this.setupDomain(e.domain);if(!(await this.s3.listBuckets()).Buckets?.some((m)=>m.Name===a))await this.s3.createBucket(a);await this.setupReceiving({domain:e.domain,ruleSetName:t,ruleName:s,bucketName:a,prefix:e.storage?.prefix||"inbox/",accountId:e.accountId,recipients:e.catchAll?[e.domain]:e.mailboxes,scanEnabled:!0});let d=await this.getDnsRecords(e.domain);return{success:!0,domainVerified:i.domainVerified,dkimStatus:i.dkimStatus,receiptRuleSet:t,storageBucket:a,dnsRecords:d}}async undeploy(e){let t=`${e.appName}-${e.environment}-email-rules`,s=`${e.appName}-inbound-email`,a=`${e.appName}-${e.environment}-email`;try{await this.ses.deleteReceiptRule(t,s)}catch{}try{await this.ses.deleteReceiptRuleSet(t)}catch{}if(e.deleteBucket)try{await this.s3.emptyAndDeleteBucket(a)}catch{}}async getSendingStats(){let e=await this.ses.getSendQuota();return{sentLast24Hours:e.SentLast24Hours||0,maxSendRate:e.MaxSendRate||0,max24HourSend:e.Max24HourSend||0}}buildRawEmail(e,t,s){let a=`----=_Part_${Date.now()}_${Math.random().toString(36).substring(2)}`,i="";if(i+=`From: ${t}\r
2
+ `,i+=`To: ${s.join(", ")}\r
3
+ `,e.cc){let c=Array.isArray(e.cc)?e.cc:[e.cc];i+=`Cc: ${c.join(", ")}\r
4
+ `}if(i+=`Subject: ${e.subject}\r
5
+ `,i+=`MIME-Version: 1.0\r
6
+ `,i+=`Content-Type: multipart/mixed; boundary="${a}"\r
7
+ `,i+=`\r
8
+ `,e.text||e.html)if(i+=`--${a}\r
9
+ `,e.html&&e.text){let c=`----=_Alt_${Date.now()}`;i+=`Content-Type: multipart/alternative; boundary="${c}"\r
10
+ `,i+=`\r
11
+ `,i+=`--${c}\r
12
+ `,i+=`Content-Type: text/plain; charset="UTF-8"\r
13
+ `,i+=`\r
14
+ `,i+=`${e.text}\r
15
+ `,i+=`--${c}\r
16
+ `,i+=`Content-Type: text/html; charset="UTF-8"\r
17
+ `,i+=`\r
18
+ `,i+=`${e.html}\r
19
+ `,i+=`--${c}--\r
20
+ `}else if(e.html)i+=`Content-Type: text/html; charset="UTF-8"\r
21
+ `,i+=`\r
22
+ `,i+=`${e.html}\r
23
+ `;else i+=`Content-Type: text/plain; charset="UTF-8"\r
24
+ `,i+=`\r
25
+ `,i+=`${e.text}\r
26
+ `;if(e.attachments)for(let c of e.attachments)i+=`--${a}\r
27
+ `,i+=`Content-Type: ${c.contentType||"application/octet-stream"}; name="${c.filename}"\r
28
+ `,i+=`Content-Transfer-Encoding: base64\r
29
+ `,i+=`Content-Disposition: attachment; filename="${c.filename}"\r
30
+ `,i+=`\r
31
+ `,i+=`${c.content}\r
32
+ `;return i+=`--${a}--\r
33
+ `,i}}var Dh=new Sn;
34
+ export{fe,tt,Sn,Dh};
@@ -1,4 +1,4 @@
1
- import{z,oe,T,ae,dr}from"./chunk-e8e1h2h9.js";import{o}from"./chunk-yd40pg8g.js";import{A}from"./chunk-31tvc877.js";import{y}from"./chunk-9wmer0zx.js";import{h}from"./chunk-ptq9v346.js";function Ba(t){let{bucketName:s,domain:u,aliases:e,certificateArn:p,defaultRootObject:i="index.html",errorDocument:a="404.html",passthroughUrls:c=!1,singlePageApp:g=!1,dynamicApp:C=!1,computeOriginDomain:w,computeOriginPort:x=3008,computeOriginId:E="app-compute",retainOnStackDelete:M=!1}=t,S=M?{DeletionPolicy:"Retain",UpdateReplacePolicy:"Retain"}:{},N=C&&!!w,j=N?["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"]:["GET","HEAD"],v=N?["GET","HEAD"]:["GET","HEAD"],O={},B={};O.S3Bucket={Type:"AWS::S3::Bucket",...S,Properties:{BucketName:s,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:i,ErrorDocument:a}}},B.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},B.BucketArn={Description:"S3 Bucket ARN",Value:{"Fn::GetAtt":["S3Bucket","Arn"]}},O.CloudFrontOAC={Type:"AWS::CloudFront::OriginAccessControl",...S,Properties:{OriginAccessControlConfig:{Name:`OAC-${s}`,Description:`OAC for ${s}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}};let I;if(c&&N)I="InstallRootRedirectFunction",O[I]={Type:"AWS::CloudFront::Function",Properties:{Name:{"Fn::Sub":"${AWS::StackName}-install-root-redirect"},AutoPublish:!0,FunctionConfig:{Comment:"Redirect curl pantry.dev | bash (GET /) to /install.sh on S3",Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) {
1
+ import{z,oe,T,ae,dr}from"./chunk-e8e1h2h9.js";import{o}from"./chunk-9asn5fpt.js";import{A}from"./chunk-31tvc877.js";import{y}from"./chunk-9wmer0zx.js";import{h}from"./chunk-ptq9v346.js";function Ba(t){let{bucketName:s,domain:u,aliases:e,certificateArn:p,defaultRootObject:i="index.html",errorDocument:a="404.html",passthroughUrls:c=!1,singlePageApp:g=!1,dynamicApp:C=!1,computeOriginDomain:w,computeOriginPort:x=3008,computeOriginId:E="app-compute",retainOnStackDelete:M=!1}=t,S=M?{DeletionPolicy:"Retain",UpdateReplacePolicy:"Retain"}:{},N=C&&!!w,j=N?["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"]:["GET","HEAD"],v=N?["GET","HEAD"]:["GET","HEAD"],O={},B={};O.S3Bucket={Type:"AWS::S3::Bucket",...S,Properties:{BucketName:s,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:i,ErrorDocument:a}}},B.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},B.BucketArn={Description:"S3 Bucket ARN",Value:{"Fn::GetAtt":["S3Bucket","Arn"]}},O.CloudFrontOAC={Type:"AWS::CloudFront::OriginAccessControl",...S,Properties:{OriginAccessControlConfig:{Name:`OAC-${s}`,Description:`OAC for ${s}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}};let I;if(c&&N)I="InstallRootRedirectFunction",O[I]={Type:"AWS::CloudFront::Function",Properties:{Name:{"Fn::Sub":"${AWS::StackName}-install-root-redirect"},AutoPublish:!0,FunctionConfig:{Comment:"Redirect curl pantry.dev | bash (GET /) to /install.sh on S3",Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) {
2
2
  var request = event.request;
3
3
  if (request.uri === '/' || request.uri === '') {
4
4
  return {
@@ -42,7 +42,7 @@ import{z,oe,T,ae,dr}from"./chunk-e8e1h2h9.js";import{o}from"./chunk-yd40pg8g.js"
42
42
  │ │
43
43
  │ Verification typically takes 1-2 business days. │
44
44
  │ After verification, re-run: bunx bunpress deploy │
45
- └─────────────────────────────────────────────────────────────────────────────┘`),{success:!1,stackId:B,stackName:i,bucket:N,message:"CloudFront account verification required. Please contact AWS Support."}}return{success:!1,stackId:B,stackName:i,bucket:N,message:`Stack deployment failed: ${n.message}`}}let d=(await a.describeStacks({stackName:i})).Stacks[0]?.Outputs||[],k=(n)=>d.find((r)=>r.OutputKey===n)?.OutputValue,b=k("DistributionDomain");if(b&&g)console.log(`Creating DNS records via ${g.name}...`),await H(g,e,b);else if(b&&!g)console.log("Skipping DNS record creation (DNS verification was skipped)");return{success:!0,stackId:B,stackName:i,bucket:k("BucketName")||N,distributionId:k("DistributionId"),distributionDomain:b,domain:e,certificateArn:C,message:"Static site infrastructure deployed successfully with external DNS"}}async function H(t,s,u){if(!t){console.log("Skipping DNS record creation (DNS verification was skipped)");return}if(s.split(".").length===2)if(t instanceof z){console.log(`Creating Route53 alias record for apex domain ${s} -> ${u}`);let i=await t.createCloudFrontAlias({domain:s,name:s,cloudFrontDomainName:u});if(!i.success)console.warn(`Warning: Could not create Route53 alias record: ${i.message}`),console.warn("Please manually create an A-record alias in Route53:"),console.warn(` ${s} -> ${u}`);else console.log(`Created Route53 alias record: ${s} -> ${u}`);let a=`www.${s}`;console.log(`Creating Route53 alias record for ${a} -> ${u}`);let c=await t.createCloudFrontAlias({domain:s,name:a,cloudFrontDomainName:u});if(!c.success)console.warn(`Warning: Could not create www Route53 alias: ${c.message}`),console.warn("Please manually create an A-record alias in Route53:"),console.warn(` ${a} -> ${u}`);else console.log(`Created Route53 alias record: ${a} -> ${u}`)}else{try{let g=await t.listRecords(s,"A");if(g.success)for(let C of g.records){let w=C.name.replace(/\.$/,"");if(w===s||w==="")console.log(`Removing existing root A record (${C.content}) to make room for ALIAS...`),await t.deleteRecord(s,{name:s,type:"A",content:C.content})}}catch(g){console.log(`Note: Could not check for conflicting A records: ${g instanceof Error?g.message:g}`)}console.log(`Creating ALIAS record for apex domain ${s} -> ${u}`);let i=await t.upsertRecord(s,{name:s,type:"ALIAS",content:u,ttl:600});if(!i.success)console.warn(`Warning: Could not create ALIAS record: ${i.message}`),console.warn("Please manually create an ALIAS record in your DNS provider:"),console.warn(` ${s} -> ${u}`);else console.log(`Created ALIAS record: ${s} -> ${u}`);let a=`www.${s}`;console.log(`Creating CNAME record for ${a} -> ${u}`);let c=await t.upsertRecord(s,{name:a,type:"CNAME",content:u,ttl:600});if(!c.success)console.warn(`Warning: Could not create www DNS record: ${c.message}`),console.warn("Please manually create a CNAME record:"),console.warn(` ${a} -> ${u}`);else console.log(`Created CNAME record: ${a} -> ${u}`)}else{console.log(`Creating CNAME record for ${s} -> ${u}`);let i=await t.upsertRecord(s,{name:s,type:"CNAME",content:u,ttl:600});if(!i.success)console.warn(`Warning: Could not create DNS record: ${i.message}`),console.warn("Please manually create a CNAME record:"),console.warn(` ${s} -> ${u}`);else console.log(`Created CNAME record: ${s} -> ${u}`)}}async function un(t){let{sourceDir:s,cleanBucket:u=!1,onProgress:e,...p}=t;e?.("infrastructure","Deploying CloudFormation stack...");let i=await ln(p);if(!i.success)return i;if(u){e?.("clean","Cleaning old files from S3...");try{await new o(p.region||"us-east-1").emptyBucket(i.bucket)}catch(C){console.log(`Note: Could not clean bucket: ${C.message}`)}}e?.("upload","Uploading files to S3...");let{uploadStaticFiles:a}=await import("./chunk-rtn4gj6y.js"),c=await a({sourceDir:s,bucket:i.bucket,region:p.region||"us-east-1",cacheControl:p.cacheControl,onProgress:(C,w,x)=>{e?.("upload",`${C}/${w}: ${x}`)}});if(c.errors.length>0)return{...i,success:!1,message:`Upload errors: ${c.errors.join(", ")}`,filesUploaded:c.uploaded};if(i.distributionId&&c.uploaded>0){e?.("invalidate","Invalidating CloudFront cache...");let{invalidateCache:C}=await import("./chunk-rtn4gj6y.js");await C(i.distributionId)}e?.("complete","Deployment complete!");let g=c.skipped>0?`Deployed ${c.uploaded} files (${c.skipped} unchanged) with external DNS`:`Deployed ${c.uploaded} files successfully with external DNS`;return{...i,filesUploaded:c.uploaded,filesSkipped:c.skipped,message:g}}function Zi(t){let{bucketName:s,domain:u,certificateArn:e,hostedZoneId:p,defaultRootObject:i="index.html",errorDocument:a="404.html"}=t,c={},g={};c.S3Bucket={Type:"AWS::S3::Bucket",Properties:{BucketName:s,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:i,ErrorDocument:a}}},g.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},g.BucketArn={Description:"S3 Bucket ARN",Value:{"Fn::GetAtt":["S3Bucket","Arn"]}},c.CloudFrontOAC={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`OAC-${s}`,Description:`OAC for ${s}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},c.UrlRewriteFunction={Type:"AWS::CloudFront::Function",Properties:{Name:{"Fn::Sub":"${AWS::StackName}-url-rewrite"},AutoPublish:!0,FunctionConfig:{Comment:"Append .html extension to URLs without extensions",Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) {
45
+ └─────────────────────────────────────────────────────────────────────────────┘`),{success:!1,stackId:B,stackName:i,bucket:N,message:"CloudFront account verification required. Please contact AWS Support."}}return{success:!1,stackId:B,stackName:i,bucket:N,message:`Stack deployment failed: ${n.message}`}}let d=(await a.describeStacks({stackName:i})).Stacks[0]?.Outputs||[],k=(n)=>d.find((r)=>r.OutputKey===n)?.OutputValue,b=k("DistributionDomain");if(b&&g)console.log(`Creating DNS records via ${g.name}...`),await H(g,e,b);else if(b&&!g)console.log("Skipping DNS record creation (DNS verification was skipped)");return{success:!0,stackId:B,stackName:i,bucket:k("BucketName")||N,distributionId:k("DistributionId"),distributionDomain:b,domain:e,certificateArn:C,message:"Static site infrastructure deployed successfully with external DNS"}}async function H(t,s,u){if(!t){console.log("Skipping DNS record creation (DNS verification was skipped)");return}if(s.split(".").length===2)if(t instanceof z){console.log(`Creating Route53 alias record for apex domain ${s} -> ${u}`);let i=await t.createCloudFrontAlias({domain:s,name:s,cloudFrontDomainName:u});if(!i.success)console.warn(`Warning: Could not create Route53 alias record: ${i.message}`),console.warn("Please manually create an A-record alias in Route53:"),console.warn(` ${s} -> ${u}`);else console.log(`Created Route53 alias record: ${s} -> ${u}`);let a=`www.${s}`;console.log(`Creating Route53 alias record for ${a} -> ${u}`);let c=await t.createCloudFrontAlias({domain:s,name:a,cloudFrontDomainName:u});if(!c.success)console.warn(`Warning: Could not create www Route53 alias: ${c.message}`),console.warn("Please manually create an A-record alias in Route53:"),console.warn(` ${a} -> ${u}`);else console.log(`Created Route53 alias record: ${a} -> ${u}`)}else{try{let g=await t.listRecords(s,"A");if(g.success)for(let C of g.records){let w=C.name.replace(/\.$/,"");if(w===s||w==="")console.log(`Removing existing root A record (${C.content}) to make room for ALIAS...`),await t.deleteRecord(s,{name:s,type:"A",content:C.content})}}catch(g){console.log(`Note: Could not check for conflicting A records: ${g instanceof Error?g.message:g}`)}console.log(`Creating ALIAS record for apex domain ${s} -> ${u}`);let i=await t.upsertRecord(s,{name:s,type:"ALIAS",content:u,ttl:600});if(!i.success)console.warn(`Warning: Could not create ALIAS record: ${i.message}`),console.warn("Please manually create an ALIAS record in your DNS provider:"),console.warn(` ${s} -> ${u}`);else console.log(`Created ALIAS record: ${s} -> ${u}`);let a=`www.${s}`;console.log(`Creating CNAME record for ${a} -> ${u}`);let c=await t.upsertRecord(s,{name:a,type:"CNAME",content:u,ttl:600});if(!c.success)console.warn(`Warning: Could not create www DNS record: ${c.message}`),console.warn("Please manually create a CNAME record:"),console.warn(` ${a} -> ${u}`);else console.log(`Created CNAME record: ${a} -> ${u}`)}else{console.log(`Creating CNAME record for ${s} -> ${u}`);let i=await t.upsertRecord(s,{name:s,type:"CNAME",content:u,ttl:600});if(!i.success)console.warn(`Warning: Could not create DNS record: ${i.message}`),console.warn("Please manually create a CNAME record:"),console.warn(` ${s} -> ${u}`);else console.log(`Created CNAME record: ${s} -> ${u}`)}}async function un(t){let{sourceDir:s,cleanBucket:u=!1,onProgress:e,...p}=t;e?.("infrastructure","Deploying CloudFormation stack...");let i=await ln(p);if(!i.success)return i;if(u){e?.("clean","Cleaning old files from S3...");try{await new o(p.region||"us-east-1").emptyBucket(i.bucket)}catch(C){console.log(`Note: Could not clean bucket: ${C.message}`)}}e?.("upload","Uploading files to S3...");let{uploadStaticFiles:a}=await import("./chunk-07rjctzz.js"),c=await a({sourceDir:s,bucket:i.bucket,region:p.region||"us-east-1",cacheControl:p.cacheControl,onProgress:(C,w,x)=>{e?.("upload",`${C}/${w}: ${x}`)}});if(c.errors.length>0)return{...i,success:!1,message:`Upload errors: ${c.errors.join(", ")}`,filesUploaded:c.uploaded};if(i.distributionId&&c.uploaded>0){e?.("invalidate","Invalidating CloudFront cache...");let{invalidateCache:C}=await import("./chunk-07rjctzz.js");await C(i.distributionId)}e?.("complete","Deployment complete!");let g=c.skipped>0?`Deployed ${c.uploaded} files (${c.skipped} unchanged) with external DNS`:`Deployed ${c.uploaded} files successfully with external DNS`;return{...i,filesUploaded:c.uploaded,filesSkipped:c.skipped,message:g}}function Zi(t){let{bucketName:s,domain:u,certificateArn:e,hostedZoneId:p,defaultRootObject:i="index.html",errorDocument:a="404.html"}=t,c={},g={};c.S3Bucket={Type:"AWS::S3::Bucket",Properties:{BucketName:s,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:i,ErrorDocument:a}}},g.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},g.BucketArn={Description:"S3 Bucket ARN",Value:{"Fn::GetAtt":["S3Bucket","Arn"]}},c.CloudFrontOAC={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`OAC-${s}`,Description:`OAC for ${s}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},c.UrlRewriteFunction={Type:"AWS::CloudFront::Function",Properties:{Name:{"Fn::Sub":"${AWS::StackName}-url-rewrite"},AutoPublish:!0,FunctionConfig:{Comment:"Append .html extension to URLs without extensions",Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) {
46
46
  const request = event.request;
47
47
  var uri = request.uri;
48
48