@stacksjs/ts-cloud 0.16.71 → 0.16.73

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 (67) hide show
  1. package/dist/bin/{chunk-p0hg1v92.js → chunk-02kcxvf3.js} +1 -1
  2. package/dist/bin/{chunk-q4xy79vr.js → chunk-0sa000g6.js} +47 -47
  3. package/dist/bin/{chunk-f0sqt3ez.js → chunk-maes42nn.js} +1 -1
  4. package/dist/bin/cli.js +4 -4
  5. package/dist/bin/dashboard-server.js +1 -1
  6. package/dist/{chunk-tneb9hcw.js → chunk-1np2k92z.js} +1 -1
  7. package/dist/{chunk-wnr96ssq.js → chunk-f4h7bn7y.js} +42 -42
  8. package/dist/deploy/index.js +1 -1
  9. package/dist/drivers/hetzner/client.d.ts +5 -0
  10. package/dist/drivers/index.js +1 -1
  11. package/dist/drivers/shared/runtime-isolation.d.ts +1 -1
  12. package/dist/index.js +1 -1
  13. package/dist/ui/404.html +1 -1
  14. package/dist/ui/accept-invitation.html +1 -1
  15. package/dist/ui/access-denied.html +1 -1
  16. package/dist/ui/account/automation.html +6 -6
  17. package/dist/ui/account/security.html +2 -2
  18. package/dist/ui/applications/compose.html +6 -6
  19. package/dist/ui/applications/new.html +2 -2
  20. package/dist/ui/data/backups.html +6 -6
  21. package/dist/ui/data/services.html +5 -5
  22. package/dist/ui/data/volumes.html +6 -6
  23. package/dist/ui/index.html +6 -6
  24. package/dist/ui/infrastructure/topology.html +5 -5
  25. package/dist/ui/integrations.html +2 -2
  26. package/dist/ui/operations/alerts.html +6 -6
  27. package/dist/ui/operations/configuration.html +6 -6
  28. package/dist/ui/operations/jobs.html +6 -6
  29. package/dist/ui/operations/maintenance.html +6 -6
  30. package/dist/ui/operations/observability.html +6 -6
  31. package/dist/ui/operations/previews.html +6 -6
  32. package/dist/ui/operations/queue.html +6 -6
  33. package/dist/ui/operations/regions.html +6 -6
  34. package/dist/ui/operations/releases.html +6 -6
  35. package/dist/ui/operations/spend.html +6 -6
  36. package/dist/ui/operations/workloads.html +6 -6
  37. package/dist/ui/security.html +2 -2
  38. package/dist/ui/server/actions.html +6 -6
  39. package/dist/ui/server/activity.html +2 -2
  40. package/dist/ui/server/capacity.html +5 -5
  41. package/dist/ui/server/database.html +6 -6
  42. package/dist/ui/server/deployments.html +5 -5
  43. package/dist/ui/server/diagnostics.html +1 -1
  44. package/dist/ui/server/firewall.html +6 -6
  45. package/dist/ui/server/fleet.html +5 -5
  46. package/dist/ui/server/logs.html +6 -6
  47. package/dist/ui/server/metrics.html +5 -5
  48. package/dist/ui/server/security.html +2 -2
  49. package/dist/ui/server/services.html +2 -2
  50. package/dist/ui/server/sites.html +6 -6
  51. package/dist/ui/server/ssh-keys.html +6 -6
  52. package/dist/ui/server/team.html +6 -6
  53. package/dist/ui/server/terminal.html +2 -2
  54. package/dist/ui/serverless/alarms.html +6 -6
  55. package/dist/ui/serverless/assets.html +2 -2
  56. package/dist/ui/serverless/cost.html +2 -2
  57. package/dist/ui/serverless/data.html +6 -6
  58. package/dist/ui/serverless/deployments.html +2 -2
  59. package/dist/ui/serverless/firewall.html +2 -2
  60. package/dist/ui/serverless/functions.html +6 -6
  61. package/dist/ui/serverless/logs.html +6 -6
  62. package/dist/ui/serverless/metrics.html +2 -2
  63. package/dist/ui/serverless/queues.html +6 -6
  64. package/dist/ui/serverless/secrets.html +6 -6
  65. package/dist/ui/serverless/traces.html +6 -6
  66. package/dist/ui/serverless.html +5 -5
  67. package/package.json +3 -3
@@ -9,14 +9,14 @@ ${Yi(c)}`:u}),s=r.length-n.length,i=s>0?[`(+${s} more instance${s===1?"":"s"} fa
9
9
  `)}function Xi(e){let t=2166136261,r=16777619;for(let n=0;n<e.length;n++){let s=e.charCodeAt(n);t=Math.imul(t^s,16777619)>>>0,r=Math.imul(r+s,2246822507)>>>0}return`${t.toString(36)}${r.toString(36)}`.padEnd(12,"0").slice(0,12)}function Og(e,t,r={}){let n=r.mode??"testing",s=r.maxAge??604800,i=r.mx?.length?r.mx:[e.hostname],a=`${["version: STSv1",`mode: ${n}`,...i.map((u)=>`mx: ${u}`),`max_age: ${s}`].join(`\r
10
10
  `)}\r
11
11
  `,c=Xi(a);return{host:`mta-sts.${t}`,body:a,id:c,txt:`v=STSv1; id=${c}`}}var _g=8461;function Fh(e,t=_g){return[`const policy = ${JSON.stringify(e.body)}`,"Bun.serve({",` port: ${t},`," hostname: '127.0.0.1',"," fetch(req) {"," const { pathname } = new URL(req.url)"," if (pathname !== '/.well-known/mta-sts.txt') return new Response('Not Found', { status: 404 })"," return new Response(policy, { headers: { 'content-type': 'text/plain; charset=utf-8' } })"," },","})"].join(`
12
- `)}var Ot={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 p="/opt/pantry";function Qt(e){return`'${e.split("'").join("'\\''")}'`}function ft(e={}){let t=e.installDir??"/usr/local/bin",r=e.version?`export PANTRY_VERSION=${Qt(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 Oe(){return'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true'}function Ce(e){if(e.length===0)return[];return[`(cd /opt/pantry && pantry install ${[...new Set(e)].map(Qt).join(" ")})`]}function nr(e){return[...new Set(e)].flatMap((t)=>[`(cd /opt/pantry && pantry start ${Qt(t)})`,`(cd /opt/pantry && pantry enable ${Qt(t)})`])}var _e="/etc/mail",Ee="mail-server",Zr="mail",en=`${p}/pantry/.bin`;function Re(e){return`'${String(e).split("'").join("'\\''")}'`}function We(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function Qi(e){return[e.version?`${Ot.mail}@${e.version}`:Ot.mail]}function tn(e,t){return`${_e}/dkim/${t}.${e.dkim.selector}.pem`}function ns(e){return`${e.storagePath}/smtp.db`}function ea(e){let t=["# Generated by ts-cloud. Edits are overwritten on the next deploy —","# change `services.mail` in the cloud config instead.","","[server]",`host = ${We(e.bindAddress)}`,`port = ${e.ports.smtp}`,`hostname = ${We(e.hostname)}`];if(e.domains.length>0)t.push(`local_domains = ${We(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 = ${We(e.tls.certPath)}`);if(e.tls.keyPath)t.push(`key_path = ${We(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 = ${We(e.tls.acmeEmail)}`);if(t.push("","[webhook]",`enabled = ${!!e.webhookUrl}`),e.webhookUrl)t.push(`url = ${We(e.webhookUrl)}`);return t.push(""),t.join(`
12
+ `)}var Ot={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 p="/opt/pantry";function Qt(e){return`'${e.split("'").join("'\\''")}'`}function ft(e={}){let t=e.installDir??"/usr/local/bin",r=e.version?`export PANTRY_VERSION=${Qt(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 Oe(){return'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true'}function Ce(e){if(e.length===0)return[];return[`(cd /opt/pantry && pantry install ${[...new Set(e)].map(Qt).join(" ")})`]}function nr(e){return[...new Set(e)].flatMap((t)=>[`(cd /opt/pantry && pantry start ${Qt(t)})`,`(cd /opt/pantry && pantry enable ${Qt(t)})`])}var $e="/etc/mail",Ee="mail-server",Zr="mail",en=`${p}/pantry/.bin`;function Re(e){return`'${String(e).split("'").join("'\\''")}'`}function We(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function Qi(e){return[e.version?`${Ot.mail}@${e.version}`:Ot.mail]}function tn(e,t){return`${$e}/dkim/${t}.${e.dkim.selector}.pem`}function ns(e){return`${e.storagePath}/smtp.db`}function ea(e){let t=["# Generated by ts-cloud. Edits are overwritten on the next deploy —","# change `services.mail` in the cloud config instead.","","[server]",`host = ${We(e.bindAddress)}`,`port = ${e.ports.smtp}`,`hostname = ${We(e.hostname)}`];if(e.domains.length>0)t.push(`local_domains = ${We(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 = ${We(e.tls.certPath)}`);if(e.tls.keyPath)t.push(`key_path = ${We(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 = ${We(e.tls.acmeEmail)}`);if(t.push("","[webhook]",`enabled = ${!!e.webhookUrl}`),e.webhookUrl)t.push(`url = ${We(e.webhookUrl)}`);return t.push(""),t.join(`
13
13
  `)}function ta(e){let t=["# Generated by ts-cloud. See /etc/mail/config.toml for the rest.",`SMTP_DB_PATH=${ns(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=${tn(e,r)}`),n.length>0){let s=n.map((i)=>`${i}:${e.dkim.selector}:${tn(e,i)}`);t.push(`DKIM_EXTRA_KEYS=${s.join(",")}`)}}return t.push(""),t.join(`
14
- `)}function ra(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=${Ee}`,`Group=${Ee}`,`WorkingDirectory=${e.storagePath}`,`EnvironmentFile=${_e}/mail.env`,`Environment="PATH=${en}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"`,`ExecStart=${en}/mail serve --config ${_e}/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} ${_e}`,"","[Install]","WantedBy=multi-user.target",""].join(`
15
- `)}function na(e){if(!e.dkim.enabled||e.domains.length===0)return[];let t=[`mkdir -p ${_e}/dkim`];for(let r of e.domains){let n=tn(e,r);t.push(`if [ ! -f ${Re(n)} ]; then openssl genrsa -out ${Re(n)} 2048; fi`,`chmod 0600 ${Re(n)}`,`echo "DKIM ${e.dkim.selector}._domainkey.${r} IN TXT v=DKIM1; k=rsa; p=$(openssl rsa -in ${Re(n)} -pubout -outform PEM 2>/dev/null | grep -v '^-----' | tr -d '\\n')"`)}return t.push(`chown -R ${Ee}:${Ee} ${_e}/dkim`),t}function sa(e){if(e.accounts.length===0)return[];let t=(r)=>`runuser -u ${Ee} -- env SMTP_DB_PATH="$TS_CLOUD_MAIL_DB" ${en}/mail user:local ${r}`;return e.accounts.flatMap((r)=>[t(`create ${Re(r.address)} ${Re(r.password)} ${Re(r.address)}`),...r.passwordPolicy==="managed"?[t(`change-password ${Re(r.address)} ${Re(r.password)}`)]:[]])}function ss(e){if(!e.enabled)return[];return[...Ce(Qi(e)),`id -u ${Ee} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin ${Ee}`,`mkdir -p ${e.storagePath} ${_e}`,`chown -R ${Ee}:${Ee} ${e.storagePath}`,`TS_CLOUD_MAIL_DB="$(grep -sE '^SMTP_DB_PATH=' ${_e}/mail.env | head -1 | cut -d= -f2- || true)"`,`[ -n "$TS_CLOUD_MAIL_DB" ] || TS_CLOUD_MAIL_DB=${Re(ns(e))}`,`cat > ${_e}/config.toml <<'TS_CLOUD_MAIL_CONF_EOF'`,ea(e),"TS_CLOUD_MAIL_CONF_EOF",`cat > ${_e}/mail.env <<'TS_CLOUD_MAIL_ENV_EOF'`,ta(e),"TS_CLOUD_MAIL_ENV_EOF",`sed -i "s|^SMTP_DB_PATH=.*|SMTP_DB_PATH=$TS_CLOUD_MAIL_DB|" ${_e}/mail.env`,`chmod 0640 ${_e}/mail.env`,`chown root:${Ee} ${_e}/mail.env`,...na(e),`cat > /etc/systemd/system/${Zr}.service <<'TS_CLOUD_MAIL_UNIT_EOF'`,ra(e),"TS_CLOUD_MAIL_UNIT_EOF","systemctl daemon-reload",`systemctl enable ${Zr}`,`systemctl restart ${Zr}`,...sa(e)]}var be=`${p}/pantry/.bin`,sn=15306,rn=15991,sr=15999,os=16101,or=2379,xe="/var/lib/vitess",on=100;function xt(e){return e===!0||typeof e==="object"&&e!==null}function oa(e){return typeof e==="object"&&e!==null?e:{}}function ue(e){return`'${String(e).split("'").join("'\\''")}'`}function ia(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 ve="vitess",aa=`${be}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`,ls="/usr/local/lib/vitess",an=new Map;function nn(e){return`${ls}/${e}.sh`}function ot(e,t){return an.set(e,ca(t)),`/bin/sh ${nn(e)}`}function is(){let e=[`mkdir -p ${ls}`];for(let[t,r]of an)e.push(`cat > ${nn(t)} <<'TS_CLOUD_VITESS_LAUNCHER_EOF'`,r,"TS_CLOUD_VITESS_LAUNCHER_EOF",`chmod 0755 ${nn(t)}`);return e}function ca(e){return["#!/bin/sh","set -e",`cd ${p}`,`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 ${be}/mysqld 2>/dev/null)")")"`,`VTROOT="$(dirname "$(dirname "$(readlink -f ${be}/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(`
16
- `)}function it(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=${ve}`,`Group=${ve}`,`Environment="PATH=${aa}"`,`Environment="VTDATAROOT=${xe}"`,...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(`
17
- `)}function as(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_VITESS_UNIT_EOF'`,t,"TS_CLOUD_VITESS_UNIT_EOF"]}function la(e){let t=e.cell??"zone1",r=e.vtgatePort??sn,s=`${((e.keyspaces?.length)?e.keyspaces:[{name:"app"}]).map((i)=>{let a=(i.sharded?["-80","80-"]:["0"]).map((c)=>`shards:{name:"${c}"}`).join(" ");return`keyspaces:{name:"${i.name}" ${a}}`}).join(" ")} cells:"${t}"`;return it({description:"Vitess (vtcombo, single-process development stack)",execStart:ot("vtcombo",[`${be}/vtcombo`,`--cell ${t}`,`--proto-topo ${ue(s)}`,`--mysql-server-port ${r}`,"--mysql-server-bind-address 127.0.0.1","--mysql-auth-server-impl none","--start-mysql",`--port ${rn}`,`--grpc-port ${sr}`])})}function ua(){return it({description:"etcd (Vitess topology store)",execStart:ot("etcd",[`${be}/etcd`,`--data-dir ${xe}/etcd`,`--listen-client-urls http://127.0.0.1:${or}`,`--advertise-client-urls http://127.0.0.1:${or}`]),execStartPre:[`+/bin/mkdir -p ${xe}/etcd`,`+/bin/chown ${ve}:${ve} ${xe}/etcd`]})}function cn(e){return["--topo-implementation etcd2",`--topo-global-server-address ${e.etcdEndpoint??`http://127.0.0.1:${or}`}`,"--topo-global-root /vitess/global"]}function pa(e){let t=!e.etcdEndpoint;return it({description:"Vitess vtctld (control plane)",after:t?["vitess-etcd.service"]:[],requires:t?["vitess-etcd.service"]:[],execStart:ot("vtctld",[`${be}/vtctld`,...cn(e),`--cell ${e.cell??"zone1"}`,"--service-map grpc-vtctl,grpc-vtctld",`--grpc-port ${sr}`,`--port ${sr+1}`])})}function da(e,t,r){let n=e.cell??"zone1";return it({description:`Vitess vttablet (${t}/${r})`,after:["vitess-vtctld.service","vitess-mysqlctld.service"],requires:["vitess-mysqlctld.service"],execStart:ot("vttablet",[`${be}/vttablet`,...cn(e),`--tablet-path ${n}-${String(on).padStart(10,"0")}`,`--init-keyspace ${t}`,`--init-shard ${r}`,"--init-tablet-type replica",`--service-map ${ue("grpc-queryservice,grpc-tabletmanager,grpc-updatestream")}`,`--port ${os}`,`--grpc-port ${os+1}`,`--db-port ${e.mysqlPort??3306}`,`--mycnf-mysql-port ${e.mysqlPort??3306}`])})}function ma(e){return it({description:"Vitess mysqlctld (managed mysqld)",execStart:ot("mysqlctld",[`${be}/mysqlctld`,`--tablet-uid ${on}`,`--mysql-port ${e.mysqlPort??3306}`,'--init-db-sql-file "$VTROOT/config/init_db.sql"',"--wait-time 2m"]),execStartPre:[`+/bin/mkdir -p ${xe}`,`+/bin/chown ${ve}:${ve} ${xe}`]})}var us="/etc/vitess/auth.json",Dt="/var/lib/vitess/vtgate-auth.sha256";function fa(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 ${Dt} ] && [ "$(cat ${Dt})" = "$VTESS_VTGATE_AUTH_SHA" ]; then VTESS_VTGATE_AUTH_CHANGED=0; fi`,`install -o ${ve} -g ${ve} -m 0600 "$VTESS_AUTH_TMP" ${us}`,'rm -f "$VTESS_AUTH_TMP"']}function ga(e){let t=e.cell??"zone1";return it({description:"Vitess vtgate (query router)",after:["vitess-vtctld.service"],execStart:ot("vtgate",[`${be}/vtgate`,...cn(e),`--cell ${t}`,`--cells-to-watch ${t}`,"--tablet-types-to-wait PRIMARY,REPLICA",`--service-map ${ue("grpc-vtgateservice")}`,`--mysql-server-port ${e.vtgatePort??sn}`,`--mysql-server-bind-address ${e.bindAddress??"127.0.0.1"}`,"--mysql-auth-server-impl static",`--mysql-auth-server-static-file ${us}`,`--port ${rn}`,`--grpc-port ${rn+1}`])})}function ha(e){let t=e.cell??"zone1",r=e.etcdEndpoint??`http://127.0.0.1:${or}`,n=`${be}/vtctldclient --server 127.0.0.1:${sr}`,s=[`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 ${ue(t)}; then`,` ${n} AddCellInfo --root ${ue(`/vitess/${t}`)} --server-address ${ue(r)} ${ue(t)}`,"fi"];for(let i of e.keyspaces??[]){let a=i.sharded?" --sharded":"";s.push(`if ! ${n} GetKeyspace ${ue(i.name)} >/dev/null 2>&1; then`,` ${n} CreateKeyspace${a} ${ue(i.name)}`,"fi");let c=`${t}-${String(on).padStart(10,"0")}`;for(let u of i.sharded?["-80","80-"]:["0"]){let f=`${i.name}/${u}`;s.push("for i in $(seq 1 90); do",` if ${n} GetShard ${ue(f)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then break; fi`,` ${n} PlannedReparentShard ${ue(f)} --new-primary ${ue(c)} >/dev/null 2>&1 && break`,` ${n} InitShardPrimary --force ${ue(f)} ${ue(c)} >/dev/null 2>&1 && break`," sleep 2","done",`if ! ${n} GetShard ${ue(f)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then`,` echo "no primary could be elected for ${f}" >&2; exit 1`,"fi")}s.push(`${n} RebuildKeyspaceGraph ${ue(i.name)} >/dev/null`)}return s}function cs(e){let t=e.vtgatePort??sn;return["for i in $(seq 1 60); do",` if (cd ${p} && eval "$(pantry env 2>/dev/null)"; MYSQL_PWD=${ue(e.password??"")} ${be}/mysql -h 127.0.0.1 -P ${t} -u ${ue(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 Zs(e){if(!xt(e))return[];let t=oa(e),r=t.mode==="combo";an.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",...Ce(ia(t)),`VT_MYSQL_LIB="$(dirname "$(dirname "$(readlink -f ${be}/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 ${ve} >/dev/null 2>&1 || useradd --system --home-dir ${xe} --shell /usr/sbin/nologin ${ve}`,`mkdir -p ${xe}`,`chown -R ${ve}:${ve} ${xe}`];if(r)return n.push(...as("vitess-vtcombo",la(t)),...is(),"systemctl daemon-reload","systemctl enable --now vitess-vtcombo.service",...cs(t)),n;n.push(...fa(t));let s=[];if(!t.etcdEndpoint)s.push(["vitess-etcd",ua()]);s.push(["vitess-vtctld",pa(t)],["vitess-mysqlctld",ma(t)],["vitess-vtgate",ga(t)]);for(let i of t.keyspaces??[])for(let a of i.sharded?["-80","80-"]:["0"])s.push([`vitess-vttablet-${i.name}-${a.replace(/-/g,"x")}`,da(t,i.name,a)]);for(let[i,a]of s)n.push(...as(i,a));n.push(...is()),n.push("systemctl daemon-reload");for(let[i]of s)n.push(`systemctl enable --now ${i}.service`);return n.push(`if [ "$VTESS_VTGATE_AUTH_CHANGED" = 1 ]; then systemctl restart vitess-vtgate.service; printf '%s\\n' "$VTESS_VTGATE_AUTH_SHA" > ${Dt}; chown ${ve}:${ve} ${Dt}; chmod 0600 ${Dt}; fi`,...ha(t),...cs(t)),n}var Sa=new Set(["singlestore","vitess"]);function Zn(e){if(e?.engine&&Sa.has(e.engine))return!1;return!e?.host||e.host==="127.0.0.1"||e.host==="localhost"}function Yt(e,t="psql"){let r=e?.port??5432;if(Zn(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 Ae(e){return e===!0||typeof e==="object"&&e!=null}function va(e){let t=[],r=[];if(Ae(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(Ae(e.mariadb))t.push(Ot.mariadb),r.push("mariadb");if(Ae(e.postgres))t.push("postgresql.org"),r.push("postgres");if(Ae(e.redis))t.push("redis.io"),r.push("redis");if(Ae(e.memcached))t.push("memcached.org"),r.push("memcached");if(Ae(e.meilisearch))t.push("meilisearch.com"),r.push("meilisearch");return{packages:t,services:r}}function ir(e={},t={}){let r=va(e),n=Zs(e.vitess),s=t.mail?ss(t.mail):[];if(r.packages.length===0)return[...n,...s];return[...Ce(r.packages),...nr(r.services),...n,...s]}function at(e,t={}){if(!e?.name)return[];if(!Zn(e))return[];let r=e.name,n=e.username||r,s=e.password||"",i=Ae(t.postgres)||e.engine==="postgres",a=Ae(t.mariadb)||e.engine==="mariadb",c=Ae(t.mysql)||e.engine==="mysql";if(i&&!c&&!a){let _=(x)=>`"${x.replace(/"/g,'""')}"`,y=(x)=>`'${x.replace(/'/g,"''")}'`,b=(x,k)=>["DO $$ BEGIN",` IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${y(x)}) THEN`,` CREATE ROLE ${_(x)} LOGIN PASSWORD ${y(k)};`," ELSE",` ALTER ROLE ${_(x)} LOGIN PASSWORD ${y(k)};`," END IF;","END $$;"],D=(x)=>{let k=x.databases&&x.databases.length>0?x.databases:[r],I=[];for(let Y of k)if(x.access==="readonly")I.push(`GRANT CONNECT ON DATABASE ${_(Y)} TO ${_(x.username)};`,`\\connect ${_(Y)}`,`GRANT USAGE ON SCHEMA public TO ${_(x.username)};`,`GRANT SELECT ON ALL TABLES IN SCHEMA public TO ${_(x.username)};`,`ALTER DEFAULT PRIVILEGES FOR ROLE ${_(n)} IN SCHEMA public GRANT SELECT ON TABLES TO ${_(x.username)};`,"\\connect postgres");else I.push(`GRANT ALL PRIVILEGES ON DATABASE ${_(Y)} TO ${_(x.username)};`);return I},V=e.users||[],H=e.port??5432;return[Oe(),`for i in $(seq 1 30); do pg_isready -p ${H} -q && break; sleep 2; done`,`${Yt(e)} <<'TS_CLOUD_PG_EOF'`,...b(n,s),`SELECT 'CREATE DATABASE ${_(r)} OWNER ${_(n)}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = ${y(r)})\\gexec`,...V.flatMap((x)=>[...b(x.username,x.password),...D(x)]),"TS_CLOUD_PG_EOF",..._a(e)]}let u=a?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock",f=(_)=>_.replace(/`/g,"``"),h=(_)=>_.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),S=(_)=>{let y=_.databases&&_.databases.length>0?_.databases:[r],b=_.access==="readonly"?"SELECT":"ALL PRIVILEGES",D=[`CREATE USER IF NOT EXISTS '${h(_.username)}'@'%' IDENTIFIED BY '${h(_.password)}';`,`CREATE USER IF NOT EXISTS '${h(_.username)}'@'localhost' IDENTIFIED BY '${h(_.password)}';`,`ALTER USER '${h(_.username)}'@'%' IDENTIFIED BY '${h(_.password)}';`,`ALTER USER '${h(_.username)}'@'localhost' IDENTIFIED BY '${h(_.password)}';`];for(let V of y)D.push(`GRANT ${b} ON \`${f(V)}\`.* TO '${h(_.username)}'@'%';`,`GRANT ${b} ON \`${f(V)}\`.* TO '${h(_.username)}'@'localhost';`);return D},v=e.users||[];return[Oe(),`for i in $(seq 1 30); do mysqladmin --socket=${u} -u root ping 2>/dev/null | grep -q alive && break; sleep 2; done`,`mysql --socket=${u} -u root <<'TS_CLOUD_SQL_EOF'`,`CREATE DATABASE IF NOT EXISTS \`${f(r)}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`,...S({username:n,password:s}),...v.flatMap(S),"FLUSH PRIVILEGES;","TS_CLOUD_SQL_EOF"]}function _a(e){return[`${Yt(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 ps(e){if(!e?.name)return{};let t=e.engine==="singlestore",r=e.engine==="vitess",n=e.engine==="postgres"?"pgsql":t?"singlestore":r?"vitess":"mysql",s=e.port??(e.engine==="postgres"?5432:r?15306:3306),i={DB_CONNECTION:n,DB_HOST:e.host||"127.0.0.1",DB_PORT:String(s),DB_DATABASE:e.name};if(e.username)i.DB_USERNAME=e.username;if(e.password)i.DB_PASSWORD=e.password;if((t||r)&&e.ssl!==!1)i.DB_SSL="true";return i}var un="/var/backups/ts-cloud",$a="/etc/ts-cloud/backups.config.ts",ds="/etc/cron.d/ts-cloud-backups",_r="/usr/local/bin/ts-cloud-backup.sh";function ya(e){if(!e.name)return null;let t=e.host||"127.0.0.1",r=e.engine==="postgres",n=r?"postgresql":"mysql",s=e.port??(r?5432:3306),i=(a)=>a.replace(/\\/g,"\\\\").replace(/'/g,"\\'");return[" {",` type: '${n}',`,` name: '${i(e.name)}',`," connection: {",` hostname: '${i(t)}',`,` port: ${s},`,` database: '${i(e.name)}',`,` username: '${i(e.username||e.name)}',`,` password: '${i(e.password||"")}',`," ssl: false,"," },"," includeSchema: true,"," includeData: true,"," },"].join(`
14
+ `)}function ra(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=${Ee}`,`Group=${Ee}`,`WorkingDirectory=${e.storagePath}`,`EnvironmentFile=${$e}/mail.env`,`Environment="PATH=${en}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"`,`ExecStart=${en}/mail serve --config ${$e}/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} ${$e}`,"","[Install]","WantedBy=multi-user.target",""].join(`
15
+ `)}function na(e){if(!e.dkim.enabled||e.domains.length===0)return[];let t=[`mkdir -p ${$e}/dkim`];for(let r of e.domains){let n=tn(e,r);t.push(`if [ ! -f ${Re(n)} ]; then openssl genrsa -out ${Re(n)} 2048; fi`,`chmod 0600 ${Re(n)}`,`echo "DKIM ${e.dkim.selector}._domainkey.${r} IN TXT v=DKIM1; k=rsa; p=$(openssl rsa -in ${Re(n)} -pubout -outform PEM 2>/dev/null | grep -v '^-----' | tr -d '\\n')"`)}return t.push(`chown -R ${Ee}:${Ee} ${$e}/dkim`),t}function sa(e){if(e.accounts.length===0)return[];let t=(r)=>`runuser -u ${Ee} -- env SMTP_DB_PATH="$TS_CLOUD_MAIL_DB" ${en}/mail user:local ${r}`;return e.accounts.flatMap((r)=>[t(`create ${Re(r.address)} ${Re(r.password)} ${Re(r.address)}`),...r.passwordPolicy==="managed"?[t(`change-password ${Re(r.address)} ${Re(r.password)}`)]:[]])}function ss(e){if(!e.enabled)return[];return[...Ce(Qi(e)),`id -u ${Ee} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin ${Ee}`,`mkdir -p ${e.storagePath} ${$e}`,`chown -R ${Ee}:${Ee} ${e.storagePath}`,`TS_CLOUD_MAIL_DB="$(grep -sE '^SMTP_DB_PATH=' ${$e}/mail.env | head -1 | cut -d= -f2- || true)"`,`[ -n "$TS_CLOUD_MAIL_DB" ] || TS_CLOUD_MAIL_DB=${Re(ns(e))}`,`cat > ${$e}/config.toml <<'TS_CLOUD_MAIL_CONF_EOF'`,ea(e),"TS_CLOUD_MAIL_CONF_EOF",`cat > ${$e}/mail.env <<'TS_CLOUD_MAIL_ENV_EOF'`,ta(e),"TS_CLOUD_MAIL_ENV_EOF",`sed -i "s|^SMTP_DB_PATH=.*|SMTP_DB_PATH=$TS_CLOUD_MAIL_DB|" ${$e}/mail.env`,`chmod 0640 ${$e}/mail.env`,`chown root:${Ee} ${$e}/mail.env`,...na(e),`cat > /etc/systemd/system/${Zr}.service <<'TS_CLOUD_MAIL_UNIT_EOF'`,ra(e),"TS_CLOUD_MAIL_UNIT_EOF","systemctl daemon-reload",`systemctl enable ${Zr}`,`systemctl restart ${Zr}`,...sa(e)]}var be=`${p}/pantry/.bin`,sn=15306,rn=15991,sr=15999,os=16101,or=2379,xe="/var/lib/vitess",on=100;function xt(e){return e===!0||typeof e==="object"&&e!==null}function oa(e){return typeof e==="object"&&e!==null?e:{}}function ue(e){return`'${String(e).split("'").join("'\\''")}'`}function ia(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 _e="vitess",aa=`${be}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`,ls="/usr/local/lib/vitess",an=new Map;function nn(e){return`${ls}/${e}.sh`}function ot(e,t){return an.set(e,ca(t)),`/bin/sh ${nn(e)}`}function is(){let e=[`mkdir -p ${ls}`];for(let[t,r]of an)e.push(`cat > ${nn(t)} <<'TS_CLOUD_VITESS_LAUNCHER_EOF'`,r,"TS_CLOUD_VITESS_LAUNCHER_EOF",`chmod 0755 ${nn(t)}`);return e}function ca(e){return["#!/bin/sh","set -e",`cd ${p}`,`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 ${be}/mysqld 2>/dev/null)")")"`,`VTROOT="$(dirname "$(dirname "$(readlink -f ${be}/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(`
16
+ `)}function it(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=${_e}`,`Group=${_e}`,`Environment="PATH=${aa}"`,`Environment="VTDATAROOT=${xe}"`,...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(`
17
+ `)}function as(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_VITESS_UNIT_EOF'`,t,"TS_CLOUD_VITESS_UNIT_EOF"]}function la(e){let t=e.cell??"zone1",r=e.vtgatePort??sn,s=`${((e.keyspaces?.length)?e.keyspaces:[{name:"app"}]).map((i)=>{let a=(i.sharded?["-80","80-"]:["0"]).map((c)=>`shards:{name:"${c}"}`).join(" ");return`keyspaces:{name:"${i.name}" ${a}}`}).join(" ")} cells:"${t}"`;return it({description:"Vitess (vtcombo, single-process development stack)",execStart:ot("vtcombo",[`${be}/vtcombo`,`--cell ${t}`,`--proto-topo ${ue(s)}`,`--mysql-server-port ${r}`,"--mysql-server-bind-address 127.0.0.1","--mysql-auth-server-impl none","--start-mysql",`--port ${rn}`,`--grpc-port ${sr}`])})}function ua(){return it({description:"etcd (Vitess topology store)",execStart:ot("etcd",[`${be}/etcd`,`--data-dir ${xe}/etcd`,`--listen-client-urls http://127.0.0.1:${or}`,`--advertise-client-urls http://127.0.0.1:${or}`]),execStartPre:[`+/bin/mkdir -p ${xe}/etcd`,`+/bin/chown ${_e}:${_e} ${xe}/etcd`]})}function cn(e){return["--topo-implementation etcd2",`--topo-global-server-address ${e.etcdEndpoint??`http://127.0.0.1:${or}`}`,"--topo-global-root /vitess/global"]}function pa(e){let t=!e.etcdEndpoint;return it({description:"Vitess vtctld (control plane)",after:t?["vitess-etcd.service"]:[],requires:t?["vitess-etcd.service"]:[],execStart:ot("vtctld",[`${be}/vtctld`,...cn(e),`--cell ${e.cell??"zone1"}`,"--service-map grpc-vtctl,grpc-vtctld",`--grpc-port ${sr}`,`--port ${sr+1}`])})}function da(e,t,r){let n=e.cell??"zone1";return it({description:`Vitess vttablet (${t}/${r})`,after:["vitess-vtctld.service","vitess-mysqlctld.service"],requires:["vitess-mysqlctld.service"],execStart:ot("vttablet",[`${be}/vttablet`,...cn(e),`--tablet-path ${n}-${String(on).padStart(10,"0")}`,`--init-keyspace ${t}`,`--init-shard ${r}`,"--init-tablet-type replica",`--service-map ${ue("grpc-queryservice,grpc-tabletmanager,grpc-updatestream")}`,`--port ${os}`,`--grpc-port ${os+1}`,`--db-port ${e.mysqlPort??3306}`,`--mycnf-mysql-port ${e.mysqlPort??3306}`])})}function ma(e){return it({description:"Vitess mysqlctld (managed mysqld)",execStart:ot("mysqlctld",[`${be}/mysqlctld`,`--tablet-uid ${on}`,`--mysql-port ${e.mysqlPort??3306}`,'--init-db-sql-file "$VTROOT/config/init_db.sql"',"--wait-time 2m"]),execStartPre:[`+/bin/mkdir -p ${xe}`,`+/bin/chown ${_e}:${_e} ${xe}`]})}var us="/etc/vitess/auth.json",Dt="/var/lib/vitess/vtgate-auth.sha256";function fa(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 ${Dt} ] && [ "$(cat ${Dt})" = "$VTESS_VTGATE_AUTH_SHA" ]; then VTESS_VTGATE_AUTH_CHANGED=0; fi`,`install -o ${_e} -g ${_e} -m 0600 "$VTESS_AUTH_TMP" ${us}`,'rm -f "$VTESS_AUTH_TMP"']}function ga(e){let t=e.cell??"zone1";return it({description:"Vitess vtgate (query router)",after:["vitess-vtctld.service"],execStart:ot("vtgate",[`${be}/vtgate`,...cn(e),`--cell ${t}`,`--cells-to-watch ${t}`,"--tablet-types-to-wait PRIMARY,REPLICA",`--service-map ${ue("grpc-vtgateservice")}`,`--mysql-server-port ${e.vtgatePort??sn}`,`--mysql-server-bind-address ${e.bindAddress??"127.0.0.1"}`,"--mysql-auth-server-impl static",`--mysql-auth-server-static-file ${us}`,`--port ${rn}`,`--grpc-port ${rn+1}`])})}function ha(e){let t=e.cell??"zone1",r=e.etcdEndpoint??`http://127.0.0.1:${or}`,n=`${be}/vtctldclient --server 127.0.0.1:${sr}`,s=[`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 ${ue(t)}; then`,` ${n} AddCellInfo --root ${ue(`/vitess/${t}`)} --server-address ${ue(r)} ${ue(t)}`,"fi"];for(let i of e.keyspaces??[]){let a=i.sharded?" --sharded":"";s.push(`if ! ${n} GetKeyspace ${ue(i.name)} >/dev/null 2>&1; then`,` ${n} CreateKeyspace${a} ${ue(i.name)}`,"fi");let c=`${t}-${String(on).padStart(10,"0")}`;for(let u of i.sharded?["-80","80-"]:["0"]){let f=`${i.name}/${u}`;s.push("for i in $(seq 1 90); do",` if ${n} GetShard ${ue(f)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then break; fi`,` ${n} PlannedReparentShard ${ue(f)} --new-primary ${ue(c)} >/dev/null 2>&1 && break`,` ${n} InitShardPrimary --force ${ue(f)} ${ue(c)} >/dev/null 2>&1 && break`," sleep 2","done",`if ! ${n} GetShard ${ue(f)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then`,` echo "no primary could be elected for ${f}" >&2; exit 1`,"fi")}s.push(`${n} RebuildKeyspaceGraph ${ue(i.name)} >/dev/null`)}return s}function cs(e){let t=e.vtgatePort??sn;return["for i in $(seq 1 60); do",` if (cd ${p} && eval "$(pantry env 2>/dev/null)"; MYSQL_PWD=${ue(e.password??"")} ${be}/mysql -h 127.0.0.1 -P ${t} -u ${ue(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 Zs(e){if(!xt(e))return[];let t=oa(e),r=t.mode==="combo";an.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",...Ce(ia(t)),`VT_MYSQL_LIB="$(dirname "$(dirname "$(readlink -f ${be}/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 ${_e} >/dev/null 2>&1 || useradd --system --home-dir ${xe} --shell /usr/sbin/nologin ${_e}`,`mkdir -p ${xe}`,`chown -R ${_e}:${_e} ${xe}`];if(r)return n.push(...as("vitess-vtcombo",la(t)),...is(),"systemctl daemon-reload","systemctl enable --now vitess-vtcombo.service",...cs(t)),n;n.push(...fa(t));let s=[];if(!t.etcdEndpoint)s.push(["vitess-etcd",ua()]);s.push(["vitess-vtctld",pa(t)],["vitess-mysqlctld",ma(t)],["vitess-vtgate",ga(t)]);for(let i of t.keyspaces??[])for(let a of i.sharded?["-80","80-"]:["0"])s.push([`vitess-vttablet-${i.name}-${a.replace(/-/g,"x")}`,da(t,i.name,a)]);for(let[i,a]of s)n.push(...as(i,a));n.push(...is()),n.push("systemctl daemon-reload");for(let[i]of s)n.push(`systemctl enable --now ${i}.service`);return n.push(`if [ "$VTESS_VTGATE_AUTH_CHANGED" = 1 ]; then systemctl restart vitess-vtgate.service; printf '%s\\n' "$VTESS_VTGATE_AUTH_SHA" > ${Dt}; chown ${_e}:${_e} ${Dt}; chmod 0600 ${Dt}; fi`,...ha(t),...cs(t)),n}var Sa=new Set(["singlestore","vitess"]);function Zn(e){if(e?.engine&&Sa.has(e.engine))return!1;return!e?.host||e.host==="127.0.0.1"||e.host==="localhost"}function Yt(e,t="psql"){let r=e?.port??5432;if(Zn(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 Ae(e){return e===!0||typeof e==="object"&&e!=null}function va(e){let t=[],r=[];if(Ae(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(Ae(e.mariadb))t.push(Ot.mariadb),r.push("mariadb");if(Ae(e.postgres))t.push("postgresql.org"),r.push("postgres");if(Ae(e.redis))t.push("redis.io"),r.push("redis");if(Ae(e.memcached))t.push("memcached.org"),r.push("memcached");if(Ae(e.meilisearch))t.push("meilisearch.com"),r.push("meilisearch");return{packages:t,services:r}}function ir(e={},t={}){let r=va(e),n=Zs(e.vitess),s=t.mail?ss(t.mail):[];if(r.packages.length===0)return[...n,...s];return[...Ce(r.packages),...nr(r.services),...n,...s]}function at(e,t={}){if(!e?.name)return[];if(!Zn(e))return[];let r=e.name,n=e.username||r,s=e.password||"",i=Ae(t.postgres)||e.engine==="postgres",a=Ae(t.mariadb)||e.engine==="mariadb",c=Ae(t.mysql)||e.engine==="mysql";if(i&&!c&&!a){let _=(R)=>`"${R.replace(/"/g,'""')}"`,y=(R)=>`'${R.replace(/'/g,"''")}'`,T=(R,L)=>["DO $$ BEGIN",` IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${y(R)}) THEN`,` CREATE ROLE ${_(R)} LOGIN PASSWORD ${y(L)};`," ELSE",` ALTER ROLE ${_(R)} LOGIN PASSWORD ${y(L)};`," END IF;","END $$;"],x=(R)=>{let L=R.databases&&R.databases.length>0?R.databases:[r],I=[];for(let V of L)if(R.access==="readonly")I.push(`GRANT CONNECT ON DATABASE ${_(V)} TO ${_(R.username)};`,`\\connect ${_(V)}`,`GRANT USAGE ON SCHEMA public TO ${_(R.username)};`,`GRANT SELECT ON ALL TABLES IN SCHEMA public TO ${_(R.username)};`,`ALTER DEFAULT PRIVILEGES FOR ROLE ${_(n)} IN SCHEMA public GRANT SELECT ON TABLES TO ${_(R.username)};`,"\\connect postgres");else I.push(`GRANT ALL PRIVILEGES ON DATABASE ${_(V)} TO ${_(R.username)};`);return I},W=e.users||[],H=e.port??5432;return[Oe(),`for i in $(seq 1 30); do pg_isready -p ${H} -q && break; sleep 2; done`,`${Yt(e)} <<'TS_CLOUD_PG_EOF'`,...T(n,s),`SELECT 'CREATE DATABASE ${_(r)} OWNER ${_(n)}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = ${y(r)})\\gexec`,...W.flatMap((R)=>[...T(R.username,R.password),...x(R)]),"TS_CLOUD_PG_EOF",..._a(e)]}let u=a?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock",f=(_)=>_.replace(/`/g,"``"),h=(_)=>_.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),S=(_)=>{let y=_.databases&&_.databases.length>0?_.databases:[r],T=_.access==="readonly"?"SELECT":"ALL PRIVILEGES",x=[`CREATE USER IF NOT EXISTS '${h(_.username)}'@'%' IDENTIFIED BY '${h(_.password)}';`,`CREATE USER IF NOT EXISTS '${h(_.username)}'@'localhost' IDENTIFIED BY '${h(_.password)}';`,`ALTER USER '${h(_.username)}'@'%' IDENTIFIED BY '${h(_.password)}';`,`ALTER USER '${h(_.username)}'@'localhost' IDENTIFIED BY '${h(_.password)}';`];for(let W of y)x.push(`GRANT ${T} ON \`${f(W)}\`.* TO '${h(_.username)}'@'%';`,`GRANT ${T} ON \`${f(W)}\`.* TO '${h(_.username)}'@'localhost';`);return x},v=e.users||[];return[Oe(),`for i in $(seq 1 30); do mysqladmin --socket=${u} -u root ping 2>/dev/null | grep -q alive && break; sleep 2; done`,`mysql --socket=${u} -u root <<'TS_CLOUD_SQL_EOF'`,`CREATE DATABASE IF NOT EXISTS \`${f(r)}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`,...S({username:n,password:s}),...v.flatMap(S),"FLUSH PRIVILEGES;","TS_CLOUD_SQL_EOF"]}function _a(e){return[`${Yt(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 ps(e){if(!e?.name)return{};let t=e.engine==="singlestore",r=e.engine==="vitess",n=e.engine==="postgres"?"pgsql":t?"singlestore":r?"vitess":"mysql",s=e.port??(e.engine==="postgres"?5432:r?15306:3306),i={DB_CONNECTION:n,DB_HOST:e.host||"127.0.0.1",DB_PORT:String(s),DB_DATABASE:e.name};if(e.username)i.DB_USERNAME=e.username;if(e.password)i.DB_PASSWORD=e.password;if((t||r)&&e.ssl!==!1)i.DB_SSL="true";return i}var un="/var/backups/ts-cloud",$a="/etc/ts-cloud/backups.config.ts",ds="/etc/cron.d/ts-cloud-backups",_r="/usr/local/bin/ts-cloud-backup.sh";function ya(e){if(!e.name)return null;let t=e.host||"127.0.0.1",r=e.engine==="postgres",n=r?"postgresql":"mysql",s=e.port??(r?5432:3306),i=(a)=>a.replace(/\\/g,"\\\\").replace(/'/g,"\\'");return[" {",` type: '${n}',`,` name: '${i(e.name)}',`," connection: {",` hostname: '${i(t)}',`,` port: ${s},`,` database: '${i(e.name)}',`,` username: '${i(e.username||e.name)}',`,` password: '${i(e.password||"")}',`," ssl: false,"," },"," includeSchema: true,"," includeData: true,"," },"].join(`
18
18
  `)}function ba(e,t){let r=e?ya(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: '${un}',`," retention: {",` count: ${t.retentionCount??5},`,` maxAge: ${t.retentionDays??30},`," },"," databases: [",...r?[r]:[]," ],",...n,"}","","export default config",""].join(`
19
- `)}function ar(e){let{database:t,backups:r}=e;if(!r.enabled)return[];let n=r.schedule||"0 2 * * *",s=ba(t,r);return["export DEBIAN_FRONTEND=noninteractive",`mkdir -p /etc/ts-cloud ${un}`,"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 > ${$a} <<'TS_CLOUD_BACKUP_CFG_EOF'`,s.replace(/\n$/,""),"TS_CLOUD_BACKUP_CFG_EOF",`cat > ${_r} <<'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 ${_r}`,`cat > ${ds} <<'TS_CLOUD_BACKUP_CRON_EOF'`,`${n} root ${_r} >> /var/log/ts-cloud-backup.log 2>&1`,"TS_CLOUD_BACKUP_CRON_EOF",`chmod 644 ${ds}`]}function Ta(e){return e==="mariadb"?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock"}function Lg(e,t={}){if(!e?.name)return[];let r=e.name,n=e.engine==="postgres",s=t.from?`TS_CLOUD_DUMP="${t.from}"`:`TS_CLOUD_DUMP="$(find ${un} -type f -name '*${r}*.sql' -o -type f -name '*${r}*.sql.gz' 2>/dev/null | xargs -r ls -1t 2>/dev/null | head -1)"`,i=n?`${Yt(e)} -d "${r}"`:`mysql --socket=${Ta(e.engine)} -u root "${r}"`;return["set -uo pipefail",'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true',s,'[ -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 | ${i}`,'echo "restore complete"']}function wa(e){return`/etc/ts-cloud/${e}-upgrade.env`}function Ca(e){return`${e}-upgrade`}function eo(e){if(!e||e.length===0)return[];let t=["mkdir -p /etc/ts-cloud"],r=[];for(let n of e){if(n.enabled===!1)continue;if(!n.service||!n.binary)continue;let{service:s,binary:i,command:a="upgrade",channel:c="stable",schedule:u="daily",randomizedDelay:f="4h",args:h=[]}=n,S=Ca(s),v=wa(s),_=[`--path ${i}`,`--service ${s}`,...c==="canary"?["--canary"]:[],...h].join(" ");t.push(`if [ ! -f ${v} ]; then`,` cat > ${v} <<'TS_CLOUD_APPUPD_ENV_EOF'`,"# Set to false to pause automatic updates without disabling the timer.","ENABLED=true","# Extra flags appended to the update command.","ARGS=","TS_CLOUD_APPUPD_ENV_EOF","fi",`chmod 644 ${v}`,`cat > /etc/systemd/system/${S}.service <<'TS_CLOUD_APPUPD_SVC_EOF'`,"[Unit]",`Description=Check for and install ${s} updates`,"After=network-online.target","Wants=network-online.target","","[Service]","Type=oneshot",`EnvironmentFile=-${v}`,`ExecStart=/bin/sh -c 'if [ "\${ENABLED:-true}" != "true" ]; then echo "auto-update disabled via ${v}"; exit 0; fi; exec ${i} ${a} ${_} $ARGS'`,"TS_CLOUD_APPUPD_SVC_EOF",`cat > /etc/systemd/system/${S}.timer <<'TS_CLOUD_APPUPD_TMR_EOF'`,"[Unit]",`Description=Scheduled ${s} update check`,"","[Timer]",`OnCalendar=${u}`,`RandomizedDelaySec=${f}`,"Persistent=true","","[Install]","WantedBy=timers.target","TS_CLOUD_APPUPD_TMR_EOF"),r.push(`systemctl enable --now ${S}.timer`)}if(r.length===0)return[];return[...t,"systemctl daemon-reload",...r]}function Me(e=!0){if(!e)return[];return["export DEBIAN_FRONTEND=noninteractive","dpkg-query -W -f='${Status}' unattended-upgrades 2>/dev/null | grep -q 'ok installed' || apt-get install -y unattended-upgrades","cat > /etc/apt/apt.conf.d/20auto-upgrades <<'TS_CLOUD_AUTOUPD_EOF'",'APT::Periodic::Update-Package-Lists "1";','APT::Periodic::Unattended-Upgrade "1";','APT::Periodic::Download-Upgradeable-Packages "1";','APT::Periodic::AutocleanInterval "7";',"TS_CLOUD_AUTOUPD_EOF","systemctl enable --now unattended-upgrades 2>/dev/null || true"]}var ms=[["nginx",80],["https",443],["phpFpm",9074],["mysql",3306],["postgres",5432],["redis",6379],["meilisearch",7700],["typesense",8108],["smtp",25]];function Pa(e=!0){let t=typeof e==="object"?e:{},r=typeof e==="boolean"?e:e.enabled!==!1,n=Number(t.alerts?.bandwidthTb??0);return{enabled:r,cpuLoadPerCore:t.alerts?.cpuLoadPerCore??2,memPercent:t.alerts?.memPercent??90,diskPercent:t.alerts?.diskPercent??90,bandwidthTb:Number.isFinite(n)&&n>0?n:0,bandwidthPercent:t.alerts?.bandwidthPercent??80}}function Le(e=!0){let{enabled:t,cpuLoadPerCore:r,memPercent:n,diskPercent:s,bandwidthTb:i,bandwidthPercent:a}=Pa(e);if(!t)return[];let c=Math.round(i*1000000000000),u=ms.map(([y,b])=>`SVC_${y.toUpperCase()}=$(probe ${b})`),f=ms.map(([y])=>`"${y}":"$SVC_${y.toUpperCase()}"`).join(","),h=(typeof e==="object"?e.filesystems:void 0)??["/"];if(!h.length)throw Error("monitoring.filesystems must include at least one path");let S=h.map((y)=>typeof y==="string"?{path:y,requiredMount:!1}:y);for(let y of S)if(y.path!=="/"&&(!y.path.startsWith("/")||!y.path.slice(1).split("/").every((b)=>/^[\w-]+$/.test(b))))throw Error(`Invalid monitoring filesystem path: ${y.path}`);let v=S.flatMap((y,b)=>[`DISK_${b}_MOUNTED=true; DISK_${b}_PCT=null`,...y.requiredMount?[`if ! mountpoint -q '${y.path}'; then DISK_${b}_MOUNTED=false; DISK_ALERTS="$DISK_ALERTS missing-mount=${y.path}"; ALERT_KEY="$ALERT_KEY mount:${y.path}"; fi`]:[],`if [ "$DISK_${b}_MOUNTED" = true ]; then`,` DISK_${b}_PCT=$(df -Pk '${y.path}' 2>/dev/null | awk 'NR==2{gsub("%","",$5);print $5}')`,` if [[ "$DISK_${b}_PCT" =~ ^[0-9]+$ ]]; then`,` [ "$DISK_${b}_PCT" -le "$DISK_PCT" ] || DISK_PCT=$DISK_${b}_PCT`,` if [ "$DISK_${b}_PCT" -ge ${s} ]; then DISK_ALERTS="$DISK_ALERTS disk=${y.path}:$DISK_${b}_PCT%"; ALERT_KEY="$ALERT_KEY disk:${y.path}"; fi`,` else DISK_${b}_PCT=null; DISK_ALERTS="$DISK_ALERTS unreadable-disk=${y.path}"; ALERT_KEY="$ALERT_KEY unreadable:${y.path}"; fi`,"fi"]),_=S.map((y,b)=>`{"path":"${y.path}","usedPercent":$DISK_${b}_PCT,"mounted":$DISK_${b}_MOUNTED}`).join(",");return["if ! command -v sadf >/dev/null 2>&1; then export DEBIAN_FRONTEND=noninteractive; apt-get update -qq; apt-get install -y -qq sysstat; fi","systemctl enable --now sysstat.service 2>/dev/null || true","mkdir -p /var/lib/ts-cloud","cat > /usr/local/bin/ts-cloud-metrics.sh <<'TS_CLOUD_METRICS_EOF'","#!/bin/bash","set -uo pipefail","LOAD=$(cut -d' ' -f1 /proc/loadavg)","CPUS=$(nproc)",`read MEM_TOTAL MEM_USED SWAP_TOTAL SWAP_USED <<EOF
19
+ `)}function ar(e){let{database:t,backups:r}=e;if(!r.enabled)return[];let n=r.schedule||"0 2 * * *",s=ba(t,r);return["export DEBIAN_FRONTEND=noninteractive",`mkdir -p /etc/ts-cloud ${un}`,"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 > ${$a} <<'TS_CLOUD_BACKUP_CFG_EOF'`,s.replace(/\n$/,""),"TS_CLOUD_BACKUP_CFG_EOF",`cat > ${_r} <<'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 ${_r}`,`cat > ${ds} <<'TS_CLOUD_BACKUP_CRON_EOF'`,`${n} root ${_r} >> /var/log/ts-cloud-backup.log 2>&1`,"TS_CLOUD_BACKUP_CRON_EOF",`chmod 644 ${ds}`]}function Ta(e){return e==="mariadb"?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock"}function Lg(e,t={}){if(!e?.name)return[];let r=e.name,n=e.engine==="postgres",s=t.from?`TS_CLOUD_DUMP="${t.from}"`:`TS_CLOUD_DUMP="$(find ${un} -type f -name '*${r}*.sql' -o -type f -name '*${r}*.sql.gz' 2>/dev/null | xargs -r ls -1t 2>/dev/null | head -1)"`,i=n?`${Yt(e)} -d "${r}"`:`mysql --socket=${Ta(e.engine)} -u root "${r}"`;return["set -uo pipefail",'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true',s,'[ -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 | ${i}`,'echo "restore complete"']}function wa(e){return`/etc/ts-cloud/${e}-upgrade.env`}function Ca(e){return`${e}-upgrade`}function eo(e){if(!e||e.length===0)return[];let t=["mkdir -p /etc/ts-cloud"],r=[];for(let n of e){if(n.enabled===!1)continue;if(!n.service||!n.binary)continue;let{service:s,binary:i,command:a="upgrade",channel:c="stable",schedule:u="daily",randomizedDelay:f="4h",args:h=[]}=n,S=Ca(s),v=wa(s),_=[`--path ${i}`,`--service ${s}`,...c==="canary"?["--canary"]:[],...h].join(" ");t.push(`if [ ! -f ${v} ]; then`,` cat > ${v} <<'TS_CLOUD_APPUPD_ENV_EOF'`,"# Set to false to pause automatic updates without disabling the timer.","ENABLED=true","# Extra flags appended to the update command.","ARGS=","TS_CLOUD_APPUPD_ENV_EOF","fi",`chmod 644 ${v}`,`cat > /etc/systemd/system/${S}.service <<'TS_CLOUD_APPUPD_SVC_EOF'`,"[Unit]",`Description=Check for and install ${s} updates`,"After=network-online.target","Wants=network-online.target","","[Service]","Type=oneshot",`EnvironmentFile=-${v}`,`ExecStart=/bin/sh -c 'if [ "\${ENABLED:-true}" != "true" ]; then echo "auto-update disabled via ${v}"; exit 0; fi; exec ${i} ${a} ${_} $ARGS'`,"TS_CLOUD_APPUPD_SVC_EOF",`cat > /etc/systemd/system/${S}.timer <<'TS_CLOUD_APPUPD_TMR_EOF'`,"[Unit]",`Description=Scheduled ${s} update check`,"","[Timer]",`OnCalendar=${u}`,`RandomizedDelaySec=${f}`,"Persistent=true","","[Install]","WantedBy=timers.target","TS_CLOUD_APPUPD_TMR_EOF"),r.push(`systemctl enable --now ${S}.timer`)}if(r.length===0)return[];return[...t,"systemctl daemon-reload",...r]}function Me(e=!0){if(!e)return[];return["export DEBIAN_FRONTEND=noninteractive","dpkg-query -W -f='${Status}' unattended-upgrades 2>/dev/null | grep -q 'ok installed' || apt-get install -y unattended-upgrades","cat > /etc/apt/apt.conf.d/20auto-upgrades <<'TS_CLOUD_AUTOUPD_EOF'",'APT::Periodic::Update-Package-Lists "1";','APT::Periodic::Unattended-Upgrade "1";','APT::Periodic::Download-Upgradeable-Packages "1";','APT::Periodic::AutocleanInterval "7";',"TS_CLOUD_AUTOUPD_EOF","systemctl enable --now unattended-upgrades 2>/dev/null || true"]}var ms=[["nginx",80],["https",443],["phpFpm",9074],["mysql",3306],["postgres",5432],["redis",6379],["meilisearch",7700],["typesense",8108],["smtp",25]];function Pa(e=!0){let t=typeof e==="object"?e:{},r=typeof e==="boolean"?e:e.enabled!==!1,n=Number(t.alerts?.bandwidthTb??0);return{enabled:r,cpuLoadPerCore:t.alerts?.cpuLoadPerCore??2,memPercent:t.alerts?.memPercent??90,diskPercent:t.alerts?.diskPercent??90,bandwidthTb:Number.isFinite(n)&&n>0?n:0,bandwidthPercent:t.alerts?.bandwidthPercent??80}}function Le(e=!0){let{enabled:t,cpuLoadPerCore:r,memPercent:n,diskPercent:s,bandwidthTb:i,bandwidthPercent:a}=Pa(e);if(!t)return[];let c=Math.round(i*1000000000000),u=ms.map(([y,T])=>`SVC_${y.toUpperCase()}=$(probe ${T})`),f=ms.map(([y])=>`"${y}":"$SVC_${y.toUpperCase()}"`).join(","),h=(typeof e==="object"?e.filesystems:void 0)??["/"];if(!h.length)throw Error("monitoring.filesystems must include at least one path");let S=h.map((y)=>typeof y==="string"?{path:y,requiredMount:!1}:y);for(let y of S)if(y.path!=="/"&&(!y.path.startsWith("/")||!y.path.slice(1).split("/").every((T)=>/^[\w-]+$/.test(T))))throw Error(`Invalid monitoring filesystem path: ${y.path}`);let v=S.flatMap((y,T)=>[`DISK_${T}_MOUNTED=true; DISK_${T}_PCT=null`,...y.requiredMount?[`if ! mountpoint -q '${y.path}'; then DISK_${T}_MOUNTED=false; DISK_ALERTS="$DISK_ALERTS missing-mount=${y.path}"; ALERT_KEY="$ALERT_KEY mount:${y.path}"; fi`]:[],`if [ "$DISK_${T}_MOUNTED" = true ]; then`,` DISK_${T}_PCT=$(df -Pk '${y.path}' 2>/dev/null | awk 'NR==2{gsub("%","",$5);print $5}')`,` if [[ "$DISK_${T}_PCT" =~ ^[0-9]+$ ]]; then`,` [ "$DISK_${T}_PCT" -le "$DISK_PCT" ] || DISK_PCT=$DISK_${T}_PCT`,` if [ "$DISK_${T}_PCT" -ge ${s} ]; then DISK_ALERTS="$DISK_ALERTS disk=${y.path}:$DISK_${T}_PCT%"; ALERT_KEY="$ALERT_KEY disk:${y.path}"; fi`,` else DISK_${T}_PCT=null; DISK_ALERTS="$DISK_ALERTS unreadable-disk=${y.path}"; ALERT_KEY="$ALERT_KEY unreadable:${y.path}"; fi`,"fi"]),_=S.map((y,T)=>`{"path":"${y.path}","usedPercent":$DISK_${T}_PCT,"mounted":$DISK_${T}_MOUNTED}`).join(",");return["if ! command -v sadf >/dev/null 2>&1; then export DEBIAN_FRONTEND=noninteractive; apt-get update -qq; apt-get install -y -qq sysstat; fi","systemctl enable --now sysstat.service 2>/dev/null || true","mkdir -p /var/lib/ts-cloud","cat > /usr/local/bin/ts-cloud-metrics.sh <<'TS_CLOUD_METRICS_EOF'","#!/bin/bash","set -uo pipefail","LOAD=$(cut -d' ' -f1 /proc/loadavg)","CPUS=$(nproc)",`read MEM_TOTAL MEM_USED SWAP_TOTAL SWAP_USED <<EOF
20
20
  $(free -m | awk '/^Mem:/{total=$2; used=$3} /^Swap:/{print total, used, $2, $3}')
21
21
  EOF`,'DISK_PCT=0; DISK_ALERTS=""; ALERT_KEY=""',...v,"UPTIME_SEC=$(cut -d' ' -f1 /proc/uptime | cut -d. -f1)",`RX_BYTES=$(awk -F'[: ]+' 'NR>2 && $2!="lo"{rx+=$3} END{print rx+0}' /proc/net/dev)`,`TX_BYTES=$(awk -F'[: ]+' 'NR>2 && $2!="lo"{tx+=$11} END{print tx+0}' /proc/net/dev)`,"NOW_EPOCH=$(date -u +%s); TODAY=$(date -u +%Y-%m-%d); MONTH=$(date -u +%Y-%m)","if [ -r /var/lib/ts-cloud/bandwidth-state ]; then . /var/lib/ts-cloud/bandwidth-state; fi","PREV_EPOCH=${PREV_EPOCH:-0}; PREV_RX=${PREV_RX:-0}; PREV_TX=${PREV_TX:-0}","DAY_KEY=${DAY_KEY:-$TODAY}; MONTH_KEY=${MONTH_KEY:-$MONTH}","DAY_RX=${DAY_RX:-0}; DAY_TX=${DAY_TX:-0}; MONTH_RX=${MONTH_RX:-0}; MONTH_TX=${MONTH_TX:-0}","ELAPSED=$(( NOW_EPOCH - PREV_EPOCH ))",'if [ "$PREV_EPOCH" -le 0 ] || [ "$ELAPSED" -le 0 ] || [ "$RX_BYTES" -lt "$PREV_RX" ] || [ "$TX_BYTES" -lt "$PREV_TX" ]; then'," DELTA_RX=0; DELTA_TX=0; ELAPSED=0","else"," DELTA_RX=$(( RX_BYTES - PREV_RX )); DELTA_TX=$(( TX_BYTES - PREV_TX ))","fi",'if [ "$DAY_KEY" != "$TODAY" ]; then DAY_KEY=$TODAY; DAY_RX=0; DAY_TX=0; fi','if [ "$MONTH_KEY" != "$MONTH" ]; then MONTH_KEY=$MONTH; MONTH_RX=0; MONTH_TX=0; fi',"DAY_RX=$(( DAY_RX + DELTA_RX )); DAY_TX=$(( DAY_TX + DELTA_TX ))","MONTH_RX=$(( MONTH_RX + DELTA_RX )); MONTH_TX=$(( MONTH_TX + DELTA_TX ))",'if [ "$ELAPSED" -gt 0 ]; then RX_RATE=$(( DELTA_RX / ELAPSED )); TX_RATE=$(( DELTA_TX / ELAPSED )); else RX_RATE=0; TX_RATE=0; fi',"cat > /var/lib/ts-cloud/bandwidth-state.tmp <<BWSTATE","PREV_EPOCH=$NOW_EPOCH","PREV_RX=$RX_BYTES","PREV_TX=$TX_BYTES","RX_RATE=$RX_RATE","TX_RATE=$TX_RATE","DAY_KEY=$DAY_KEY","DAY_RX=$DAY_RX","DAY_TX=$DAY_TX","MONTH_KEY=$MONTH_KEY","MONTH_RX=$MONTH_RX","MONTH_TX=$MONTH_TX","BWSTATE","mv -f /var/lib/ts-cloud/bandwidth-state.tmp /var/lib/ts-cloud/bandwidth-state","probe(){ (exec 3<>/dev/tcp/127.0.0.1/$1) 2>/dev/null && echo up || echo down; }",...u,"LOAD=${LOAD:-0}; CPUS=${CPUS:-1}; MEM_TOTAL=${MEM_TOTAL:-0}; MEM_USED=${MEM_USED:-0}","SWAP_TOTAL=${SWAP_TOTAL:-0}; SWAP_USED=${SWAP_USED:-0}; DISK_PCT=${DISK_PCT:-0}","UPTIME_SEC=${UPTIME_SEC:-0}; RX_BYTES=${RX_BYTES:-0}; TX_BYTES=${TX_BYTES:-0}","MEM_PCT=$(( MEM_TOTAL > 0 ? MEM_USED * 100 / MEM_TOTAL : 0 ))","cat > /var/lib/ts-cloud/metrics.json.tmp <<JSON",`{"load":$LOAD,"cpus":$CPUS,"memTotalMb":$MEM_TOTAL,"memUsedMb":$MEM_USED,"memUsedPct":$MEM_PCT,"swapTotalMb":$SWAP_TOTAL,"swapUsedMb":$SWAP_USED,"diskUsedPct":$DISK_PCT,"uptimeSec":$UPTIME_SEC,"disks":[${_}],"network":{"rxBytes":$RX_BYTES,"txBytes":$TX_BYTES,"rxBytesPerSec":$RX_RATE,"txBytesPerSec":$TX_RATE,"dayKey":"$DAY_KEY","rxBytesToday":$DAY_RX,"txBytesToday":$DAY_TX,"monthKey":"$MONTH_KEY","rxBytesMonth":$MONTH_RX,"txBytesMonth":$MONTH_TX,"budgetBytes":${c}},"services":{`+f+"}}","JSON","mv -f /var/lib/ts-cloud/metrics.json.tmp /var/lib/ts-cloud/metrics.json",'ALERTS="$DISK_ALERTS"',`if awk -v l="$LOAD" -v c="$CPUS" -v t=${r} 'BEGIN{exit !(c>0 && l/c > t)}'; then ALERTS="$ALERTS load=$LOAD/${r}xCPU"; ALERT_KEY="$ALERT_KEY cpu"; fi`,`if [ "\${MEM_PCT:-0}" -ge ${n} ]; then ALERTS="$ALERTS mem=\${MEM_PCT}%"; ALERT_KEY="$ALERT_KEY memory"; fi`,"PREV=$(cat /var/lib/ts-cloud/alert-state 2>/dev/null || echo ok)",'if [ -n "$ALERTS" ]; then',` if [ "$PREV" != "$ALERT_KEY" ] && [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "⚠️ $(hostname): resource alert:$ALERTS"; then printf '%s\\n' "$ALERT_KEY" > ${"/var/lib/ts-cloud/alert-state"}; fi`,"else",` if [ "$PREV" != ok ] && [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "✅ $(hostname): resource usage back to normal"; then echo ok > ${"/var/lib/ts-cloud/alert-state"}; fi`,"fi",...c>0?["BW_TOTAL=$(( MONTH_RX + MONTH_TX ))",`BW_PCT=$(( BW_TOTAL * 100 / ${c} ))`,"BW_PREV=$(cat /var/lib/ts-cloud/bandwidth-alert-state 2>/dev/null || echo ok)",`if [ "$BW_PCT" -ge ${a} ]; then`,` if [ "$BW_PREV" != alert ] && [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "⚠️ $(hostname): bandwidth at \${BW_PCT}% of the ${i} TB monthly allowance ($MONTH_KEY)"; then echo alert > ${"/var/lib/ts-cloud/bandwidth-alert-state"}; fi`,"else",` if [ "$BW_PREV" = alert ] && [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "✅ $(hostname): bandwidth back under the monthly allowance (\${BW_PCT}%)"; then echo ok > ${"/var/lib/ts-cloud/bandwidth-alert-state"}; fi`,"fi"]:[],"TS_CLOUD_METRICS_EOF","chmod +x /usr/local/bin/ts-cloud-metrics.sh","cat > /etc/systemd/system/ts-cloud-metrics.service <<'TS_CLOUD_METRICS_SVC_EOF'","[Unit]","Description=ts-cloud metrics collector","","[Service]","Type=oneshot","ExecStart=/usr/local/bin/ts-cloud-metrics.sh","TS_CLOUD_METRICS_SVC_EOF","cat > /etc/systemd/system/ts-cloud-metrics.timer <<'TS_CLOUD_METRICS_TMR_EOF'","[Unit]","Description=Run ts-cloud metrics collector every minute","","[Timer]","OnCalendar=*-*-* *:*:00","AccuracySec=1s","RandomizedDelaySec=5s","Persistent=true","","[Install]","WantedBy=timers.target","TS_CLOUD_METRICS_TMR_EOF","systemctl daemon-reload","systemctl enable --now ts-cloud-metrics.timer","systemctl start ts-cloud-metrics.service"]}var Ea={"opcache.enable":"1","opcache.enable_cli":"1","opcache.memory_consumption":"256","opcache.interned_strings_buffer":"16","opcache.max_accelerated_files":"20000","opcache.validate_timestamps":"0","opcache.revalidate_freq":"0","opcache.save_comments":"1","opcache.fast_shutdown":"1",realpath_cache_size:"4096K",realpath_cache_ttl:"600"},Ra="127.0.0.1:9074";function fs(e){return Ra}function Oa(e={}){let t=e.versions?.length?e.versions:["8.3"];return e.default&&t.includes(e.default)?e.default:t[0]}function Da(e={}){return{...e.optimizeForProduction===!1?{}:{...Ea},...e.ini||{}}}function xa(e={}){let t=Da(e),r=Object.keys(t);if(r.length===0)return[];let n=r.map((i)=>`${i}=${t[i]}`),s="ts-cloud-managed";return[Oe(),"TS_CLOUD_SCAN_DIR=$(php -i 2>/dev/null | awk -F' => ' '/^Scan this dir for additional .ini files/{print $2}' | head -1)",`TS_CLOUD_LOADED_INI=$(php -r 'echo php_ini_loaded_file() ?: "";' 2>/dev/null)`,'if [ -n "$TS_CLOUD_SCAN_DIR" ] && [ "$TS_CLOUD_SCAN_DIR" != "(none)" ]; then',' mkdir -p "$TS_CLOUD_SCAN_DIR"',' TS_CLOUD_PHP_INI="$TS_CLOUD_SCAN_DIR/zz-ts-cloud.ini"',` cat > "$TS_CLOUD_PHP_INI" <<'TS_CLOUD_PHPINI_EOF'`,`; ${s} — production PHP tuning`,...n,"TS_CLOUD_PHPINI_EOF","else",' if [ -z "$TS_CLOUD_LOADED_INI" ]; then'," TS_CLOUD_INI_DIR=$(php -i 2>/dev/null | awk -F' => ' '/^Configuration File \\(php.ini\\) Path/{print $2}' | head -1)",' TS_CLOUD_LOADED_INI="$TS_CLOUD_INI_DIR/php.ini"',' mkdir -p "$TS_CLOUD_INI_DIR"',' touch "$TS_CLOUD_LOADED_INI"'," fi",` sed -i '/; ${s} BEGIN/,/; ${s} END/d' "$TS_CLOUD_LOADED_INI"`,` cat >> "$TS_CLOUD_LOADED_INI" <<'TS_CLOUD_PHPINI_EOF'`,`; ${s} BEGIN`,...n,`; ${s} END`,"TS_CLOUD_PHPINI_EOF","fi",`(cd ${p} && pantry restart php-fpm) 2>/dev/null || true`]}function cr(e={}){let t=Oa(e),r=e.installNginx!==!1,n=e.installComposer!==!1,s=[`php.net@${t}`];if(n)s.push("getcomposer.org");if(r)s.push("nginx.org");return[...Ce(s),...nr(["php-fpm"]),...xa(e)]}function pn(e,t){if(!e)return[];let r=[];if(e.template&&t?.[e.template])r.push(...t[e.template]);if(e.serverSnippet)r.push(...e.serverSnippet);return r}function Ia(e){if(!e)return"";let t=typeof e==="object"?e:{},n=[`max-age=${t.maxAge??31536000}`];if(t.includeSubDomains??!0)n.push("includeSubDomains");if(t.preload)n.push("preload");return` add_header Strict-Transport-Security "${n.join("; ")}" always;`}function Aa(e){if(!e||!e.allow?.length&&!e.deny?.length)return[];let t=[];for(let r of e.deny||[])t.push(` deny ${r};`);if(e.allow?.length){for(let r of e.allow)t.push(` allow ${r};`);t.push(" deny all;")}return t}function gs(e){return`/etc/nginx/.htpasswd-${e}`}var La=new Set(["laravel","php","statamic","wordpress"]);function Ua(e){return La.has(e)}function ka(e){return e==="laravel"||e==="statamic"?"public":""}function Ha(e,t){let r=e.replace(/\/+$/,""),n=t.replace(/^\/+|\/+$/g,"");return n?`${r}/${n}`:r}function Na(e){let t=e.type??"laravel",r=e.webDirectory??ka(t),n=Ha(e.appDir,r),s=Ua(t),i=e.phpVersion??"8.3",a=[` root ${n};`,"",' add_header X-Frame-Options "SAMEORIGIN";',' add_header X-Content-Type-Options "nosniff";'],c=Ia(e.hsts);if(c)a.push(c);for(let u of Aa(e.security))a.push(u);if(a.push("",` index ${s?"index.php index.html":"index.html index.htm"};`,""," charset utf-8;",""),e.clientMaxBodySize)a.push(` client_max_body_size ${e.clientMaxBodySize};`,"");if(e.auth)a.push(` auth_basic "${e.auth.realm||"Restricted"}";`,` auth_basic_user_file ${gs(e.siteName)};`,"");for(let[u,f]of Object.entries(e.redirects||{}))a.push(` location = ${u} { return 301 ${f}; }`);if(Object.keys(e.redirects||{}).length>0)a.push("");if(s){if(a.push(" location / {"," try_files $uri $uri/ /index.php?$query_string;"," }",""," location = /favicon.ico { access_log off; log_not_found off; }"," location = /robots.txt { access_log off; log_not_found off; }",""," error_page 404 /index.php;",""," location ~ \\.php$ {",` fastcgi_pass ${e.fastcgiPass??fs(i)};`," fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;"," include fastcgi_params;"," }",""," location ~ /\\.(?!well-known).* {"," deny all;"," }"),t==="wordpress")a.push(""," location = /xmlrpc.php { deny all; }"," location ~* /(?:wp-config\\.php|readme\\.html|license\\.txt)$ { deny all; }"," location ~* /wp-content/uploads/.*\\.php$ { deny all; }")}else if(t==="spa")a.push(" location / {"," try_files $uri $uri/ /index.html;"," }");else a.push(" location / {"," try_files $uri $uri/ =404;"," }");if(e.serverSnippet&&e.serverSnippet.length>0){a.push("");for(let u of e.serverSnippet)a.push(u?` ${u}`:"")}return a}function Ma(e){let t=[e.domain,...e.aliases||[]].filter(Boolean);for(let i of t)if(!/^(?=.{1,253}$)(?:\*\.)?[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i.test(i.trim()))throw Error(`Refusing to build a vhost: '${i}' is not a valid hostname.`);if(!t.length)throw Error("Refusing to build a vhost: no server_name (domain) was given.");let r=t.join(" "),n=Na(e);if(e.ssl){let i=["server {"," listen 80;"," listen [::]:80;",` server_name ${r};`," return 301 https://$host$request_uri;","}"],a=["server {"," listen 443 ssl;"," listen [::]:443 ssl;",` server_name ${r};`,` ssl_certificate ${e.ssl.certPath};`,` ssl_certificate_key ${e.ssl.keyPath};`,...e.tlsProtocols?.length?[` ssl_protocols ${e.tlsProtocols.join(" ")};`]:[],"",...n,"}"];return`${[...i,"",...a].join(`
22
22
  `)}
@@ -134,31 +134,31 @@ ${y.join(`
134
134
  `)}
135
135
  `}return v+=`
136
136
  echo "ts-cloud bootstrap complete — instance is ready for site deploys"
137
- `,v}var Ps="/aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id";function Es(e,t){let r=[{port:22,protocol:"tcp",cidr:"0.0.0.0/0"},{port:80,protocol:"tcp",cidr:"0.0.0.0/0"},{port:443,protocol:"tcp",cidr:"0.0.0.0/0"}],n=new Set;for(let s of Object.values(e.sites||{}))if(s&&typeof s.port==="number"&&![22,80,443].includes(s.port))n.add(s.port);for(let s of Ye(C(e,{environment:t})))n.add(s);for(let s of n)r.push({port:s,protocol:"tcp",cidr:"0.0.0.0/0"});return r}function Rs(e,t){let r={...e.infrastructure?.compute,proxy:w(e,{environment:t})},n=Je(e,{environment:t}),s=r.proxy?.engine==="rpx"?G({proxy:r.proxy,config:B(e.sites??{},{proxy:r.proxy,slug:e.project.slug,mail:C(e,{environment:t})}),slug:e.project.slug,bunBin:r.runtime==="node"||r.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0;return M({runtime:n.runtime,runtimeVersion:n.runtimeVersion,systemPackages:r.systemPackages,database:e.infrastructure?.database,phpProvision:n.phpProvision,servicesProvision:n.servicesProvision,rpxProvision:s,baked:r.bakedImage===!0,swapGb:r.swapGb})}function Os(e){return Buffer.from(e,"utf8").toString("base64")}function Ds(e){return e.infrastructure?.compute?.image??null}function ur(e,t){return`${e}-${t}-app-sg`}function gn(e,t,r="app"){return[{Key:"Project",Value:e},{Key:"Environment",Value:t},{Key:"Role",Value:r},{Key:"ManagedBy",Value:"ts-cloud"}]}function Ya(e,t,r){if(!e?.length)return!1;let n=(s)=>e.find((i)=>i.Key===s)?.Value;return n("Project")===t&&n("Environment")===r}function xs(e,t){let r=ur(t.slug,t.environment);return e.find((n)=>{if(n.GroupName!==r)return!1;if(t.vpcId&&n.VpcId&&n.VpcId!==t.vpcId)return!1;if(!!n.Tags?.some((i)=>i.Key==="Project"))return Ya(n.Tags,t.slug,t.environment);return!!t.vpcId&&n.VpcId===t.vpcId})}function Ja(e){try{let t=Is(Xa(process.cwd(),"storage/cloud/state",`${e}.json`),"utf8"),r=JSON.parse(t);return typeof r.instanceId==="string"&&r.instanceId.length>0?r.instanceId:null}catch{return null}}class Lr{name="aws";usesCloudFormation=!0;region;ec2Client;cfnClient;constructor(e={}){this.region=e.region||"us-east-1",this.ec2Client=e.ec2Client??((t)=>new Vr(t)),this.cfnClient=e.cfnClient??((t)=>new A(t))}resolveRegion(e){return e.project.region||this.region}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e,n=this.resolveRegion(t),s=t.project.slug,i=t.infrastructure?.compute;if(!i)throw Error("infrastructure.compute is required to provision AWS compute");let a=this.ec2Client(n),c=await this.findComputeTargets({slug:s,environment:r,role:"app",region:n});if(c.length>0){let W=c[0];return{appInstanceId:W.id,appPublicIp:W.publicIp,appPublicIpv6:W.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}let u=Ds(t);if(!u){if(u=(await new Be(n).getParameter({Name:Ps})).Parameter?.Value??null,!u)throw Error("Could not resolve the Ubuntu 24.04 AMI from SSM")}let f=await a.describeVpcs(),h=(f.Vpcs||[]).find((W)=>W.IsDefault)||(f.Vpcs||[])[0];if(!h?.VpcId)throw Error("No VPC found to launch the instance into");let S=(await a.describeSubnets({Filters:[{Name:"vpc-id",Values:[h.VpcId]}]})).Subnets||[],v=S.find((W)=>W.MapPublicIpOnLaunch)||S[0],_=v?.SubnetId;if(!v?.MapPublicIpOnLaunch)console.warn("ts-cloud: no public subnet found; the instance may not get a public IP (deploys/SSL need one).");let y=ur(s,r),D=(await a.describeSecurityGroups({Filters:[{Name:"group-name",Values:[y]},{Name:"vpc-id",Values:[h.VpcId]}]})).SecurityGroups?.[0]?.GroupId;if(!D)D=(await a.createSecurityGroup({GroupName:y,Description:`ts-cloud ${s}/${r} app`,VpcId:h.VpcId,TagSpecifications:[{ResourceType:"security-group",Tags:gn(s,r)}]})).GroupId;let V=Es(t,r);await a.authorizeSecurityGroupIngress({GroupId:D,IpPermissions:V.map((W)=>({IpProtocol:W.protocol,FromPort:W.port,ToPort:W.port,IpRanges:[{CidrIp:W.cidr}]}))}).catch((W)=>{if(!/InvalidPermission\.Duplicate/.test(W instanceof Error?W.message:""))throw W});let H=Os(Rs(t,r)),x=i.server?.instanceType||"t3.small",I=(await a.runInstances({ImageId:u,InstanceType:x,MinCount:1,MaxCount:1,SecurityGroupIds:D?[D]:void 0,SubnetId:_,UserData:H,IamInstanceProfile:i.server?.iamInstanceProfile?{Name:i.server.iamInstanceProfile}:void 0,TagSpecifications:[{ResourceType:"instance",Tags:[{Key:"Name",Value:`${s}-${r}-app`},...gn(s,r)]}]})).Instances?.[0]?.InstanceId;if(!I)throw Error("RunInstances did not return an instance id");let Y=await a.waitForInstanceState(I,"running");if(!Y)throw Error(`Instance ${I} did not reach 'running' before timeout`);return{appInstanceId:I,appPublicIp:Y.PublicIpAddress,appPublicIpv6:De(Y.Ipv6Address),sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}async destroyCompute(e){let{config:t,environment:r}=e,n=t.project.slug,s=this.resolveRegion(t),i=this.ec2Client(s),a=[],u=(await this.findComputeTargets({slug:n,environment:r,role:"app",region:s})).map((y)=>y.id),f;if(u.length>0)f=(await i.describeInstances({InstanceIds:u}).catch(()=>({Reservations:[]}))).Reservations?.flatMap((b)=>b.Instances??[]).find((b)=>b.VpcId)?.VpcId;if(u.length>0)await i.terminateInstances(u),a.push(...u.map((y)=>`instance ${y}`)),await Promise.all(u.map((y)=>i.waitForInstanceState(y,"terminated").catch(()=>{return})));let h=ur(n,r),S=[{Name:"group-name",Values:[h]}];if(f)S.push({Name:"vpc-id",Values:[f]});let v=await i.describeSecurityGroups({Filters:S}).catch(()=>({SecurityGroups:[]})),_=xs(v.SecurityGroups??[],{slug:n,environment:r,vpcId:f});if(_?.GroupId)for(let y=0;y<10;y++)try{await i.deleteSecurityGroup(_.GroupId),a.push(`security group ${h}`);break}catch{await new Promise((b)=>setTimeout(b,3000))}return{destroyed:a}}async getComputeOutputs(e){let t=this.resolveRegion(e.config),r=m(e.config,e.environment),n=this.cfnClient(t);try{let s=await n.getStackOutputs(r);return{deployBucketName:s.deployBucketName,appInstanceId:s.appInstanceId,appPublicIp:s.appPublicIp,sshUser:"ec2-user"}}catch(s){if(!/does not exist|ValidationError/i.test(s instanceof Error?s.message:""))throw s;let a=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",region:t}))[0];return{appInstanceId:a?.id,appPublicIp:a?.publicIp,appPublicIpv6:a?.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}}async uploadRelease(e){let t=this.resolveRegion(e.config),n=(await this.getComputeOutputs({config:e.config,environment:e.environment})).deployBucketName;if(!n)throw Error("No deployBucketName in stack outputs. Re-deploy infrastructure to add the staging bucket.");return await new o(t).putObject({bucket:n,key:e.remoteKey,body:Is(e.localPath),contentType:"application/gzip"}),{artifactRef:`s3://${n}/${e.remoteKey}`}}async findComputeTargets(e){let t=e.region??this.region,r=this.ec2Client(t),n=[{Name:"tag:Project",Values:[e.slug]},{Name:"tag:Environment",Values:[e.environment]},{Name:"tag:Role",Values:[e.role||"app"]},{Name:"instance-state-name",Values:["running","pending"]}],s=await r.describeInstances({Filters:n}),i=this.reservationsToTargets(s.Reservations);if(i.length>0||(e.role||"app")!=="app")return i;let a=e.stackName??`${e.slug}-${e.environment}`,c=Ja(a);if(!c)try{c=(await this.cfnClient(t).getStackOutputs(a)).appInstanceId??null}catch{c=null}if(!c)return[];try{let u=await r.describeInstances({InstanceIds:[c],Filters:[{Name:"instance-state-name",Values:["running","pending"]}]});return this.reservationsToTargets(u.Reservations)}catch{return[]}}reservationsToTargets(e){let t=[];for(let r of e||[])for(let n of r.Instances||[]){if(!n.InstanceId)continue;let s=n.Tags?.find((i)=>i.Key==="Name")?.Value;t.push({id:n.InstanceId,name:s,publicIp:n.PublicIpAddress,publicIpv6:De(n.Ipv6Address),privateIp:n.PrivateIpAddress,status:n.State?.Name})}return t}bashWrap(e){return["bash <<'TS_CLOUD_BASH_EOF'",e.join(`
138
- `),"TS_CLOUD_BASH_EOF"]}async runRemoteDeploy(e){let t=this.region,r=new Be(t);if(e.targets.length>0){let s=await r.sendCommand({InstanceIds:e.targets.map((i)=>i.id),DocumentName:"AWS-RunShellScript",Parameters:{commands:this.bashWrap(e.commands)},TimeoutSeconds:e.timeoutSeconds||600,Comment:e.comment});if(!s.CommandId)return{success:!1,instanceCount:0,perInstance:[],error:"Failed to send SSM command"};return this.pollSsmCommand(r,s.CommandId,e.targets.length,((e.timeoutSeconds||600)+30)*1000)}if(!e.tags||Object.keys(e.tags).length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets or tags provided for AWS deploy"};let n=await r.sendCommandByTags({tags:e.tags,commands:this.bashWrap(e.commands),timeoutSeconds:e.timeoutSeconds||600,comment:e.comment});return{success:n.success,instanceCount:n.instanceCount,perInstance:n.perInstance.map((s)=>({instanceId:s.instanceId,status:s.status,output:s.output,error:s.error})),error:n.error}}async pollSsmCommand(e,t,r,n=600000){let i=Date.now(),a=new Set(["Success","Failed","Cancelled","TimedOut"]),c=[];while(Date.now()-i<n){await new Promise((h)=>setTimeout(h,3000));try{if(c=await e.listCommandInvocations({CommandId:t,Details:!0}),c.length>=r&&c.every((S)=>a.has(S.Status||"")))break}catch{}}let u=c.map((h)=>({instanceId:h.InstanceId,status:h.Status||"Unknown",output:h.StandardOutputContent,error:h.StandardErrorContent})),f=u.length>0&&u.every((h)=>h.status==="Success");return{success:f,instanceCount:u.length,perInstance:u,error:f?void 0:Xt(u,"One or more SSM command invocations failed")}}}import{execFileSync as nl,execSync as go}from"node:child_process";import{createHash as sl,randomUUID as ho}from"node:crypto";import{createReadStream as ol,existsSync as al,readFileSync as cl}from"node:fs";async function As(e,t){let r=await import("node:fs"),n=await import("node:path"),s=await import("node:child_process"),i="/etc/ts-cloud/compute-storage.json",a="/var/lib/ts-cloud/compute-storage-state.json",c="/run/ts-cloud-root-web",u=t[0]??"status";if(!["plan","status","check","apply","ensure-site","reclaim"].includes(u))throw Error(`Unknown compute storage command: ${u}`);let f=(T,L)=>{try{return JSON.parse(r.readFileSync(T,"utf8"))}catch(P){if(P.code==="ENOENT")return L;throw P}},h=(T,L)=>{r.mkdirSync(n.dirname(T),{recursive:!0});let P=`${T}.${process.pid}.tmp`;r.writeFileSync(P,`${JSON.stringify(L,null,2)}
139
- `,{mode:420}),r.renameSync(P,T)},S=(T,L)=>s.execFileSync(T,L,{encoding:"utf8",maxBuffer:16777216}),v=(T,L)=>{let P=s.spawnSync(T,L,{encoding:"utf8"});return P.status===0?P.stdout.trim():""},_=(T)=>!!v("findmnt",["-n","--mountpoint",T]),y=(T,L)=>{try{let P=r.statSync(T),R=r.statSync(L);return P.dev===R.dev&&P.ino===R.ino}catch{return!1}},b=f("/var/lib/ts-cloud/compute-storage-state.json",{entries:[]}),D=e.deploymentStorage,V=e.volumes.find((T)=>T.key===D?.volume),H=(T,L)=>{if(!V)return[];let P=[];for(let R of r.readdirSync(e.webRoot,{withFileTypes:!0})){if(!R.isDirectory()||R.isSymbolicLink())continue;let O=n.join(e.webRoot,R.name);if(T&&O!==T&&O!==n.join(e.webRoot,`${L}-shared`))continue;for(let J of["releases",...D?.includeBackups===!1?[]:["backups"]]){let q=n.join(O,J);if(!r.existsSync(q)||!r.lstatSync(q).isDirectory())continue;P.push({source:q,destination:n.join(V.mountPath,J,R.name)})}}return P},x=(T)=>{try{return _(T.mountPath)&&r.statSync(T.mountPath).dev===r.statSync(T.device).rdev}catch{return!1}},k=(T)=>{let L=r.statfsSync(T),P=(L.blocks-L.bfree)*L.bsize,R=L.bavail*L.bsize;return{path:T,sizeBytes:L.blocks*L.bsize,usedBytes:P,availableBytes:R,usedPercent:Math.ceil(100*P/(P+R))}},I=()=>{let T=[],L=[k("/")];for(let R of e.volumes)if(!x(R))T.push(`missing or incorrect volume mount: ${R.mountPath}`);else L.push(k(R.mountPath));for(let R of b.entries)if(!_(R.source)||!y(R.source,R.destination))T.push(`missing deployment mount: ${R.source}`);let P=new Set(b.entries.map((R)=>R.source));for(let R of H())if(!P.has(R.source))T.push(`deployment needs volume placement: ${R.source}`);return{timestamp:new Date().toISOString(),volumes:e.volumes.map((R)=>({key:R.key,name:R.name,id:R.id,size:R.size,mountPath:R.mountPath})),disks:L,mounts:b.entries.length,problems:T}};if(u==="plan")return console.log(JSON.stringify({volumes:e.volumes,entries:H(),state:b},null,2));if(u==="status"||u==="check"){let T=I();if(u==="check"){h("/var/lib/ts-cloud/compute-storage-status.json",T);let L="/var/lib/ts-cloud/compute-storage-alert.json",P=f(L,{problems:[]});if(JSON.stringify(P.problems)!==JSON.stringify(T.problems)){let R=T.problems.join("; ")||"all configured mounts are healthy",O=`${T.problems.length?"Storage alert":"Storage recovered"} on ${v("hostname",[])}: ${R}`;S("/usr/local/bin/ts-cloud-notify",[O.length>1800?`${O.slice(0,1600)}... Full report: /var/lib/ts-cloud/compute-storage-status.json`:O])}h(L,{problems:T.problems,timestamp:T.timestamp})}if(console.log(JSON.stringify(T)),T.problems.length)process.exitCode=1;return T}if(process.getuid?.()!==0)throw Error("Compute storage changes require root");let Y=()=>{let R=r.readFileSync("/etc/fstab","utf8");if(!r.existsSync("/etc/fstab.before-ts-cloud-storage"))r.copyFileSync("/etc/fstab","/etc/fstab.before-ts-cloud-storage");let O=[];for(let X of e.volumes){let Z=S("blkid",["-s","UUID","-o","value",X.device]).trim();if(!Z)throw Error(`Volume ${X.name} has no filesystem UUID`);O.push(`UUID=${Z} ${X.mountPath} ext4 defaults,noatime,nodev,nosuid,nofail,x-systemd.device-timeout=30s 0 2`)}for(let X of b.entries)O.push(`${X.destination} ${X.source} none bind,nofail,x-systemd.requires-mounts-for=${V.mountPath} 0 0`);let J=`# BEGIN ts-cloud compute storage
140
- ${O.join(`
137
+ `,v}var Ps="/aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id";function Es(e,t){let r=[{port:22,protocol:"tcp",cidr:"0.0.0.0/0"},{port:80,protocol:"tcp",cidr:"0.0.0.0/0"},{port:443,protocol:"tcp",cidr:"0.0.0.0/0"}],n=new Set;for(let s of Object.values(e.sites||{}))if(s&&typeof s.port==="number"&&![22,80,443].includes(s.port))n.add(s.port);for(let s of Ye(C(e,{environment:t})))n.add(s);for(let s of n)r.push({port:s,protocol:"tcp",cidr:"0.0.0.0/0"});return r}function Rs(e,t){let r={...e.infrastructure?.compute,proxy:w(e,{environment:t})},n=Je(e,{environment:t}),s=r.proxy?.engine==="rpx"?G({proxy:r.proxy,config:B(e.sites??{},{proxy:r.proxy,slug:e.project.slug,mail:C(e,{environment:t})}),slug:e.project.slug,bunBin:r.runtime==="node"||r.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0;return M({runtime:n.runtime,runtimeVersion:n.runtimeVersion,systemPackages:r.systemPackages,database:e.infrastructure?.database,phpProvision:n.phpProvision,servicesProvision:n.servicesProvision,rpxProvision:s,baked:r.bakedImage===!0,swapGb:r.swapGb})}function Os(e){return Buffer.from(e,"utf8").toString("base64")}function Ds(e){return e.infrastructure?.compute?.image??null}function ur(e,t){return`${e}-${t}-app-sg`}function gn(e,t,r="app"){return[{Key:"Project",Value:e},{Key:"Environment",Value:t},{Key:"Role",Value:r},{Key:"ManagedBy",Value:"ts-cloud"}]}function Ya(e,t,r){if(!e?.length)return!1;let n=(s)=>e.find((i)=>i.Key===s)?.Value;return n("Project")===t&&n("Environment")===r}function xs(e,t){let r=ur(t.slug,t.environment);return e.find((n)=>{if(n.GroupName!==r)return!1;if(t.vpcId&&n.VpcId&&n.VpcId!==t.vpcId)return!1;if(!!n.Tags?.some((i)=>i.Key==="Project"))return Ya(n.Tags,t.slug,t.environment);return!!t.vpcId&&n.VpcId===t.vpcId})}function Ja(e){try{let t=Is(Xa(process.cwd(),"storage/cloud/state",`${e}.json`),"utf8"),r=JSON.parse(t);return typeof r.instanceId==="string"&&r.instanceId.length>0?r.instanceId:null}catch{return null}}class Lr{name="aws";usesCloudFormation=!0;region;ec2Client;cfnClient;constructor(e={}){this.region=e.region||"us-east-1",this.ec2Client=e.ec2Client??((t)=>new Vr(t)),this.cfnClient=e.cfnClient??((t)=>new A(t))}resolveRegion(e){return e.project.region||this.region}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e,n=this.resolveRegion(t),s=t.project.slug,i=t.infrastructure?.compute;if(!i)throw Error("infrastructure.compute is required to provision AWS compute");let a=this.ec2Client(n),c=await this.findComputeTargets({slug:s,environment:r,role:"app",region:n});if(c.length>0){let q=c[0];return{appInstanceId:q.id,appPublicIp:q.publicIp,appPublicIpv6:q.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}let u=Ds(t);if(!u){if(u=(await new Be(n).getParameter({Name:Ps})).Parameter?.Value??null,!u)throw Error("Could not resolve the Ubuntu 24.04 AMI from SSM")}let f=await a.describeVpcs(),h=(f.Vpcs||[]).find((q)=>q.IsDefault)||(f.Vpcs||[])[0];if(!h?.VpcId)throw Error("No VPC found to launch the instance into");let S=(await a.describeSubnets({Filters:[{Name:"vpc-id",Values:[h.VpcId]}]})).Subnets||[],v=S.find((q)=>q.MapPublicIpOnLaunch)||S[0],_=v?.SubnetId;if(!v?.MapPublicIpOnLaunch)console.warn("ts-cloud: no public subnet found; the instance may not get a public IP (deploys/SSL need one).");let y=ur(s,r),x=(await a.describeSecurityGroups({Filters:[{Name:"group-name",Values:[y]},{Name:"vpc-id",Values:[h.VpcId]}]})).SecurityGroups?.[0]?.GroupId;if(!x)x=(await a.createSecurityGroup({GroupName:y,Description:`ts-cloud ${s}/${r} app`,VpcId:h.VpcId,TagSpecifications:[{ResourceType:"security-group",Tags:gn(s,r)}]})).GroupId;let W=Es(t,r);await a.authorizeSecurityGroupIngress({GroupId:x,IpPermissions:W.map((q)=>({IpProtocol:q.protocol,FromPort:q.port,ToPort:q.port,IpRanges:[{CidrIp:q.cidr}]}))}).catch((q)=>{if(!/InvalidPermission\.Duplicate/.test(q instanceof Error?q.message:""))throw q});let H=Os(Rs(t,r)),R=i.server?.instanceType||"t3.small",I=(await a.runInstances({ImageId:u,InstanceType:R,MinCount:1,MaxCount:1,SecurityGroupIds:x?[x]:void 0,SubnetId:_,UserData:H,IamInstanceProfile:i.server?.iamInstanceProfile?{Name:i.server.iamInstanceProfile}:void 0,TagSpecifications:[{ResourceType:"instance",Tags:[{Key:"Name",Value:`${s}-${r}-app`},...gn(s,r)]}]})).Instances?.[0]?.InstanceId;if(!I)throw Error("RunInstances did not return an instance id");let V=await a.waitForInstanceState(I,"running");if(!V)throw Error(`Instance ${I} did not reach 'running' before timeout`);return{appInstanceId:I,appPublicIp:V.PublicIpAddress,appPublicIpv6:De(V.Ipv6Address),sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}async destroyCompute(e){let{config:t,environment:r}=e,n=t.project.slug,s=this.resolveRegion(t),i=this.ec2Client(s),a=[],u=(await this.findComputeTargets({slug:n,environment:r,role:"app",region:s})).map((y)=>y.id),f;if(u.length>0)f=(await i.describeInstances({InstanceIds:u}).catch(()=>({Reservations:[]}))).Reservations?.flatMap((T)=>T.Instances??[]).find((T)=>T.VpcId)?.VpcId;if(u.length>0)await i.terminateInstances(u),a.push(...u.map((y)=>`instance ${y}`)),await Promise.all(u.map((y)=>i.waitForInstanceState(y,"terminated").catch(()=>{return})));let h=ur(n,r),S=[{Name:"group-name",Values:[h]}];if(f)S.push({Name:"vpc-id",Values:[f]});let v=await i.describeSecurityGroups({Filters:S}).catch(()=>({SecurityGroups:[]})),_=xs(v.SecurityGroups??[],{slug:n,environment:r,vpcId:f});if(_?.GroupId)for(let y=0;y<10;y++)try{await i.deleteSecurityGroup(_.GroupId),a.push(`security group ${h}`);break}catch{await new Promise((T)=>setTimeout(T,3000))}return{destroyed:a}}async getComputeOutputs(e){let t=this.resolveRegion(e.config),r=m(e.config,e.environment),n=this.cfnClient(t);try{let s=await n.getStackOutputs(r);return{deployBucketName:s.deployBucketName,appInstanceId:s.appInstanceId,appPublicIp:s.appPublicIp,sshUser:"ec2-user"}}catch(s){if(!/does not exist|ValidationError/i.test(s instanceof Error?s.message:""))throw s;let a=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",region:t}))[0];return{appInstanceId:a?.id,appPublicIp:a?.publicIp,appPublicIpv6:a?.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}}async uploadRelease(e){let t=this.resolveRegion(e.config),n=(await this.getComputeOutputs({config:e.config,environment:e.environment})).deployBucketName;if(!n)throw Error("No deployBucketName in stack outputs. Re-deploy infrastructure to add the staging bucket.");return await new o(t).putObject({bucket:n,key:e.remoteKey,body:Is(e.localPath),contentType:"application/gzip"}),{artifactRef:`s3://${n}/${e.remoteKey}`}}async findComputeTargets(e){let t=e.region??this.region,r=this.ec2Client(t),n=[{Name:"tag:Project",Values:[e.slug]},{Name:"tag:Environment",Values:[e.environment]},{Name:"tag:Role",Values:[e.role||"app"]},{Name:"instance-state-name",Values:["running","pending"]}],s=await r.describeInstances({Filters:n}),i=this.reservationsToTargets(s.Reservations);if(i.length>0||(e.role||"app")!=="app")return i;let a=e.stackName??`${e.slug}-${e.environment}`,c=Ja(a);if(!c)try{c=(await this.cfnClient(t).getStackOutputs(a)).appInstanceId??null}catch{c=null}if(!c)return[];try{let u=await r.describeInstances({InstanceIds:[c],Filters:[{Name:"instance-state-name",Values:["running","pending"]}]});return this.reservationsToTargets(u.Reservations)}catch{return[]}}reservationsToTargets(e){let t=[];for(let r of e||[])for(let n of r.Instances||[]){if(!n.InstanceId)continue;let s=n.Tags?.find((i)=>i.Key==="Name")?.Value;t.push({id:n.InstanceId,name:s,publicIp:n.PublicIpAddress,publicIpv6:De(n.Ipv6Address),privateIp:n.PrivateIpAddress,status:n.State?.Name})}return t}bashWrap(e){return["bash <<'TS_CLOUD_BASH_EOF'",e.join(`
138
+ `),"TS_CLOUD_BASH_EOF"]}async runRemoteDeploy(e){let t=this.region,r=new Be(t);if(e.targets.length>0){let s=await r.sendCommand({InstanceIds:e.targets.map((i)=>i.id),DocumentName:"AWS-RunShellScript",Parameters:{commands:this.bashWrap(e.commands)},TimeoutSeconds:e.timeoutSeconds||600,Comment:e.comment});if(!s.CommandId)return{success:!1,instanceCount:0,perInstance:[],error:"Failed to send SSM command"};return this.pollSsmCommand(r,s.CommandId,e.targets.length,((e.timeoutSeconds||600)+30)*1000)}if(!e.tags||Object.keys(e.tags).length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets or tags provided for AWS deploy"};let n=await r.sendCommandByTags({tags:e.tags,commands:this.bashWrap(e.commands),timeoutSeconds:e.timeoutSeconds||600,comment:e.comment});return{success:n.success,instanceCount:n.instanceCount,perInstance:n.perInstance.map((s)=>({instanceId:s.instanceId,status:s.status,output:s.output,error:s.error})),error:n.error}}async pollSsmCommand(e,t,r,n=600000){let i=Date.now(),a=new Set(["Success","Failed","Cancelled","TimedOut"]),c=[];while(Date.now()-i<n){await new Promise((h)=>setTimeout(h,3000));try{if(c=await e.listCommandInvocations({CommandId:t,Details:!0}),c.length>=r&&c.every((S)=>a.has(S.Status||"")))break}catch{}}let u=c.map((h)=>({instanceId:h.InstanceId,status:h.Status||"Unknown",output:h.StandardOutputContent,error:h.StandardErrorContent})),f=u.length>0&&u.every((h)=>h.status==="Success");return{success:f,instanceCount:u.length,perInstance:u,error:f?void 0:Xt(u,"One or more SSM command invocations failed")}}}import{execFileSync as nl,execSync as go}from"node:child_process";import{createHash as sl,randomUUID as ho}from"node:crypto";import{createReadStream as ol,existsSync as al,readFileSync as cl}from"node:fs";async function As(e,t){let r=await import("node:fs"),n=await import("node:path"),s=await import("node:child_process"),i="/etc/ts-cloud/compute-storage.json",a="/var/lib/ts-cloud/compute-storage-state.json",c="/run/ts-cloud-root-web",u=t[0]??"status";if(!["plan","status","check","apply","ensure-site","reclaim"].includes(u))throw Error(`Unknown compute storage command: ${u}`);let f=(b,k)=>{try{return JSON.parse(r.readFileSync(b,"utf8"))}catch(P){if(P.code==="ENOENT")return k;throw P}},h=(b,k)=>{r.mkdirSync(n.dirname(b),{recursive:!0});let P=`${b}.${process.pid}.tmp`;r.writeFileSync(P,`${JSON.stringify(k,null,2)}
139
+ `,{mode:420}),r.renameSync(P,b)},S=(b,k)=>s.execFileSync(b,k,{encoding:"utf8",maxBuffer:16777216}),v=(b,k)=>{let P=s.spawnSync(b,k,{encoding:"utf8"});return P.status===0?P.stdout.trim():""},_=(b)=>!!v("findmnt",["-n","--mountpoint",b]),y=(b,k)=>{try{let P=r.statSync(b),O=r.statSync(k);return P.dev===O.dev&&P.ino===O.ino}catch{return!1}},T=f("/var/lib/ts-cloud/compute-storage-state.json",{entries:[]}),x=e.deploymentStorage,W=e.volumes.find((b)=>b.key===x?.volume),H=(b,k)=>{if(!W)return[];let P=[];for(let O of r.readdirSync(e.webRoot,{withFileTypes:!0})){if(!O.isDirectory()||O.isSymbolicLink())continue;let D=n.join(e.webRoot,O.name);if(b&&D!==b&&D!==n.join(e.webRoot,`${k}-shared`))continue;for(let J of["releases",...x?.includeBackups===!1?[]:["backups"]]){let Y=n.join(D,J);if(!r.existsSync(Y)||!r.lstatSync(Y).isDirectory())continue;P.push({source:Y,destination:n.join(W.mountPath,J,O.name)})}}return P},R=(b)=>{try{return _(b.mountPath)&&r.statSync(b.mountPath).dev===r.statSync(b.device).rdev}catch{return!1}},L=(b)=>{let k=r.statfsSync(b),P=(k.blocks-k.bfree)*k.bsize,O=k.bavail*k.bsize;return{path:b,sizeBytes:k.blocks*k.bsize,usedBytes:P,availableBytes:O,usedPercent:Math.ceil(100*P/(P+O))}},I=()=>{let b=[],k=[L("/")];for(let O of e.volumes)if(!R(O))b.push(`missing or incorrect volume mount: ${O.mountPath}`);else k.push(L(O.mountPath));for(let O of T.entries)if(!_(O.source)||!y(O.source,O.destination))b.push(`missing deployment mount: ${O.source}`);let P=new Set(T.entries.map((O)=>O.source));for(let O of H())if(!P.has(O.source))b.push(`deployment needs volume placement: ${O.source}`);return{timestamp:new Date().toISOString(),volumes:e.volumes.map((O)=>({key:O.key,name:O.name,id:O.id,size:O.size,mountPath:O.mountPath})),disks:k,mounts:T.entries.length,problems:b}};if(u==="plan")return console.log(JSON.stringify({volumes:e.volumes,entries:H(),state:T},null,2));if(u==="status"||u==="check"){let b=I();if(u==="check"){h("/var/lib/ts-cloud/compute-storage-status.json",b);let k="/var/lib/ts-cloud/compute-storage-alert.json",P=f(k,{problems:[]});if(JSON.stringify(P.problems)!==JSON.stringify(b.problems)){let O=b.problems.join("; ")||"all configured mounts are healthy",D=`${b.problems.length?"Storage alert":"Storage recovered"} on ${v("hostname",[])}: ${O}`;S("/usr/local/bin/ts-cloud-notify",[D.length>1800?`${D.slice(0,1600)}... Full report: /var/lib/ts-cloud/compute-storage-status.json`:D])}h(k,{problems:b.problems,timestamp:b.timestamp})}if(console.log(JSON.stringify(b)),b.problems.length)process.exitCode=1;return b}if(process.getuid?.()!==0)throw Error("Compute storage changes require root");let V=()=>{let O=r.readFileSync("/etc/fstab","utf8");if(!r.existsSync("/etc/fstab.before-ts-cloud-storage"))r.copyFileSync("/etc/fstab","/etc/fstab.before-ts-cloud-storage");let D=[];for(let X of e.volumes){let Z=S("blkid",["-s","UUID","-o","value",X.device]).trim();if(!Z)throw Error(`Volume ${X.name} has no filesystem UUID`);D.push(`UUID=${Z} ${X.mountPath} ext4 defaults,noatime,nodev,nosuid,nofail,x-systemd.device-timeout=30s 0 2`)}for(let X of T.entries)D.push(`${X.destination} ${X.source} none bind,nofail,x-systemd.requires-mounts-for=${W.mountPath} 0 0`);let J=`# BEGIN ts-cloud compute storage
140
+ ${D.join(`
141
141
  `)}
142
- # END ts-cloud compute storage`,q;if(R.includes("# BEGIN ts-cloud compute storage")){let X=R.indexOf("# BEGIN ts-cloud compute storage"),Z=R.indexOf("# END ts-cloud compute storage",X);if(Z<0)throw Error("Incomplete managed storage block in fstab");q=R.slice(0,X)+J+R.slice(Z+30)}else q=`${R.trimEnd()}
142
+ # END ts-cloud compute storage`,Y;if(O.includes("# BEGIN ts-cloud compute storage")){let X=O.indexOf("# BEGIN ts-cloud compute storage"),Z=O.indexOf("# END ts-cloud compute storage",X);if(Z<0)throw Error("Incomplete managed storage block in fstab");Y=O.slice(0,X)+J+O.slice(Z+30)}else Y=`${O.trimEnd()}
143
143
  ${J}
144
- `;r.writeFileSync("/etc/fstab.ts-cloud-new",q),r.renameSync("/etc/fstab.ts-cloud-new","/etc/fstab")},W=()=>{for(let T of e.volumes){if(!r.existsSync(T.device)||!r.statSync(T.device).isBlockDevice())throw Error(`Volume device missing: ${T.device}`);let L=v("blkid",["-s","TYPE","-o","value",T.device]);if(!L){if(!T.allowFormat)throw Error(`Refusing to format adopted volume ${T.name}; no recognized filesystem`);S("mkfs.ext4",["-m","1",T.device]),L="ext4"}if(L!=="ext4")throw Error(`Refusing to replace ${L} filesystem on ${T.name}`);if(r.mkdirSync(T.mountPath,{recursive:!0}),_(T.mountPath)&&!x(T))throw Error(`Another filesystem occupies ${T.mountPath}`);if(!_(T.mountPath)&&r.readdirSync(T.mountPath).length)throw Error(`Refusing to hide existing files beneath ${T.mountPath}`);if(!_(T.mountPath))S("mount",["-o","noatime,nodev,nosuid",T.device,T.mountPath]);if(!x(T))throw Error(`Volume identity verification failed: ${T.name}`);S("resize2fs",[T.device]),T.allowFormat=!1}h("/etc/ts-cloud/compute-storage.json",e),Y(),S("systemctl",["daemon-reload"])},{dlopen:K,read:ee}=await import("bun:ffi"),re=K("libc.so.6",{flock:{args:["i32","i32"],returns:"i32"},__errno_location:{args:[],returns:"ptr"}}),te=[],ie=(T,L=!0)=>{r.mkdirSync(n.dirname(T),{recursive:!0});let P=r.openSync(T,r.constants.O_CREAT|r.constants.O_RDWR|r.constants.O_NOFOLLOW,384);if(re.symbols.flock(P,L?2:6)!==0){let R=ee.i32(re.symbols.__errno_location());if(r.closeSync(P),!L&&R===11)return!1;throw Error(`Could not acquire lock: ${T} (errno ${R})`)}return te.push(P),!0},oe=()=>{let T=[];for(let L of r.readdirSync("/proc").filter((P)=>/^\d+$/.test(P))){let P=[];try{P=r.readdirSync(`/proc/${L}/fd`)}catch{continue}for(let R of["cwd","exe",...P.map((O)=>`fd/${O}`)]){let O=`/proc/${L}/${R}`;try{let J=r.readlinkSync(O);if(!J.startsWith(`${e.webRoot}/`)||!J.includes("/releases/"))continue;let q=!1;if(R.startsWith("fd/")){let X=r.readFileSync(`/proc/${L}/fdinfo/${R.slice(3)}`,"utf8").match(/^flags:\s+(\d+)/m);q=!!X&&(Number.parseInt(X[1],8)&3)!==0&&r.statSync(O).isFile()}T.push({file:J,write:q,device:r.statSync(O).dev})}catch{}}}return T},ne=async(T,L)=>{r.mkdirSync(T.destination,{recursive:!0});let P=["rsync","-aHAXx","--numeric-ids","--delete",...L?["--checksum"]:[],`${T.source}/`,`${T.destination}/`],O=await Bun.spawn(P,{stdout:"inherit",stderr:"inherit"}).exited;if(O!==0&&!(O===24&&!L))throw Error(`rsync failed (${O}): ${T.source}`)},he=async()=>{let T=S("systemctl",["list-units","--type=service","--state=running","--no-legend","--plain"]).split(`
145
- `).map((q)=>q.trim().split(/\s+/)[0]).filter(Boolean),L={};if(T.length){let q=S("systemctl",["show",...T,"-p","Id","-p","MainPID","-p","WorkingDirectory"]);for(let X of q.split(`
144
+ `;r.writeFileSync("/etc/fstab.ts-cloud-new",Y),r.renameSync("/etc/fstab.ts-cloud-new","/etc/fstab")},q=()=>{for(let b of e.volumes){if(!r.existsSync(b.device)||!r.statSync(b.device).isBlockDevice())throw Error(`Volume device missing: ${b.device}`);let k=v("blkid",["-s","TYPE","-o","value",b.device]);if(!k){if(!b.allowFormat)throw Error(`Refusing to format adopted volume ${b.name}; no recognized filesystem`);S("mkfs.ext4",["-m","1",b.device]),k="ext4"}if(k!=="ext4")throw Error(`Refusing to replace ${k} filesystem on ${b.name}`);if(r.mkdirSync(b.mountPath,{recursive:!0}),_(b.mountPath)&&!R(b))throw Error(`Another filesystem occupies ${b.mountPath}`);if(!_(b.mountPath)&&r.readdirSync(b.mountPath).length)throw Error(`Refusing to hide existing files beneath ${b.mountPath}`);if(!_(b.mountPath))S("mount",["-o","noatime,nodev,nosuid",b.device,b.mountPath]);if(!R(b))throw Error(`Volume identity verification failed: ${b.name}`);S("resize2fs",[b.device]),b.allowFormat=!1}h("/etc/ts-cloud/compute-storage.json",e),V(),S("systemctl",["daemon-reload"])},{dlopen:K,read:ee}=await import("bun:ffi"),te=K("libc.so.6",{flock:{args:["i32","i32"],returns:"i32"},__errno_location:{args:[],returns:"ptr"}}),ne=[],ie=(b,k=!0)=>{r.mkdirSync(n.dirname(b),{recursive:!0});let P=r.openSync(b,r.constants.O_CREAT|r.constants.O_RDWR|r.constants.O_NOFOLLOW,384);if(te.symbols.flock(P,k?2:6)!==0){let O=ee.i32(te.symbols.__errno_location());if(r.closeSync(P),!k&&O===11)return!1;throw Error(`Could not acquire lock: ${b} (errno ${O})`)}return ne.push(P),!0},oe=()=>{let b=[];for(let k of r.readdirSync("/proc").filter((P)=>/^\d+$/.test(P))){let P=[];try{P=r.readdirSync(`/proc/${k}/fd`)}catch{continue}for(let O of["cwd","exe",...P.map((D)=>`fd/${D}`)]){let D=`/proc/${k}/${O}`;try{let J=r.readlinkSync(D);if(!J.startsWith(`${e.webRoot}/`)||!J.includes("/releases/"))continue;let Y=!1;if(O.startsWith("fd/")){let X=r.readFileSync(`/proc/${k}/fdinfo/${O.slice(3)}`,"utf8").match(/^flags:\s+(\d+)/m);Y=!!X&&(Number.parseInt(X[1],8)&3)!==0&&r.statSync(D).isFile()}b.push({file:J,write:Y,device:r.statSync(D).dev})}catch{}}}return b},re=async(b,k)=>{r.mkdirSync(b.destination,{recursive:!0});let P=["rsync","-aHAXx","--numeric-ids","--delete",...k?["--checksum"]:[],`${b.source}/`,`${b.destination}/`],D=await Bun.spawn(P,{stdout:"inherit",stderr:"inherit"}).exited;if(D!==0&&!(D===24&&!k))throw Error(`rsync failed (${D}): ${b.source}`)},pe=async()=>{let b=S("systemctl",["list-units","--type=service","--state=running","--no-legend","--plain"]).split(`
145
+ `).map((Y)=>Y.trim().split(/\s+/)[0]).filter(Boolean),k={};if(b.length){let Y=S("systemctl",["show",...b,"-p","Id","-p","MainPID","-p","WorkingDirectory"]);for(let X of Y.split(`
146
146
 
147
147
  `)){let Z=Object.fromEntries(X.split(`
148
- `).filter(Boolean).map((le)=>{let E=le.indexOf("=");return[le.slice(0,E),le.slice(E+1)]}));if(Z.WorkingDirectory?.startsWith(`${e.webRoot}/`)||/^(?:mail|rpx-gateway|postgresql|mysql|redis)[@.]/.test(Z.Id??""))L[Z.Id]=Number(Z.MainPID)}}let P=new Map;if(r.existsSync("/etc/rpx/sites.d"))for(let q of r.readdirSync("/etc/rpx/sites.d").filter((X)=>X.endsWith(".json"))){let X=JSON.parse(r.readFileSync(n.join("/etc/rpx/sites.d",q),"utf8"));for(let Z of X.proxies??[]){if(typeof Z.to!=="string"||!/^[a-zA-Z0-9.-]+$/.test(Z.to))continue;let le=typeof Z.path==="string"&&Z.path.startsWith("/")?Z.path:"/";P.set(`${Z.to}${le}`,{domain:Z.to,path:le})}}let R=[...P.values()],O=[],J=0;return await Promise.all(Array.from({length:Math.min(8,R.length)},async()=>{while(J<R.length){let q=R[J++],X=Bun.spawn(["curl","-sS","--max-time","12","--output","/dev/null","--write-out","%{http_code}","--resolve",`${q.domain}:443:127.0.0.1`,`https://${q.domain}${q.path}`],{stdout:"pipe",stderr:"pipe"}),[Z,,le]=await Promise.all([new Response(X.stdout).text(),new Response(X.stderr).text(),X.exited]),E=Number(Z);O.push({...q,status:E,ok:le===0&&E>=200&&E<500})}})),{routes:O.sort((q,X)=>`${q.domain}${q.path}`.localeCompare(`${X.domain}${X.path}`)),services:L}},ye=()=>{let T=[V.mountPath,...b.entries.map((P)=>P.source)],L=new Set(["rpx-gateway.service",...D?.dependentUnits??[]]);for(let P of r.readdirSync("/etc/systemd/system")){if(!P.endsWith(".service"))continue;try{if(r.readFileSync(`/etc/systemd/system/${P}`,"utf8").includes(e.webRoot))L.add(P)}catch{}}for(let P of L){let R=`/etc/systemd/system/${P}.d`;r.mkdirSync(R,{recursive:!0}),r.writeFileSync(`${R}/ts-cloud-storage.conf`,`[Unit]
149
- RequiresMountsFor=${T.join(" ")}
150
- `)}S("systemctl",["daemon-reload"])};try{let T=[...new Set([...D?.locks??[],"/run/lock/ts-cloud-host-cleanup.lock"])];if(u==="reclaim"){for(let E of["/run/lock/ts-cloud-compute-storage.lock",...T])if(!ie(E,!1))return console.log(`Deferring deployment storage reclamation; lock busy: ${E}`),{deferred:!0,lock:E}}else ie("/run/lock/ts-cloud-compute-storage.lock");b=f("/var/lib/ts-cloud/compute-storage-state.json",{entries:[]});let L=f("/etc/ts-cloud/compute-storage.json",null);if(L){for(let E of L.volumes)if(!e.volumes.some((N)=>N.id===E.id&&N.key===E.key&&N.mountPath===E.mountPath))throw Error(`Refusing to remove or relocate managed volume ${E.name}; migrate its data explicitly first`);if(b.entries.length&&(L.deploymentStorage?.volume!==D?.volume||L.deploymentStorage?.includeBackups!==!1!==(D?.includeBackups!==!1)))throw Error("Refusing to change an active deployment-storage policy; migrate its data explicitly first")}if(u==="apply")W();for(let E of e.volumes)if(!x(E))throw Error(`Required volume is not mounted: ${E.name}`);if(!D||!V)return{volumes:e.volumes};if(u==="ensure-site"){let[E,N]=t.slice(1);if(!E?.startsWith(`${e.webRoot}/`)||!/^[\w-]+$/.test(n.basename(E))||E.includes("..")||!/^[\w-]+$/.test(N??""))throw Error("Invalid deployment site path or project slug");if(r.mkdirSync(n.join(E,"releases"),{recursive:!0}),D.includeBackups!==!1)r.mkdirSync(n.join(e.webRoot,`${N}-shared`,"backups"),{recursive:!0})}let P=(u==="reclaim"?[]:H(u==="ensure-site"?t[1]:void 0,t[2])).filter((E)=>!b.entries.some((N)=>N.source===E.source));for(let E of b.entries)if(!_(E.source)||!y(E.source,E.destination))throw Error(`Recorded deployment mount is missing: ${E.source}`);if(!P.length&&u==="ensure-site")return{inherited:!0,volume:V.name};if(!P.length&&u==="apply"){ye();let E=I();return h("/var/lib/ts-cloud/compute-storage-status.json",E),console.log(JSON.stringify(E)),E}if(!D.migrateExisting&&P.some((E)=>r.readdirSync(E.source).length>0))throw Error("Existing deployments require deploymentStorage.migrateExisting: true");if(P.length){let E=S("du",["-scx","--block-size=1",...P.map((fe)=>fe.source)]).trim().split(`
151
- `).at(-1)?.split(/\s+/)[0],N=r.statfsSync(V.mountPath);if(Number(E)>N.bavail*N.bsize)throw Error("Insufficient free volume capacity for a verified deployment copy")}if(!r.existsSync("/run/ts-cloud-root-web"))r.mkdirSync("/run/ts-cloud-root-web");if(!_("/run/ts-cloud-root-web"))S("mount",["--bind",e.webRoot,"/run/ts-cloud-root-web"]);S("mount",["--make-private","/run/ts-cloud-root-web"]);let R=r.statSync(e.webRoot).dev;for(let E of b.entries){let N=n.join("/run/ts-cloud-root-web",n.relative(e.webRoot,E.source));if(r.existsSync(N)&&(r.statSync(N).dev!==R||y(N,E.destination)))throw Error(`Root recovery view contains a deployment mount: ${N}`)}for(let E=0;E<P.length;E++){if(_(P[E].source)&&y(P[E].source,P[E].destination))continue;console.log(`copy ${E+1}/${P.length}: ${P[E].source}`),await ne(P[E],!1)}if(u!=="reclaim")for(let E of T)ie(E);for(let E of r.readdirSync(e.webRoot,{withFileTypes:!0}).filter((N)=>N.isDirectory()).sort((N,fe)=>N.name.localeCompare(fe.name)))ie(n.join(e.webRoot,E.name,".ts-cloud/deploy.lock"));for(let E of u==="reclaim"?[]:H(u==="ensure-site"?t[1]:void 0,t[2]))if(!b.entries.some((N)=>N.source===E.source)&&!P.some((N)=>N.source===E.source))P.push(E);if(P.length)console.log("Checking application services and HTTPS routes before activation");let O=P.length?await he():void 0;if(O)h("/var/lib/ts-cloud/compute-storage-health-before.json",O);let J=oe().filter((E)=>E.write);if(J.length)throw Error(`Live writable files must be shared before migration: ${J.map((E)=>E.file).join(", ")}`);let q={entries:[...b.entries],fstab:r.readFileSync("/etc/fstab","utf8")};if(P.length)S("sync",[]);let X=[];try{for(let E=0;E<P.length;E++){let N=P[E];if(_(N.source)){if(!y(N.source,N.destination))throw Error(`Unrecorded mount occupies ${N.source}`);b.entries.push(N),h("/var/lib/ts-cloud/compute-storage-state.json",b);continue}if(console.log(`verify and mount ${E+1}/${P.length}: ${N.source}`),await ne(N,!0),S("mount",["--bind",N.destination,N.source]),!y(N.source,N.destination))throw Error(`Bind verification failed: ${N.source}`);X.push(N),b.entries.push(N),h("/var/lib/ts-cloud/compute-storage-state.json",b),Y()}if(Y(),S("findmnt",["--verify"]),b.activatedAt=new Date().toISOString(),h("/var/lib/ts-cloud/compute-storage-state.json",b),ye(),O){console.log("Checking application services and HTTPS routes after activation");let E=await he();h("/var/lib/ts-cloud/compute-storage-health-after.json",E);let N=O.routes.filter((ae)=>ae.ok&&!E.routes.some((Se)=>Se.domain===ae.domain&&Se.path===ae.path&&Se.ok)),fe=Object.keys(O.services).filter((ae)=>!E.services[ae]);if(N.length||fe.length)throw Error(`Application verification failed: ${N.map((ae)=>ae.domain+ae.path).concat(fe).join(", ")}`);console.log(`Verified ${E.routes.length} routes and ${Object.keys(E.services).length} services`)}}catch(E){let N=[];for(let fe of X.reverse())try{S("umount",[fe.source])}catch{N.push(fe),console.error(`Rollback mount busy, original data retained: ${fe.source}`)}if(b.entries=[...q.entries,...N],r.writeFileSync("/etc/fstab",q.fstab),N.length)Y();throw h("/var/lib/ts-cloud/compute-storage-state.json",b),S("systemctl",["daemon-reload"]),E}let Z=oe().filter((E)=>E.device===R).map((E)=>E.file);for(let E of b.entries){if(!_(E.source)||!y(E.source,E.destination))throw Error(`Lost deployment mount: ${E.source}`);let N=n.join("/run/ts-cloud-root-web",n.relative(e.webRoot,E.source));if(!r.existsSync(N))continue;if(r.statSync(N).dev!==R||y(N,E.destination))throw Error(`Refusing to clean a deployment volume through the root recovery view: ${N}`);let fe="";try{fe=n.basename(r.realpathSync(n.join(n.dirname(E.source),"current")))}catch{}for(let ae of r.readdirSync(N,{withFileTypes:!0})){let Se=n.join(N,ae.name);if(n.basename(E.source)==="backups"){if(ae.isFile()&&r.existsSync(n.join(E.destination,ae.name)))r.unlinkSync(Se)}else if(ae.isDirectory()&&!ae.isSymbolicLink()&&ae.name!==fe&&!Z.some((Rt)=>Rt===n.join(E.source,ae.name)||Rt.startsWith(`${n.join(E.source,ae.name)}/`)))r.rmSync(Se,{recursive:!0})}}S("sync",[]);let le=I();return h("/var/lib/ts-cloud/compute-storage-status.json",le),console.log(JSON.stringify(le)),le}finally{for(let T of te.reverse())re.symbols.flock(T,8),r.closeSync(T);re.close()}}var hn="/etc/ts-cloud/compute-storage.json",ze="/usr/local/lib/ts-cloud/compute-storage.mjs";function ei(e,t){let r=Object.entries(e.infrastructure?.compute?.volumes??{}).map(([s,i])=>{if(!/^[a-z][a-z0-9-]*$/.test(s))throw Error(`Invalid compute volume key: ${s}`);if(!Number.isInteger(i.size)||i.size<10||i.size>10240)throw Error(`compute.volumes.${s}.size must be a whole number from 10 to 10240 GB`);if(!i.mountPath.startsWith("/")||!i.mountPath.slice(1).split("/").every((c)=>/^[\w-]+$/.test(c))||i.mountPath==="/var"||i.mountPath==="/var/lib"||["/etc","/usr","/var/www","/root","/boot","/dev","/proc","/sys","/run","/bin","/sbin","/lib"].some((c)=>i.mountPath===c||i.mountPath.startsWith(`${c}/`)))throw Error(`Unsafe compute volume mount path: ${i.mountPath}`);let a=i.name??`${e.project.slug}-${t}-${s}`;if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(a))throw Error(`Invalid compute volume name: ${a}`);return{...i,key:s,name:a,mountPath:i.mountPath.replace(/\/+$/,"")}});for(let s of r)if(r.some((i)=>i!==s&&(i.name===s.name||i.mountPath===s.mountPath||i.mountPath.startsWith(`${s.mountPath}/`))))throw Error("Compute volumes must have distinct names and non-overlapping mount paths");let n=e.infrastructure?.compute?.deploymentStorage;for(let s of n?.locks??[])if(!s.startsWith("/run/lock/")||!s.slice(10).split("/").every((i)=>/^[\w.-]+$/.test(i)&&i!=="."&&i!=="..")||s==="/run/lock/ts-cloud-compute-storage.lock")throw Error(`Invalid deployment storage lock: ${s}`);for(let s of n?.dependentUnits??[])if(!/^[\w@.-]+\.service$/.test(s))throw Error(`Invalid deployment storage dependent unit: ${s}`);if(n&&!r.some((s)=>s.key===n.volume))throw Error(`deploymentStorage.volume references an undeclared compute volume: ${n.volume}`);return r}function dr(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function ti(e){let t=`${hn}.candidate`,r=`#!/usr/bin/env bun
148
+ `).filter(Boolean).map((le)=>{let E=le.indexOf("=");return[le.slice(0,E),le.slice(E+1)]}));if(Z.WorkingDirectory?.startsWith(`${e.webRoot}/`)||/^(?:mail|rpx-gateway|postgresql|mysql|redis)[@.]/.test(Z.Id??""))k[Z.Id]=Number(Z.MainPID)}}let P=new Map;if(r.existsSync("/etc/rpx/sites.d"))for(let Y of r.readdirSync("/etc/rpx/sites.d").filter((X)=>X.endsWith(".json"))){let X=JSON.parse(r.readFileSync(n.join("/etc/rpx/sites.d",Y),"utf8"));for(let Z of X.proxies??[]){if(typeof Z.to!=="string"||!/^[a-zA-Z0-9.-]+$/.test(Z.to))continue;let le=typeof Z.path==="string"&&Z.path.startsWith("/")?Z.path:"/";P.set(`${Z.to}${le}`,{domain:Z.to,path:le})}}let O=[...P.values()],D=[],J=0;return await Promise.all(Array.from({length:Math.min(8,O.length)},async()=>{while(J<O.length){let Y=O[J++],X=Bun.spawn(["curl","-sS","--max-time","12","--output","/dev/null","--write-out","%{http_code}","--resolve",`${Y.domain}:443:127.0.0.1`,`https://${Y.domain}${Y.path}`],{stdout:"pipe",stderr:"pipe"}),[Z,,le]=await Promise.all([new Response(X.stdout).text(),new Response(X.stderr).text(),X.exited]),E=Number(Z);D.push({...Y,status:E,ok:le===0&&E>=200&&E<500})}})),{routes:D.sort((Y,X)=>`${Y.domain}${Y.path}`.localeCompare(`${X.domain}${X.path}`)),services:k}},ge=()=>{let b=[W.mountPath,...T.entries.map((P)=>P.source)],k=new Set(["rpx-gateway.service",...x?.dependentUnits??[]]);for(let P of r.readdirSync("/etc/systemd/system")){if(!P.endsWith(".service"))continue;try{if(r.readFileSync(`/etc/systemd/system/${P}`,"utf8").includes(e.webRoot))k.add(P)}catch{}}for(let P of k){let O=`/etc/systemd/system/${P}.d`;r.mkdirSync(O,{recursive:!0}),r.writeFileSync(`${O}/ts-cloud-storage.conf`,`[Unit]
149
+ RequiresMountsFor=${b.join(" ")}
150
+ `)}S("systemctl",["daemon-reload"])};try{let b=[...new Set([...x?.locks??[],"/run/lock/ts-cloud-host-cleanup.lock"])];if(u==="reclaim"){for(let E of["/run/lock/ts-cloud-compute-storage.lock",...b])if(!ie(E,!1))return console.log(`Deferring deployment storage reclamation; lock busy: ${E}`),{deferred:!0,lock:E}}else ie("/run/lock/ts-cloud-compute-storage.lock");T=f("/var/lib/ts-cloud/compute-storage-state.json",{entries:[]});let k=f("/etc/ts-cloud/compute-storage.json",null);if(k){for(let E of k.volumes)if(!e.volumes.some((N)=>N.id===E.id&&N.key===E.key&&N.mountPath===E.mountPath))throw Error(`Refusing to remove or relocate managed volume ${E.name}; migrate its data explicitly first`);if(T.entries.length&&(k.deploymentStorage?.volume!==x?.volume||k.deploymentStorage?.includeBackups!==!1!==(x?.includeBackups!==!1)))throw Error("Refusing to change an active deployment-storage policy; migrate its data explicitly first")}if(u==="apply")q();for(let E of e.volumes)if(!R(E))throw Error(`Required volume is not mounted: ${E.name}`);if(!x||!W)return{volumes:e.volumes};if(u==="ensure-site"){let[E,N]=t.slice(1);if(!E?.startsWith(`${e.webRoot}/`)||!/^[\w-]+$/.test(n.basename(E))||E.includes("..")||!/^[\w-]+$/.test(N??""))throw Error("Invalid deployment site path or project slug");if(r.mkdirSync(n.join(E,"releases"),{recursive:!0}),x.includeBackups!==!1)r.mkdirSync(n.join(e.webRoot,`${N}-shared`,"backups"),{recursive:!0})}let P=(u==="reclaim"?[]:H(u==="ensure-site"?t[1]:void 0,t[2])).filter((E)=>!T.entries.some((N)=>N.source===E.source));for(let E of T.entries)if(!_(E.source)||!y(E.source,E.destination))throw Error(`Recorded deployment mount is missing: ${E.source}`);if(!P.length&&u==="ensure-site")return{inherited:!0,volume:W.name};if(!P.length&&u==="apply"){ge();let E=I();return h("/var/lib/ts-cloud/compute-storage-status.json",E),console.log(JSON.stringify(E)),E}if(!x.migrateExisting&&P.some((E)=>r.readdirSync(E.source).length>0))throw Error("Existing deployments require deploymentStorage.migrateExisting: true");if(P.length){let E=S("du",["-scx","--block-size=1",...P.map((he)=>he.source)]).trim().split(`
151
+ `).at(-1)?.split(/\s+/)[0],N=r.statfsSync(W.mountPath);if(Number(E)>N.bavail*N.bsize)throw Error("Insufficient free volume capacity for a verified deployment copy")}if(!r.existsSync("/run/ts-cloud-root-web"))r.mkdirSync("/run/ts-cloud-root-web");if(!_("/run/ts-cloud-root-web"))S("mount",["--bind",e.webRoot,"/run/ts-cloud-root-web"]);S("mount",["--make-private","/run/ts-cloud-root-web"]);let O=r.statSync(e.webRoot).dev;for(let E of T.entries){let N=n.join("/run/ts-cloud-root-web",n.relative(e.webRoot,E.source));if(r.existsSync(N)&&(r.statSync(N).dev!==O||y(N,E.destination)))throw Error(`Root recovery view contains a deployment mount: ${N}`)}for(let E=0;E<P.length;E++){if(_(P[E].source)&&y(P[E].source,P[E].destination))continue;console.log(`copy ${E+1}/${P.length}: ${P[E].source}`),await re(P[E],!1)}if(u!=="reclaim")for(let E of b)ie(E);for(let E of r.readdirSync(e.webRoot,{withFileTypes:!0}).filter((N)=>N.isDirectory()).sort((N,he)=>N.name.localeCompare(he.name)))ie(n.join(e.webRoot,E.name,".ts-cloud/deploy.lock"));for(let E of u==="reclaim"?[]:H(u==="ensure-site"?t[1]:void 0,t[2]))if(!T.entries.some((N)=>N.source===E.source)&&!P.some((N)=>N.source===E.source))P.push(E);if(P.length)console.log("Checking application services and HTTPS routes before activation");let D=P.length?await pe():void 0;if(D)h("/var/lib/ts-cloud/compute-storage-health-before.json",D);let J=oe().filter((E)=>E.write);if(J.length)throw Error(`Live writable files must be shared before migration: ${J.map((E)=>E.file).join(", ")}`);let Y={entries:[...T.entries],fstab:r.readFileSync("/etc/fstab","utf8")};if(P.length)S("sync",[]);let X=[];try{for(let E=0;E<P.length;E++){let N=P[E];if(_(N.source)){if(!y(N.source,N.destination))throw Error(`Unrecorded mount occupies ${N.source}`);T.entries.push(N),h("/var/lib/ts-cloud/compute-storage-state.json",T);continue}if(console.log(`verify and mount ${E+1}/${P.length}: ${N.source}`),await re(N,!0),S("mount",["--bind",N.destination,N.source]),!y(N.source,N.destination))throw Error(`Bind verification failed: ${N.source}`);X.push(N),T.entries.push(N),h("/var/lib/ts-cloud/compute-storage-state.json",T),V()}if(V(),S("findmnt",["--verify"]),T.activatedAt=new Date().toISOString(),h("/var/lib/ts-cloud/compute-storage-state.json",T),ge(),D){console.log("Checking application services and HTTPS routes after activation");let E=await pe();h("/var/lib/ts-cloud/compute-storage-health-after.json",E);let N=D.routes.filter((ae)=>ae.ok&&!E.routes.some((ve)=>ve.domain===ae.domain&&ve.path===ae.path&&ve.ok)),he=Object.keys(D.services).filter((ae)=>!E.services[ae]);if(N.length||he.length)throw Error(`Application verification failed: ${N.map((ae)=>ae.domain+ae.path).concat(he).join(", ")}`);console.log(`Verified ${E.routes.length} routes and ${Object.keys(E.services).length} services`)}}catch(E){let N=[];for(let he of X.reverse())try{S("umount",[he.source])}catch{N.push(he),console.error(`Rollback mount busy, original data retained: ${he.source}`)}if(T.entries=[...Y.entries,...N],r.writeFileSync("/etc/fstab",Y.fstab),N.length)V();throw h("/var/lib/ts-cloud/compute-storage-state.json",T),S("systemctl",["daemon-reload"]),E}let Z=oe().filter((E)=>E.device===O).map((E)=>E.file);for(let E of T.entries){if(!_(E.source)||!y(E.source,E.destination))throw Error(`Lost deployment mount: ${E.source}`);let N=n.join("/run/ts-cloud-root-web",n.relative(e.webRoot,E.source));if(!r.existsSync(N))continue;if(r.statSync(N).dev!==O||y(N,E.destination))throw Error(`Refusing to clean a deployment volume through the root recovery view: ${N}`);let he="";try{he=n.basename(r.realpathSync(n.join(n.dirname(E.source),"current")))}catch{}for(let ae of r.readdirSync(N,{withFileTypes:!0})){let ve=n.join(N,ae.name);if(n.basename(E.source)==="backups"){if(ae.isFile()&&r.existsSync(n.join(E.destination,ae.name)))r.unlinkSync(ve)}else if(ae.isDirectory()&&!ae.isSymbolicLink()&&ae.name!==he&&!Z.some((Rt)=>Rt===n.join(E.source,ae.name)||Rt.startsWith(`${n.join(E.source,ae.name)}/`)))r.rmSync(ve,{recursive:!0})}}S("sync",[]);let le=I();return h("/var/lib/ts-cloud/compute-storage-status.json",le),console.log(JSON.stringify(le)),le}finally{for(let b of ne.reverse())te.symbols.flock(b,8),r.closeSync(b);te.close()}}var hn="/etc/ts-cloud/compute-storage.json",ze="/usr/local/lib/ts-cloud/compute-storage.mjs";function ei(e,t){let r=Object.entries(e.infrastructure?.compute?.volumes??{}).map(([s,i])=>{if(!/^[a-z][a-z0-9-]*$/.test(s))throw Error(`Invalid compute volume key: ${s}`);if(!Number.isInteger(i.size)||i.size<10||i.size>10240)throw Error(`compute.volumes.${s}.size must be a whole number from 10 to 10240 GB`);if(!i.mountPath.startsWith("/")||!i.mountPath.slice(1).split("/").every((c)=>/^[\w-]+$/.test(c))||i.mountPath==="/var"||i.mountPath==="/var/lib"||["/etc","/usr","/var/www","/root","/boot","/dev","/proc","/sys","/run","/bin","/sbin","/lib"].some((c)=>i.mountPath===c||i.mountPath.startsWith(`${c}/`)))throw Error(`Unsafe compute volume mount path: ${i.mountPath}`);let a=i.name??`${e.project.slug}-${t}-${s}`;if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(a))throw Error(`Invalid compute volume name: ${a}`);return{...i,key:s,name:a,mountPath:i.mountPath.replace(/\/+$/,"")}});for(let s of r)if(r.some((i)=>i!==s&&(i.name===s.name||i.mountPath===s.mountPath||i.mountPath.startsWith(`${s.mountPath}/`))))throw Error("Compute volumes must have distinct names and non-overlapping mount paths");let n=e.infrastructure?.compute?.deploymentStorage;for(let s of n?.locks??[])if(!s.startsWith("/run/lock/")||!s.slice(10).split("/").every((i)=>/^[\w.-]+$/.test(i)&&i!=="."&&i!=="..")||s==="/run/lock/ts-cloud-compute-storage.lock")throw Error(`Invalid deployment storage lock: ${s}`);for(let s of n?.dependentUnits??[])if(!/^[\w@.-]+\.service$/.test(s))throw Error(`Invalid deployment storage dependent unit: ${s}`);if(n&&!r.some((s)=>s.key===n.volume))throw Error(`deploymentStorage.volume references an undeclared compute volume: ${n.volume}`);return r}function dr(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function ti(e){let t=`${hn}.candidate`,r=`#!/usr/bin/env bun
152
152
  await (${As.toString()})(JSON.parse(await Bun.file(process.env.TS_CLOUD_STORAGE_POLICY || ${JSON.stringify(hn)}).text()), process.argv.slice(2));
153
- `;return['command -v bun >/dev/null 2>&1 || { echo "Configured compute storage requires Bun on the host" >&2; exit 1; }',"install -d -m 0755 /etc/ts-cloud /usr/local/lib/ts-cloud /var/lib/ts-cloud",`printf %s ${dr(Buffer.from(r).toString("base64"))} | base64 -d > ${ze}.new`,`chmod 0755 ${ze}.new && mv ${ze}.new ${ze}`,`printf %s ${dr(JSON.stringify(e))} > ${t}`,`chmod 0644 ${t}`,`TS_CLOUD_STORAGE_POLICY=${t} bun ${ze} apply 2>&1 | tee /var/log/ts-cloud-compute-storage.log`,`rm -f ${t}`,"cat > /etc/systemd/system/ts-cloud-storage-check.service <<'TS_CLOUD_STORAGE_SERVICE'","[Unit]","Description=Check configured compute storage and deployment mounts","[Service]","Type=oneshot",`ExecStart=/usr/local/bin/bun ${ze} check`,"TS_CLOUD_STORAGE_SERVICE","cat > /etc/systemd/system/ts-cloud-storage-check.timer <<'TS_CLOUD_STORAGE_TIMER'","[Unit]","Description=Check compute storage every minute","[Timer]","OnBootSec=2min","OnUnitActiveSec=1min","[Install]","WantedBy=timers.target","TS_CLOUD_STORAGE_TIMER","systemctl daemon-reload","systemctl enable --now ts-cloud-storage-check.timer","cat > /etc/systemd/system/ts-cloud-storage-reclaim.service <<'TS_CLOUD_RECLAIM_SERVICE'","[Unit]","Description=Reclaim inactive root copies of volume-backed deployments","[Service]","Type=oneshot",`ExecStart=/usr/local/bin/bun ${ze} reclaim`,"Nice=19","IOSchedulingClass=idle","TS_CLOUD_RECLAIM_SERVICE","cat > /etc/systemd/system/ts-cloud-storage-reclaim.timer <<'TS_CLOUD_RECLAIM_TIMER'","[Unit]","Description=Reclaim retired deployment copies hourly","[Timer]","OnCalendar=hourly","RandomizedDelaySec=5min","Persistent=true","[Install]","WantedBy=timers.target","TS_CLOUD_RECLAIM_TIMER","systemctl daemon-reload","systemctl enable --now ts-cloud-storage-reclaim.timer"]}function $r(e,t){return[`if [ -f ${hn} ]; then bun ${ze} ensure-site ${dr(e)} ${dr(t)}; fi`]}import{createHash as Za}from"node:crypto";function ut(e){if(!/^[a-z0-9][a-z0-9-]*$/.test(e))throw Error("Runtime isolation requires a safe project slug");return`tsc-${e.length<=24?e:`${e.slice(0,15)}-${Za("sha256").update(e).digest("hex").slice(0,8)}`}`}function Ut(e){return[`User=${e}`,`Group=${e}`,"NoNewPrivileges=true","PrivateTmp=true","ProtectHome=true","InaccessiblePaths=-/run/postgresql -/var/run/postgresql","UMask=0077",`Environment=HOME=/var/lib/ts-cloud/${e}`]}function Ls(e,t,r){let n=ut(e);if(!t.startsWith(`/var/www/${e}-`)||t.slice(9).includes("/"))throw Error("Runtime isolation requires a project-namespaced application directory");let s=`/var/lib/ts-cloud/${n}`,i=`/var/www/${e}-shared`,a=[...new Set([t,...r])];for(let c of a)if(!/^\/[a-zA-Z0-9_./-]+$/.test(c)||c.split("/").includes("..")||!(c===t||c.startsWith(`${t}/`)||c===i||c.startsWith(`${i}/`)))throw Error(`Runtime isolation cannot take ownership outside project ${e}`);return[`if ! id -u ${n} >/dev/null 2>&1; then useradd --system --user-group --create-home --home-dir ${s} --shell /usr/sbin/nologin ${n}; fi`,`[ "$(id -u ${n})" != 0 ] && [ "$(getent passwd ${n} | cut -d: -f6)" = ${s} ] || { echo 'Unexpected runtime isolation identity' >&2; exit 1; }`,`install -d -m 700 -o ${n} -g ${n} ${s}`,...a.map((c)=>`chown -hR ${n}:${n} ${c}`),`chmod 750 ${t}`]}function fr(e){return Object.entries(e).map(([t,r])=>`${t}=${Qa(String(r))}`).join(`
153
+ `;return['command -v bun >/dev/null 2>&1 || { echo "Configured compute storage requires Bun on the host" >&2; exit 1; }',"install -d -m 0755 /etc/ts-cloud /usr/local/lib/ts-cloud /var/lib/ts-cloud",`printf %s ${dr(Buffer.from(r).toString("base64"))} | base64 -d > ${ze}.new`,`chmod 0755 ${ze}.new && mv ${ze}.new ${ze}`,`printf %s ${dr(JSON.stringify(e))} > ${t}`,`chmod 0644 ${t}`,`TS_CLOUD_STORAGE_POLICY=${t} bun ${ze} apply 2>&1 | tee /var/log/ts-cloud-compute-storage.log`,`rm -f ${t}`,"cat > /etc/systemd/system/ts-cloud-storage-check.service <<'TS_CLOUD_STORAGE_SERVICE'","[Unit]","Description=Check configured compute storage and deployment mounts","[Service]","Type=oneshot",`ExecStart=/usr/local/bin/bun ${ze} check`,"TS_CLOUD_STORAGE_SERVICE","cat > /etc/systemd/system/ts-cloud-storage-check.timer <<'TS_CLOUD_STORAGE_TIMER'","[Unit]","Description=Check compute storage every minute","[Timer]","OnBootSec=2min","OnUnitActiveSec=1min","[Install]","WantedBy=timers.target","TS_CLOUD_STORAGE_TIMER","systemctl daemon-reload","systemctl enable --now ts-cloud-storage-check.timer","cat > /etc/systemd/system/ts-cloud-storage-reclaim.service <<'TS_CLOUD_RECLAIM_SERVICE'","[Unit]","Description=Reclaim inactive root copies of volume-backed deployments","[Service]","Type=oneshot",`ExecStart=/usr/local/bin/bun ${ze} reclaim`,"Nice=19","IOSchedulingClass=idle","TS_CLOUD_RECLAIM_SERVICE","cat > /etc/systemd/system/ts-cloud-storage-reclaim.timer <<'TS_CLOUD_RECLAIM_TIMER'","[Unit]","Description=Reclaim retired deployment copies hourly","[Timer]","OnCalendar=hourly","RandomizedDelaySec=5min","Persistent=true","[Install]","WantedBy=timers.target","TS_CLOUD_RECLAIM_TIMER","systemctl daemon-reload","systemctl enable --now ts-cloud-storage-reclaim.timer"]}function $r(e,t){return[`if [ -f ${hn} ]; then bun ${ze} ensure-site ${dr(e)} ${dr(t)}; fi`]}import{createHash as Za}from"node:crypto";function ut(e){if(!/^[a-z0-9][a-z0-9-]*$/.test(e))throw Error("Runtime isolation requires a safe project slug");return`tsc-${e.length<=24?e:`${e.slice(0,15)}-${Za("sha256").update(e).digest("hex").slice(0,8)}`}`}function Ut(e,t,r){return[`User=${e}`,`Group=${e}`,"NoNewPrivileges=true","PrivateTmp=true","ProtectHome=true","ProtectProc=invisible","InaccessiblePaths=-/run/postgresql -/var/run/postgresql","TemporaryFileSystem=/var/www:ro",`BindPaths=${t} -/var/www/${r}-shared`,"UMask=0077",`Environment=HOME=/var/lib/ts-cloud/${e}`]}function Ls(e,t,r){let n=ut(e);if(!t.startsWith(`/var/www/${e}-`)||t.slice(9).includes("/"))throw Error("Runtime isolation requires a project-namespaced application directory");let s=`/var/lib/ts-cloud/${n}`,i=`/var/www/${e}-shared`,a=[...new Set([t,...r])];for(let c of a)if(!/^\/[a-zA-Z0-9_./-]+$/.test(c)||c.split("/").includes("..")||!(c===t||c.startsWith(`${t}/`)||c===i||c.startsWith(`${i}/`)))throw Error(`Runtime isolation cannot take ownership outside project ${e}`);return[`if ! id -u ${n} >/dev/null 2>&1; then useradd --system --user-group --create-home --home-dir ${s} --shell /usr/sbin/nologin ${n}; fi`,`[ "$(id -u ${n})" != 0 ] && [ "$(getent passwd ${n} | cut -d: -f6)" = ${s} ] || { echo 'Unexpected runtime isolation identity' >&2; exit 1; }`,`install -d -m 700 -o ${n} -g ${n} ${s}`,...a.map((c)=>`chown -hR ${n}:${n} ${c}`),`chmod 750 ${t}`]}function fr(e){return Object.entries(e).map(([t,r])=>`${t}=${Qa(String(r))}`).join(`
154
154
  `)}function Qa(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}var gr=["storage",".env"],Ht=4;function Ue(e){return`${e.replace(/\/+$/,"")}/.ts-cloud`}function ec(e){return`${Ue(e)}/deploy-history.log`}function tc(e,t){return`${Ue(e)}/deploys/${t}.log`}function Us(e){return`${Ue(e)}/shared-paths`}function hr(e){return`${e.shared}/stx-images`}function Nt(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 ks(e){let t=e.split("/").pop()||e;if(t===".env"||t.startsWith(".env."))return!0;return/\.[a-z0-9]+$/i.test(t)}function Sn(e){return typeof e==="string"?e:e.path}function Hs(e){let t=new Map;for(let r of e)t.set(Sn(r),r);return[...t.values()]}function Ns(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 rc(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 Mt(e,t=gr){let r=[`mkdir -p ${e.releases} ${e.shared} ${hr(e)} ${Nt(e)}`,...rc(e)],n=t.map((i)=>Ns(e,i));for(let{path:i,target:a,seed:c}of n){if(!c)continue;if(r.push(`ts_cloud_adopt_shared '${i}' '${a}'`),ks(i))r.push(`mkdir -p "$(dirname ${a})"`,`touch ${a}`);else if(i==="storage")r.push(`mkdir -p ${a}/app/public`,`mkdir -p ${a}/framework/cache/data`,`mkdir -p ${a}/framework/sessions`,`mkdir -p ${a}/framework/testing`,`mkdir -p ${a}/framework/views`,`mkdir -p ${a}/logs`);else r.push(`mkdir -p ${a}`)}let s=Us(e.base);return r.push(`mkdir -p ${Ue(e.base)}`,`cat > ${s} <<'TS_CLOUD_SHARED_PATHS_EOF'`,...n.map((i)=>`${i.path} ${i.target}`),"TS_CLOUD_SHARED_PATHS_EOF"),r}function vn(e,t=900){let r=`${Ue(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 _n(e){let t=`${e.release}.incoming`;return[`rm -rf ${t}`,`mkdir -p ${t}`,...nc(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 $n(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 nc(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 yn(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 sc(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 Sr(e,t=gr){let r=[];for(let n of t){let{path:s,target:i,seed:a}=Ns(e,n),c=`${e.release}/${s}`,u=[`rm -rf ${c}`,`mkdir -p "$(dirname ${c})"`,`ln -sfn ${i} ${c}`];if(a){if(s!==".env"&&ks(s))r.push(...sc(c,i));r.push(...u);continue}r.push(`if [ -e ${i} ]; then`,...u.map((f)=>` ${f}`),"fi")}return r}function oc(e,t){let r=Us(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 pt(e){return[`ln -sfn ${e.release} ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`]}function bn(e){return`${Ue(e)}/previous-release`}function Tn(e,t="TS_CLOUD_PREV_CURRENT"){let r=bn(e.base);return[`if [ -n "\${${t}:-}" ] && [ -d "$${t}" ] && [ "$(readlink -f "$${t}")" != "$(readlink -f ${e.release})" ]; then mkdir -p ${Ue(e.base)}; basename "$${t}" > ${r}; fi`]}function Ms(e,t){let r=bn(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 $g(e,t={}){return[...Ms(e,t.to),'echo "would roll back from $(basename "${TS_CLOUD_CURRENT:-none}") to $TS_CLOUD_RB_ID (dry run: nothing changed)"']}function Mg(e,t={}){let r=Math.max(1,t.gateSeconds??5),n=t.systemdDir??"/etc/systemd/system",s=[`ln -sfn "$TS_CLOUD_RB_TARGET" ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`,`rm -f ${bn(e.base)}`,'echo "rolled back to $TS_CLOUD_RB_ID"'],i=[...Ms(e,t.to),...oc(e,'"$TS_CLOUD_RB_TARGET"')];if(!t.unitBase)return[...i,...s];let a=t.unitBase,c=`${a}@\${TS_CLOUD_RB_ID}.service`;return[...i,`if [ -f ${n}/${a}@.service ]; then`,` systemctl start "${c}"`,` for TS_CLOUD_I in $(seq 1 ${r}); do sleep 1; systemctl is-active --quiet "${c}" || { echo "the release rolled back to, $TS_CLOUD_RB_ID, did not stay up; the current release keeps serving" >&2; journalctl -u "${c}" -n 30 --no-pager >&2 || true; systemctl stop "${c}" 2>/dev/null || true; exit 1; }; done`,...s.map((u)=>` ${u}`),` systemctl enable "${c}" 2>/dev/null || true`,` systemctl list-units --plain --no-legend --type=service "${a}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v "^${a}@\${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}/${a}.service ]; then`,...s.map((u)=>` ${u}`),` systemctl restart ${a}.service`,"else",...s.map((u)=>` ${u}`),"fi"]}function dt(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 ic(e){return`${Ue(e)}/owner`}function wn(e,t){let r=ic(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 vr(e,t){let r=Ue(e),n=tc(e,t.releaseId),s=ec(e),i=Math.max(1,t.keepLogs??20),a=t.commit||"",c=t.branch||"";return[`mkdir -p ${r}/deploys`,`exec > >(tee -a ${n}) 2>&1`,`echo "[ts-cloud] deploy ${t.releaseId} commit=${a} branch=${c} 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}" "${a}" "$TS_CLOUD_ST" "$TS_CLOUD_RC" >> ${s}`,"}","trap ts_cloud_record_deploy EXIT",`ls -1t ${r}/deploys/*.log 2>/dev/null | tail -n +${i+1} | while read -r TS_CLOUD_OLDLOG; do rm -f "$TS_CLOUD_OLDLOG"; done`]}var ac=new Set(["sqlite","sqlite3"]),cc=new Set([":memory:","memory"]);function lc(e){let t=e?.DB_CONNECTION?.trim().toLowerCase();return t!=null&&ac.has(t)}function uc(e){let t=e.trim().replace(/^\.\//,"");if(t===""||t.startsWith("/")||t.startsWith("~"))return;if(t.split("/").includes(".."))return;return t.replace(/\/+$/,"")}function Cn(e,t=[]){if(!lc(e))return{};let r=e?.DB_DATABASE_PATH?.trim()||e?.DB_DATABASE?.trim();if(r&&cc.has(r.toLowerCase()))return{};if(!r)return{warning:"DB_CONNECTION is sqlite but neither DB_DATABASE_PATH nor DB_DATABASE names a file, so ts-cloud cannot tell where the database lives. If it is written inside the release directory, the next deploy discards it. Set DB_DATABASE_PATH, or list the file in the site's `sharedPaths`."};let n=uc(r);if(!n)return{};if(t.some((s)=>Sn(s)===n))return{};return{path:n}}function yr(e,t=[]){let{path:r}=Cn(e,t);return r?[r]:[]}var Mr="/var/ts-cloud/artifacts",Uh="/usr/local/bin/ts-cloud-host-cleanup.sh",Qh="ts-cloud-host-cleanup";var Fg=Object.freeze({stagingMaxAgeMinutes:60,artifactMaxAgeDays:2,artifactUploadMaxAgeMinutes:60,bunCacheMaxAgeDays:7,journalMaxAgeDays:14,journalMaxSizeMb:512,containerImageMaxAgeHours:168}),Ug=Object.freeze({artifactMaxAgeDays:0,bunCacheMaxAgeDays:1,journalMaxAgeDays:3,journalMaxSizeMb:256,containerImageMaxAgeHours:24}),Hh=50,Gh=85,Vh="daily";function Fs(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function Ze(e,t,r=0){if(!Number.isInteger(t)||t<r)throw Error(`hostCleanup: ${e} must be a whole number >= ${r} (got ${t})`)}function zs(e,t){for(let[r,n]of Object.entries(t))Ze(`${e}.${r}`,n);Ze(`${e}.stagingMaxAgeMinutes`,t.stagingMaxAgeMinutes,15),Ze(`${e}.artifactUploadMaxAgeMinutes`,t.artifactUploadMaxAgeMinutes,15),Ze(`${e}.journalMaxSizeMb`,t.journalMaxSizeMb,1)}function pc(e,t){let r=`hostCleanup.paths[${t}]`,n=e.path?.replace(/\/+$/,"")??"";if(!n.startsWith("/")||n===""||/[\s'"`$\\]/.test(n)||n.split("/").includes(".."))throw Error(`${r}.path must be an absolute directory with no spaces, quotes or '..' (got ${JSON.stringify(e.path)})`);if(n==="/var/www"||n.startsWith("/var/www/"))throw Error(`${r}.path must not be under /var/www: releases are pruned by keepReleases`);if(!e.pattern||/^[*?]+$/.test(e.pattern)||e.pattern.includes("/")||/[\n'"`]/.test(e.pattern))throw Error(`${r}.pattern must be a file-name glob naming something, not a bare wildcard (got ${JSON.stringify(e.pattern)})`);if(Ze(`${r}.maxAgeDays`,e.maxAgeDays),e.type!==void 0&&e.type!=="file"&&e.type!=="directory")throw Error(`${r}.type must be 'file' or 'directory'`)}function Fr(e){let t=typeof e==="object"&&e!==null?e:{},r=e!==!1,n={...Fg,...Bs(t.retention)};zs("hostCleanup.retention",n);let s=null;if(t.pressure!==!1){let c=typeof t.pressure==="object"?t.pressure:{},u=c.lowWaterPercent??50,f=c.highWaterPercent??85;if(Ze("hostCleanup.pressure.lowWaterPercent",u),Ze("hostCleanup.pressure.highWaterPercent",f,1),f>100||u>=f)throw Error(`hostCleanup.pressure: need 0 <= lowWaterPercent < highWaterPercent <= 100 (got ${u} and ${f})`);let h={...Ug,...Bs(c.escalated)},S=Object.fromEntries(Object.keys(n).map((v)=>[v,Math.min(n[v],h[v]??n[v])]));zs("hostCleanup.pressure.escalated",S),s={lowWaterPercent:u,highWaterPercent:f,escalated:S}}let i=t.schedule??"daily";if(!/^[\w*:,./~ -]+$/.test(i))throw Error(`hostCleanup.schedule must be a systemd OnCalendar expression (got ${JSON.stringify(i)})`);let a=t.paths??[];return a.forEach(pc),{enabled:r,timer:r&&t.timer!==!1,schedule:i,retention:n,pressure:s,paths:a}}function Bs(e){return Object.fromEntries(Object.entries(e??{}).filter(([,t])=>t!==void 0))}var Ft={stagingMaxAgeMinutes:"TS_CLOUD_HC_STAGING_MIN",artifactMaxAgeDays:"TS_CLOUD_HC_ARTIFACT_DAYS",artifactUploadMaxAgeMinutes:"TS_CLOUD_HC_UPLOAD_MIN",bunCacheMaxAgeDays:"TS_CLOUD_HC_BUN_DAYS",journalMaxAgeDays:"TS_CLOUD_HC_JOURNAL_DAYS",journalMaxSizeMb:"TS_CLOUD_HC_JOURNAL_MB",containerImageMaxAgeHours:"TS_CLOUD_HC_IMAGE_HOURS"};function Pn(e){return Object.keys(Ft).map((t)=>`${Ft[t]}=${e[t]}`).join(" ")}var Ke=(e)=>`"$${Ft[e]}"`;function Ks(e){return[`find /var/ts-cloud/staging -xdev -maxdepth 1 -type f -mmin +${Ke("stagingMaxAgeMinutes")} -delete 2>/dev/null || true`,`find /tmp -xdev -maxdepth 1 -type f -name "*-release.tar.gz" -mmin +${Ke("stagingMaxAgeMinutes")} -delete 2>/dev/null || true`,`find /var/ts-cloud/artifacts -xdev -maxdepth 1 -type f -name "*.tar.gz" -mtime +${Ke("artifactMaxAgeDays")} -delete 2>/dev/null || true`,`find /var/ts-cloud/artifacts -xdev -maxdepth 1 -type f -name ".*.tmp" -mmin +${Ke("artifactUploadMaxAgeMinutes")} -delete 2>/dev/null || true`,...e.map(dc),`journalctl --vacuum-time=${Ke("journalMaxAgeDays")}d --vacuum-size=${Ke("journalMaxSizeMb")}M >/dev/null 2>&1 || true`]}function dc(e){let t=Fs(e.path.replace(/\/+$/,"")),r=Fs(e.pattern);return e.type==="directory"?`find ${t} -xdev -mindepth 1 -maxdepth 1 -type d -name ${r} -mtime +${e.maxAgeDays} -exec rm -rf -- {} + 2>/dev/null || true`:`find ${t} -xdev -mindepth 1 -maxdepth 1 -type f -name ${r} -mtime +${e.maxAgeDays} -delete 2>/dev/null || true`}function js(){return[`find /root/.bun/install/cache -xdev -type f -mtime +${Ke("bunCacheMaxAgeDays")} -delete 2>/dev/null || true`,`find /root/.bun/install/cache -xdev -depth -type d -empty -mtime +${Ke("bunCacheMaxAgeDays")} -delete 2>/dev/null || true`,`if command -v docker >/dev/null 2>&1; then docker image prune --all --force --filter "until=\${${Ft.containerImageMaxAgeHours}}h" >/dev/null 2>&1 || true; fi`,`if command -v podman >/dev/null 2>&1; then podman image prune --all --force --filter "until=\${${Ft.containerImageMaxAgeHours}}h" >/dev/null 2>&1 || true; fi`,"if command -v apt-get >/dev/null 2>&1; then apt-get clean >/dev/null 2>&1 || true; fi"]}function Gs(e){return[`${e}="$(df -P / 2>/dev/null | awk 'NR==2 {sub(/%/, "", $5); print $5}' || true)"`,`case "$${e}" in ''|*[!0-9]*) ${e}=-1 ;; esac`]}function ri(e){let{retention:t,pressure:r,paths:n}=Fr(e),s='echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',i='echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"';if(!r)return['echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',Pn(t),...Ks(n),...js(),'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"'];let{lowWaterPercent:a,highWaterPercent:c,escalated:u}=r;return['echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',...Gs("TS_CLOUD_HC_BEFORE"),"TS_CLOUD_HC_TIER=normal",Pn(t),`if [ "$TS_CLOUD_HC_BEFORE" -ge 0 ] && [ "$TS_CLOUD_HC_BEFORE" -lt ${a} ]; then`," TS_CLOUD_HC_TIER=light",` echo "[ts-cloud] host cleanup: / at \${TS_CLOUD_HC_BEFORE}% (under ${a}%), skipping cache and image pruning"`,`elif [ "$TS_CLOUD_HC_BEFORE" -ge ${c} ]; then`," TS_CLOUD_HC_TIER=pressure",` ${Pn(u)}`,` echo "[ts-cloud] warning: / at \${TS_CLOUD_HC_BEFORE}% (at or above ${c}%), host cleanup is using shortened retention windows" >&2`,"fi",...Ks(n),'if [ "$TS_CLOUD_HC_TIER" != light ]; then',...js().map((f)=>` ${f}`),"fi",'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"',...Gs("TS_CLOUD_HC_AFTER"),`echo "[ts-cloud] host-cleanup {\\"event\\":\\"host-cleanup\\",\\"tier\\":\\"$TS_CLOUD_HC_TIER\\",\\"diskBeforePercent\\":$TS_CLOUD_HC_BEFORE,\\"diskAfterPercent\\":$TS_CLOUD_HC_AFTER,\\"lowWaterPercent\\":${a},\\"highWaterPercent\\":${c}}"`,"mkdir -p /var/lib/ts-cloud 2>/dev/null || true",'TS_CLOUD_HC_PREV="$(cat /var/lib/ts-cloud/host-cleanup.alert 2>/dev/null || echo ok)"',`if [ "$TS_CLOUD_HC_AFTER" -ge ${c} ]; then`,` echo "[ts-cloud] warning: / still at \${TS_CLOUD_HC_AFTER}% after host cleanup (high-water ${c}%); something outside ts-cloud's retention rules is filling the disk" >&2`,` if [ "$TS_CLOUD_HC_PREV" != alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "⚠️ $(hostname): / at \${TS_CLOUD_HC_AFTER}% after host cleanup (high-water ${c}%)" >/dev/null 2>&1 || true; fi`," echo alert > /var/lib/ts-cloud/host-cleanup.alert 2>/dev/null || true","else",` if [ "$TS_CLOUD_HC_PREV" = alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "✅ $(hostname): / back under ${c}% after host cleanup (\${TS_CLOUD_HC_AFTER}%)" >/dev/null 2>&1 || true; fi`," echo ok > /var/lib/ts-cloud/host-cleanup.alert 2>/dev/null || true","fi"]}function Qg(e){return["#!/usr/bin/env bash","# Managed by ts-cloud: rewritten on every deploy. Configure compute.hostCleanup instead of editing.","set -uo pipefail","TS_CLOUD_HC_LOCK=/run/lock/ts-cloud-host-cleanup.lock","[ -d /run/lock ] || TS_CLOUD_HC_LOCK=/tmp/ts-cloud-host-cleanup.lock",'if command -v flock >/dev/null 2>&1 && exec 9>"$TS_CLOUD_HC_LOCK"; then',' if ! flock -n 9; then echo "[ts-cloud] host cleanup already running; skipping"; exit 0; fi',"fi",...ri(e),"exit 0"]}function En(e,t,r,n,s){return[`cat > ${e}.ts-cloud-new <<'${r}' || true`,...t,r,`if [ -s ${e}.ts-cloud-new ] && ! cmp -s ${e}.ts-cloud-new ${e}; then chmod ${n} ${e}.ts-cloud-new && mv -f ${e}.ts-cloud-new ${e}${s?` && ${s}=1`:""} || true; else rm -f ${e}.ts-cloud-new; fi`]}function to(e){let t=Fr(e),r="/etc/systemd/system/ts-cloud-host-cleanup",n=["if [ -f /etc/systemd/system/ts-cloud-host-cleanup.timer ]; then"," systemctl disable --now ts-cloud-host-cleanup.timer >/dev/null 2>&1 || true"," rm -f /etc/systemd/system/ts-cloud-host-cleanup.timer /etc/systemd/system/ts-cloud-host-cleanup.service"," systemctl daemon-reload >/dev/null 2>&1 || true","fi"];if(!t.enabled)return[...n,"rm -f /usr/local/bin/ts-cloud-host-cleanup.sh"];let s=En("/usr/local/bin/ts-cloud-host-cleanup.sh",Qg(e),"TS_CLOUD_HOST_CLEANUP_EOF","755");if(!t.timer)return[...s,...n];return[...s,"TS_CLOUD_HC_UNITS_CHANGED=0","if command -v systemctl >/dev/null 2>&1 && [ -d /etc/systemd/system ]; then",...En("/etc/systemd/system/ts-cloud-host-cleanup.service",["[Unit]","Description=ts-cloud host cleanup (bounded disk retention)","After=local-fs.target","","[Service]","Type=oneshot","ExecStart=/usr/local/bin/ts-cloud-host-cleanup.sh","Nice=19","IOSchedulingClass=idle"],"TS_CLOUD_HOST_CLEANUP_SVC_EOF","644","TS_CLOUD_HC_UNITS_CHANGED"),...En("/etc/systemd/system/ts-cloud-host-cleanup.timer",["[Unit]","Description=Run ts-cloud host cleanup on a schedule, independent of deploys","","[Timer]",`OnCalendar=${t.schedule}`,"RandomizedDelaySec=1h","Persistent=true","","[Install]","WantedBy=timers.target"],"TS_CLOUD_HOST_CLEANUP_TMR_EOF","644","TS_CLOUD_HC_UNITS_CHANGED"),' if [ "$TS_CLOUD_HC_UNITS_CHANGED" -eq 1 ]; then systemctl daemon-reload >/dev/null 2>&1 || true; fi'," systemctl enable --now ts-cloud-host-cleanup.timer >/dev/null 2>&1 || true","fi"]}function ni(e){let t=to(e);if(!Fr(e).enabled)return t;return[...t,'if [ -x /usr/local/bin/ts-cloud-host-cleanup.sh ]; then /usr/local/bin/ts-cloud-host-cleanup.sh < /dev/null || echo "[ts-cloud] warning: host cleanup exited $?" >&2; fi']}var mc=/\.(?:[cm]?[jt]sx?)$/;function ii(e,t,r){let n=t==="bun"?"/usr/local/bin/bun":t==="deno"?"/usr/local/bin/deno":"/usr/local/bin/node",s=e.trim();if(/^(?:bun|node|deno)\s+/.test(s))return`${n} ${s.replace(/^(?:bun|node|deno)\s+/,"")}`;let[i="",...a]=s.split(/\s+/);if(i&&!mc.test(i)){let c=i.startsWith("/")?i:r&&i.startsWith("./")?`${r.replace(/\/+$/,"")}/${i.replace(/^\.\//,"")}`:void 0;if(c)return[c,...a].join(" ")}return`${n} ${s}`}function Vs(e){return["TS_CLOUD_MEM_MB=$(awk '/^MemTotal:/{print int($2/1024)}' /proc/meminfo)","TS_CLOUD_HIGH_MB=$((TS_CLOUD_MEM_MB / 8))",'[ "$TS_CLOUD_HIGH_MB" -lt 512 ] && TS_CLOUD_HIGH_MB=512','[ "$TS_CLOUD_HIGH_MB" -gt 4096 ] && TS_CLOUD_HIGH_MB=4096',`mkdir -p /etc/systemd/system/${e}.d`,`printf '# Written by ts-cloud: memoryHigh resolved from this box.
155
155
  # An eighth of %sMB RAM. Set memoryHigh in config to override.
156
156
  [Service]
157
157
  MemoryAccounting=true
158
158
  MemoryHigh=%sM
159
- ' "$TS_CLOUD_MEM_MB" "$TS_CLOUD_HIGH_MB" > /etc/systemd/system/${e}.d/50-ts-cloud-memory.conf`,"systemctl daemon-reload",'echo "[ts-cloud] memoryHigh=auto resolved to ${TS_CLOUD_HIGH_MB}M (one eighth of ${TS_CLOUD_MEM_MB}M)"',...On()]}function br(e,t={auto:!0}){let r=t.auto===!1?[]:[`/etc/systemd/system/${e}.d/50-ts-cloud-memory.conf`];for(let n of["/etc/systemd/system.control","/run/systemd/system.control"]){if(t.high)r.push(`${n}/${e}.d/50-MemoryHigh.conf`);if(t.max)r.push(`${n}/${e}.d/50-MemoryMax.conf`)}if(r.length===0)return[];return["TS_CLOUD_MEM_CLEARED=0",...r.map((n)=>`if [ -f ${n} ]; then rm -f ${n}; TS_CLOUD_MEM_CLEARED=1; echo "[ts-cloud] removed ${n}: memory limits now come from config"; fi`),'if [ "$TS_CLOUD_MEM_CLEARED" = 1 ]; then systemctl daemon-reload; fi']}function On(){return[`TS_CLOUD_COMMIT=$(for f in /sys/fs/cgroup/system.slice/*.service/memory.high /sys/fs/cgroup/system.slice/*.slice/*.service/memory.high; do [ -f "$f" ] || continue; v=$(cat "$f" 2>/dev/null); [ "$v" = "max" ] && continue; echo "$v"; done | awk '{s+=$1} END {print int(s/1048576)}')`,"TS_CLOUD_RAM=$(awk '/^MemTotal:/{print int($2/1024)}' /proc/meminfo)",'if [ -n "$TS_CLOUD_COMMIT" ] && [ "$TS_CLOUD_COMMIT" -gt 0 ] && [ "$TS_CLOUD_RAM" -gt 0 ]; then TS_CLOUD_PCT=$((TS_CLOUD_COMMIT * 100 / TS_CLOUD_RAM)); if [ "$TS_CLOUD_PCT" -gt 300 ]; then echo "[ts-cloud] WARNING: services on this box declare ${TS_CLOUD_COMMIT}M of MemoryHigh against ${TS_CLOUD_RAM}M of RAM (${TS_CLOUD_PCT}% committed). Soft ceilings, so this is not fatal - but no ceiling can protect the box once enough of them are drawn on at once."; else echo "[ts-cloud] memory commitment: ${TS_CLOUD_COMMIT}M declared against ${TS_CLOUD_RAM}M RAM (${TS_CLOUD_PCT}%)"; fi; fi']}function fc(e){return[`TS_CLOUD_SLICE=$(systemctl show ${e} -p Slice --value 2>/dev/null || true)`,'if [ -n "$TS_CLOUD_SLICE" ] && [ "$TS_CLOUD_SLICE" != "system.slice" ]; then systemctl set-property --runtime "$TS_CLOUD_SLICE" MemoryHigh=infinity MemoryMax=infinity 2>/dev/null || true; systemctl set-property "$TS_CLOUD_SLICE" MemoryHigh=infinity MemoryMax=infinity 2>/dev/null || true; fi']}var Qe={path:"/",intervalSeconds:60,failuresBeforeRestart:3,timeoutSeconds:10,startupGraceSeconds:600,maxBackoffSeconds:3600,backoffBaseSeconds:300};function zt(e,t,r){return typeof e==="number"&&Number.isFinite(e)?Math.max(r,Math.floor(e)):t}function Ws(e){let{unitBase:t,unitPattern:r,port:n}=e,s=e.path&&e.path.startsWith("/")?e.path:Qe.path,i=zt(e.intervalSeconds,Qe.intervalSeconds,10),a=zt(e.failuresBeforeRestart,Qe.failuresBeforeRestart,1),c=zt(e.timeoutSeconds,Qe.timeoutSeconds,1),u=zt(e.startupGraceSeconds,Qe.startupGraceSeconds,0),f=zt(e.maxBackoffSeconds,Qe.maxBackoffSeconds,0),h=Math.min(Qe.backoffBaseSeconds,f),S=`/usr/local/sbin/${t}-liveness`,v=`/run/${t}-liveness`,_=`${t}-liveness`,y=`127.0.0.1:${n}${s}`,D=r.includes("@*")?`TS_CLOUD_UNIT=$(systemctl list-units --plain --no-legend --type=service '${r}' 2>/dev/null | awk '{print $1}' | head -1)`:`TS_CLOUD_UNIT=${r}`;return[`cat > ${S} <<'TS_CLOUD_LIVENESS_EOF'`,"#!/bin/sh",`# Liveness check for ${t}, written by ts-cloud on every deploy.`,`# Settings: interval=${i}s timeout=${c}s failures=${a} startup-grace=${u}s max-backoff=${f}s`,"set -eu",`TS_CLOUD_STATE=${v}`,'exec 9>"$TS_CLOUD_STATE.lock"',"flock -n 9 || exit 0",D,'[ -n "$TS_CLOUD_UNIT" ] || exit 0','systemctl is-active --quiet "$TS_CLOUD_UNIT" || exit 0',"TS_CLOUD_RC=0",`curl -s -o /dev/null --max-time ${c} "http://${y}" || TS_CLOUD_RC=$?`,'if [ "$TS_CLOUD_RC" -eq 0 ]; then',' rm -f "$TS_CLOUD_STATE.fail"',' if [ -f "$TS_CLOUD_STATE.restarts" ]; then',` TS_CLOUD_LAST=$(awk '{print $2}' "$TS_CLOUD_STATE.restarts" 2>/dev/null || true)`,` case "$TS_CLOUD_LAST" in ''|*[!0-9]*) TS_CLOUD_LAST=0 ;; esac`,` [ $(($(date +%s) - TS_CLOUD_LAST)) -lt ${f} ] || rm -f "$TS_CLOUD_STATE.restarts"`," fi"," exit 0","fi",'case "$TS_CLOUD_RC" in'," 7) TS_CLOUD_WHY='connection refused' ;;",` 28) TS_CLOUD_WHY='no response within ${c}s' ;;`,' *) TS_CLOUD_WHY="curl exit $TS_CLOUD_RC" ;;',"esac",'TS_CLOUD_SINCE=$(systemctl show "$TS_CLOUD_UNIT" -p ActiveEnterTimestampMonotonic --value 2>/dev/null || true)',"TS_CLOUD_UPTIME=$(cut -d' ' -f1 /proc/uptime 2>/dev/null || true)",`TS_CLOUD_AGE=$(awk -v up="$TS_CLOUD_UPTIME" -v since="$TS_CLOUD_SINCE" 'BEGIN { if (since + 0 > 0 && up + 0 > 0) print int(up - since / 1000000); else print -1 }')`,`case "$TS_CLOUD_AGE" in ''|*[!0-9-]*) TS_CLOUD_AGE=-1 ;; esac`,'if [ "$TS_CLOUD_AGE" -lt 0 ]; then',' TS_CLOUD_PID=$(systemctl show "$TS_CLOUD_UNIT" -p MainPID --value 2>/dev/null || true)',` case "$TS_CLOUD_PID" in ''|0|*[!0-9]*) ;; *) TS_CLOUD_AGE=$(ps -o etimes= -p "$TS_CLOUD_PID" 2>/dev/null | tr -d ' ' || true) ;; esac`,` case "$TS_CLOUD_AGE" in ''|*[!0-9]*) TS_CLOUD_AGE=-1 ;; esac`,"fi",`if [ "$TS_CLOUD_AGE" -ge 0 ] && [ "$TS_CLOUD_AGE" -lt ${u} ]; then`,' rm -f "$TS_CLOUD_STATE.fail"',` logger -t ${_} "$TS_CLOUD_UNIT is \${TS_CLOUD_AGE}s old, inside its ${u}s startup grace; not counting this failed check on ${y} ($TS_CLOUD_WHY)"`," exit 0","fi",'TS_CLOUD_FAILS=$(cat "$TS_CLOUD_STATE.fail" 2>/dev/null || echo 0)',`case "$TS_CLOUD_FAILS" in ''|*[!0-9]*) TS_CLOUD_FAILS=0 ;; esac`,"TS_CLOUD_FAILS=$((TS_CLOUD_FAILS + 1))",'echo "$TS_CLOUD_FAILS" > "$TS_CLOUD_STATE.fail"',`if [ "$TS_CLOUD_FAILS" -lt ${a} ]; then`,` logger -t ${_} "check $TS_CLOUD_FAILS of ${a} failed on ${y} ($TS_CLOUD_WHY)"`," exit 0","fi","TS_CLOUD_NOW=$(date +%s)","TS_CLOUD_STREAK=0","TS_CLOUD_LAST=0",'[ ! -f "$TS_CLOUD_STATE.restarts" ] || read -r TS_CLOUD_STREAK TS_CLOUD_LAST < "$TS_CLOUD_STATE.restarts" || true',`case "$TS_CLOUD_STREAK" in ''|*[!0-9]*) TS_CLOUD_STREAK=0 ;; esac`,`case "$TS_CLOUD_LAST" in ''|*[!0-9]*) TS_CLOUD_LAST=0 ;; esac`,'if [ "$TS_CLOUD_STREAK" -gt 0 ]; then',` TS_CLOUD_WAIT=${h}`," TS_CLOUD_I=1",` while [ "$TS_CLOUD_I" -lt "$TS_CLOUD_STREAK" ] && [ "$TS_CLOUD_WAIT" -lt ${f} ]; do TS_CLOUD_WAIT=$((TS_CLOUD_WAIT * 2)); TS_CLOUD_I=$((TS_CLOUD_I + 1)); done`,` [ "$TS_CLOUD_WAIT" -le ${f} ] || TS_CLOUD_WAIT=${f}`," TS_CLOUD_ELAPSED=$((TS_CLOUD_NOW - TS_CLOUD_LAST))",' if [ "$TS_CLOUD_ELAPSED" -lt "$TS_CLOUD_WAIT" ]; then',` logger -t ${_} "holding off: $TS_CLOUD_STREAK liveness restart(s) in a row have not brought $TS_CLOUD_UNIT back; next restart allowed in $((TS_CLOUD_WAIT - TS_CLOUD_ELAPSED))s ($TS_CLOUD_WHY on ${y})"`," exit 0"," fi","fi","TS_CLOUD_STREAK=$((TS_CLOUD_STREAK + 1))",`logger -t ${_} "no HTTP response on ${y} after $TS_CLOUD_FAILS checks ($TS_CLOUD_WHY); restarting $TS_CLOUD_UNIT (liveness restart $TS_CLOUD_STREAK in a row)"`,'echo "$TS_CLOUD_STREAK $TS_CLOUD_NOW" > "$TS_CLOUD_STATE.restarts"','rm -f "$TS_CLOUD_STATE.fail"','systemctl restart "$TS_CLOUD_UNIT"',"TS_CLOUD_LIVENESS_EOF",`chmod +x ${S}`,`rm -f ${v}.fail ${v}.restarts`,`cat > /etc/systemd/system/${t}-liveness.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=Liveness check for ${t} (managed by ts-cloud)`,"","[Service]","Type=oneshot",`ExecStart=${S}`,"TS_CLOUD_UNIT_EOF",`cat > /etc/systemd/system/${t}-liveness.timer <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=Run the ${t} liveness check every ${i}s`,"","[Timer]",`OnUnitActiveSec=${i}s`,`OnBootSec=${i}s`,"Persistent=true","","[Install]","WantedBy=timers.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",`systemctl enable --now ${t}-liveness.timer >/dev/null 2>&1 || true`]}var qs=20,Rn=3,gc=5,hc=60;function Sc(e){let{paths:t,unitBase:r,releaseId:n,port:s}=e,i=`${r}@${n}.service`,a=`${r}.service`,c=Math.max(1,e.healthGateSeconds??5),u=e.healthCheckPath?e.healthCheckPath.startsWith("/")?e.healthCheckPath:`/${e.healthCheckPath}`:null,f=u?`curl -sf -o /dev/null --max-time ${gc} "http://127.0.0.1:${s}${u}"`:null,h=(S)=>`{ echo "[ts-cloud] release ${n} ${S}" >&2; ts_cloud_restore_previous; exit 1; }`;return[`TS_CLOUD_OLD_UNITS=$(systemctl list-units --plain --no-legend --type=service "${r}@*.service" 2>/dev/null | awk '{print $1}' | grep -v "^${i}$" || true)`,`TS_CLOUD_PREV_CURRENT="$(readlink ${t.current} 2>/dev/null || true)"`,"TS_CLOUD_LEGACY_STOPPED=0","ts_cloud_restore_previous() {",` journalctl -u ${i} -n 50 --no-pager >&2 || true`,` systemctl stop ${i} 2>/dev/null || true`,` systemctl disable ${i} 2>/dev/null || true`,` if [ -n "$TS_CLOUD_PREV_CURRENT" ] && [ -d "$TS_CLOUD_PREV_CURRENT" ]; then ln -sfn "$TS_CLOUD_PREV_CURRENT" ${t.current}.tmp && mv -Tf ${t.current}.tmp ${t.current}; fi`,' for TS_CLOUD_RU in ${TS_CLOUD_OLD_UNITS}; do systemctl enable "$TS_CLOUD_RU" 2>/dev/null || true; systemctl start "$TS_CLOUD_RU" 2>/dev/null || true; done',` if [ "$TS_CLOUD_LEGACY_STOPPED" -eq 1 ]; then systemctl start ${a} 2>/dev/null || true; fi`,' if [ -n "$TS_CLOUD_OLD_UNITS" ] || [ "$TS_CLOUD_LEGACY_STOPPED" -eq 1 ]; then echo "[ts-cloud] previous release restored and serving" >&2; else echo "[ts-cloud] there was no previous release to restore" >&2; fi',"}",`if [ -f /etc/systemd/system/${a} ] && systemctl is-active --quiet ${a}; then echo "[ts-cloud] retiring pre-zero-downtime unit ${a} (one-time restart cutover)"; systemctl stop ${a}; TS_CLOUD_LEGACY_STOPPED=1; fi`,'TS_CLOUD_STARTED_AT="@$(date +%s)"',`systemctl restart ${i}`,`TS_CLOUD_GATE_OK=1; for TS_CLOUD_I in $(seq 1 ${c}); do sleep 1; systemctl is-active --quiet ${i} || { TS_CLOUD_GATE_OK=0; break; }; done`,'if [ "$TS_CLOUD_GATE_OK" -ne 1 ]; then',` if journalctl -u ${i} --since "$TS_CLOUD_STARTED_AT" -o cat --no-pager 2>/dev/null | grep -iE 'EADDRINUSE|address already in use|port [0-9]+ (is )?in use|Failed to start server' >/dev/null; then`,` echo "[ts-cloud] release ${n} could not share :${s} with the previous release (no SO_REUSEPORT?) — retiring it and retrying" >&2`,' for TS_CLOUD_RU in ${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_RU" 2>/dev/null || true; done',` systemctl restart ${i}`,` for TS_CLOUD_I in $(seq 1 ${c}); do sleep 1; systemctl is-active --quiet ${i} || ${h("failed its health gate on the free port")}; done`," else",` ${h("crashed on start — the previous release was never stopped")}`," fi","fi",`if ss -ltnpH "sport = :${s}" >/dev/null 2>&1; then`," TS_CLOUD_BOUND=0",` for TS_CLOUD_I in $(seq 1 ${hc}); do`,` TS_CLOUD_NEW_PID="$(systemctl show -p MainPID --value ${i} 2>/dev/null || true)"`,` if [ -n "$TS_CLOUD_NEW_PID" ] && [ "$TS_CLOUD_NEW_PID" != "0" ] && ss -ltnpH "sport = :${s}" 2>/dev/null | grep "pid=$TS_CLOUD_NEW_PID," >/dev/null; then TS_CLOUD_BOUND=1; break; fi`,` systemctl is-active --quiet ${i} || break`,` sleep ${Rn}`," done",` [ "$TS_CLOUD_BOUND" -eq 1 ] || ${h(`never took :${s}`)}`,"else",' echo "[ts-cloud] cannot read listener PIDs on this host — the response probes run without the bind check" >&2',"fi",...f?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${qs}); do if ${f}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${Rn}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${h(`never answered ${u}`)}`]:[],...pt(t),`systemctl enable ${i} 2>/dev/null || true`,'for TS_CLOUD_U in ${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done',`TS_CLOUD_LISTENING=0; for TS_CLOUD_I in $(seq 1 ${c}); do if ss -ltnH "sport = :${s}" 2>/dev/null | grep . >/dev/null; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done`,`if [ "$TS_CLOUD_LISTENING" -ne 1 ]; then echo "[ts-cloud] nothing is listening on ${s} after retiring the previous release — restarting ${i} on the now-free port" >&2; systemctl restart ${i}; for TS_CLOUD_I in $(seq 1 ${c}); do if ss -ltnH "sport = :${s}" 2>/dev/null | grep . >/dev/null; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done; fi`,`[ "$TS_CLOUD_LISTENING" -eq 1 ] || ${h(`is active but never bound :${s}`)}`,...f?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${qs}); do if ${f}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${Rn}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${h(`stopped answering ${u} once it served alone`)}`]:[],...Tn(t),`systemctl list-unit-files --plain --no-legend "${r}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v -e "^${i}$" -e "^${r}@\\.service$" || true; } | while read -r TS_CLOUD_U; do systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done`,`if [ -f /etc/systemd/system/${a} ]; then systemctl disable ${a} 2>/dev/null || true; rm -f /etc/systemd/system/${a}; systemctl daemon-reload; fi`]}function Ys(e,t){if(!t.length)return[];let r=et(e.release);return[`if [ -e ${r} ] || [ -L ${r} ]; then`,...t,"fi"]}function si(e){let{siteName:t,slug:r,artifactFetch:n,releaseId:s,execStart:i,envEntries:a,port:c,keepReleases:u=Ht,preStartCommands:f=[],postActivateCommands:h=[],beforeResetCommands:S=[],healthCheckPath:v,healthGateSeconds:_=5,liveness:y,memoryHigh:b="auto",memoryMax:D,cpuWeight:V,ioWeight:H,tasksMax:x,stopTimeout:k}=e,I=[...V!=null?[`CPUWeight=${V}`]:[],...H!=null?[`IOWeight=${H}`]:[],...x!=null?[`TasksMax=${x}`]:[],...k?[`TimeoutStopSec=${k}`]:[]],Y=e.zeroDowntime??c!=null,W=e.appDir??`/var/www/${t}`,K=Zt(W,s),ee=`${r}-${t}`,re=`${ee}.service`,te=ai(r,t,s),ie=e.sharedPaths??[],oe=Hs([".env",...ie,...yr(a,ie)]),ne=fr(a),he=f.length>0?[`cd ${K.release}`,...f]:[],ye=["set -euo pipefail",...vn(K),...n,...Mt(K,oe),...Ys(K,S),$n(K),..._n(K),`tar xzf ${te} -C "$TS_CLOUD_STAGED"`,`rm -f ${te}`,`cat > ${K.shared}/.env <<'TS_CLOUD_ENV_EOF'`,ne,"TS_CLOUD_ENV_EOF",`chmod 600 ${K.shared}/.env`,...yn(K),`find ${K.release} -maxdepth 1 \\( -type f -o -type l \\) -name '.env*' ! -name '.env.example' ! -name '*.example' -delete`,`sed -i -E '/^[[:space:]]*(PORT|PORT_BACKEND|PORT_ADMIN|PORT_FRONTEND)[[:space:]]*=/d' ${K.shared}/.env 2>/dev/null || true`,...Sr(K,oe),...he,...e.isolation?Ls(e.slug||t,K.base,oe.flatMap((T)=>typeof T==="string"||!T.target?[]:[T.target])):[]];if(Y&&c!=null){let T=`${ee}@${s}.service`,L=v?v.startsWith("/")?v:`/${v}`:null;return[...ye,`cat > /etc/systemd/system/${ee}@.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} release %i (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",...e.isolation?Ut(ut(e.slug||t)):[],`WorkingDirectory=${K.releases}/%i`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...b&&b!=="auto"?[`MemoryHigh=${b}`]:[],...D?[`MemoryMax=${D}`]:[],...I,`EnvironmentFile=${K.releases}/%i/.env`,`Environment=PORT=${c}`,`Environment=STX_IMAGE_CACHE_DIR=${hr(K)}`,`Environment=STX_BUNDLE_CACHE_DIR=${Nt(K)}`,`Environment=STX_BUNDLE_CACHE_DIR=${Nt(K)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...b==="auto"?Vs(`${ee}@.service`):[...br(`${ee}@.service`),...On()],...fc(T),...Sc({paths:K,unitBase:ee,releaseId:s,port:c,healthCheckPath:L,healthGateSeconds:_}),...h,...dt(K,u),...y===!1?[]:Ws({...y,unitBase:ee,unitPattern:`${ee}@*.service`,port:c,path:y?.path??v})]}return[...ye,`cat > /etc/systemd/system/${re} <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",...e.isolation?Ut(ut(e.slug||t)):[],`WorkingDirectory=${K.current}`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...b&&b!=="auto"?[`MemoryHigh=${b}`]:[],...D?[`MemoryMax=${D}`]:[],...I,`EnvironmentFile=${K.current}/.env`,...c?[`Environment=PORT=${c}`]:[],`Environment=STX_IMAGE_CACHE_DIR=${hr(K)}`,`Environment=STX_BUNDLE_CACHE_DIR=${Nt(K)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...br(re,{auto:b!=="auto",high:b!=="auto",max:Boolean(D)}),...b==="auto"?Vs(re):On(),`systemctl enable ${re}`,`TS_CLOUD_PREV_CURRENT="$(readlink ${K.current} 2>/dev/null || true)"`,...pt(K),`systemctl restart ${re}`,`for TS_CLOUD_I in $(seq 1 ${Math.max(1,_)}); do sleep 1; systemctl is-active --quiet ${re} || { echo "[ts-cloud] release ${s} of ${re} did not stay up — restoring the previous release" >&2; journalctl -u ${re} -n 50 --no-pager >&2 || true; if [ -n "$TS_CLOUD_PREV_CURRENT" ] && [ -d "$TS_CLOUD_PREV_CURRENT" ] && [ "$(readlink -f "$TS_CLOUD_PREV_CURRENT")" != "$(readlink -f ${K.release})" ]; then ln -sfn "$TS_CLOUD_PREV_CURRENT" ${K.current}.tmp && mv -Tf ${K.current}.tmp ${K.current}; systemctl restart ${re} || true; fi; exit 1; }; done`,...Tn(K),...h,...dt(K,u),...y===!1||!c?[]:Ws({...y,unitBase:ee,unitPattern:re,port:c,path:y?.path??v})]}function oi(e){let{siteName:t,artifactFetch:r,releaseId:n,keepReleases:s=Ht,preStartCommands:i=[],postActivateCommands:a=[],beforeResetCommands:c=[]}=e,u=e.appDir??`/var/www/${t}`,f=Zt(u,n),h=ai(e.slug,t,n),S=i.length>0?[`cd ${f.release}`,...i]:[];return["set -euo pipefail",...vn(f),...r,...Mt(f,[]),...Ys(f,c),$n(f),..._n(f),`tar xzf ${h} -C "$TS_CLOUD_STAGED"`,...yn(f),`rm -f ${h}`,...S,...pt(f),...a,...dt(f,s)]}function ai(e,t,r){return`/tmp/${[e,t,r].filter(Boolean).join("-")}-release.tar.gz`}function $c(e,t,r,n){return[`aws s3 cp "s3://${e}/${t}" ${n} --region ${r}`]}function Mc(e,t){return[`mv "${e}" ${t}`]}function et(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function Tr(e,t,r){return["set -euo pipefail",`chmod 600 ${et(e)}`,`mv -f -- ${et(e)} ${et(t)}`,`cp -- ${et(t)} ${et(r)}`].join(`
159
+ ' "$TS_CLOUD_MEM_MB" "$TS_CLOUD_HIGH_MB" > /etc/systemd/system/${e}.d/50-ts-cloud-memory.conf`,"systemctl daemon-reload",'echo "[ts-cloud] memoryHigh=auto resolved to ${TS_CLOUD_HIGH_MB}M (one eighth of ${TS_CLOUD_MEM_MB}M)"',...On()]}function br(e,t={auto:!0}){let r=t.auto===!1?[]:[`/etc/systemd/system/${e}.d/50-ts-cloud-memory.conf`];for(let n of["/etc/systemd/system.control","/run/systemd/system.control"]){if(t.high)r.push(`${n}/${e}.d/50-MemoryHigh.conf`);if(t.max)r.push(`${n}/${e}.d/50-MemoryMax.conf`)}if(r.length===0)return[];return["TS_CLOUD_MEM_CLEARED=0",...r.map((n)=>`if [ -f ${n} ]; then rm -f ${n}; TS_CLOUD_MEM_CLEARED=1; echo "[ts-cloud] removed ${n}: memory limits now come from config"; fi`),'if [ "$TS_CLOUD_MEM_CLEARED" = 1 ]; then systemctl daemon-reload; fi']}function On(){return[`TS_CLOUD_COMMIT=$(for f in /sys/fs/cgroup/system.slice/*.service/memory.high /sys/fs/cgroup/system.slice/*.slice/*.service/memory.high; do [ -f "$f" ] || continue; v=$(cat "$f" 2>/dev/null); [ "$v" = "max" ] && continue; echo "$v"; done | awk '{s+=$1} END {print int(s/1048576)}')`,"TS_CLOUD_RAM=$(awk '/^MemTotal:/{print int($2/1024)}' /proc/meminfo)",'if [ -n "$TS_CLOUD_COMMIT" ] && [ "$TS_CLOUD_COMMIT" -gt 0 ] && [ "$TS_CLOUD_RAM" -gt 0 ]; then TS_CLOUD_PCT=$((TS_CLOUD_COMMIT * 100 / TS_CLOUD_RAM)); if [ "$TS_CLOUD_PCT" -gt 300 ]; then echo "[ts-cloud] WARNING: services on this box declare ${TS_CLOUD_COMMIT}M of MemoryHigh against ${TS_CLOUD_RAM}M of RAM (${TS_CLOUD_PCT}% committed). Soft ceilings, so this is not fatal - but no ceiling can protect the box once enough of them are drawn on at once."; else echo "[ts-cloud] memory commitment: ${TS_CLOUD_COMMIT}M declared against ${TS_CLOUD_RAM}M RAM (${TS_CLOUD_PCT}%)"; fi; fi']}function fc(e){return[`TS_CLOUD_SLICE=$(systemctl show ${e} -p Slice --value 2>/dev/null || true)`,'if [ -n "$TS_CLOUD_SLICE" ] && [ "$TS_CLOUD_SLICE" != "system.slice" ]; then systemctl set-property --runtime "$TS_CLOUD_SLICE" MemoryHigh=infinity MemoryMax=infinity 2>/dev/null || true; systemctl set-property "$TS_CLOUD_SLICE" MemoryHigh=infinity MemoryMax=infinity 2>/dev/null || true; fi']}var Qe={path:"/",intervalSeconds:60,failuresBeforeRestart:3,timeoutSeconds:10,startupGraceSeconds:600,maxBackoffSeconds:3600,backoffBaseSeconds:300};function zt(e,t,r){return typeof e==="number"&&Number.isFinite(e)?Math.max(r,Math.floor(e)):t}function Ws(e){let{unitBase:t,unitPattern:r,port:n}=e,s=e.path&&e.path.startsWith("/")?e.path:Qe.path,i=zt(e.intervalSeconds,Qe.intervalSeconds,10),a=zt(e.failuresBeforeRestart,Qe.failuresBeforeRestart,1),c=zt(e.timeoutSeconds,Qe.timeoutSeconds,1),u=zt(e.startupGraceSeconds,Qe.startupGraceSeconds,0),f=zt(e.maxBackoffSeconds,Qe.maxBackoffSeconds,0),h=Math.min(Qe.backoffBaseSeconds,f),S=`/usr/local/sbin/${t}-liveness`,v=`/run/${t}-liveness`,_=`${t}-liveness`,y=`127.0.0.1:${n}${s}`,x=r.includes("@*")?`TS_CLOUD_UNIT=$(systemctl list-units --plain --no-legend --type=service '${r}' 2>/dev/null | awk '{print $1}' | head -1)`:`TS_CLOUD_UNIT=${r}`;return[`cat > ${S} <<'TS_CLOUD_LIVENESS_EOF'`,"#!/bin/sh",`# Liveness check for ${t}, written by ts-cloud on every deploy.`,`# Settings: interval=${i}s timeout=${c}s failures=${a} startup-grace=${u}s max-backoff=${f}s`,"set -eu",`TS_CLOUD_STATE=${v}`,'exec 9>"$TS_CLOUD_STATE.lock"',"flock -n 9 || exit 0",x,'[ -n "$TS_CLOUD_UNIT" ] || exit 0','systemctl is-active --quiet "$TS_CLOUD_UNIT" || exit 0',"TS_CLOUD_RC=0",`curl -s -o /dev/null --max-time ${c} "http://${y}" || TS_CLOUD_RC=$?`,'if [ "$TS_CLOUD_RC" -eq 0 ]; then',' rm -f "$TS_CLOUD_STATE.fail"',' if [ -f "$TS_CLOUD_STATE.restarts" ]; then',` TS_CLOUD_LAST=$(awk '{print $2}' "$TS_CLOUD_STATE.restarts" 2>/dev/null || true)`,` case "$TS_CLOUD_LAST" in ''|*[!0-9]*) TS_CLOUD_LAST=0 ;; esac`,` [ $(($(date +%s) - TS_CLOUD_LAST)) -lt ${f} ] || rm -f "$TS_CLOUD_STATE.restarts"`," fi"," exit 0","fi",'case "$TS_CLOUD_RC" in'," 7) TS_CLOUD_WHY='connection refused' ;;",` 28) TS_CLOUD_WHY='no response within ${c}s' ;;`,' *) TS_CLOUD_WHY="curl exit $TS_CLOUD_RC" ;;',"esac",'TS_CLOUD_SINCE=$(systemctl show "$TS_CLOUD_UNIT" -p ActiveEnterTimestampMonotonic --value 2>/dev/null || true)',"TS_CLOUD_UPTIME=$(cut -d' ' -f1 /proc/uptime 2>/dev/null || true)",`TS_CLOUD_AGE=$(awk -v up="$TS_CLOUD_UPTIME" -v since="$TS_CLOUD_SINCE" 'BEGIN { if (since + 0 > 0 && up + 0 > 0) print int(up - since / 1000000); else print -1 }')`,`case "$TS_CLOUD_AGE" in ''|*[!0-9-]*) TS_CLOUD_AGE=-1 ;; esac`,'if [ "$TS_CLOUD_AGE" -lt 0 ]; then',' TS_CLOUD_PID=$(systemctl show "$TS_CLOUD_UNIT" -p MainPID --value 2>/dev/null || true)',` case "$TS_CLOUD_PID" in ''|0|*[!0-9]*) ;; *) TS_CLOUD_AGE=$(ps -o etimes= -p "$TS_CLOUD_PID" 2>/dev/null | tr -d ' ' || true) ;; esac`,` case "$TS_CLOUD_AGE" in ''|*[!0-9]*) TS_CLOUD_AGE=-1 ;; esac`,"fi",`if [ "$TS_CLOUD_AGE" -ge 0 ] && [ "$TS_CLOUD_AGE" -lt ${u} ]; then`,' rm -f "$TS_CLOUD_STATE.fail"',` logger -t ${_} "$TS_CLOUD_UNIT is \${TS_CLOUD_AGE}s old, inside its ${u}s startup grace; not counting this failed check on ${y} ($TS_CLOUD_WHY)"`," exit 0","fi",'TS_CLOUD_FAILS=$(cat "$TS_CLOUD_STATE.fail" 2>/dev/null || echo 0)',`case "$TS_CLOUD_FAILS" in ''|*[!0-9]*) TS_CLOUD_FAILS=0 ;; esac`,"TS_CLOUD_FAILS=$((TS_CLOUD_FAILS + 1))",'echo "$TS_CLOUD_FAILS" > "$TS_CLOUD_STATE.fail"',`if [ "$TS_CLOUD_FAILS" -lt ${a} ]; then`,` logger -t ${_} "check $TS_CLOUD_FAILS of ${a} failed on ${y} ($TS_CLOUD_WHY)"`," exit 0","fi","TS_CLOUD_NOW=$(date +%s)","TS_CLOUD_STREAK=0","TS_CLOUD_LAST=0",'[ ! -f "$TS_CLOUD_STATE.restarts" ] || read -r TS_CLOUD_STREAK TS_CLOUD_LAST < "$TS_CLOUD_STATE.restarts" || true',`case "$TS_CLOUD_STREAK" in ''|*[!0-9]*) TS_CLOUD_STREAK=0 ;; esac`,`case "$TS_CLOUD_LAST" in ''|*[!0-9]*) TS_CLOUD_LAST=0 ;; esac`,'if [ "$TS_CLOUD_STREAK" -gt 0 ]; then',` TS_CLOUD_WAIT=${h}`," TS_CLOUD_I=1",` while [ "$TS_CLOUD_I" -lt "$TS_CLOUD_STREAK" ] && [ "$TS_CLOUD_WAIT" -lt ${f} ]; do TS_CLOUD_WAIT=$((TS_CLOUD_WAIT * 2)); TS_CLOUD_I=$((TS_CLOUD_I + 1)); done`,` [ "$TS_CLOUD_WAIT" -le ${f} ] || TS_CLOUD_WAIT=${f}`," TS_CLOUD_ELAPSED=$((TS_CLOUD_NOW - TS_CLOUD_LAST))",' if [ "$TS_CLOUD_ELAPSED" -lt "$TS_CLOUD_WAIT" ]; then',` logger -t ${_} "holding off: $TS_CLOUD_STREAK liveness restart(s) in a row have not brought $TS_CLOUD_UNIT back; next restart allowed in $((TS_CLOUD_WAIT - TS_CLOUD_ELAPSED))s ($TS_CLOUD_WHY on ${y})"`," exit 0"," fi","fi","TS_CLOUD_STREAK=$((TS_CLOUD_STREAK + 1))",`logger -t ${_} "no HTTP response on ${y} after $TS_CLOUD_FAILS checks ($TS_CLOUD_WHY); restarting $TS_CLOUD_UNIT (liveness restart $TS_CLOUD_STREAK in a row)"`,'echo "$TS_CLOUD_STREAK $TS_CLOUD_NOW" > "$TS_CLOUD_STATE.restarts"','rm -f "$TS_CLOUD_STATE.fail"','systemctl restart "$TS_CLOUD_UNIT"',"TS_CLOUD_LIVENESS_EOF",`chmod +x ${S}`,`rm -f ${v}.fail ${v}.restarts`,`cat > /etc/systemd/system/${t}-liveness.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=Liveness check for ${t} (managed by ts-cloud)`,"","[Service]","Type=oneshot",`ExecStart=${S}`,"TS_CLOUD_UNIT_EOF",`cat > /etc/systemd/system/${t}-liveness.timer <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=Run the ${t} liveness check every ${i}s`,"","[Timer]",`OnUnitActiveSec=${i}s`,`OnBootSec=${i}s`,"Persistent=true","","[Install]","WantedBy=timers.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",`systemctl enable --now ${t}-liveness.timer >/dev/null 2>&1 || true`]}var qs=20,Rn=3,gc=5,hc=60;function Sc(e){let{paths:t,unitBase:r,releaseId:n,port:s}=e,i=`${r}@${n}.service`,a=`${r}.service`,c=Math.max(1,e.healthGateSeconds??5),u=e.healthCheckPath?e.healthCheckPath.startsWith("/")?e.healthCheckPath:`/${e.healthCheckPath}`:null,f=u?`curl -sf -o /dev/null --max-time ${gc} "http://127.0.0.1:${s}${u}"`:null,h=(S)=>`{ echo "[ts-cloud] release ${n} ${S}" >&2; ts_cloud_restore_previous; exit 1; }`;return[`TS_CLOUD_OLD_UNITS=$(systemctl list-units --plain --no-legend --type=service "${r}@*.service" 2>/dev/null | awk '{print $1}' | grep -v "^${i}$" || true)`,`TS_CLOUD_PREV_CURRENT="$(readlink ${t.current} 2>/dev/null || true)"`,"TS_CLOUD_LEGACY_STOPPED=0","ts_cloud_restore_previous() {",` journalctl -u ${i} -n 50 --no-pager >&2 || true`,` systemctl stop ${i} 2>/dev/null || true`,` systemctl disable ${i} 2>/dev/null || true`,` if [ -n "$TS_CLOUD_PREV_CURRENT" ] && [ -d "$TS_CLOUD_PREV_CURRENT" ]; then ln -sfn "$TS_CLOUD_PREV_CURRENT" ${t.current}.tmp && mv -Tf ${t.current}.tmp ${t.current}; fi`,' for TS_CLOUD_RU in ${TS_CLOUD_OLD_UNITS}; do systemctl enable "$TS_CLOUD_RU" 2>/dev/null || true; systemctl start "$TS_CLOUD_RU" 2>/dev/null || true; done',` if [ "$TS_CLOUD_LEGACY_STOPPED" -eq 1 ]; then systemctl start ${a} 2>/dev/null || true; fi`,' if [ -n "$TS_CLOUD_OLD_UNITS" ] || [ "$TS_CLOUD_LEGACY_STOPPED" -eq 1 ]; then echo "[ts-cloud] previous release restored and serving" >&2; else echo "[ts-cloud] there was no previous release to restore" >&2; fi',"}",`if [ -f /etc/systemd/system/${a} ] && systemctl is-active --quiet ${a}; then echo "[ts-cloud] retiring pre-zero-downtime unit ${a} (one-time restart cutover)"; systemctl stop ${a}; TS_CLOUD_LEGACY_STOPPED=1; fi`,'TS_CLOUD_STARTED_AT="@$(date +%s)"',`systemctl restart ${i}`,`TS_CLOUD_GATE_OK=1; for TS_CLOUD_I in $(seq 1 ${c}); do sleep 1; systemctl is-active --quiet ${i} || { TS_CLOUD_GATE_OK=0; break; }; done`,'if [ "$TS_CLOUD_GATE_OK" -ne 1 ]; then',` if journalctl -u ${i} --since "$TS_CLOUD_STARTED_AT" -o cat --no-pager 2>/dev/null | grep -iE 'EADDRINUSE|address already in use|port [0-9]+ (is )?in use|Failed to start server' >/dev/null; then`,` echo "[ts-cloud] release ${n} could not share :${s} with the previous release (no SO_REUSEPORT?) — retiring it and retrying" >&2`,' for TS_CLOUD_RU in ${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_RU" 2>/dev/null || true; done',` systemctl restart ${i}`,` for TS_CLOUD_I in $(seq 1 ${c}); do sleep 1; systemctl is-active --quiet ${i} || ${h("failed its health gate on the free port")}; done`," else",` ${h("crashed on start — the previous release was never stopped")}`," fi","fi",`if ss -ltnpH "sport = :${s}" >/dev/null 2>&1; then`," TS_CLOUD_BOUND=0",` for TS_CLOUD_I in $(seq 1 ${hc}); do`,` TS_CLOUD_NEW_PID="$(systemctl show -p MainPID --value ${i} 2>/dev/null || true)"`,` if [ -n "$TS_CLOUD_NEW_PID" ] && [ "$TS_CLOUD_NEW_PID" != "0" ] && ss -ltnpH "sport = :${s}" 2>/dev/null | grep "pid=$TS_CLOUD_NEW_PID," >/dev/null; then TS_CLOUD_BOUND=1; break; fi`,` systemctl is-active --quiet ${i} || break`,` sleep ${Rn}`," done",` [ "$TS_CLOUD_BOUND" -eq 1 ] || ${h(`never took :${s}`)}`,"else",' echo "[ts-cloud] cannot read listener PIDs on this host — the response probes run without the bind check" >&2',"fi",...f?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${qs}); do if ${f}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${Rn}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${h(`never answered ${u}`)}`]:[],...pt(t),`systemctl enable ${i} 2>/dev/null || true`,'for TS_CLOUD_U in ${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done',`TS_CLOUD_LISTENING=0; for TS_CLOUD_I in $(seq 1 ${c}); do if ss -ltnH "sport = :${s}" 2>/dev/null | grep . >/dev/null; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done`,`if [ "$TS_CLOUD_LISTENING" -ne 1 ]; then echo "[ts-cloud] nothing is listening on ${s} after retiring the previous release — restarting ${i} on the now-free port" >&2; systemctl restart ${i}; for TS_CLOUD_I in $(seq 1 ${c}); do if ss -ltnH "sport = :${s}" 2>/dev/null | grep . >/dev/null; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done; fi`,`[ "$TS_CLOUD_LISTENING" -eq 1 ] || ${h(`is active but never bound :${s}`)}`,...f?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${qs}); do if ${f}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${Rn}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${h(`stopped answering ${u} once it served alone`)}`]:[],...Tn(t),`systemctl list-unit-files --plain --no-legend "${r}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v -e "^${i}$" -e "^${r}@\\.service$" || true; } | while read -r TS_CLOUD_U; do systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done`,`if [ -f /etc/systemd/system/${a} ]; then systemctl disable ${a} 2>/dev/null || true; rm -f /etc/systemd/system/${a}; systemctl daemon-reload; fi`]}function Ys(e,t){if(!t.length)return[];let r=et(e.release);return[`if [ -e ${r} ] || [ -L ${r} ]; then`,...t,"fi"]}function si(e){let{siteName:t,slug:r,artifactFetch:n,releaseId:s,execStart:i,envEntries:a,port:c,keepReleases:u=Ht,preStartCommands:f=[],postActivateCommands:h=[],beforeResetCommands:S=[],healthCheckPath:v,healthGateSeconds:_=5,liveness:y,memoryHigh:T="auto",memoryMax:x,cpuWeight:W,ioWeight:H,tasksMax:R,stopTimeout:L}=e,I=[...W!=null?[`CPUWeight=${W}`]:[],...H!=null?[`IOWeight=${H}`]:[],...R!=null?[`TasksMax=${R}`]:[],...L?[`TimeoutStopSec=${L}`]:[]],V=e.zeroDowntime??c!=null,q=e.appDir??`/var/www/${t}`,K=Zt(q,s),ee=`${r}-${t}`,te=`${ee}.service`,ne=ai(r,t,s),ie=e.sharedPaths??[],oe=Hs([".env",...ie,...yr(a,ie)]),re=fr(a),pe=f.length>0?[`cd ${K.release}`,...f]:[],ge=["set -euo pipefail",...vn(K),...n,...Mt(K,oe),...Ys(K,S),$n(K),..._n(K),`tar xzf ${ne} -C "$TS_CLOUD_STAGED"`,`rm -f ${ne}`,`cat > ${K.shared}/.env <<'TS_CLOUD_ENV_EOF'`,re,"TS_CLOUD_ENV_EOF",`chmod 600 ${K.shared}/.env`,...yn(K),`find ${K.release} -maxdepth 1 \\( -type f -o -type l \\) -name '.env*' ! -name '.env.example' ! -name '*.example' -delete`,`sed -i -E '/^[[:space:]]*(PORT|PORT_BACKEND|PORT_ADMIN|PORT_FRONTEND)[[:space:]]*=/d' ${K.shared}/.env 2>/dev/null || true`,...Sr(K,oe),...pe,...e.isolation?Ls(e.slug||t,K.base,oe.flatMap((b)=>typeof b==="string"||!b.target?[]:[b.target])):[]];if(V&&c!=null){let b=`${ee}@${s}.service`,k=v?v.startsWith("/")?v:`/${v}`:null;return[...ge,`cat > /etc/systemd/system/${ee}@.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} release %i (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",...e.isolation?Ut(ut(e.slug||t),K.base,e.slug||t):[],`WorkingDirectory=${K.releases}/%i`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...T&&T!=="auto"?[`MemoryHigh=${T}`]:[],...x?[`MemoryMax=${x}`]:[],...I,`EnvironmentFile=${K.releases}/%i/.env`,`Environment=PORT=${c}`,`Environment=STX_IMAGE_CACHE_DIR=${hr(K)}`,`Environment=STX_BUNDLE_CACHE_DIR=${Nt(K)}`,`Environment=STX_BUNDLE_CACHE_DIR=${Nt(K)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...T==="auto"?Vs(`${ee}@.service`):[...br(`${ee}@.service`),...On()],...fc(b),...Sc({paths:K,unitBase:ee,releaseId:s,port:c,healthCheckPath:k,healthGateSeconds:_}),...h,...dt(K,u),...y===!1?[]:Ws({...y,unitBase:ee,unitPattern:`${ee}@*.service`,port:c,path:y?.path??v})]}return[...ge,`cat > /etc/systemd/system/${te} <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",...e.isolation?Ut(ut(e.slug||t),K.base,e.slug||t):[],`WorkingDirectory=${K.current}`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...T&&T!=="auto"?[`MemoryHigh=${T}`]:[],...x?[`MemoryMax=${x}`]:[],...I,`EnvironmentFile=${K.current}/.env`,...c?[`Environment=PORT=${c}`]:[],`Environment=STX_IMAGE_CACHE_DIR=${hr(K)}`,`Environment=STX_BUNDLE_CACHE_DIR=${Nt(K)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...br(te,{auto:T!=="auto",high:T!=="auto",max:Boolean(x)}),...T==="auto"?Vs(te):On(),`systemctl enable ${te}`,`TS_CLOUD_PREV_CURRENT="$(readlink ${K.current} 2>/dev/null || true)"`,...pt(K),`systemctl restart ${te}`,`for TS_CLOUD_I in $(seq 1 ${Math.max(1,_)}); do sleep 1; systemctl is-active --quiet ${te} || { echo "[ts-cloud] release ${s} of ${te} did not stay up — restoring the previous release" >&2; journalctl -u ${te} -n 50 --no-pager >&2 || true; if [ -n "$TS_CLOUD_PREV_CURRENT" ] && [ -d "$TS_CLOUD_PREV_CURRENT" ] && [ "$(readlink -f "$TS_CLOUD_PREV_CURRENT")" != "$(readlink -f ${K.release})" ]; then ln -sfn "$TS_CLOUD_PREV_CURRENT" ${K.current}.tmp && mv -Tf ${K.current}.tmp ${K.current}; systemctl restart ${te} || true; fi; exit 1; }; done`,...Tn(K),...h,...dt(K,u),...y===!1||!c?[]:Ws({...y,unitBase:ee,unitPattern:te,port:c,path:y?.path??v})]}function oi(e){let{siteName:t,artifactFetch:r,releaseId:n,keepReleases:s=Ht,preStartCommands:i=[],postActivateCommands:a=[],beforeResetCommands:c=[]}=e,u=e.appDir??`/var/www/${t}`,f=Zt(u,n),h=ai(e.slug,t,n),S=i.length>0?[`cd ${f.release}`,...i]:[];return["set -euo pipefail",...vn(f),...r,...Mt(f,[]),...Ys(f,c),$n(f),..._n(f),`tar xzf ${h} -C "$TS_CLOUD_STAGED"`,...yn(f),`rm -f ${h}`,...S,...pt(f),...a,...dt(f,s)]}function ai(e,t,r){return`/tmp/${[e,t,r].filter(Boolean).join("-")}-release.tar.gz`}function $c(e,t,r,n){return[`aws s3 cp "s3://${e}/${t}" ${n} --region ${r}`]}function Mc(e,t){return[`mv "${e}" ${t}`]}function et(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function Tr(e,t,r){return["set -euo pipefail",`chmod 600 ${et(e)}`,`mv -f -- ${et(e)} ${et(t)}`,`cp -- ${et(t)} ${et(r)}`].join(`
160
160
  `)}function wr(e){return`rm -f -- ${et(e)} 2>/dev/null || true`}function Dn(e={}){let t=Math.max(1,e.appServers??e.instances??1),r=!!e.servicesServer||t>1,n=t>1||!!e.server?.loadBalancer;return{appServers:t,loadBalancer:n,dedicatedServices:r,servicesOnApp:!r}}function Xs(e,t){let r={REDIS_HOST:e,MEILISEARCH_HOST:`http://${e}:7700`};if(t?.name){if(r.DB_CONNECTION=t.engine==="postgres"?"pgsql":"mysql",r.DB_HOST=e,r.DB_PORT=String(t.port??(t.engine==="postgres"?5432:3306)),r.DB_DATABASE=t.name,t.username)r.DB_USERNAME=t.username;if(t.password)r.DB_PASSWORD=t.password}return r}function xn(e){let t=e.infrastructure?.compute??{},r=g(e);return[...ir(t.managedServices??{mysql:!0,redis:!0},{bindPrivate:!0}),...at(r,t.managedServices??{mysql:!0}),...Me(!0),...Le(!0),...ct(t.sshKeys),...Xe(e.notifications),...t.backups?.enabled?[...ar({database:r,backups:t.backups})]:[]]}var Bt=["-S","ssh"];function ci(e={},t="ssh"){let r=[];if(e.identityFile)r.push("-i",e.identityFile);if(e.port)r.push(t==="scp"?"-P":"-p",String(e.port));return r.push("-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR","-o",`ConnectTimeout=${e.connectTimeoutSec??10}`),r}async function Ur(e,t,r={}){let n=Bun.spawn(["ssh",...ci(r),`${r.user??"root"}@${e}`,t],{stdout:"pipe",stderr:"pipe"}),[s,i]=await Promise.all([new Response(n.stdout).text(),new Response(n.stderr).text()]);return{code:await n.exited,stdout:s,stderr:i}}async function Ie(e,t,r={}){let n=await Ur(e,t,r);if(n.code!==0)throw Error(`ssh \`${t}\` on ${e} failed (${n.code}): ${n.stderr.trim()||n.stdout.trim()}`);return n.stdout}async function Fc(e,t,r,n={}){let s=Bun.spawn(["scp",...Bt,...ci(n,"scp"),...t,`${n.user??"root"}@${e}:${r}`],{stdout:"pipe",stderr:"pipe"}),i=await s.exited;if(i!==0){let a=await new Response(s.stderr).text();throw Error(`scp to ${e}:${r} failed (${i}): ${a.trim()}`)}}async function ht(e,t={}){let r=t.timeoutMs??180000,n=t.pollIntervalMs??5000,s=Date.now();while(Date.now()-s<r){let i=await Ur(e,"echo ready",t);if(i.code===0&&i.stdout.includes("ready"))return;await new Promise((a)=>setTimeout(a,n))}throw Error(`SSH not ready on ${e} after ${r}ms`)}async function Uc(e,t={}){let r=t.timeoutMs??300000,n=t.pollIntervalMs??5000,s=Date.now();while(Date.now()-s<r){let i=await Ur(e,"cloud-init status 2>/dev/null || echo unknown",t);if(i.stdout.includes("status: done"))return;if(i.stdout.includes("status: error"))throw Error(`cloud-init reported an error on ${e}; check /var/log/cloud-init-output.log`);await new Promise((a)=>setTimeout(a,n))}throw Error(`cloud-init did not finish on ${e} after ${r}ms`)}function di(e={}){return["set -e","ts_cloud_script=$(mktemp /tmp/ts-cloud-deploy.XXXXXXXX)",`trap 'rm -f "$ts_cloud_script"' EXIT`,'cat > "$ts_cloud_script"',e.sudo?'sudo -n -H bash "$ts_cloud_script" < /dev/null':'bash "$ts_cloud_script" < /dev/null'].join(`
161
- `)}var Qc=di();import{homedir as vc}from"node:os";import{join as yc}from"node:path";var Cr={location:"fsn1",image:"ubuntu-24.04",sshUser:"root",sshPrivateKeyPath:"~/.ssh/id_ed25519"};function Pr(e){return e.startsWith("~/")?yc(vc(),e.slice(2)):e}function mt(...e){for(let t of e){let r=process.env[t]?.trim();if(r)return r}return}function gt(...e){for(let t of e){let r=t?.trim();if(r)return r}return}function Kt(e,t){return gt(e,t?.hetzner?.apiToken,mt("HCLOUD_TOKEN","HETZNER_API_TOKEN"))}function Hc(e,t){return gt(t,e?.hetzner?.location,mt("HCLOUD_LOCATION","HETZNER_LOCATION"))??Cr.location}function jt(e,t){let r=e?.infrastructure?.compute;return gt(t,r?.image,e?.hetzner?.image,mt("HCLOUD_IMAGE","HETZNER_IMAGE"))??Cr.image}function bc(e,t){return gt(t,e?.hetzner?.sshUser,mt("HCLOUD_SSH_USER","HETZNER_SSH_USER"))??Cr.sshUser}function Js(e,t){return Pr(gt(t,e?.hetzner?.sshPrivateKeyPath,mt("HCLOUD_SSH_KEY","HETZNER_SSH_KEY"))??Cr.sshPrivateKeyPath)}function Tc(e,t,r){let n=gt(t,e?.hetzner?.sshPublicKeyPath,mt("HCLOUD_SSH_PUBLIC_KEY","HETZNER_SSH_PUBLIC_KEY"));if(n)return Pr(n);return`${r??Js(e)}.pub`}function Qs(e,t={}){let r=Js(e,t.sshPrivateKeyPath);return{apiToken:Kt(t.apiToken,e),location:Hc(e,t.location),image:jt(e,t.image),sshUser:bc(e,t.sshUser),sshPrivateKeyPath:r,sshPublicKeyPath:Tc(e,t.sshPublicKeyPath,r)}}var wc="https://api.hetzner.cloud/v1";class Er extends Error{status;code;details;constructor(e,t,r,n){super(e);this.status=t;this.code=r;this.details=n;this.name="HetznerApiError"}}class Rr extends Error{action;constructor(e,t){super(e);this.action=t;this.name="HetznerActionError"}}function uo(e){return e.map((t)=>({type:"server",server:{id:t.server}}))}class Qr{name="hetzner";apiToken;baseUrl;fetchImpl;constructor(e){this.apiToken=e.apiToken,this.baseUrl=e.baseUrl??wc,this.fetchImpl=e.fetchImpl??fetch}async request(e,t,r){let n=await this.fetchImpl(`${this.baseUrl}${t}`,{method:e,headers:{Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},body:r===void 0?void 0:JSON.stringify(r)}),s=await n.text(),i;try{i=s?JSON.parse(s):{}}catch{if(!n.ok){let a=s.trim().slice(0,200)||n.statusText||"Hetzner API error";throw Error(`Hetzner API ${e} ${t} (${n.status}): ${a}`)}throw Error(`Hetzner API ${e} ${t}: unexpected non-JSON response`)}if(!n.ok){let a=i.error?.message||n.statusText||"Hetzner API error",c=i.error?.code?` [${i.error.code}]`:"";throw new Er(`Hetzner API ${e} ${t} (${n.status})${c}: ${a}`,n.status,i.error?.code,i.error?.details)}return i}async requestAll(e,t){let r=[],n=1;for(;;){let s=e.includes("?")?"&":"?",i=await this.request("GET",`${e}${s}per_page=50&page=${n}`);r.push(...i[t]??[]);let a=i.meta?.pagination?.next_page;if(!a)return r;n=a}}async listServers(){return this.requestAll("/servers","servers")}async getServer(e){return(await this.request("GET",`/servers/${e}`)).server}async listVolumes(){return this.requestAll("/volumes","volumes")}async getVolume(e){return(await this.request("GET",`/volumes/${e}`)).volume}async createVolume(e){return this.request("POST","/volumes",{...e,automount:!1})}async attachVolume(e,t){return(await this.request("POST",`/volumes/${e}/actions/attach`,{server:t,automount:!1})).action}async resizeVolume(e,t){return(await this.request("POST",`/volumes/${e}/actions/resize`,{size:t})).action}async protectVolume(e,t){return(await this.request("POST",`/volumes/${e}/actions/change_protection`,{delete:t})).action}async getServerMetrics(e,t){let r=new URLSearchParams({type:t.types.join(","),start:t.start.toISOString(),end:t.end.toISOString(),step:String(Math.max(60,Math.floor(t.step??60)))});return(await this.request("GET",`/servers/${e}/metrics?${r}`)).metrics}async listServerTypes(e){let t=e?`?name=${encodeURIComponent(e)}`:"";return this.requestAll(`/server_types${t}`,"server_types")}async getServerType(e){return(await this.listServerTypes(e)).find((t)=>t.name===e)??null}async createServer(e){let t=await this.request("POST","/servers",{name:e.name,server_type:e.serverType,image:e.image,location:e.location,datacenter:e.datacenter,ssh_keys:e.sshKeys,user_data:e.userData,labels:e.labels,firewalls:e.firewalls,networks:e.networks,start_after_create:!0});return{server:t.server,action:t.action}}async listNetworks(){return this.requestAll("/networks","networks")}async createNetwork(e){let t=e.ipRange??"10.0.0.0/16";return(await this.request("POST","/networks",{name:e.name,ip_range:t,subnets:[{type:"cloud",ip_range:t,network_zone:"eu-central"}],labels:e.labels})).network}async deleteNetwork(e){await this.request("DELETE",`/networks/${e}`)}async listLoadBalancers(){return this.requestAll("/load_balancers","load_balancers")}async createLoadBalancer(e){return(await this.request("POST","/load_balancers",{name:e.name,load_balancer_type:e.type??"lb11",location:e.location,network_zone:e.network?void 0:e.networkZone??"eu-central",network:e.network,labels:e.labels,targets:[{type:"label_selector",label_selector:{selector:e.labelSelector},use_private_ip:!!e.network}],services:e.services.map((r)=>({protocol:r.protocol??"tcp",listen_port:r.listenPort,destination_port:r.destinationPort,health_check:{protocol:"http",port:80,interval:15,timeout:10,retries:3,http:{path:"/",status_codes:["2??","3??"]}}}))})).load_balancer}async deleteLoadBalancer(e){await this.request("DELETE",`/load_balancers/${e}`)}async deleteServer(e){return(await this.request("DELETE",`/servers/${e}`)).action}async listFirewalls(){return this.requestAll("/firewalls","firewalls")}async createFirewall(e){let t=await this.request("POST","/firewalls",{name:e.name,rules:e.rules,labels:e.labels,apply_to:e.applyTo?uo(e.applyTo):void 0});return{firewall:t.firewall,actions:t.actions}}async setFirewallRules(e,t){return(await this.request("POST",`/firewalls/${e}/actions/set_rules`,{rules:t})).actions??[]}async deleteFirewall(e){await this.request("DELETE",`/firewalls/${e}`)}async applyFirewallToResources(e,t){return(await this.request("POST",`/firewalls/${e}/actions/apply_to_resources`,{apply_to:uo(t)})).actions}async listSshKeys(){return this.requestAll("/ssh_keys","ssh_keys")}async createSshKey(e){return(await this.request("POST","/ssh_keys",{name:e.name,public_key:e.publicKey,labels:e.labels})).ssh_key}async deleteSshKey(e){await this.request("DELETE",`/ssh_keys/${e}`)}async getAction(e){return(await this.request("GET",`/actions/${e}`)).action}async shutdownServer(e){return(await this.request("POST",`/servers/${e}/actions/shutdown`,{})).action}async powerOnServer(e){return(await this.request("POST",`/servers/${e}/actions/poweron`,{})).action}async changeServerType(e,t,r){return(await this.request("POST",`/servers/${e}/actions/change_type`,{server_type:t,upgrade_disk:r})).action}async powerOffServer(e){return(await this.request("POST",`/servers/${e}/actions/poweroff`,{})).action}async stopServer(e,t){if((await this.getServer(e)).status==="off")return;await this.shutdownServer(e);let n=t?.gracefulWaitMs??120000,s=t?.pollIntervalMs??3000,i=Date.now();while(Date.now()-i<n){if((await this.getServer(e)).status==="off")return;await new Promise((c)=>setTimeout(c,s))}let a=await this.powerOffServer(e);await this.waitForAction(a.id),await this.waitForServerStatus(e,"off")}async renameServer(e,t){return(await this.request("PUT",`/servers/${e}`,{name:t})).server}async listImages(e){let t=e?.type?`?type=${encodeURIComponent(e.type)}`:"";return this.requestAll(`/images${t}`,"images")}async getImage(e){return(await this.request("GET",`/images/${e}`)).image}async createImage(e,t){return this.request("POST",`/servers/${e}/actions/create_image`,{description:t.description,type:t.type??"snapshot",labels:t.labels})}async deleteImage(e){await this.request("DELETE",`/images/${e}`)}async rebuildServer(e,t){return(await this.request("POST",`/servers/${e}/actions/rebuild`,{image:t})).action}async listPrimaryIps(){return this.requestAll("/primary_ips","primary_ips")}async unassignPrimaryIp(e){return(await this.request("POST",`/primary_ips/${e}/actions/unassign`,{})).action}async assignPrimaryIp(e,t){return(await this.request("POST",`/primary_ips/${e}/actions/assign`,{assignee_id:t,assignee_type:"server"})).action}async waitForAction(e,t){let r=t?.pollIntervalMs??2000,n=t?.maxWaitMs??300000,s=Date.now();while(Date.now()-s<n){let i=await this.getAction(e);if(i.status==="success")return i;if(i.status==="error")throw new Rr(i.error?.message||"Hetzner action failed",i);await new Promise((a)=>setTimeout(a,r))}throw Error(`Timed out waiting for Hetzner action ${e}`)}async waitForServerRunning(e,t){let r=t?.pollIntervalMs??3000,n=t?.maxWaitMs??600000,s=Date.now();while(Date.now()-s<n){let i=await this.getServer(e);if(i.status==="running")return i;await new Promise((a)=>setTimeout(a,r))}throw Error(`Timed out waiting for server ${e} to reach running state`)}async waitForServerStatus(e,t,r){let n=r?.pollIntervalMs??3000,s=r?.maxWaitMs??600000,i=Date.now();while(Date.now()-i<s){let a=await this.getServer(e);if(a.status===t)return a;await new Promise((c)=>setTimeout(c,n))}throw Error(`Timed out waiting for server ${e} to reach ${t} state`)}}function Gc(e,t){let r=Kt(e,t);if(!r)throw Error("Hetzner API token required. Set hetzner.apiToken in cloud.config.ts or HCLOUD_TOKEN / HETZNER_API_TOKEN.");return r}function Ve(e){let[t,r]=e.trim().split(/\s+/);return r?`${t} ${r}`:t}function mo(e){if(!e)return"";return e.endsWith(`
161
+ `)}var Qc=di();import{homedir as vc}from"node:os";import{join as yc}from"node:path";var Cr={location:"fsn1",image:"ubuntu-24.04",sshUser:"root",sshPrivateKeyPath:"~/.ssh/id_ed25519"};function Pr(e){return e.startsWith("~/")?yc(vc(),e.slice(2)):e}function mt(...e){for(let t of e){let r=process.env[t]?.trim();if(r)return r}return}function gt(...e){for(let t of e){let r=t?.trim();if(r)return r}return}function Kt(e,t){return gt(e,t?.hetzner?.apiToken,mt("HCLOUD_TOKEN","HETZNER_API_TOKEN"))}function Hc(e,t){return gt(t,e?.hetzner?.location,mt("HCLOUD_LOCATION","HETZNER_LOCATION"))??Cr.location}function jt(e,t){let r=e?.infrastructure?.compute;return gt(t,r?.image,e?.hetzner?.image,mt("HCLOUD_IMAGE","HETZNER_IMAGE"))??Cr.image}function bc(e,t){return gt(t,e?.hetzner?.sshUser,mt("HCLOUD_SSH_USER","HETZNER_SSH_USER"))??Cr.sshUser}function Js(e,t){return Pr(gt(t,e?.hetzner?.sshPrivateKeyPath,mt("HCLOUD_SSH_KEY","HETZNER_SSH_KEY"))??Cr.sshPrivateKeyPath)}function Tc(e,t,r){let n=gt(t,e?.hetzner?.sshPublicKeyPath,mt("HCLOUD_SSH_PUBLIC_KEY","HETZNER_SSH_PUBLIC_KEY"));if(n)return Pr(n);return`${r??Js(e)}.pub`}function Qs(e,t={}){let r=Js(e,t.sshPrivateKeyPath);return{apiToken:Kt(t.apiToken,e),location:Hc(e,t.location),image:jt(e,t.image),sshUser:bc(e,t.sshUser),sshPrivateKeyPath:r,sshPublicKeyPath:Tc(e,t.sshPublicKeyPath,r)}}var wc="https://api.hetzner.cloud/v1";class Er extends Error{status;code;details;constructor(e,t,r,n){super(e);this.status=t;this.code=r;this.details=n;this.name="HetznerApiError"}}class Rr extends Error{action;constructor(e,t){super(e);this.action=t;this.name="HetznerActionError"}}function uo(e){return e.map((t)=>({type:"server",server:{id:t.server}}))}class Qr{name="hetzner";apiToken;baseUrl;fetchImpl;constructor(e){this.apiToken=e.apiToken,this.baseUrl=e.baseUrl??wc,this.fetchImpl=e.fetchImpl??fetch}async request(e,t,r){let n=await this.fetchImpl(`${this.baseUrl}${t}`,{method:e,headers:{Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},body:r===void 0?void 0:JSON.stringify(r)}),s=await n.text(),i;try{i=s?JSON.parse(s):{}}catch{if(!n.ok){let a=s.trim().slice(0,200)||n.statusText||"Hetzner API error";throw Error(`Hetzner API ${e} ${t} (${n.status}): ${a}`)}throw Error(`Hetzner API ${e} ${t}: unexpected non-JSON response`)}if(!n.ok){let a=i.error?.message||n.statusText||"Hetzner API error",c=i.error?.code?` [${i.error.code}]`:"";throw new Er(`Hetzner API ${e} ${t} (${n.status})${c}: ${a}`,n.status,i.error?.code,i.error?.details)}return i}async requestAll(e,t){let r=[],n=1;for(;;){let s=e.includes("?")?"&":"?",i=await this.request("GET",`${e}${s}per_page=50&page=${n}`);r.push(...i[t]??[]);let a=i.meta?.pagination?.next_page;if(!a)return r;n=a}}async listServers(){return this.requestAll("/servers","servers")}async getLocation(e){let r=(await this.request("GET",`/locations?name=${encodeURIComponent(e)}`)).locations.find((n)=>n.name===e);if(!r)throw Error(`Hetzner location not found: ${e}`);return r}async getServer(e){return(await this.request("GET",`/servers/${e}`)).server}async listVolumes(){return this.requestAll("/volumes","volumes")}async getVolume(e){return(await this.request("GET",`/volumes/${e}`)).volume}async createVolume(e){return this.request("POST","/volumes",{...e,automount:!1})}async attachVolume(e,t){return(await this.request("POST",`/volumes/${e}/actions/attach`,{server:t,automount:!1})).action}async resizeVolume(e,t){return(await this.request("POST",`/volumes/${e}/actions/resize`,{size:t})).action}async protectVolume(e,t){return(await this.request("POST",`/volumes/${e}/actions/change_protection`,{delete:t})).action}async getServerMetrics(e,t){let r=new URLSearchParams({type:t.types.join(","),start:t.start.toISOString(),end:t.end.toISOString(),step:String(Math.max(60,Math.floor(t.step??60)))});return(await this.request("GET",`/servers/${e}/metrics?${r}`)).metrics}async listServerTypes(e){let t=e?`?name=${encodeURIComponent(e)}`:"";return this.requestAll(`/server_types${t}`,"server_types")}async getServerType(e){return(await this.listServerTypes(e)).find((t)=>t.name===e)??null}async createServer(e){let t=await this.request("POST","/servers",{name:e.name,server_type:e.serverType,image:e.image,location:e.location,datacenter:e.datacenter,ssh_keys:e.sshKeys,user_data:e.userData,labels:e.labels,firewalls:e.firewalls,networks:e.networks,start_after_create:!0});return{server:t.server,action:t.action}}async listNetworks(){return this.requestAll("/networks","networks")}async createNetwork(e){let t=e.ipRange??"10.0.0.0/16";return(await this.request("POST","/networks",{name:e.name,ip_range:t,subnets:[{type:"cloud",ip_range:t,network_zone:"eu-central"}],labels:e.labels})).network}async deleteNetwork(e){await this.request("DELETE",`/networks/${e}`)}async listLoadBalancers(){return this.requestAll("/load_balancers","load_balancers")}async createLoadBalancer(e){return(await this.request("POST","/load_balancers",{name:e.name,load_balancer_type:e.type??"lb11",location:e.location,network_zone:e.network?void 0:e.networkZone??"eu-central",network:e.network,labels:e.labels,targets:[{type:"label_selector",label_selector:{selector:e.labelSelector},use_private_ip:!!e.network}],services:e.services.map((r)=>({protocol:r.protocol??"tcp",listen_port:r.listenPort,destination_port:r.destinationPort,health_check:{protocol:"http",port:80,interval:15,timeout:10,retries:3,http:{path:"/",status_codes:["2??","3??"]}}}))})).load_balancer}async deleteLoadBalancer(e){await this.request("DELETE",`/load_balancers/${e}`)}async deleteServer(e){return(await this.request("DELETE",`/servers/${e}`)).action}async listFirewalls(){return this.requestAll("/firewalls","firewalls")}async createFirewall(e){let t=await this.request("POST","/firewalls",{name:e.name,rules:e.rules,labels:e.labels,apply_to:e.applyTo?uo(e.applyTo):void 0});return{firewall:t.firewall,actions:t.actions}}async setFirewallRules(e,t){return(await this.request("POST",`/firewalls/${e}/actions/set_rules`,{rules:t})).actions??[]}async deleteFirewall(e){await this.request("DELETE",`/firewalls/${e}`)}async applyFirewallToResources(e,t){return(await this.request("POST",`/firewalls/${e}/actions/apply_to_resources`,{apply_to:uo(t)})).actions}async listSshKeys(){return this.requestAll("/ssh_keys","ssh_keys")}async createSshKey(e){return(await this.request("POST","/ssh_keys",{name:e.name,public_key:e.publicKey,labels:e.labels})).ssh_key}async deleteSshKey(e){await this.request("DELETE",`/ssh_keys/${e}`)}async getAction(e){return(await this.request("GET",`/actions/${e}`)).action}async shutdownServer(e){return(await this.request("POST",`/servers/${e}/actions/shutdown`,{})).action}async powerOnServer(e){return(await this.request("POST",`/servers/${e}/actions/poweron`,{})).action}async changeServerType(e,t,r){return(await this.request("POST",`/servers/${e}/actions/change_type`,{server_type:t,upgrade_disk:r})).action}async powerOffServer(e){return(await this.request("POST",`/servers/${e}/actions/poweroff`,{})).action}async stopServer(e,t){if((await this.getServer(e)).status==="off")return;await this.shutdownServer(e);let n=t?.gracefulWaitMs??120000,s=t?.pollIntervalMs??3000,i=Date.now();while(Date.now()-i<n){if((await this.getServer(e)).status==="off")return;await new Promise((c)=>setTimeout(c,s))}let a=await this.powerOffServer(e);await this.waitForAction(a.id),await this.waitForServerStatus(e,"off")}async renameServer(e,t){return(await this.request("PUT",`/servers/${e}`,{name:t})).server}async listImages(e){let t=e?.type?`?type=${encodeURIComponent(e.type)}`:"";return this.requestAll(`/images${t}`,"images")}async getImage(e){return(await this.request("GET",`/images/${e}`)).image}async createImage(e,t){return this.request("POST",`/servers/${e}/actions/create_image`,{description:t.description,type:t.type??"snapshot",labels:t.labels})}async deleteImage(e){await this.request("DELETE",`/images/${e}`)}async rebuildServer(e,t){return(await this.request("POST",`/servers/${e}/actions/rebuild`,{image:t})).action}async listPrimaryIps(){return this.requestAll("/primary_ips","primary_ips")}async unassignPrimaryIp(e){return(await this.request("POST",`/primary_ips/${e}/actions/unassign`,{})).action}async assignPrimaryIp(e,t){return(await this.request("POST",`/primary_ips/${e}/actions/assign`,{assignee_id:t,assignee_type:"server"})).action}async waitForAction(e,t){let r=t?.pollIntervalMs??2000,n=t?.maxWaitMs??300000,s=Date.now();while(Date.now()-s<n){let i=await this.getAction(e);if(i.status==="success")return i;if(i.status==="error")throw new Rr(i.error?.message||"Hetzner action failed",i);await new Promise((a)=>setTimeout(a,r))}throw Error(`Timed out waiting for Hetzner action ${e}`)}async waitForServerRunning(e,t){let r=t?.pollIntervalMs??3000,n=t?.maxWaitMs??600000,s=Date.now();while(Date.now()-s<n){let i=await this.getServer(e);if(i.status==="running")return i;await new Promise((a)=>setTimeout(a,r))}throw Error(`Timed out waiting for server ${e} to reach running state`)}async waitForServerStatus(e,t,r){let n=r?.pollIntervalMs??3000,s=r?.maxWaitMs??600000,i=Date.now();while(Date.now()-i<s){let a=await this.getServer(e);if(a.status===t)return a;await new Promise((c)=>setTimeout(c,n))}throw Error(`Timed out waiting for server ${e} to reach ${t} state`)}}function Gc(e,t){let r=Kt(e,t);if(!r)throw Error("Hetzner API token required. Set hetzner.apiToken in cloud.config.ts or HCLOUD_TOKEN / HETZNER_API_TOKEN.");return r}function Ve(e){let[t,r]=e.trim().split(/\s+/);return r?`${t} ${r}`:t}function mo(e){if(!e)return"";return e.endsWith(`
162
162
  `)?e:`${e}
163
163
  `}function se(e,t={}){let r=t.scriptPath??"/var/lib/cloud/ts-cloud-bootstrap.sh",n=t.permissions??"0755",s=e.split(`
164
164
  `).map((i)=>` ${i}`).join(`
@@ -171,7 +171,7 @@ ${mo(t.before)}write_files:
171
171
  ${s}
172
172
  runcmd:
173
173
  - [ bash, ${r} ]
174
- ${mo(t.after)}`}function Dr(e){let t=new Set([80,443,...e.sitePorts,...e.allowedPorts??[]]);if(e.allowSsh)t.add(22);return[...t].map((r)=>({direction:"in",protocol:"tcp",port:String(r),source_ips:["0.0.0.0/0","::/0"],description:`ts-cloud port ${r}`}))}var In={micro:"cpx11",small:"cx23",medium:"cx33",large:"cx43",xlarge:"cx53","2xlarge":"ccx33"};function Ge(e){if(!e)return In.micro;if(e in In)return In[e];return e}var pe="ts-cloud";function me(e,t,r="app"){return{[`${pe}/project`]:e,[`${pe}/environment`]:t,[`${pe}/role`]:r,[`${pe}/managed-by`]:"ts-cloud"}}function $e(e,t,r,n="app"){return An(e,t,r)&&e[`${pe}/role`]===n}function An(e,t,r){if(!e)return!1;return e[`${pe}/project`]===t&&e[`${pe}/environment`]===r}function Cc(e){return e.location?.name??e.datacenter?.location.name??"unknown"}function vt(e){return typeof e==="number"&&Number.isFinite(e)?e:0}function Pc(e,t){if(e.architecture&&t.architecture&&e.architecture!==t.architecture)throw Error(`Cannot resize ${e.name} (${e.architecture}) to ${t.name} (${t.architecture}) in place.`);let r=[];if(vt(t.cores)<vt(e.cores))r.push("CPU");if(vt(t.memory)<vt(e.memory))r.push("memory");if(vt(t.disk)<vt(e.disk))r.push("disk");if(r.length>0)throw Error(`Refusing an in-place downgrade from ${e.name} to ${t.name}: ${r.join(", ")} would shrink.`)}async function er(e,t,r,n=!0){let[s,i]=await Promise.all([e.getServer(t),e.getServerType(r)]);if(!i)throw Error(`Hetzner server type ${r} was not found.`);let a=s.server_type,c=a.name===i.name;if(!c)Pc(a,i);let u=Cc(s),f=i.locations?.find((h)=>h.name===u);return{serverId:t,serverName:s.name,location:u,currentType:a,targetType:i,capacityAvailable:f?.available!==!1,alreadyComplete:c,upgradeDisk:n}}function Hg(e){if(e instanceof Er&&e.code==="resource_unavailable")return!0;if(e instanceof Rr){if(e.action.error?.code==="resource_unavailable")return!0;if(/no fitting vhost|placement|free resources/i.test(e.action.error?.message??""))return!0}return/resource_unavailable|no fitting vhost|error during placement|free resources/i.test(e instanceof Error?e.message:String(e))}async function He(e,t,r){await e?.onPhase?.(t,r)}async function Ln(e,t,r){await e.waitForAction(t.id,{pollIntervalMs:r.actionPollIntervalMs,maxWaitMs:r.actionTimeoutMs})}var xr=async({client:e,hooks:t,actionPollIntervalMs:r,actionTimeoutMs:n,serverPollIntervalMs:s,serverTimeoutMs:i},a,c,u)=>{let f=await e.getServer(a.serverId);if(f.status!=="running"){await He(t,u?"recovering":"powering-on",{serverId:a.serverId});let S=await e.powerOnServer(a.serverId);await Ln(e,S,{actionPollIntervalMs:r,actionTimeoutMs:n}),f=await e.waitForServerRunning(a.serverId,{pollIntervalMs:s,maxWaitMs:i})}await He(t,"verifying",{serverId:a.serverId,recovered:u});let h=await t?.afterBoot?.(f,a.targetType,c,{recovered:u});return{server:f,verification:h}};async function li(e){let{client:t,hooks:r}=e,n=e.upgradeDisk??!0;await He(r,"planning",{serverId:e.serverId,targetType:e.targetType});let s=await er(t,e.serverId,e.targetType,n),i=await t.getServer(s.serverId);if(s.alreadyComplete){let u=await xr(e,s,e.manifest,!1);return await He(r,"complete",{alreadyComplete:!0}),{status:"already-complete",plan:s,verification:u.verification}}if(!s.capacityAvailable&&!e.attemptUnavailable)return await He(r,"waiting-capacity",{location:s.location,targetType:s.targetType.name}),{status:"waiting-capacity",plan:s};let a=e.manifest;if(i.status==="off"&&!e.resumeFromOff){let u=await xr(e,s,void 0,!0);return{status:"recovered",plan:s,server:u.server,verification:u.verification,retryable:!0,error:"Server was already off without a resumable resize checkpoint; powered it back on."}}if(i.status==="running"){await He(r,"preflight",{serverId:s.serverId}),a=await r?.preflight?.(i,s.targetType),await He(r,"shutting-down",{serverId:s.serverId});let u=await t.shutdownServer(s.serverId);await Ln(t,u,e),i=await t.waitForServerStatus(s.serverId,"off",{pollIntervalMs:e.serverPollIntervalMs,maxWaitMs:e.serverTimeoutMs})}try{await He(r,"resizing",{serverId:s.serverId,from:s.currentType.name,to:s.targetType.name,upgradeDisk:n});let u=await t.changeServerType(s.serverId,s.targetType.name,n);await Ln(t,u,e)}catch(u){let f=await xr(e,s,a,!0);return{status:"recovered",plan:s,server:f.server,manifest:a,verification:f.verification,retryable:Hg(u),error:u instanceof Error?u.message:String(u)}}let c=await xr(e,s,a,!1);if(c.verification&&!c.verification.ok)throw Error(`Resize completed but verification failed: ${(c.verification.failures??[]).join("; ")}`);return await He(r,"complete",{serverId:s.serverId,targetType:s.targetType.name}),{status:"completed",plan:s,server:c.server,manifest:a,verification:c.verification}}var Ec=String.raw`
174
+ ${mo(t.after)}`}function Dr(e){let t=new Set([80,443,...e.sitePorts,...e.allowedPorts??[]]);if(e.allowSsh)t.add(22);return[...t].map((r)=>({direction:"in",protocol:"tcp",port:String(r),source_ips:["0.0.0.0/0","::/0"],description:`ts-cloud port ${r}`}))}var In={micro:"cpx11",small:"cx23",medium:"cx33",large:"cx43",xlarge:"cx53","2xlarge":"ccx33"};function Ge(e){if(!e)return In.micro;if(e in In)return In[e];return e}var me="ts-cloud";function fe(e,t,r="app"){return{[`${me}/project`]:e,[`${me}/environment`]:t,[`${me}/role`]:r,[`${me}/managed-by`]:"ts-cloud"}}function ye(e,t,r,n="app"){return An(e,t,r)&&e[`${me}/role`]===n}function An(e,t,r){if(!e)return!1;return e[`${me}/project`]===t&&e[`${me}/environment`]===r}function Cc(e){return e.location?.name??e.datacenter?.location.name??"unknown"}function vt(e){return typeof e==="number"&&Number.isFinite(e)?e:0}function Pc(e,t){if(e.architecture&&t.architecture&&e.architecture!==t.architecture)throw Error(`Cannot resize ${e.name} (${e.architecture}) to ${t.name} (${t.architecture}) in place.`);let r=[];if(vt(t.cores)<vt(e.cores))r.push("CPU");if(vt(t.memory)<vt(e.memory))r.push("memory");if(vt(t.disk)<vt(e.disk))r.push("disk");if(r.length>0)throw Error(`Refusing an in-place downgrade from ${e.name} to ${t.name}: ${r.join(", ")} would shrink.`)}async function er(e,t,r,n=!0){let[s,i]=await Promise.all([e.getServer(t),e.getServerType(r)]);if(!i)throw Error(`Hetzner server type ${r} was not found.`);let a=s.server_type,c=a.name===i.name;if(!c)Pc(a,i);let u=Cc(s),f=i.locations?.find((h)=>h.name===u);return{serverId:t,serverName:s.name,location:u,currentType:a,targetType:i,capacityAvailable:f?.available!==!1,alreadyComplete:c,upgradeDisk:n}}function Hg(e){if(e instanceof Er&&e.code==="resource_unavailable")return!0;if(e instanceof Rr){if(e.action.error?.code==="resource_unavailable")return!0;if(/no fitting vhost|placement|free resources/i.test(e.action.error?.message??""))return!0}return/resource_unavailable|no fitting vhost|error during placement|free resources/i.test(e instanceof Error?e.message:String(e))}async function He(e,t,r){await e?.onPhase?.(t,r)}async function Ln(e,t,r){await e.waitForAction(t.id,{pollIntervalMs:r.actionPollIntervalMs,maxWaitMs:r.actionTimeoutMs})}var xr=async({client:e,hooks:t,actionPollIntervalMs:r,actionTimeoutMs:n,serverPollIntervalMs:s,serverTimeoutMs:i},a,c,u)=>{let f=await e.getServer(a.serverId);if(f.status!=="running"){await He(t,u?"recovering":"powering-on",{serverId:a.serverId});let S=await e.powerOnServer(a.serverId);await Ln(e,S,{actionPollIntervalMs:r,actionTimeoutMs:n}),f=await e.waitForServerRunning(a.serverId,{pollIntervalMs:s,maxWaitMs:i})}await He(t,"verifying",{serverId:a.serverId,recovered:u});let h=await t?.afterBoot?.(f,a.targetType,c,{recovered:u});return{server:f,verification:h}};async function li(e){let{client:t,hooks:r}=e,n=e.upgradeDisk??!0;await He(r,"planning",{serverId:e.serverId,targetType:e.targetType});let s=await er(t,e.serverId,e.targetType,n),i=await t.getServer(s.serverId);if(s.alreadyComplete){let u=await xr(e,s,e.manifest,!1);return await He(r,"complete",{alreadyComplete:!0}),{status:"already-complete",plan:s,verification:u.verification}}if(!s.capacityAvailable&&!e.attemptUnavailable)return await He(r,"waiting-capacity",{location:s.location,targetType:s.targetType.name}),{status:"waiting-capacity",plan:s};let a=e.manifest;if(i.status==="off"&&!e.resumeFromOff){let u=await xr(e,s,void 0,!0);return{status:"recovered",plan:s,server:u.server,verification:u.verification,retryable:!0,error:"Server was already off without a resumable resize checkpoint; powered it back on."}}if(i.status==="running"){await He(r,"preflight",{serverId:s.serverId}),a=await r?.preflight?.(i,s.targetType),await He(r,"shutting-down",{serverId:s.serverId});let u=await t.shutdownServer(s.serverId);await Ln(t,u,e),i=await t.waitForServerStatus(s.serverId,"off",{pollIntervalMs:e.serverPollIntervalMs,maxWaitMs:e.serverTimeoutMs})}try{await He(r,"resizing",{serverId:s.serverId,from:s.currentType.name,to:s.targetType.name,upgradeDisk:n});let u=await t.changeServerType(s.serverId,s.targetType.name,n);await Ln(t,u,e)}catch(u){let f=await xr(e,s,a,!0);return{status:"recovered",plan:s,server:f.server,manifest:a,verification:f.verification,retryable:Hg(u),error:u instanceof Error?u.message:String(u)}}let c=await xr(e,s,a,!1);if(c.verification&&!c.verification.ok)throw Error(`Resize completed but verification failed: ${(c.verification.failures??[]).join("; ")}`);return await He(r,"complete",{serverId:s.serverId,targetType:s.targetType.name}),{status:"completed",plan:s,server:c.server,manifest:a,verification:c.verification}}var Ec=String.raw`
175
175
  const { readdir, readFile, readlink, stat } = await import('node:fs/promises')
176
176
 
177
177
  const text = (command) => {
@@ -276,12 +276,12 @@ case "$root_fs" in
276
276
  xfs) xfs_growfs / ;;
277
277
  *) echo "Unsupported root filesystem: $root_fs" >&2; exit 1 ;;
278
278
  esac`,e)}async function Nc(e,t){let r=Buffer.from(t.join(`
279
- `)).toString("base64");await Ie(e.host,`printf %s ${r} | base64 -d | while read -r unit; do [ -z "$unit" ] || systemctl is-active --quiet "$unit" || systemctl start "$unit"; done`,e)}async function jc(e,t,r,n={recovered:!1}){if(await ht(e.host,{...e,timeoutMs:e.sshTimeoutMs??600000}),!n.recovered)await kc(e);if(r)await Nc(e,r.runningServices);let s=await Vc(e),i=[],a=r?_t(r.runningServices,s.runningServices):[],c=r?_t(r.releaseLinks,s.releaseLinks):[],u=r?_t(r.routeFragments,s.routeFragments):[],f=r?_t(r.routeIds,s.routeIds):[],h=r?.persistentData.map((k)=>k.split("=")[0])??[],S=s.persistentData.map((k)=>k.split("=")[0]),v=_t(h,S),_=r?_t(r.dataCatalog,s.dataCatalog):[],y=s.routeProbes.filter((k)=>!k.ok),b=n.recovered&&r?r.cpuCores:t.cores??0,D=n.recovered&&r?r.memoryBytes:Ac(t),V=s.cpuCores>=b,H=s.memoryBytes>=D*0.9,x=n.recovered||s.rootDiskBytes>=(t.disk??0)*1e9*0.95;if(s.failedUnits.length>0)i.push(`Failed services: ${s.failedUnits.join(", ")}`);if(a.length>0)i.push(`Services did not return: ${a.join(", ")}`);if(c.length>0)i.push(`Release links changed: ${c.join(", ")}`);if(u.length>0)i.push(`Route manifests changed: ${u.join(", ")}`);if(f.length>0)i.push(`Routes disappeared: ${f.join(", ")}`);if(v.length>0)i.push(`Persistent data paths disappeared: ${v.join(", ")}`);if(_.length>0)i.push(`Databases or volumes disappeared: ${_.join(", ")}`);if(y.length>0)i.push(`Unhealthy routes: ${y.map((k)=>k.domain).join(", ")}`);if(!V)i.push(`Expected at least ${b} CPU cores, found ${s.cpuCores}`);if(!H)i.push(`Expected at least ${D} bytes of RAM`);if(!x)i.push(`Expected approximately ${t.disk??0} GB root disk`);return{ok:i.length===0,checks:{cpuCores:s.cpuCores,memoryBytes:s.memoryBytes,rootDiskBytes:s.rootDiskBytes,rootFilesystemBytes:s.rootFilesystemBytes,runningServices:s.runningServices.length,releaseLinks:s.releaseLinks.length,routeFragments:s.routeFragments.length,routes:s.routeIds.length,healthyRoutes:s.routeProbes.filter((k)=>k.ok).length,persistentDataPaths:s.persistentData.length,databasesAndVolumes:s.dataCatalog.length,failedUnits:s.failedUnits.length},failures:i}}import{mkdir as Bc,readFile as el,rename as tl,writeFile as rl}from"node:fs/promises";import{join as fo}from"node:path";var zc="storage/cloud/state";function At(e=process.cwd()){return il()?l(e,"state"):fo(e,zc)}function qe(e,t=process.cwd()){return fo(At(t),`${e}.json`)}async function je(e,t=process.cwd()){try{let r=await el(qe(e,t),"utf8");return JSON.parse(r)}catch{return null}}async function yt(e,t,r=process.cwd()){let n=qe(e,r);await Bc(At(r),{recursive:!0});let s=`${n}.${process.pid}.tmp`;await rl(s,`${JSON.stringify(t,null,2)}
280
- `,"utf8"),await tl(s,n)}async function tt(e){return je(e)}async function rt(e,t){await yt(e,t)}async function ui(e,t,r){let n=r.length?await e.listVolumes():[];return r.map((s)=>{let i=n.filter((f)=>f.name===s.name);if(i.length>1)throw Error(`Ambiguous volume name: ${s.name}`);let a=i[0];if(a&&a.server!==null&&a.server!==t.id)throw Error(`Volume ${a.name} belongs to another server; refusing to detach live storage`);let c=t.location?.name??t.datacenter?.location.name;if(a&&a.location.name!==c)throw Error(`Volume ${a.name} is in ${a.location.name}, server is in ${c}`);if(a&&a.size>s.size)throw Error(`Refusing to shrink volume ${a.name}: ${a.size} GB to ${s.size} GB`);let u=[];if(!a)u.push("create");else{if(a.server===null)u.push("attach");if(a.size<s.size)u.push("grow")}if(!a||a.protection.delete!==(s.deleteProtection!==!1))u.push("protect");return u.push("mount"),{declaration:s,existing:a,actions:u}})}async function gi(e,t,r){let n=[];for(let s of r){let i=s.existing,a=!i;if(!i){let c=await e.createVolume({name:s.declaration.name,size:s.declaration.size,server:t.id,labels:{...t.labels,"ts-cloud/volume":s.declaration.key}});await e.waitForAction(c.action.id);for(let u of c.next_actions??[])await e.waitForAction(u.id);i=await e.getVolume(c.volume.id)}if(i.server===null)await e.waitForAction((await e.attachVolume(i.id,t.id)).id),i=await e.getVolume(i.id);if(i.server!==t.id||i.location.name!==(t.location?.name??t.datacenter?.location.name))throw Error(`Volume attachment verification failed: ${i.name}`);if(i.linux_device!==`/dev/disk/by-id/scsi-0HC_Volume_${i.id}`)throw Error(`Unexpected Hetzner volume device: ${i.name}`);if(i.size<s.declaration.size)await e.waitForAction((await e.resizeVolume(i.id,s.declaration.size)).id);if(i.protection.delete!==(s.declaration.deleteProtection!==!1))await e.waitForAction((await e.protectVolume(i.id,s.declaration.deleteProtection!==!1)).id);n.push({...s.declaration,id:i.id,device:i.linux_device,allowFormat:a})}return n}var Un=268435456;function Gt(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function ll(e){let t=sl("sha256");for await(let r of ol(e))t.update(r);return t.digest("hex")}class Pe{name="hetzner";usesCloudFormation=!1;client;sshPrivateKeyPath;sshPublicKeyPath;sshUser;location;stateOnly;residency;waitForBoot;bootWait;async applyComputeChanges(e){let{config:t,environment:r}=e;if(t.cloud?.attachTo)throw Error("Only the compute owner may reconcile server size and volumes");let n=t.infrastructure?.compute;if(n?.resize&&!n.size)throw Error("compute.resize requires an explicit compute.size");let s=ei(t,r),i=Dn(n??{});if(i.appServers>1||i.dedicatedServices)throw Error("Managed compute volumes currently require a single app server");let a=await this.getComputeOutputs(e);if(!a.appInstanceId)throw Error("No existing compute server found; provision the server first");let c=await this.client.getServer(Number(a.appInstanceId)),u=await ui(this.client,c,s),f=n?.resize&&n.size?await er(this.client,c.id,Ge(n.size),n.resize.upgradeDisk!==!1):void 0,h={serverId:String(c.id),changes:u.flatMap((y)=>y.actions.map((b)=>({resource:y.declaration.name,action:b,detail:`${y.declaration.size} GB at ${y.declaration.mountPath}`})))};if(n?.deploymentStorage)h.changes.push({resource:n.deploymentStorage.volume,action:"place-deployments",detail:`Reconcile release directories${n.deploymentStorage.includeBackups!==!1?" and deployment backups":""} on the volume; ${n.deploymentStorage.migrateExisting?"verify and migrate existing files":"refuse nonempty directories"}`});if(f&&!f.alreadyComplete)if(!f.capacityAvailable){if(n?.resize?.whenUnavailable!=="keep-current")throw Error(`${f.targetType.name} is unavailable in ${f.location}`);h.waitingForCapacity=`${f.targetType.name} unavailable in ${f.location}; keeping ${c.server_type.name} running`}else h.changes.push({resource:c.name,action:"resize",detail:`${c.server_type.name} to ${f.targetType.name}`});if(e.dryRun)return h;if(h.waitingForCapacity)console.warn(`[ts-cloud] ${h.waitingForCapacity}`);let S=await gi(this.client,c,u),v=[{id:String(c.id),name:c.name,publicIp:c.public_net.ipv4?.ip}],_=[...Xe(t.notifications),...n?.volumes||n?.deploymentStorage?ti({volumes:S,deploymentStorage:n?.deploymentStorage,webRoot:"/var/www"}):[],...n?.monitoring!==!1?Le(n?.monitoring):[]];if(_.length){let y=await this.runRemoteDeploy({targets:v,commands:_,timeoutSeconds:7200,comment:"ts-cloud apply configured compute storage"});if(!y.success)throw Error(y.error||y.perInstance.map((b)=>b.error||b.output).join(`
281
- `))}if(f?.capacityAvailable&&!f.alreadyComplete){let y={host:v[0].publicIp,user:this.sshUser,identityFile:this.sshPrivateKeyPath},b=await li({client:this.client,serverId:c.id,targetType:f.targetType.name,upgradeDisk:f.upgradeDisk,hooks:{preflight:()=>qc(y),afterBoot:(D,V,H,x)=>jc(y,V,H,x)}});if(b.status!=="completed"&&b.status!=="already-complete")throw Error(`Resize did not complete: ${b.status}`)}return h}constructor(e={}){this.residency=e.residency;let t=Kt(e.apiToken);if(this.stateOnly=!e.client&&!t&&e.allowStateOnly===!0,!e.client&&!t&&!this.stateOnly)throw Error("Hetzner API token required. Set hetzner.apiToken in cloud.config.ts or HCLOUD_TOKEN / HETZNER_API_TOKEN.");this.client=e.client??new Qr({apiToken:t??""});let r=Qs(void 0,{sshPrivateKeyPath:e.sshPrivateKeyPath,sshPublicKeyPath:e.sshPublicKeyPath,sshUser:e.sshUser,location:e.location});this.sshPrivateKeyPath=r.sshPrivateKeyPath,this.sshPublicKeyPath=r.sshPublicKeyPath,this.sshUser=r.sshUser,this.location=r.location,this.waitForBoot=e.waitForBoot??!0,this.bootWait={sshIntervalMs:e.bootWait?.sshIntervalMs??5000,sshTimeoutMs:e.bootWait?.sshTimeoutMs??300000,cloudInitIntervalMs:e.bootWait?.cloudInitIntervalMs??5000,cloudInitTimeoutMs:e.bootWait?.cloudInitTimeoutMs??600000}}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e,n=t.project.slug,s=t.infrastructure?.compute;if(!s)throw Error("infrastructure.compute is required to provision Hetzner compute");if(t.cloud?.attachTo)return this.attachToComputeInfrastructure(t.cloud.attachTo,t,r);let i=m(t,r),a=`${n}-${r}-app`,c=s.runtime==="php"||!!s.php,u=Dn(s);if(u.dedicatedServices||u.appServers>1)return c?this.provisionFleet(e,u):this.provisionBunFleet(e,u);let f=me(n,r,"app"),h=t.sites||{},S=j(s)?[]:this.collectUpstreamPorts(h),v=`${n}-${r}-app-fw`,{firewall:_}=await this.ensureFirewall(v,f,Dr({allowSsh:s.allowSsh!==!1,sitePorts:S,allowedPorts:[...s.firewall?.allowedPorts??[],...Cs(t.infrastructure?.sftp),...Ye(C(t,{environment:r}))]})),y=await this.ensureSshKey(n,r,f),b=await tt(i);if(b?.serverId){let ne=await this.tryGetServer(b.serverId);if(ne&&ne.status!=="off"){if(s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(b,ne)}}let D=await this.findExistingServer(n,r,a);if(D&&D.status!=="off"){let ne={provider:"hetzner",stackName:i,serverId:D.id,serverName:D.name,publicIp:D.public_net.ipv4?.ip,publicIpv6:De(D.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};if(await rt(i,ne),s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(ne,D)}let V=w(t,{environment:r}),H=V?.engine==="rpx"?G({proxy:V,config:B(h,{proxy:V,slug:t.project.slug,mail:C(t,{environment:r})}),slug:t.project.slug,bunBin:s.runtime==="node"||s.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,x=Je(t,{environment:r}),k=s.bakedImage===!0,I=M({runtime:x.runtime,runtimeVersion:x.runtimeVersion,systemPackages:s.systemPackages,database:t.infrastructure?.database,phpProvision:x.phpProvision,servicesProvision:x.servicesProvision,rpxProvision:H,baked:k,swapGb:s.swapGb}),Y=se(I),W=Ge(s.size),K=jt(t),{server:ee,action:re}=await this.client.createServer({name:a,serverType:W,image:K,location:t.hetzner?.location||this.location,userData:Y,labels:f,sshKeys:y?[y]:void 0,firewalls:[{firewall:_.id}]});await this.client.waitForAction(re.id);let te=await this.client.waitForServerRunning(ee.id),ie={provider:"hetzner",stackName:i,serverId:te.id,serverName:te.name,firewallId:_.id,publicIp:te.public_net.ipv4?.ip,publicIpv6:De(te.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};await rt(i,ie);let oe=te.public_net.ipv4?.ip;if(oe&&this.waitForBoot)await this.waitForSshReady(oe),await this.waitForCloudInit(oe);if(s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(ie,te)}async provisionFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,i=r.infrastructure.compute,a=m(r,n),c=Ge(i.size),u=jt(r),f=r.hetzner?.location||this.location,h=i.bakedImage===!0,S=await tt(a);if(S?.loadBalancerId){let R=(await this.client.listLoadBalancers().catch(()=>[])).find((O)=>O.id===S.loadBalancerId);if(R)return{appPublicIp:R.public_net?.ipv4?.ip,loadBalancerIp:R.public_net?.ipv4?.ip,servicesPrivateIp:S.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}let v=await this.ensureSshKey(s,n,me(s,n,"app")),_=`${s}-${n}-net`,b=(await this.client.listNetworks().catch(()=>[])).find((P)=>P.name===_)??await this.client.createNetwork({name:_,labels:me(s,n,"app")}),{firewall:D}=await this.ensureFirewall(`${s}-${n}-app-fw`,me(s,n,"app"),Dr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),{firewall:V}=await this.ensureFirewall(`${s}-${n}-services-fw`,me(s,n,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[b.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[b.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[b.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[b.ip_range]}]),H=xn(r),x=se(M({runtime:"php",servicesProvision:H,baked:h,swapGb:i.swapGb})),k=await this.client.listServers().catch(()=>[]),I=[],Y=k.find((P)=>$e(P.labels,s,n,"services"));if(!Y){let{server:P,action:R}=await this.client.createServer({name:`${s}-${n}-services`,serverType:Ge(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:u,location:f,userData:x,labels:me(s,n,"services"),sshKeys:v?[v]:void 0,firewalls:[{firewall:V.id}],networks:[b.id]});await this.client.waitForAction(R.id),Y=await this.client.waitForServerRunning(P.id),I.push(P.id)}let W=Y.id,K=Y.private_net?.[0]?.ip??(await this.client.getServer(W)).private_net?.[0]?.ip,ee=[...Me(!0),...Le(!0),...ct(i.sshKeys),...Xe(r.notifications)],re=cr({versions:i.php?.versions,default:i.php?.default,extensions:i.php?.extensions,installNginx:!j(i),optimizeForProduction:i.php?.optimizeForProduction,ini:i.php?.ini}),te=se(M({runtime:"php",phpProvision:re,servicesProvision:ee,baked:h,swapGb:i.swapGb})),ie=k.filter((P)=>$e(P.labels,s,n,"app")),oe=ie.map((P)=>P.id);if(ie.length>t.appServers)for(let P of ie.slice(t.appServers))await this.client.deleteServer(P.id).catch(()=>{}),oe.splice(oe.indexOf(P.id),1);for(let P=ie.length;P<t.appServers;P++){let{server:R,action:O}=await this.client.createServer({name:`${s}-${n}-app-${P+1}`,serverType:c,image:u,location:f,userData:te,labels:me(s,n,"app"),sshKeys:v?[v]:void 0,firewalls:[{firewall:D.id}],networks:[b.id]});await this.client.waitForAction(O.id),oe.push(R.id),I.push(R.id)}if(this.waitForBoot&&I.length>0)await Promise.all(I.map(async(P)=>{let O=(await this.client.waitForServerRunning(P)).public_net.ipv4?.ip;if(O)await this.waitForSshReady(O),await this.waitForCloudInit(O)}));let ne=`${s}-${n}-lb`,he,ye;if(t.loadBalancer){let R=(await this.client.listLoadBalancers().catch(()=>[])).find((O)=>O.name===ne)??await this.client.createLoadBalancer({name:ne,location:f,network:b.id,labels:me(s,n,"lb"),labelSelector:`ts-cloud/project=${s},ts-cloud/environment=${n},ts-cloud/role=app`,services:[{listenPort:80,destinationPort:80},{listenPort:443,destinationPort:443}]});ye=R.id,he=R.public_net?.ipv4?.ip}let T=he??(await this.client.getServer(oe[0]).catch(()=>{return}))?.public_net.ipv4?.ip,L={provider:"hetzner",stackName:a,networkId:b.id,loadBalancerId:ye,servicesServerId:W,servicesPrivateIp:K,publicIp:T,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await rt(a,L),{appPublicIp:T,loadBalancerIp:he,servicesPrivateIp:K,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async provisionBunFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,i=r.infrastructure.compute,a=m(r,n),c=Ge(i.size),u=jt(r),f=r.hetzner?.location||this.location,h=i.bakedImage===!0,S=r.sites||{},v=await tt(a);if(v?.lbServerId){let O=await this.tryGetServer(v.lbServerId);if(O&&O.status!=="off"){let J=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"},q=await this.findComputeTargets({slug:s,environment:n,role:"app",stackName:a});return this.refreshLbRoutes(O,S,q.map((X)=>({privateIp:X.privateIp,publicIp:X.publicIp})),J,s),{appPublicIp:O.public_net.ipv4?.ip??v.publicIp,loadBalancerIp:O.public_net.ipv4?.ip??v.publicIp,servicesPrivateIp:v.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}}let _=await this.ensureSshKey(s,n,me(s,n,"app")),y=`${s}-${n}-net`,D=(await this.client.listNetworks().catch(()=>[])).find((O)=>O.name===y)??await this.client.createNetwork({name:y,labels:me(s,n,"app")}),V=this.collectUpstreamPorts(S),{firewall:H}=await this.ensureFirewall(`${s}-${n}-app-fw`,me(s,n,"app"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},...V.map((O)=>({direction:"in",protocol:"tcp",port:String(O),source_ips:[D.ip_range],description:`ts-cloud port ${O} (private, LB-only)`}))]),{firewall:x}=await this.ensureFirewall(`${s}-${n}-lb-fw`,me(s,n,"lb"),Dr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),k=await this.client.listServers().catch(()=>[]),I=[],Y,W,K=!!i.servicesServer||!!i.managedServices,ee=t.dedicatedServices&&K;if(ee){let{firewall:O}=await this.ensureFirewall(`${s}-${n}-services-fw`,me(s,n,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[D.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[D.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[D.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[D.ip_range]}]),J=xn(r),q=se(M({runtime:"bun",servicesProvision:J,baked:h,swapGb:i.swapGb})),X=k.find((Z)=>$e(Z.labels,s,n,"services"));if(!X){let{server:Z,action:le}=await this.client.createServer({name:`${s}-${n}-services`,serverType:Ge(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:u,location:f,userData:q,labels:me(s,n,"services"),sshKeys:_?[_]:void 0,firewalls:[{firewall:O.id}],networks:[D.id]});await this.client.waitForAction(le.id),X=await this.client.waitForServerRunning(Z.id),I.push(Z.id)}Y=X.id,W=X.private_net?.[0]?.ip??(await this.client.getServer(Y)).private_net?.[0]?.ip}let re=ee?{...i,managedServices:void 0,backups:void 0}:i,te=Je({...r,infrastructure:{...r.infrastructure,compute:re}},{environment:n}),ie=se(M({runtime:te.runtime,runtimeVersion:te.runtimeVersion,systemPackages:i.systemPackages,database:r.infrastructure?.database,servicesProvision:te.servicesProvision,baked:h,swapGb:i.swapGb})),oe=k.filter((O)=>$e(O.labels,s,n,"app")),ne=oe.map((O)=>O.id);if(oe.length>t.appServers)for(let O of oe.slice(t.appServers))await this.client.deleteServer(O.id).catch(()=>{}),ne.splice(ne.indexOf(O.id),1);for(let O=oe.length;O<t.appServers;O++){let{server:J,action:q}=await this.client.createServer({name:`${s}-${n}-app-${O+1}`,serverType:c,image:u,location:f,userData:ie,labels:me(s,n,"app"),sshKeys:_?[_]:void 0,firewalls:[{firewall:H.id}],networks:[D.id]});await this.client.waitForAction(q.id),ne.push(J.id),I.push(J.id)}if(this.waitForBoot&&I.length>0)await Promise.all(I.map(async(O)=>{let q=(await this.client.waitForServerRunning(O)).public_net.ipv4?.ip;if(q)await this.waitForSshReady(q),await this.waitForCloudInit(q)}));let he=[];for(let O of ne){let J=k.find((q)=>q.id===O);if(!J||!J.private_net?.[0]?.ip)J=await this.client.getServer(O).catch(()=>J);he.push({privateIp:J?.private_net?.[0]?.ip,publicIp:J?.public_net.ipv4?.ip})}let ye=`${s}-${n}-lb`,T,L;if(t.loadBalancer){let O=k.find((q)=>$e(q.labels,s,n,"lb")),J=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"};if(!O){let q=G({proxy:J,config:rr(S,he,{proxy:J,slug:s}),slug:s,bunBin:te.runtime==="node"||te.runtime==="deno"?void 0:"/usr/local/bin/bun"}),X=se(M({runtime:"bun",rpxProvision:q,baked:!1})),Z=typeof i.loadBalancer==="object"?i.loadBalancer.size:void 0,{server:le,action:E}=await this.client.createServer({name:ye,serverType:Ge(Z??"micro"),image:u,location:f,userData:X,labels:me(s,n,"lb"),sshKeys:_?[_]:void 0,firewalls:[{firewall:x.id}],networks:[D.id]});if(await this.client.waitForAction(E.id),O=await this.client.waitForServerRunning(le.id),this.waitForBoot){let N=O.public_net.ipv4?.ip;if(N)await this.waitForSshReady(N),await this.waitForCloudInit(N)}}else this.refreshLbRoutes(O,S,he,J,s);T=O.id,L=O.public_net.ipv4?.ip}let P=L??(await this.client.getServer(ne[0]).catch(()=>{return}))?.public_net.ipv4?.ip,R={provider:"hetzner",stackName:a,networkId:D.id,lbServerId:T,appServerIds:ne,servicesServerId:Y,servicesPrivateIp:W,publicIp:P,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await rt(a,R),{appPublicIp:P,loadBalancerIp:L,servicesPrivateIp:W,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async destroyCompute(e){let{config:t,environment:r}=e,n=t.project.slug,s=m(t,r),i=await tt(s),a=[],c=`${n}-${r}-lb`,f=(await this.client.listLoadBalancers().catch(()=>[])).find((H)=>H.name===c);if(f)try{await this.client.deleteLoadBalancer(f.id),a.push(`load balancer ${c}`)}catch{}let h=await this.client.listServers().catch(()=>[]),S=new Set;for(let H of h)if($e(H.labels,n,r,"app")||$e(H.labels,n,r,"services")||$e(H.labels,n,r,"lb"))S.add(H.id);if(i?.serverId)S.add(i.serverId);if(i?.servicesServerId)S.add(i.servicesServerId);if(i?.lbServerId)S.add(i.lbServerId);for(let H of i?.appServerIds??[])S.add(H);for(let H of S)try{await this.client.deleteServer(H),a.push(`server ${H}`)}catch{}let v=await this.client.listFirewalls().catch(()=>[]);for(let H of[`${n}-${r}-app-fw`,`${n}-${r}-services-fw`,`${n}-${r}-lb-fw`]){let x=v.find((k)=>k.name===H);if(!x)continue;for(let k=0;k<12;k++)try{await this.client.deleteFirewall(x.id),a.push(`firewall ${H}`);break}catch{await this.sleep(3000)}}let _=`${n}-${r}-net`,b=(await this.client.listNetworks().catch(()=>[])).find((H)=>H.name===_);if(b)for(let H=0;H<12;H++)try{await this.client.deleteNetwork(b.id),a.push(`network ${_}`);break}catch{await this.sleep(3000)}let V=(await this.client.listSshKeys().catch(()=>[])).filter((H)=>An(H.labels,n,r));for(let H of V)try{await this.client.deleteSshKey(H.id),a.push(`ssh key ${H.name}`)}catch{}return await rt(s,{provider:"hetzner",stackName:s}).catch(()=>{}),{destroyed:a}}async getComputeOutputs(e){let t=m(e.config,e.environment),r=await tt(t);if(r?.serverId){let i=await this.tryGetServer(r.serverId);if(i)return this.outputsFromState(r,i)}if(r?.lbServerId){let a=(await this.tryGetServer(r.lbServerId))?.public_net.ipv4?.ip??r.publicIp;return{...this.outputsFromState(r),appPublicIp:a,loadBalancerIp:a}}if(r?.loadBalancerId||r?.servicesPrivateIp)return this.outputsFromState(r);let s=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:m(e.config,e.environment)}))[0];return{deployStoragePath:"/var/ts-cloud/staging",appInstanceId:s?.id,appPublicIp:s?.publicIp,sshUser:this.sshUser}}async uploadRelease(e){let t=e.targets?.length?e.targets:await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:m(e.config,e.environment)});if(t.length===0)throw Error("No Hetzner compute targets found for release upload");let s=`/var/ts-cloud/staging/${`${e.remoteKey.replace(/^releases\//,"").replace(/\.tar\.gz$/,"").replace(/\//g,"-")}-${ho()}.tar.gz`}`,i=await ll(e.localPath),a=Mr,c=`${a}/${i}.tar.gz`;for(let u of t){if(!u.publicIp)throw Error(`Target ${u.id} has no public IP for SCP upload`);let f=["set -euo pipefail",`mkdir -p ${Gt(a)} /var/ts-cloud/staging`,`test -s ${Gt(c)}`,`cp -- ${Gt(c)} ${Gt(s)}`].join(`
282
- `);try{this.sshExec(u.publicIp,f);continue}catch{}let h=`${a}/.${i}-${ho()}.tmp`;try{this.scpToHost(u.publicIp,e.localPath,h),this.sshExec(u.publicIp,Tr(h,c,s))}catch(S){try{this.sshExec(u.publicIp,wr(h))}catch{}throw S}}return{artifactRef:s}}async findComputeTargets(e){let{assertComputeResidency:t}=await import("./chunk-nh7rcks9.js"),r=e.role||"app",n=(a)=>{if(this.residency)t(this.residency,{country:a.location?.country,location:a.location?.name||a.datacenter?.location?.name});return{id:String(a.id),name:a.name,publicIp:a.public_net.ipv4?.ip,publicIpv6:De(a.public_net.ipv6?.ip),privateIp:a.private_net?.[0]?.ip,status:a.status}};if(r==="app"||r==="lb"||r==="services"){let a=await tt(e.stackName??`${e.slug}-${e.environment}`),c=[...new Set(r==="app"?[a?.serverId,...a?.appServerIds??[]]:r==="lb"?[a?.lbServerId]:[a?.servicesServerId])].filter((h)=>typeof h==="number");if(this.stateOnly){if(this.residency)throw Error("Residency requires fresh provider evidence; a local state pin alone is insufficient");if(c.length>0&&a?.publicIp)return c.map((h)=>({id:String(h),name:h===a.serverId?a.serverName:void 0,publicIp:a.publicIp,publicIpv6:a.publicIpv6,status:"running"}));if(r!=="app")return[];throw Error(`Hetzner API token required because '${e.stackName??`${e.slug}-${e.environment}`}' has no complete local compute state pin.`)}let u=await this.client.listServers();if(c.length>0){let h=[];for(let S of c){let v=u.find((_)=>_.id===S)??await this.tryGetServer(S);if(S===a?.serverId&&a.serverName&&v?.name!==a.serverName)continue;if(v&&v.status!=="off")h.push(v)}if(h.length>0)return h.map(n)}let f=u.filter((h)=>$e(h.labels,e.slug,e.environment,r));if(f.length>0)return f.map(n);if(r==="app"){let h=u.filter((S)=>S.status!=="off"&&S.labels?.[`${pe}/managed-by`]==="ts-cloud"&&S.labels?.[`${pe}/environment`]===e.environment&&S.labels?.[`${pe}/role`]==="app");if(h.length===1)return h.map(n)}return[]}if(this.stateOnly)throw Error(`Hetzner API token required to discover '${r}' compute targets.`);let i=(await this.client.listServers()).filter((a)=>$e(a.labels,e.slug,e.environment,r));if(i.length>0)return i.map(n);return[]}async attachToComputeInfrastructure(e,t,r){let n=await this.client.listServers(),s=(v)=>n.filter((_)=>_.status!=="off"&&$e(_.labels,e,r,v)),i=s("app");if(i.length===0)throw Error(`Cannot attach '${t.project.slug}' to '${e}': no running Hetzner app server is labeled for ${e}/${r}. Deploy the owner project first.`);let a=s("lb")[0],c=s("services")[0],u=i[0],f=a??u,h=m(t,r),S={provider:"hetzner",stackName:h,serverId:u.id,serverName:u.name,appServerIds:i.map((v)=>v.id),lbServerId:a?.id,servicesServerId:c?.id,servicesPrivateIp:c?.private_net?.[0]?.ip,publicIp:f.public_net.ipv4?.ip,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await rt(h,S),this.outputsFromState(S)}async listReachableResources(){return(await this.client.listServers()).map((t)=>({name:t.name,labels:t.labels}))}async runRemoteDeploy(e){if(e.targets.length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets provided"};let t=e.commands.join(`
279
+ `)).toString("base64");await Ie(e.host,`printf %s ${r} | base64 -d | while read -r unit; do [ -z "$unit" ] || systemctl is-active --quiet "$unit" || systemctl start "$unit"; done`,e)}async function jc(e,t,r,n={recovered:!1}){if(await ht(e.host,{...e,timeoutMs:e.sshTimeoutMs??600000}),!n.recovered)await kc(e);if(r)await Nc(e,r.runningServices);let s=await Vc(e),i=[],a=r?_t(r.runningServices,s.runningServices):[],c=r?_t(r.releaseLinks,s.releaseLinks):[],u=r?_t(r.routeFragments,s.routeFragments):[],f=r?_t(r.routeIds,s.routeIds):[],h=r?.persistentData.map((L)=>L.split("=")[0])??[],S=s.persistentData.map((L)=>L.split("=")[0]),v=_t(h,S),_=r?_t(r.dataCatalog,s.dataCatalog):[],y=s.routeProbes.filter((L)=>!L.ok),T=n.recovered&&r?r.cpuCores:t.cores??0,x=n.recovered&&r?r.memoryBytes:Ac(t),W=s.cpuCores>=T,H=s.memoryBytes>=x*0.9,R=n.recovered||s.rootDiskBytes>=(t.disk??0)*1e9*0.95;if(s.failedUnits.length>0)i.push(`Failed services: ${s.failedUnits.join(", ")}`);if(a.length>0)i.push(`Services did not return: ${a.join(", ")}`);if(c.length>0)i.push(`Release links changed: ${c.join(", ")}`);if(u.length>0)i.push(`Route manifests changed: ${u.join(", ")}`);if(f.length>0)i.push(`Routes disappeared: ${f.join(", ")}`);if(v.length>0)i.push(`Persistent data paths disappeared: ${v.join(", ")}`);if(_.length>0)i.push(`Databases or volumes disappeared: ${_.join(", ")}`);if(y.length>0)i.push(`Unhealthy routes: ${y.map((L)=>L.domain).join(", ")}`);if(!W)i.push(`Expected at least ${T} CPU cores, found ${s.cpuCores}`);if(!H)i.push(`Expected at least ${x} bytes of RAM`);if(!R)i.push(`Expected approximately ${t.disk??0} GB root disk`);return{ok:i.length===0,checks:{cpuCores:s.cpuCores,memoryBytes:s.memoryBytes,rootDiskBytes:s.rootDiskBytes,rootFilesystemBytes:s.rootFilesystemBytes,runningServices:s.runningServices.length,releaseLinks:s.releaseLinks.length,routeFragments:s.routeFragments.length,routes:s.routeIds.length,healthyRoutes:s.routeProbes.filter((L)=>L.ok).length,persistentDataPaths:s.persistentData.length,databasesAndVolumes:s.dataCatalog.length,failedUnits:s.failedUnits.length},failures:i}}import{mkdir as Bc,readFile as el,rename as tl,writeFile as rl}from"node:fs/promises";import{join as fo}from"node:path";var zc="storage/cloud/state";function At(e=process.cwd()){return il()?l(e,"state"):fo(e,zc)}function qe(e,t=process.cwd()){return fo(At(t),`${e}.json`)}async function je(e,t=process.cwd()){try{let r=await el(qe(e,t),"utf8");return JSON.parse(r)}catch{return null}}async function yt(e,t,r=process.cwd()){let n=qe(e,r);await Bc(At(r),{recursive:!0});let s=`${n}.${process.pid}.tmp`;await rl(s,`${JSON.stringify(t,null,2)}
280
+ `,"utf8"),await tl(s,n)}async function tt(e){return je(e)}async function rt(e,t){await yt(e,t)}async function ui(e,t,r){let n=r.length?await e.listVolumes():[];return r.map((s)=>{let i=n.filter((f)=>f.name===s.name);if(i.length>1)throw Error(`Ambiguous volume name: ${s.name}`);let a=i[0];if(a&&a.server!==null&&a.server!==t.id)throw Error(`Volume ${a.name} belongs to another server; refusing to detach live storage`);let c=t.location?.name??t.datacenter?.location.name;if(a&&a.location.name!==c)throw Error(`Volume ${a.name} is in ${a.location.name}, server is in ${c}`);if(a&&a.size>s.size)throw Error(`Refusing to shrink volume ${a.name}: ${a.size} GB to ${s.size} GB`);let u=[];if(!a)u.push("create");else{if(a.server===null)u.push("attach");if(a.size<s.size)u.push("grow")}if(!a||a.protection.delete!==(s.deleteProtection!==!1))u.push("protect");return u.push("mount"),{declaration:s,existing:a,actions:u}})}async function gi(e,t,r){let n=[];for(let s of r){let i=s.existing,a=!i;if(!i){let c=await e.createVolume({name:s.declaration.name,size:s.declaration.size,server:t.id,labels:{...t.labels,"ts-cloud/volume":s.declaration.key}});await e.waitForAction(c.action.id);for(let u of c.next_actions??[])await e.waitForAction(u.id);i=await e.getVolume(c.volume.id)}if(i.server===null)await e.waitForAction((await e.attachVolume(i.id,t.id)).id),i=await e.getVolume(i.id);if(i.server!==t.id||i.location.name!==(t.location?.name??t.datacenter?.location.name))throw Error(`Volume attachment verification failed: ${i.name}`);if(i.linux_device!==`/dev/disk/by-id/scsi-0HC_Volume_${i.id}`)throw Error(`Unexpected Hetzner volume device: ${i.name}`);if(i.size<s.declaration.size)await e.waitForAction((await e.resizeVolume(i.id,s.declaration.size)).id);if(i.protection.delete!==(s.declaration.deleteProtection!==!1))await e.waitForAction((await e.protectVolume(i.id,s.declaration.deleteProtection!==!1)).id);n.push({...s.declaration,id:i.id,device:i.linux_device,allowFormat:a})}return n}var Un=268435456;function Gt(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function ll(e){let t=sl("sha256");for await(let r of ol(e))t.update(r);return t.digest("hex")}class Pe{name="hetzner";usesCloudFormation=!1;client;sshPrivateKeyPath;sshPublicKeyPath;sshUser;location;stateOnly;residency;waitForBoot;bootWait;async applyComputeChanges(e){let{config:t,environment:r}=e;if(t.cloud?.attachTo)throw Error("Only the compute owner may reconcile server size and volumes");let n=t.infrastructure?.compute;if(n?.resize&&!n.size)throw Error("compute.resize requires an explicit compute.size");let s=ei(t,r),i=Dn(n??{});if(i.appServers>1||i.dedicatedServices)throw Error("Managed compute volumes currently require a single app server");let a=await this.getComputeOutputs(e);if(!a.appInstanceId)throw Error("No existing compute server found; provision the server first");let c=await this.client.getServer(Number(a.appInstanceId)),u=await ui(this.client,c,s),f=n?.resize&&n.size?await er(this.client,c.id,Ge(n.size),n.resize.upgradeDisk!==!1):void 0,h={serverId:String(c.id),changes:u.flatMap((y)=>y.actions.map((T)=>({resource:y.declaration.name,action:T,detail:`${y.declaration.size} GB at ${y.declaration.mountPath}`})))};if(n?.deploymentStorage)h.changes.push({resource:n.deploymentStorage.volume,action:"place-deployments",detail:`Reconcile release directories${n.deploymentStorage.includeBackups!==!1?" and deployment backups":""} on the volume; ${n.deploymentStorage.migrateExisting?"verify and migrate existing files":"refuse nonempty directories"}`});if(f&&!f.alreadyComplete)if(!f.capacityAvailable){if(n?.resize?.whenUnavailable!=="keep-current")throw Error(`${f.targetType.name} is unavailable in ${f.location}`);h.waitingForCapacity=`${f.targetType.name} unavailable in ${f.location}; keeping ${c.server_type.name} running`}else h.changes.push({resource:c.name,action:"resize",detail:`${c.server_type.name} to ${f.targetType.name}`});if(e.dryRun)return h;if(h.waitingForCapacity)console.warn(`[ts-cloud] ${h.waitingForCapacity}`);let S=await gi(this.client,c,u),v=[{id:String(c.id),name:c.name,publicIp:c.public_net.ipv4?.ip}],_=[...Xe(t.notifications),...n?.volumes||n?.deploymentStorage?ti({volumes:S,deploymentStorage:n?.deploymentStorage,webRoot:"/var/www"}):[],...n?.monitoring!==!1?Le(n?.monitoring):[]];if(_.length){let y=await this.runRemoteDeploy({targets:v,commands:_,timeoutSeconds:7200,comment:"ts-cloud apply configured compute storage"});if(!y.success)throw Error(y.error||y.perInstance.map((T)=>T.error||T.output).join(`
281
+ `))}if(f?.capacityAvailable&&!f.alreadyComplete){let y={host:v[0].publicIp,user:this.sshUser,identityFile:this.sshPrivateKeyPath},T=await li({client:this.client,serverId:c.id,targetType:f.targetType.name,upgradeDisk:f.upgradeDisk,hooks:{preflight:()=>qc(y),afterBoot:(x,W,H,R)=>jc(y,W,H,R)}});if(T.status!=="completed"&&T.status!=="already-complete")throw Error(`Resize did not complete: ${T.status}`)}return h}constructor(e={}){this.residency=e.residency;let t=Kt(e.apiToken);if(this.stateOnly=!e.client&&!t&&e.allowStateOnly===!0,!e.client&&!t&&!this.stateOnly)throw Error("Hetzner API token required. Set hetzner.apiToken in cloud.config.ts or HCLOUD_TOKEN / HETZNER_API_TOKEN.");this.client=e.client??new Qr({apiToken:t??""});let r=Qs(void 0,{sshPrivateKeyPath:e.sshPrivateKeyPath,sshPublicKeyPath:e.sshPublicKeyPath,sshUser:e.sshUser,location:e.location});this.sshPrivateKeyPath=r.sshPrivateKeyPath,this.sshPublicKeyPath=r.sshPublicKeyPath,this.sshUser=r.sshUser,this.location=r.location,this.waitForBoot=e.waitForBoot??!0,this.bootWait={sshIntervalMs:e.bootWait?.sshIntervalMs??5000,sshTimeoutMs:e.bootWait?.sshTimeoutMs??300000,cloudInitIntervalMs:e.bootWait?.cloudInitIntervalMs??5000,cloudInitTimeoutMs:e.bootWait?.cloudInitTimeoutMs??600000}}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e,n=t.project.slug,s=t.infrastructure?.compute;if(!s)throw Error("infrastructure.compute is required to provision Hetzner compute");if(t.cloud?.attachTo)return this.attachToComputeInfrastructure(t.cloud.attachTo,t,r);let i=m(t,r),a=`${n}-${r}-app`,c=s.runtime==="php"||!!s.php,u=Dn(s),f=t.cloud?.residency||this.residency,{assertComputeResidency:h}=await import("./chunk-nh7rcks9.js"),S=(b)=>{if(f)h(f,{country:b.location?.country||b.datacenter?.location?.country,location:b.location?.name||b.datacenter?.location?.name})};if(f){if(u.dedicatedServices||u.appServers>1)throw Error("Residency policy currently requires single-host compute");let b=await this.client.getLocation(t.hetzner?.location||this.location);h(f,{country:b.country,location:b.name})}if(u.dedicatedServices||u.appServers>1)return c?this.provisionFleet(e,u):this.provisionBunFleet(e,u);let v=fe(n,r,"app"),_=t.sites||{},y=j(s)?[]:this.collectUpstreamPorts(_),T=`${n}-${r}-app-fw`,{firewall:x}=await this.ensureFirewall(T,v,Dr({allowSsh:s.allowSsh!==!1,sitePorts:y,allowedPorts:[...s.firewall?.allowedPorts??[],...Cs(t.infrastructure?.sftp),...Ye(C(t,{environment:r}))]})),W=await this.ensureSshKey(n,r,v),H=await tt(i);if(H?.serverId){let b=await this.tryGetServer(H.serverId);if(b&&b.status!=="off"&&b.labels?.["ts-cloud/project"]===n&&b.labels?.["ts-cloud/environment"]===r){if(S(b),s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(H,b)}}let R=await this.findExistingServer(n,r,a);if(R&&R.status!=="off"){S(R);let b={provider:"hetzner",stackName:i,serverId:R.id,serverName:R.name,publicIp:R.public_net.ipv4?.ip,publicIpv6:De(R.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};if(await rt(i,b),s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(b,R)}let L=w(t,{environment:r}),I=L?.engine==="rpx"?G({proxy:L,config:B(_,{proxy:L,slug:t.project.slug,mail:C(t,{environment:r})}),slug:t.project.slug,bunBin:s.runtime==="node"||s.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,V=Je(t,{environment:r}),q=s.bakedImage===!0,K=M({runtime:V.runtime,runtimeVersion:V.runtimeVersion,systemPackages:s.systemPackages,database:t.infrastructure?.database,phpProvision:V.phpProvision,servicesProvision:V.servicesProvision,rpxProvision:I,baked:q,swapGb:s.swapGb}),ee=se(K),te=Ge(s.size),ne=jt(t),{server:ie,action:oe}=await this.client.createServer({name:a,serverType:te,image:ne,location:t.hetzner?.location||this.location,userData:ee,labels:v,sshKeys:W?[W]:void 0,firewalls:[{firewall:x.id}]});await this.client.waitForAction(oe.id);let re=await this.client.waitForServerRunning(ie.id);S(re);let pe={provider:"hetzner",stackName:i,serverId:re.id,serverName:re.name,firewallId:x.id,publicIp:re.public_net.ipv4?.ip,publicIpv6:De(re.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};await rt(i,pe);let ge=re.public_net.ipv4?.ip;if(ge&&this.waitForBoot)await this.waitForSshReady(ge),await this.waitForCloudInit(ge);if(s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(pe,re)}async provisionFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,i=r.infrastructure.compute,a=m(r,n),c=Ge(i.size),u=jt(r),f=r.hetzner?.location||this.location,h=i.bakedImage===!0,S=await tt(a);if(S?.loadBalancerId){let O=(await this.client.listLoadBalancers().catch(()=>[])).find((D)=>D.id===S.loadBalancerId);if(O)return{appPublicIp:O.public_net?.ipv4?.ip,loadBalancerIp:O.public_net?.ipv4?.ip,servicesPrivateIp:S.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}let v=await this.ensureSshKey(s,n,fe(s,n,"app")),_=`${s}-${n}-net`,T=(await this.client.listNetworks().catch(()=>[])).find((P)=>P.name===_)??await this.client.createNetwork({name:_,labels:fe(s,n,"app")}),{firewall:x}=await this.ensureFirewall(`${s}-${n}-app-fw`,fe(s,n,"app"),Dr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),{firewall:W}=await this.ensureFirewall(`${s}-${n}-services-fw`,fe(s,n,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[T.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[T.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[T.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[T.ip_range]}]),H=xn(r),R=se(M({runtime:"php",servicesProvision:H,baked:h,swapGb:i.swapGb})),L=await this.client.listServers().catch(()=>[]),I=[],V=L.find((P)=>ye(P.labels,s,n,"services"));if(!V){let{server:P,action:O}=await this.client.createServer({name:`${s}-${n}-services`,serverType:Ge(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:u,location:f,userData:R,labels:fe(s,n,"services"),sshKeys:v?[v]:void 0,firewalls:[{firewall:W.id}],networks:[T.id]});await this.client.waitForAction(O.id),V=await this.client.waitForServerRunning(P.id),I.push(P.id)}let q=V.id,K=V.private_net?.[0]?.ip??(await this.client.getServer(q)).private_net?.[0]?.ip,ee=[...Me(!0),...Le(!0),...ct(i.sshKeys),...Xe(r.notifications)],te=cr({versions:i.php?.versions,default:i.php?.default,extensions:i.php?.extensions,installNginx:!j(i),optimizeForProduction:i.php?.optimizeForProduction,ini:i.php?.ini}),ne=se(M({runtime:"php",phpProvision:te,servicesProvision:ee,baked:h,swapGb:i.swapGb})),ie=L.filter((P)=>ye(P.labels,s,n,"app")),oe=ie.map((P)=>P.id);if(ie.length>t.appServers)for(let P of ie.slice(t.appServers))await this.client.deleteServer(P.id).catch(()=>{}),oe.splice(oe.indexOf(P.id),1);for(let P=ie.length;P<t.appServers;P++){let{server:O,action:D}=await this.client.createServer({name:`${s}-${n}-app-${P+1}`,serverType:c,image:u,location:f,userData:ne,labels:fe(s,n,"app"),sshKeys:v?[v]:void 0,firewalls:[{firewall:x.id}],networks:[T.id]});await this.client.waitForAction(D.id),oe.push(O.id),I.push(O.id)}if(this.waitForBoot&&I.length>0)await Promise.all(I.map(async(P)=>{let D=(await this.client.waitForServerRunning(P)).public_net.ipv4?.ip;if(D)await this.waitForSshReady(D),await this.waitForCloudInit(D)}));let re=`${s}-${n}-lb`,pe,ge;if(t.loadBalancer){let O=(await this.client.listLoadBalancers().catch(()=>[])).find((D)=>D.name===re)??await this.client.createLoadBalancer({name:re,location:f,network:T.id,labels:fe(s,n,"lb"),labelSelector:`ts-cloud/project=${s},ts-cloud/environment=${n},ts-cloud/role=app`,services:[{listenPort:80,destinationPort:80},{listenPort:443,destinationPort:443}]});ge=O.id,pe=O.public_net?.ipv4?.ip}let b=pe??(await this.client.getServer(oe[0]).catch(()=>{return}))?.public_net.ipv4?.ip,k={provider:"hetzner",stackName:a,networkId:T.id,loadBalancerId:ge,servicesServerId:q,servicesPrivateIp:K,publicIp:b,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await rt(a,k),{appPublicIp:b,loadBalancerIp:pe,servicesPrivateIp:K,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async provisionBunFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,i=r.infrastructure.compute,a=m(r,n),c=Ge(i.size),u=jt(r),f=r.hetzner?.location||this.location,h=i.bakedImage===!0,S=r.sites||{},v=await tt(a);if(v?.lbServerId){let D=await this.tryGetServer(v.lbServerId);if(D&&D.status!=="off"){let J=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"},Y=await this.findComputeTargets({slug:s,environment:n,role:"app",stackName:a});return this.refreshLbRoutes(D,S,Y.map((X)=>({privateIp:X.privateIp,publicIp:X.publicIp})),J,s),{appPublicIp:D.public_net.ipv4?.ip??v.publicIp,loadBalancerIp:D.public_net.ipv4?.ip??v.publicIp,servicesPrivateIp:v.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}}let _=await this.ensureSshKey(s,n,fe(s,n,"app")),y=`${s}-${n}-net`,x=(await this.client.listNetworks().catch(()=>[])).find((D)=>D.name===y)??await this.client.createNetwork({name:y,labels:fe(s,n,"app")}),W=this.collectUpstreamPorts(S),{firewall:H}=await this.ensureFirewall(`${s}-${n}-app-fw`,fe(s,n,"app"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},...W.map((D)=>({direction:"in",protocol:"tcp",port:String(D),source_ips:[x.ip_range],description:`ts-cloud port ${D} (private, LB-only)`}))]),{firewall:R}=await this.ensureFirewall(`${s}-${n}-lb-fw`,fe(s,n,"lb"),Dr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),L=await this.client.listServers().catch(()=>[]),I=[],V,q,K=!!i.servicesServer||!!i.managedServices,ee=t.dedicatedServices&&K;if(ee){let{firewall:D}=await this.ensureFirewall(`${s}-${n}-services-fw`,fe(s,n,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[x.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[x.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[x.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[x.ip_range]}]),J=xn(r),Y=se(M({runtime:"bun",servicesProvision:J,baked:h,swapGb:i.swapGb})),X=L.find((Z)=>ye(Z.labels,s,n,"services"));if(!X){let{server:Z,action:le}=await this.client.createServer({name:`${s}-${n}-services`,serverType:Ge(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:u,location:f,userData:Y,labels:fe(s,n,"services"),sshKeys:_?[_]:void 0,firewalls:[{firewall:D.id}],networks:[x.id]});await this.client.waitForAction(le.id),X=await this.client.waitForServerRunning(Z.id),I.push(Z.id)}V=X.id,q=X.private_net?.[0]?.ip??(await this.client.getServer(V)).private_net?.[0]?.ip}let te=ee?{...i,managedServices:void 0,backups:void 0}:i,ne=Je({...r,infrastructure:{...r.infrastructure,compute:te}},{environment:n}),ie=se(M({runtime:ne.runtime,runtimeVersion:ne.runtimeVersion,systemPackages:i.systemPackages,database:r.infrastructure?.database,servicesProvision:ne.servicesProvision,baked:h,swapGb:i.swapGb})),oe=L.filter((D)=>ye(D.labels,s,n,"app")),re=oe.map((D)=>D.id);if(oe.length>t.appServers)for(let D of oe.slice(t.appServers))await this.client.deleteServer(D.id).catch(()=>{}),re.splice(re.indexOf(D.id),1);for(let D=oe.length;D<t.appServers;D++){let{server:J,action:Y}=await this.client.createServer({name:`${s}-${n}-app-${D+1}`,serverType:c,image:u,location:f,userData:ie,labels:fe(s,n,"app"),sshKeys:_?[_]:void 0,firewalls:[{firewall:H.id}],networks:[x.id]});await this.client.waitForAction(Y.id),re.push(J.id),I.push(J.id)}if(this.waitForBoot&&I.length>0)await Promise.all(I.map(async(D)=>{let Y=(await this.client.waitForServerRunning(D)).public_net.ipv4?.ip;if(Y)await this.waitForSshReady(Y),await this.waitForCloudInit(Y)}));let pe=[];for(let D of re){let J=L.find((Y)=>Y.id===D);if(!J||!J.private_net?.[0]?.ip)J=await this.client.getServer(D).catch(()=>J);pe.push({privateIp:J?.private_net?.[0]?.ip,publicIp:J?.public_net.ipv4?.ip})}let ge=`${s}-${n}-lb`,b,k;if(t.loadBalancer){let D=L.find((Y)=>ye(Y.labels,s,n,"lb")),J=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"};if(!D){let Y=G({proxy:J,config:rr(S,pe,{proxy:J,slug:s}),slug:s,bunBin:ne.runtime==="node"||ne.runtime==="deno"?void 0:"/usr/local/bin/bun"}),X=se(M({runtime:"bun",rpxProvision:Y,baked:!1})),Z=typeof i.loadBalancer==="object"?i.loadBalancer.size:void 0,{server:le,action:E}=await this.client.createServer({name:ge,serverType:Ge(Z??"micro"),image:u,location:f,userData:X,labels:fe(s,n,"lb"),sshKeys:_?[_]:void 0,firewalls:[{firewall:R.id}],networks:[x.id]});if(await this.client.waitForAction(E.id),D=await this.client.waitForServerRunning(le.id),this.waitForBoot){let N=D.public_net.ipv4?.ip;if(N)await this.waitForSshReady(N),await this.waitForCloudInit(N)}}else this.refreshLbRoutes(D,S,pe,J,s);b=D.id,k=D.public_net.ipv4?.ip}let P=k??(await this.client.getServer(re[0]).catch(()=>{return}))?.public_net.ipv4?.ip,O={provider:"hetzner",stackName:a,networkId:x.id,lbServerId:b,appServerIds:re,servicesServerId:V,servicesPrivateIp:q,publicIp:P,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await rt(a,O),{appPublicIp:P,loadBalancerIp:k,servicesPrivateIp:q,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async destroyCompute(e){let{config:t,environment:r}=e,n=t.project.slug,s=m(t,r),i=await tt(s),a=[],c=`${n}-${r}-lb`,f=(await this.client.listLoadBalancers().catch(()=>[])).find((H)=>H.name===c);if(f)try{await this.client.deleteLoadBalancer(f.id),a.push(`load balancer ${c}`)}catch{}let h=await this.client.listServers().catch(()=>[]),S=new Set;for(let H of h)if(ye(H.labels,n,r,"app")||ye(H.labels,n,r,"services")||ye(H.labels,n,r,"lb"))S.add(H.id);if(i?.serverId)S.add(i.serverId);if(i?.servicesServerId)S.add(i.servicesServerId);if(i?.lbServerId)S.add(i.lbServerId);for(let H of i?.appServerIds??[])S.add(H);for(let H of S)try{await this.client.deleteServer(H),a.push(`server ${H}`)}catch{}let v=await this.client.listFirewalls().catch(()=>[]);for(let H of[`${n}-${r}-app-fw`,`${n}-${r}-services-fw`,`${n}-${r}-lb-fw`]){let R=v.find((L)=>L.name===H);if(!R)continue;for(let L=0;L<12;L++)try{await this.client.deleteFirewall(R.id),a.push(`firewall ${H}`);break}catch{await this.sleep(3000)}}let _=`${n}-${r}-net`,T=(await this.client.listNetworks().catch(()=>[])).find((H)=>H.name===_);if(T)for(let H=0;H<12;H++)try{await this.client.deleteNetwork(T.id),a.push(`network ${_}`);break}catch{await this.sleep(3000)}let W=(await this.client.listSshKeys().catch(()=>[])).filter((H)=>An(H.labels,n,r));for(let H of W)try{await this.client.deleteSshKey(H.id),a.push(`ssh key ${H.name}`)}catch{}return await rt(s,{provider:"hetzner",stackName:s}).catch(()=>{}),{destroyed:a}}async getComputeOutputs(e){let t=m(e.config,e.environment),r=await tt(t);if(r?.serverId){let i=await this.tryGetServer(r.serverId);if(i)return this.outputsFromState(r,i)}if(r?.lbServerId){let a=(await this.tryGetServer(r.lbServerId))?.public_net.ipv4?.ip??r.publicIp;return{...this.outputsFromState(r),appPublicIp:a,loadBalancerIp:a}}if(r?.loadBalancerId||r?.servicesPrivateIp)return this.outputsFromState(r);let s=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:m(e.config,e.environment)}))[0];return{deployStoragePath:"/var/ts-cloud/staging",appInstanceId:s?.id,appPublicIp:s?.publicIp,sshUser:this.sshUser}}async uploadRelease(e){let t=e.targets?.length?e.targets:await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:m(e.config,e.environment)});if(t.length===0)throw Error("No Hetzner compute targets found for release upload");let s=`/var/ts-cloud/staging/${`${e.remoteKey.replace(/^releases\//,"").replace(/\.tar\.gz$/,"").replace(/\//g,"-")}-${ho()}.tar.gz`}`,i=await ll(e.localPath),a=Mr,c=`${a}/${i}.tar.gz`;for(let u of t){if(!u.publicIp)throw Error(`Target ${u.id} has no public IP for SCP upload`);let f=["set -euo pipefail",`mkdir -p ${Gt(a)} /var/ts-cloud/staging`,`test -s ${Gt(c)}`,`cp -- ${Gt(c)} ${Gt(s)}`].join(`
282
+ `);try{this.sshExec(u.publicIp,f);continue}catch{}let h=`${a}/.${i}-${ho()}.tmp`;try{this.scpToHost(u.publicIp,e.localPath,h),this.sshExec(u.publicIp,Tr(h,c,s))}catch(S){try{this.sshExec(u.publicIp,wr(h))}catch{}throw S}}return{artifactRef:s}}async findComputeTargets(e){let{assertComputeResidency:t}=await import("./chunk-nh7rcks9.js"),r=e.role||"app",n=(a)=>{if(this.residency)t(this.residency,{country:a.location?.country||a.datacenter?.location?.country,location:a.location?.name||a.datacenter?.location?.name});return{id:String(a.id),name:a.name,publicIp:a.public_net.ipv4?.ip,publicIpv6:De(a.public_net.ipv6?.ip),privateIp:a.private_net?.[0]?.ip,status:a.status}};if(r==="app"||r==="lb"||r==="services"){let a=await tt(e.stackName??`${e.slug}-${e.environment}`),c=[...new Set(r==="app"?[a?.serverId,...a?.appServerIds??[]]:r==="lb"?[a?.lbServerId]:[a?.servicesServerId])].filter((h)=>typeof h==="number");if(this.stateOnly){if(this.residency)throw Error("Residency requires fresh provider evidence; a local state pin alone is insufficient");if(c.length>0&&a?.publicIp)return c.map((h)=>({id:String(h),name:h===a.serverId?a.serverName:void 0,publicIp:a.publicIp,publicIpv6:a.publicIpv6,status:"running"}));if(r!=="app")return[];throw Error(`Hetzner API token required because '${e.stackName??`${e.slug}-${e.environment}`}' has no complete local compute state pin.`)}let u=await this.client.listServers();if(c.length>0){let h=[];for(let S of c){let v=u.find((_)=>_.id===S)??await this.tryGetServer(S);if(S===a?.serverId&&a.serverName&&v?.name!==a.serverName)continue;if(v&&v.status!=="off")h.push(v)}if(h.length>0)return h.map(n)}let f=u.filter((h)=>ye(h.labels,e.slug,e.environment,r));if(f.length>0)return f.map(n);if(r==="app"){let h=u.filter((S)=>S.status!=="off"&&S.labels?.[`${me}/managed-by`]==="ts-cloud"&&S.labels?.[`${me}/environment`]===e.environment&&S.labels?.[`${me}/role`]==="app");if(h.length===1)return h.map(n)}return[]}if(this.stateOnly)throw Error(`Hetzner API token required to discover '${r}' compute targets.`);let i=(await this.client.listServers()).filter((a)=>ye(a.labels,e.slug,e.environment,r));if(i.length>0)return i.map(n);return[]}async attachToComputeInfrastructure(e,t,r){let n=await this.client.listServers(),s=(v)=>n.filter((_)=>_.status!=="off"&&ye(_.labels,e,r,v)),i=s("app");if(i.length===0)throw Error(`Cannot attach '${t.project.slug}' to '${e}': no running Hetzner app server is labeled for ${e}/${r}. Deploy the owner project first.`);let a=s("lb")[0],c=s("services")[0],u=i[0],f=a??u,h=m(t,r),S={provider:"hetzner",stackName:h,serverId:u.id,serverName:u.name,appServerIds:i.map((v)=>v.id),lbServerId:a?.id,servicesServerId:c?.id,servicesPrivateIp:c?.private_net?.[0]?.ip,publicIp:f.public_net.ipv4?.ip,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await rt(h,S),this.outputsFromState(S)}async listReachableResources(){return(await this.client.listServers()).map((t)=>({name:t.name,labels:t.labels}))}async runRemoteDeploy(e){if(e.targets.length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets provided"};let t=e.commands.join(`
283
283
  `),r=[];for(let s of e.targets){if(!s.publicIp){r.push({instanceId:s.id,status:"Failed",error:"Missing public IP"});continue}try{let i=this.sshExec(s.publicIp,t);Or(i),r.push({instanceId:s.id,status:"Success",output:i})}catch(i){r.push({instanceId:s.id,status:"Failed",error:i.message})}}let n=r.every((s)=>s.status==="Success");return{success:n,instanceCount:e.targets.length,perInstance:r,error:n?void 0:Xt(r,"One or more SSH deploy commands failed")}}async ensureSshKey(e,t,r){if(!al(this.sshPublicKeyPath))throw Error(`SSH public key not found at ${this.sshPublicKeyPath}. ts-cloud deploys to Hetzner over SSH and needs a public key to authorize on the server. Generate one (\`ssh-keygen -t ed25519\`) or set hetzner.sshPrivateKeyPath / HCLOUD_SSH_PUBLIC_KEY.`);let n=cl(this.sshPublicKeyPath,"utf8").trim(),s=Ve(n),a=(await this.client.listSshKeys()).find((u)=>Ve(u.public_key)===s);if(a)return a.id;return(await this.client.createSshKey({name:`${e}-${t}-deploy`,publicKey:n,labels:r})).id}async tryGetServer(e){try{return await this.client.getServer(e)}catch{return null}}refreshLbRoutes(e,t,r,n,s){let i=e.public_net.ipv4?.ip;if(!i){console.warn(`[ts-cloud] LB server '${e.name}' has no public IP — skipping the rpx route refresh; its routes may be stale.`);return}let a=r.filter((u)=>u.privateIp||u.publicIp);if(a.length===0){console.warn(`[ts-cloud] No routable app boxes found for LB '${e.name}' — leaving its current rpx routes untouched.`);return}let c=rr(t,a,{proxy:n,slug:s});this.sshExec(i,Ne({config:c,slug:s}).join(`
284
- `))}async findExistingServer(e,t,r){let n=await this.client.listServers(),s=n.find((a)=>$e(a.labels,e,t,"app")||a.name===r);if(s)return s;let i=n.filter((a)=>a.status!=="off"&&a.labels?.[`${pe}/managed-by`]==="ts-cloud"&&a.labels?.[`${pe}/environment`]===t&&a.labels?.[`${pe}/role`]==="app");if(i.length===1){let a=i[0],c=a.labels?.[`${pe}/project`]??"unknown";return console.warn(`[ts-cloud] No server named '${r}' found; adopting existing ts-cloud app server '${a.name}' (project label '${c}') for project '${e}' — `+"updating it in place instead of provisioning a new server."),a}return}async ensureFirewall(e,t,r){let s=(await this.client.listFirewalls()).find((a)=>a.name===e);if(s)return await this.client.setFirewallRules(s.id,r),{firewall:s};let{firewall:i}=await this.client.createFirewall({name:e,labels:t,rules:r});return{firewall:i}}collectUpstreamPorts(e){let t=new Set;for(let r of Object.values(e))if(typeof r.port==="number")t.add(r.port);return[...t].filter((r)=>![80,443].includes(r))}async sleep(e){await new Promise((t)=>setTimeout(t,e))}async waitForSshReady(e){let{sshIntervalMs:t,sshTimeoutMs:r}=this.bootWait,n=Date.now(),s;while(Date.now()-n<r)try{go(`ssh ${this.sshBaseArgs(e,["-o","ConnectTimeout=5"]).map(Gt).join(" ")} true`,{stdio:"pipe",maxBuffer:Un});return}catch(i){s=i,await this.sleep(t)}throw Error(`Timed out waiting for SSH on ${e} after ${r}ms: ${s?.message??"unknown error"}`)}async waitForCloudInit(e){let{cloudInitIntervalMs:t,cloudInitTimeoutMs:r}=this.bootWait,n=Date.now();while(Date.now()-n<r){try{let s=this.sshExec(e,"if command -v cloud-init >/dev/null 2>&1; then cloud-init status --long 2>/dev/null || true; else echo 'status: done'; fi");if(/status:\s*error/.test(s))throw Error(`cloud-init reported an error on ${e}:
284
+ `))}async findExistingServer(e,t,r){let n=await this.client.listServers(),s=n.find((a)=>ye(a.labels,e,t,"app")||a.name===r);if(s)return s;let i=n.filter((a)=>a.status!=="off"&&a.labels?.[`${me}/managed-by`]==="ts-cloud"&&a.labels?.[`${me}/environment`]===t&&a.labels?.[`${me}/role`]==="app");if(i.length===1){let a=i[0],c=a.labels?.[`${me}/project`]??"unknown";return console.warn(`[ts-cloud] No server named '${r}' found; adopting existing ts-cloud app server '${a.name}' (project label '${c}') for project '${e}' — `+"updating it in place instead of provisioning a new server."),a}return}async ensureFirewall(e,t,r){let s=(await this.client.listFirewalls()).find((a)=>a.name===e);if(s)return await this.client.setFirewallRules(s.id,r),{firewall:s};let{firewall:i}=await this.client.createFirewall({name:e,labels:t,rules:r});return{firewall:i}}collectUpstreamPorts(e){let t=new Set;for(let r of Object.values(e))if(typeof r.port==="number")t.add(r.port);return[...t].filter((r)=>![80,443].includes(r))}async sleep(e){await new Promise((t)=>setTimeout(t,e))}async waitForSshReady(e){let{sshIntervalMs:t,sshTimeoutMs:r}=this.bootWait,n=Date.now(),s;while(Date.now()-n<r)try{go(`ssh ${this.sshBaseArgs(e,["-o","ConnectTimeout=5"]).map(Gt).join(" ")} true`,{stdio:"pipe",maxBuffer:Un});return}catch(i){s=i,await this.sleep(t)}throw Error(`Timed out waiting for SSH on ${e} after ${r}ms: ${s?.message??"unknown error"}`)}async waitForCloudInit(e){let{cloudInitIntervalMs:t,cloudInitTimeoutMs:r}=this.bootWait,n=Date.now();while(Date.now()-n<r){try{let s=this.sshExec(e,"if command -v cloud-init >/dev/null 2>&1; then cloud-init status --long 2>/dev/null || true; else echo 'status: done'; fi");if(/status:\s*error/.test(s))throw Error(`cloud-init reported an error on ${e}:
285
285
  ${s}`);if(/status:\s*(?:done|degraded)/.test(s))return}catch(s){if(s instanceof Error&&/cloud-init reported an error/.test(s.message))throw s}await this.sleep(t)}throw Error(`Timed out waiting for cloud-init to finish on ${e} after ${r}ms`)}outputsFromState(e,t){return{deployStoragePath:e.deployStoragePath||"/var/ts-cloud/staging",appInstanceId:e.serverId?String(e.serverId):void 0,appPublicIp:t?.public_net.ipv4?.ip||e.publicIp,appPublicIpv6:De(t?.public_net.ipv6?.ip)||e.publicIpv6,sshUser:e.sshUser||this.sshUser,servicesPrivateIp:e.servicesPrivateIp}}static SSH_HOST_KEY_OPTS=["-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR"];static SSH_KEEPALIVE_OPTS=["-o","ConnectTimeout=30","-o","ServerAliveInterval=15","-o","ServerAliveCountMax=4"];sshBaseArgs(e,t=[]){return["-i",this.sshPrivateKeyPath,...Pe.SSH_HOST_KEY_OPTS,...Pe.SSH_KEEPALIVE_OPTS,"-o","BatchMode=yes",...t,`${this.sshUser}@${e}`]}scpToHost(e,t,r){let n=["scp",...Bt,"-i",this.sshPrivateKeyPath,...Pe.SSH_HOST_KEY_OPTS,...Pe.SSH_KEEPALIVE_OPTS,"-o","BatchMode=yes",t,`${this.sshUser}@${e}:${r}`].map((i)=>`"${i.replace(/"/g,"\\\"")}"`).join(" "),s=3;for(let i=1;i<=3;i++)try{go(n,{stdio:"pipe",maxBuffer:Un});return}catch(a){if(i===3)throw Error(Jt(a))}}sshExec(e,t){try{return nl("ssh",[...this.sshBaseArgs(e),Qc],{encoding:"utf8",input:t,stdio:["pipe","pipe","pipe"],maxBuffer:Un})}catch(r){throw Error(`${Jt(r)}${Yn(r,t)}`)}}}class ro{name="ssh";usesCloudFormation=!1;async getComputeOutputs(){return{appPublicIp:"127.0.0.1",sshUser:"root"}}async uploadRelease(e){return{artifactRef:e.localPath}}async findComputeTargets(e){if((e.role||"app")!=="app")return[];return[{id:"localhost",name:"localhost",publicIp:"127.0.0.1",status:"running"}]}async runRemoteDeploy(e){let t=e.commands.join(`
286
286
  `);try{let r=Bun.spawn(["bash","-c",t],{stdout:"pipe",stderr:"pipe",env:process.env}),[n,s,i]=await Promise.all([new Response(r.stdout).text(),new Response(r.stderr).text(),r.exited]);return{success:i===0,instanceCount:1,perInstance:[{instanceId:"localhost",status:i===0?"Success":"Failed",output:n,error:s}]}}catch(r){return{success:!1,instanceCount:1,perInstance:[{instanceId:"localhost",status:"Failed",error:r?.message??String(r)}],error:r?.message??String(r)}}}}function no(){let e=process.env.TS_CLOUD_DASHBOARD_BOX;return e!=null&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}import{createHash as wl,randomUUID as wo}from"node:crypto";import{createReadStream as Cl}from"node:fs";import{isIP as Pl}from"node:net";import{createHash as ul}from"node:crypto";import{appendFile as pl,mkdir as dl,readFile as ml}from"node:fs/promises";import{dirname as fl}from"node:path";var So=268435456,vo=async(e,t)=>{let r=Bun.spawn(e,{stdin:t===void 0?"ignore":Buffer.from(t),stdout:"pipe",stderr:"pipe"}),[n,s,i]=await Promise.all([r.exited,new Response(r.stdout).text(),new Response(r.stderr).text()]);return{code:n,signal:r.signalCode,stdout:s.slice(-So),stderr:i.slice(-So)}},Gg=["-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR"],Vg=["-o","ConnectTimeout=30","-o","ServerAliveInterval=15","-o","ServerAliveCountMax=4"];function _o(e){if(e.hostKey==="insecure")return[...Gg];return["-o",`StrictHostKeyChecking=${e.hostKey.policy==="pin"?"yes":"accept-new"}`,"-o",`UserKnownHostsFile=${e.hostKey.knownHostsFile}`,"-o","LogLevel=ERROR"]}function $o(e){let t=[...Vg];if(e.connectTimeoutSec!==void 0)t[1]=`ConnectTimeout=${e.connectTimeoutSec}`;return t}function Kc(e,t,r=[]){return["-i",e.identityFile,"-p",String(e.port??22),..._o(e),...$o(e),"-o","BatchMode=yes",...r,`${e.user}@${t}`]}function qg(e,t,r,n){return["-i",e.identityFile,"-P",String(e.port??22),..._o(e),...$o(e),"-o","BatchMode=yes",r,`${e.user}@${t}:${n}`]}function St(e){return`SHA256:${ul("sha256").update(Buffer.from(e,"base64")).digest("base64").replace(/=+$/,"")}`}async function pi(e,t=22,r=vo){let n=await r(["ssh-keyscan","-T","10","-p",String(t),"-t","ed25519",e]),s=n.stdout.split(`
287
287
  `).find((i)=>i&&!i.startsWith("#"))?.trim().split(/\s+/);if(n.code!==0||!s?.[1]||!s[2])throw Error(`SSH host-key scan failed: ${n.stderr.trim()||"no key returned"}`);return{algorithm:s[1],key:s[2]}}function Wc(e,t=22){return t===22?e:`[${e}]:${t}`}function jg(e,t,r){return`${Wc(e,t)} ${r.algorithm} ${r.key}`}function zg(e,t,r=22){let n=Wc(t,r);for(let s of e.split(`
@@ -317,9 +317,9 @@ systemctl restart systemd-journald
317
317
  # The deploy user uploads releases as itself (scp), while the scripts run as
318
318
  # root through sudo. setgid group-writable directories let both write.
319
319
  install -d -m 2775 -g "$(id -gn ${nt(e)})" /var/ts-cloud/artifacts /var/ts-cloud/staging
320
- `}function bl(e){let t=nt(e),r=`/home/${e}`;return[`chown -R ${t}:"$(id -gn ${t})" ${nt(`${r}/.ssh`)}`,`chmod 700 ${nt(`${r}/.ssh`)}`]}function mi(e){let{config:t,environment:r,profile:n,sudoUser:s}=e;io(t,n,e.facts?.arch);let i={...t.infrastructure?.compute,proxy:w(t,{environment:e.environment,environmentType:e.environment})},a=t.sites??{},c=t.project.slug,u=e.lan?{...e.lan.hostname?{hostname:e.lan.hostname}:{},tls:e.lan.tls??"local-ca",...yo(e)?{ip:yo(e)}:{}}:void 0,f=i.proxy?.engine==="rpx"?B(a,{proxy:i.proxy,slug:c,lan:u,mail:C(t,{environment:e.environment,environmentType:e.environment})}):void 0,h=i.proxy?.engine==="rpx"&&f?G({proxy:i.proxy,config:f,slug:c,profile:n,bunBin:i.runtime==="node"||i.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,S=i.proxy?.engine==="rpx"&&f?Ne({config:f,slug:c}):void 0,v=s?`/home/${s}/.ssh/authorized_keys`:void 0,_=Je(t,{environment:r,authorizedKeysPath:v}),y=s?[..._.servicesProvision??[],...bl(s)]:_.servicesProvision,b=[...new Set([...i.systemPackages??[],"psmisc","ca-certificates"])],D=i.swapGb??(n==="raspberry-pi"?Wg:void 0),V=M({runtime:_.runtime,runtimeVersion:_.runtimeVersion,systemPackages:b,database:t.infrastructure?.database,phpProvision:_.phpProvision,servicesProvision:y,rpxProvision:h,swapGb:D}).replace(/^#!\/bin\/bash\nset -euo pipefail\n/,""),H=Kg(),x=f?.localCa?` lan=${f.localCa.hosts.join(",")} tls=local-ca`:u?` lan=${u.hostname??`${c}.local`} tls=${u.tls??"local-ca"}`:"",k=`#!/bin/bash
320
+ `}function bl(e){let t=nt(e),r=`/home/${e}`;return[`chown -R ${t}:"$(id -gn ${t})" ${nt(`${r}/.ssh`)}`,`chmod 700 ${nt(`${r}/.ssh`)}`]}function mi(e){let{config:t,environment:r,profile:n,sudoUser:s}=e;io(t,n,e.facts?.arch);let i={...t.infrastructure?.compute,proxy:w(t,{environment:e.environment,environmentType:e.environment})},a=t.sites??{},c=t.project.slug,u=e.lan?{...e.lan.hostname?{hostname:e.lan.hostname}:{},tls:e.lan.tls??"local-ca",...yo(e)?{ip:yo(e)}:{}}:void 0,f=i.proxy?.engine==="rpx"?B(a,{proxy:i.proxy,slug:c,lan:u,mail:C(t,{environment:e.environment,environmentType:e.environment})}):void 0,h=i.proxy?.engine==="rpx"&&f?G({proxy:i.proxy,config:f,slug:c,profile:n,bunBin:i.runtime==="node"||i.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,S=i.proxy?.engine==="rpx"&&f?Ne({config:f,slug:c}):void 0,v=s?`/home/${s}/.ssh/authorized_keys`:void 0,_=Je(t,{environment:r,authorizedKeysPath:v}),y=s?[..._.servicesProvision??[],...bl(s)]:_.servicesProvision,T=[...new Set([...i.systemPackages??[],"psmisc","ca-certificates"])],x=i.swapGb??(n==="raspberry-pi"?Wg:void 0),W=M({runtime:_.runtime,runtimeVersion:_.runtimeVersion,systemPackages:T,database:t.infrastructure?.database,phpProvision:_.phpProvision,servicesProvision:y,rpxProvision:h,swapGb:x}).replace(/^#!\/bin\/bash\nset -euo pipefail\n/,""),H=Kg(),R=f?.localCa?` lan=${f.localCa.hosts.join(",")} tls=local-ca`:u?` lan=${u.hostname??`${c}.local`} tls=${u.tls??"local-ca"}`:"",L=`#!/bin/bash
321
321
  set -euo pipefail
322
- # ts-cloud ssh bootstrap v${ke} profile=${n}${x}
322
+ # ts-cloud ssh bootstrap v${ke} profile=${n}${R}
323
323
 
324
324
  # Idempotence guard. This script may run again (a cloud-init rerun, a repeated
325
325
  # adopt, a deploy): once this version has been applied, only the gateway's
@@ -327,17 +327,17 @@ set -euo pipefail
327
327
  # re-create swap on every boot.
328
328
  if [ -e ${nt(H)} ]; then
329
329
  echo "[ts-cloud] bootstrap v${ke} already applied; refreshing the gateway fragment only"
330
- `;if(S){let I=S[0]==="set -euo pipefail"?S.slice(1):S;k+=`${I.join(`
330
+ `;if(S){let I=S[0]==="set -euo pipefail"?S.slice(1):S;L+=`${I.join(`
331
331
  `)}
332
- `}if(k+=` exit 0
332
+ `}if(L+=` exit 0
333
333
  fi
334
- `,k+=_l(),n==="raspberry-pi")k+=$l();if(s)k+=yl(s);if(k+=`
335
- ${V}`,k+=`
334
+ `,L+=_l(),n==="raspberry-pi")L+=$l();if(s)L+=yl(s);if(L+=`
335
+ ${W}`,L+=`
336
336
  install -d -m 0755 ${nt(Xc)}
337
337
  date -u +%Y-%m-%dT%H:%M:%SZ > ${nt(H)}
338
338
  echo "[ts-cloud] bootstrap v${ke} applied (${n}); gateway fragment at ${z}/${c}.json"
339
- `,f?.localCa)k+=`echo "[ts-cloud] LAN certificate authority for ${f.localCa.hosts.join(", ")} at ${po(f.localCa.dir)} (copy it to a client to trust this box)"
340
- `;return k}var bt={user:"root",port:22,privateKeyPath:"~/.ssh/id_ed25519",hostKey:"pin",profile:"generic",publicIp:"auto"},bo=["pin","accept-new","insecure"],To=["raspberry-pi","generic"];function $t(...e){for(let t of e){let r=process.env[t]?.trim();if(r)return r}return}function Vt(...e){for(let t of e){let r=t?.trim();if(r)return r}return}function Jg(e,t){if(t?.length)return t;if(e?.ssh?.hosts?.length)return e.ssh.hosts;let r=$t("TS_CLOUD_SSH_HOST");if(r)return[{host:r}];throw Error("No ssh host configured. Set ssh.hosts in cloud.config.ts or TS_CLOUD_SSH_HOST.")}function Xg(e,t){return Vt(t,e?.user,$t("TS_CLOUD_SSH_USER"))??bt.user}function Yg(e,t){let r=[{source:"the explicit port",value:t},{source:`ssh.hosts[].port for ${e?.host??"the host"}`,value:e?.port},{source:"TS_CLOUD_SSH_PORT",value:$t("TS_CLOUD_SSH_PORT")}];for(let{source:n,value:s}of r){if(s===void 0||s==="")continue;let i=typeof s==="number"?s:Number(s);if(!Number.isInteger(i)||i<1||i>65535)throw Error(`Invalid SSH port from ${n}: ${String(s)}`);return i}return bt.port}function Zg(e,t){return Pr(Vt(t,e?.privateKeyPath,$t("TS_CLOUD_SSH_KEY"))??bt.privateKeyPath)}function ep(e,t){let r=Vt(t,e?.ssh?.hostKey,$t("TS_CLOUD_SSH_HOST_KEY"))??bt.hostKey;if(!bo.includes(r))throw Error(`Invalid ssh.hostKey '${r}'. Use one of: ${bo.join(", ")}.`);return r}function tp(e,t=bt.user,r){return r??e?.ssh?.sudo??t!=="root"}function rp(e,t){let r=Vt(t,e?.ssh?.profile,$t("TS_CLOUD_SSH_PROFILE"))??bt.profile;if(!To.includes(r))throw Error(`Invalid ssh.profile '${r}'. Use one of: ${To.join(", ")}.`);return r}function np(e,t){return Vt(t,e?.ssh?.publicIp)??bt.publicIp}function ip(e,t){return t??e?.ssh?.lan}function fi(e,t={}){let r=Jg(e,t.hosts).map((n)=>({host:n.host,user:Xg(n,t.user),port:Yg(n,t.port),privateKeyPath:Zg(n,t.privateKeyPath),role:n.role??"app"}));return{hosts:r,hostKey:ep(e,t.hostKey),sudo:tp(e,r[0]?.user,t.sudo),profile:rp(e,t.profile),publicIp:np(e,t.publicIp),lan:ip(e,t.lan)}}var hi=`set -u
339
+ `,f?.localCa)L+=`echo "[ts-cloud] LAN certificate authority for ${f.localCa.hosts.join(", ")} at ${po(f.localCa.dir)} (copy it to a client to trust this box)"
340
+ `;return L}var bt={user:"root",port:22,privateKeyPath:"~/.ssh/id_ed25519",hostKey:"pin",profile:"generic",publicIp:"auto"},bo=["pin","accept-new","insecure"],To=["raspberry-pi","generic"];function $t(...e){for(let t of e){let r=process.env[t]?.trim();if(r)return r}return}function Vt(...e){for(let t of e){let r=t?.trim();if(r)return r}return}function Jg(e,t){if(t?.length)return t;if(e?.ssh?.hosts?.length)return e.ssh.hosts;let r=$t("TS_CLOUD_SSH_HOST");if(r)return[{host:r}];throw Error("No ssh host configured. Set ssh.hosts in cloud.config.ts or TS_CLOUD_SSH_HOST.")}function Xg(e,t){return Vt(t,e?.user,$t("TS_CLOUD_SSH_USER"))??bt.user}function Yg(e,t){let r=[{source:"the explicit port",value:t},{source:`ssh.hosts[].port for ${e?.host??"the host"}`,value:e?.port},{source:"TS_CLOUD_SSH_PORT",value:$t("TS_CLOUD_SSH_PORT")}];for(let{source:n,value:s}of r){if(s===void 0||s==="")continue;let i=typeof s==="number"?s:Number(s);if(!Number.isInteger(i)||i<1||i>65535)throw Error(`Invalid SSH port from ${n}: ${String(s)}`);return i}return bt.port}function Zg(e,t){return Pr(Vt(t,e?.privateKeyPath,$t("TS_CLOUD_SSH_KEY"))??bt.privateKeyPath)}function ep(e,t){let r=Vt(t,e?.ssh?.hostKey,$t("TS_CLOUD_SSH_HOST_KEY"))??bt.hostKey;if(!bo.includes(r))throw Error(`Invalid ssh.hostKey '${r}'. Use one of: ${bo.join(", ")}.`);return r}function tp(e,t=bt.user,r){return r??e?.ssh?.sudo??t!=="root"}function rp(e,t){let r=Vt(t,e?.ssh?.profile,$t("TS_CLOUD_SSH_PROFILE"))??bt.profile;if(!To.includes(r))throw Error(`Invalid ssh.profile '${r}'. Use one of: ${To.join(", ")}.`);return r}function np(e,t){return Vt(t,e?.ssh?.publicIp)??bt.publicIp}function ip(e,t){return t??e?.ssh?.lan}function fi(e,t={}){let r=Jg(e,t.hosts).map((n)=>({host:n.host,user:Xg(n,t.user),port:Yg(n,t.port),privateKeyPath:Zg(n,t.privateKeyPath),role:n.role??"app"}));return{hosts:r,hostKey:ep(e,t.hostKey),sudo:tp(e,r[0]?.user,t.sudo),profile:rp(e,t.profile),publicIp:np(e,t.publicIp),lan:ip(e,t.lan)}}var hi=`set -u
341
341
  . /etc/os-release 2>/dev/null || true
342
342
  # Strings are stripped of quotes, backslashes and newlines rather than escaped:
343
343
  # nothing reported here legitimately contains them, and a probe that cannot
@@ -377,7 +377,7 @@ ${" ".repeat(t+10)}${r.remediation}`:n}).join(`
377
377
  `);try{await this.exec(c.publicIp,u);continue}catch{}let f=`${kn}/.${i}-${wo()}.tmp`;try{await this.transport.scp(c.publicIp,e.localPath,f),await this.exec(c.publicIp,Tr(f,a,s))}catch(h){throw await this.exec(c.publicIp,wr(f)).catch(()=>{}),h}}return{artifactRef:s}}async runRemoteDeploy(e){if(e.targets.length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets provided"};let t=e.commands.join(`
378
378
  `),r=[];for(let s of e.targets){if(!s.publicIp){r.push({instanceId:s.id,status:"Failed",error:"Missing address"});continue}try{let i=await this.exec(s.publicIp,t);Or(i),r.push({instanceId:s.id,status:"Success",output:i})}catch(i){r.push({instanceId:s.id,status:"Failed",error:i.message})}}let n=r.every((s)=>s.status==="Success");return{success:n,instanceCount:e.targets.length,perInstance:r,error:n?void 0:Xt(r,"One or more SSH deploy commands failed")}}targetHost(){return this.host.host}ensureHostKey(e=this.host.host){return this.transport.ensureHostKey(e)}async preflight(e=this.host.host){let t=await this.transport.exec(e,hi,{sudo:!1}),r=Ai(t);return{facts:r,findings:yi(r,{user:this.host.user,profile:this.settings.profile})}}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e;for(let y of op(t,this.settings))console.warn(`[ts-cloud] ${y}`);let n=this.host,s=m(t,r),i=await je(s,this.cwd),a=process.env[sp]==="1"&&i?.provider==="ssh"&&i.host===n.host&&i.bootstrapVersion===ke,c=await this.ensureHostKey(n.host);if(c.pinnedNow)console.warn(`[ts-cloud] pinned ${n.host} host key ${c.fingerprint}`);await this.waitForSshReady(n.host);let{facts:u,findings:f}=await this.preflight(n.host);if(Si(f))throw Error(`Preflight failed for ${n.host}; refusing to bootstrap it.
379
379
  ${Ii(f)}`);for(let y of f)console.warn(`[ts-cloud] ${y.severity}: ${y.message}`);if(u.cloudInitPresent&&/running/i.test(u.cloudInitStatus??""))await this.waitForCloudInit(n.host);let h=u.lanIp?.trim()||(Pl(n.host)!==0?n.host:void 0),S=i?.provider==="ssh"?i.bootstrappedAt:void 0;if(!a){let y=mi({config:t,environment:r,profile:this.settings.profile,facts:u,sudoUser:n.user!=="root"?n.user:void 0,lan:this.settings.lan,lanIp:h});Or(await this.exec(n.host,y)),S=new Date().toISOString()}let v={provider:"ssh",stackName:s,host:n.host,sshUser:n.user,sshPort:n.port,hostKeyFingerprint:c.fingerprint||void 0,publicIp:this.settings.publicIp==="auto"?void 0:this.settings.publicIp,lanIp:u.lanIp||void 0,deployStoragePath:bi,profile:this.settings.profile,bootstrapVersion:ke,bootstrappedAt:S};await yt(s,v,this.cwd);let _=await this.getComputeOutputs();if(j(t.infrastructure?.compute)&&dd(this.settings.lan)==="local-ca")_.lanCaCertPath=po(),console.warn(`[ts-cloud] LAN certificate authority on ${n.host} at ${_.lanCaCertPath}. Fetch it with: scp ${n.user}@${n.host}:${_.lanCaCertPath} ./rpx-root-ca.crt`);return _}async destroyCompute(e){let t=m(e.config,e.environment),r=this.host;return console.warn(`[ts-cloud] forgot ${r.host} for ${t}; nothing was removed on the host (stop the systemd units and remove /var/ts-cloud and /etc/rpx by hand if you want it clean).`),await yt(t,{provider:"ssh",stackName:t,host:r.host,sshUser:r.user,sshPort:r.port},this.cwd).catch(()=>{}),{destroyed:[`local state for ${t}`]}}async sleep(e){await new Promise((t)=>setTimeout(t,e))}async waitForSshReady(e){let{sshIntervalMs:t,sshTimeoutMs:r}=this.bootWait,n=Date.now();do{if(await this.transport.probe(e))return;await this.sleep(t)}while(Date.now()-n<r);throw Error(`Timed out waiting for SSH on ${e} after ${r}ms`)}async waitForCloudInit(e){let{cloudInitIntervalMs:t,cloudInitTimeoutMs:r}=this.bootWait,n=Date.now();while(Date.now()-n<r){try{let s=await this.transport.exec(e,"if command -v cloud-init >/dev/null 2>&1; then cloud-init status --long 2>/dev/null || true; else echo 'status: done'; fi",{sudo:!1});if(/status:\s*error/.test(s))throw Error(`cloud-init reported an error on ${e}:
380
- ${s}`);if(/status:\s*(?:done|degraded)/.test(s))return}catch(s){if(s instanceof Error&&/cloud-init reported an error/.test(s.message))throw s}await this.sleep(t)}throw Error(`Timed out waiting for cloud-init to finish on ${e} after ${r}ms`)}}function F(e){let t=e.provider??ce(e.config);if(e.config.cloud?.residency&&(no()||t!=="hetzner"||!e.config.cloud?.attachTo))throw Error("Residency policy currently requires an attached Hetzner host with live provider evidence");if(no())return new ro;switch(e.provider??ce(e.config)){case"aws":return new Lr({region:e.config.project.region});case"hetzner":return new Pe({apiToken:e.config.hetzner?.apiToken,allowStateOnly:Boolean(e.config.cloud?.attachTo),sshPrivateKeyPath:e.config.hetzner?.sshPrivateKeyPath,sshPublicKeyPath:e.config.hetzner?.sshPublicKeyPath,sshUser:e.config.hetzner?.sshUser,location:e.config.hetzner?.location,residency:e.config.cloud?.residency});case"ssh":return new Hr({hosts:e.config.ssh?.hosts,hostKey:e.config.ssh?.hostKey,sudo:e.config.ssh?.sudo,profile:e.config.ssh?.profile,publicIp:e.config.ssh?.publicIp,lan:e.config.ssh?.lan});case"fly":throw Error("Fly.io has no box to provision or reach over SSH: deploy it with deployToFly() from @stacksjs/ts-cloud.");default:throw Error(`Unknown cloud provider: ${e.provider??ce(e.config)}`)}}class so{drivers=new Map;getDriver(e,t){let r=t??ce(e),n=`${r}:${e.project.slug}:${e.project.region||"default"}:${JSON.stringify(e.cloud?.residency||null)}`,s=this.drivers.get(n);if(s)return s;let i=F({config:e,provider:r});return this.drivers.set(n,i),i}}var ap=new so;var cp="/var/lib/ts-cloud/bootstrap.sh",dp={"raspberry-pi-os":"bootfs",ubuntu:"system-boot"},Ol=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,Dl=/^[a-z_][a-z0-9_-]{0,31}$/,xl=/^[A-Z]{2}$/;function Te(e){return JSON.stringify(e)}function Il(e){if(!Ol.test(e.hostname))throw Error(`Invalid hostname '${e.hostname}': use lowercase letters, digits and hyphens.`);if(!Dl.test(e.user))throw Error(`Invalid user '${e.user}': use a lowercase Unix user name.`);let t=e.publicKey.trim();if(!t||t.includes(`
380
+ ${s}`);if(/status:\s*(?:done|degraded)/.test(s))return}catch(s){if(s instanceof Error&&/cloud-init reported an error/.test(s.message))throw s}await this.sleep(t)}throw Error(`Timed out waiting for cloud-init to finish on ${e} after ${r}ms`)}}function F(e){let t=e.provider??ce(e.config);if(e.config.cloud?.residency&&(no()||t!=="hetzner"))throw Error("Residency policy requires a Hetzner host with live provider evidence");if(no())return new ro;switch(e.provider??ce(e.config)){case"aws":return new Lr({region:e.config.project.region});case"hetzner":return new Pe({apiToken:e.config.hetzner?.apiToken,allowStateOnly:Boolean(e.config.cloud?.attachTo),sshPrivateKeyPath:e.config.hetzner?.sshPrivateKeyPath,sshPublicKeyPath:e.config.hetzner?.sshPublicKeyPath,sshUser:e.config.hetzner?.sshUser,location:e.config.hetzner?.location,residency:e.config.cloud?.residency});case"ssh":return new Hr({hosts:e.config.ssh?.hosts,hostKey:e.config.ssh?.hostKey,sudo:e.config.ssh?.sudo,profile:e.config.ssh?.profile,publicIp:e.config.ssh?.publicIp,lan:e.config.ssh?.lan});case"fly":throw Error("Fly.io has no box to provision or reach over SSH: deploy it with deployToFly() from @stacksjs/ts-cloud.");default:throw Error(`Unknown cloud provider: ${e.provider??ce(e.config)}`)}}class so{drivers=new Map;getDriver(e,t){let r=t??ce(e),n=`${r}:${e.project.slug}:${e.project.region||"default"}:${JSON.stringify(e.cloud?.residency||null)}`,s=this.drivers.get(n);if(s)return s;let i=F({config:e,provider:r});return this.drivers.set(n,i),i}}var ap=new so;var cp="/var/lib/ts-cloud/bootstrap.sh",dp={"raspberry-pi-os":"bootfs",ubuntu:"system-boot"},Ol=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,Dl=/^[a-z_][a-z0-9_-]{0,31}$/,xl=/^[A-Z]{2}$/;function Te(e){return JSON.stringify(e)}function Il(e){if(!Ol.test(e.hostname))throw Error(`Invalid hostname '${e.hostname}': use lowercase letters, digits and hyphens.`);if(!Dl.test(e.user))throw Error(`Invalid user '${e.user}': use a lowercase Unix user name.`);let t=e.publicKey.trim();if(!t||t.includes(`
381
381
  `)||!/^(?:ssh|ecdsa|sk)-/.test(t))throw Error("publicKey must be one public key line, e.g. the contents of ~/.ssh/id_ed25519.pub.");if(e.wifi){if(!e.wifi.ssid)throw Error("wifi.ssid is required.");if(!e.wifi.passphrase)throw Error("wifi.passphrase is required.");if(!xl.test(e.wifi.country))throw Error(`wifi.country must be a two-letter regulatory domain such as DE or US, not '${e.wifi.country}'.`)}}function Al(e,t){let r=[`hostname: ${Te(e.hostname)}`,"manage_etc_hosts: true","users:",` - name: ${Te(e.user)}`," ssh_authorized_keys:",` - ${Te(e.publicKey.trim())}`,` sudo: ${Te("ALL=(ALL) NOPASSWD:ALL")}`," shell: /bin/bash"," lock_passwd: true","ssh_pwauth: false"];if(e.timezone)r.push(`timezone: ${Te(e.timezone)}`);if(e.locale)r.push(`locale: ${Te(e.locale)}`);if(r.push("package_update: true"),t==="raspberry-pi-os")r.push("rpi:"," enable_ssh: true"," interfaces:"," spi: false"," i2c: false"," onewire: false"," remote_gpio: false"," serial:"," console: false"," hardware: false");return`${r.join(`
382
382
  `)}
383
383
  `}function Ll(e){let t=["version: 2","ethernets:"," eth0:"," match:",` name: ${Te("e*")}`," dhcp4: true"," dhcp6: true"," optional: true"];if(e.wifi)t.push("wifis:"," wlan0:"," dhcp4: true"," dhcp6: true"," optional: true",` regulatory-domain: ${Te(e.wifi.country)}`," access-points:",` ${Te(e.wifi.ssid)}:`,` password: ${Te(e.wifi.passphrase)}`);return`${t.join(`
@@ -438,17 +438,17 @@ console.log(JSON.stringify({
438
438
  `}function xo(e,t){let r=String(t.drainSignal).replace(/^SIG/i,"").toUpperCase();if(!/^[A-Z0-9]+$/.test(r))throw Error(`Box service "${e}" has an invalid drainSignal`);return`SIG${r}`}function Xl(e){return Boolean(e.drainSignal)&&(e.restart??"always")==="always"}function Io(e){let t=e.user?.name;if(!t)return["SVC_HOME=/root",'svc() { systemctl "$@"; }'];return[`SVC_UID=$(id -u ${t})`,`SVC_HOME=$(getent passwd ${t} | cut -d: -f6)`,`svc() { sudo -u ${t} XDG_RUNTIME_DIR="/run/user/$SVC_UID" systemctl --user "$@"; }`,'for _ in $(seq 1 30); do [ -S "/run/user/$SVC_UID/bus" ] && break; sleep 1; done']}function Jl(e){if(e.user?.name)Ct("user",e.user.name);let t=Object.entries(e.services??{}).filter(([,n])=>n.drainSignal),r=["set -euo pipefail",`say() { echo "${Et} $*"; }`,...Io(e)];for(let[n,s]of t){Ct("service",n);let i=xo(n,s).slice(3),a=s.drainTimeoutSec??3600;r.push(`if svc is-active --quiet ${n}.service; then`,` PID=$(svc show -p MainPID --value ${n}.service)`,` svc kill --kill-who=main -s SIG${i} ${n}.service`,` say "draining ${n} (SIG${i})"`," WAITED=0",' while [ "$PID" != 0 ] && kill -0 "$PID" 2>/dev/null; do',` if [ "$WAITED" -ge ${a} ]; then say "${n} still busy after ${a}s; not powering off"; exit 4; fi`," sleep 5; WAITED=$((WAITED + 5))"," done",` svc stop ${n}.service`,` say "drained ${n} after \${WAITED}s"`,"fi")}return r.push('say "drained"'),`${r.join(`
439
439
  `)}
440
440
  `}function Ao(e,t){if(!e.resize||t.alreadyComplete)return"none";if(t.capacityAvailable||e.resize.attemptUnavailable)return"resize";if(e.resize.whenUnavailable==="keep-current")return"unavailable";throw Error(`${t.targetType.name} is out of stock in ${t.location}; set resize.attemptUnavailable to ask anyway, or whenUnavailable: 'keep-current' to wait`)}function nd(e){return e.split(`
441
- `).filter((t)=>t.startsWith(Et)).map((t)=>t.slice(Et.length).trim())}async function Yh(e){let{box:t}=e;if(e.dryRun)return Zl(e);let r=await new wi(e.client).ensureBox({name:t.name,size:t.size,image:t.image,location:t.location,ports:t.ports,sshPublicKey:e.sshPublicKey,labels:{"ts-cloud/role":"box","ts-cloud/managed-by":"ts-cloud",...t.labels}});await ht(r.publicIp,{identityFile:e.identityFile});let n=new It({user:"root",identityFile:e.identityFile,hostKey:{policy:"pin",knownHostsFile:e.knownHostsFile}}),s=[],i=await n.ensureHostKey(r.publicIp);if(i.pinnedNow)s.push(`pinned host key ${i.fingerprint}`);if(t.resize&&!r.created){let c=await er(e.client,Number(r.id),t.size,t.resize.upgradeDisk!==!1),u=Ao(t,c);if(u==="unavailable")s.push(`${c.targetType.name} is out of stock in ${c.location}; keeping ${c.currentType.name}`);if(u==="resize"){let f=await li({client:e.client,serverId:Number(r.id),targetType:c.targetType.name,upgradeDisk:c.upgradeDisk,attemptUnavailable:t.resize.attemptUnavailable,hooks:{preflight:async()=>{s.push(...nd(await n.exec(r.publicIp,Jl(t))))},onPhase:(h)=>e.onPhase?.(h)}});if(f.status==="completed")s.push(`resized ${c.currentType.name} to ${c.targetType.name}`);else if(f.status==="recovered")s.push(`could not resize to ${c.targetType.name} (${f.error}); back on ${c.currentType.name}`);else if(f.status==="waiting-capacity")s.push(`${c.targetType.name} is out of stock in ${c.location}; keeping ${c.currentType.name}`);await ht(r.publicIp,{identityFile:e.identityFile})}}let a=await n.exec(r.publicIp,Ap(t));return{box:r,report:[...s,...nd(a)]}}async function Zl(e){let{box:t}=e,r=(await e.client.listServers()).find((i)=>i.name===t.name);if(!r)return{box:{provider:"hetzner",id:"",name:t.name,publicIp:"",created:!1},report:[`would create ${t.name} (${t.size})`,"would converge"]};let n={provider:"hetzner",id:String(r.id),name:r.name,publicIp:r.public_net?.ipv4?.ip??"",created:!1},s=[];if(t.resize){let i=await er(e.client,r.id,t.size,t.resize.upgradeDisk!==!1),a=Ao(t,i);if(a==="resize")s.push(`would resize ${i.currentType.name} to ${i.targetType.name}${i.capacityAvailable?"":" (out of stock; asking placement anyway)"}, draining ${Object.entries(t.services??{}).filter(([,c])=>c.drainSignal).map(([c])=>c).join(", ")||"nothing"} first`);else if(a==="unavailable")s.push(`${i.targetType.name} is out of stock in ${i.location}; would keep ${i.currentType.name}`)}else if(r.server_type.name!==t.size)s.push(`runs ${r.server_type.name}, declared ${t.size}; set resize to change it`);return s.push("would converge"),{box:n,report:s}}import{copyFileSync as Hu}from"node:fs";import{tmpdir as Nu}from"node:os";import{join as Mu}from"node:path";var Ql=`${pe}/project`;function Lo(e,t){let r=t.ownerSlug.trim(),n=t.selfSlug?.trim(),s={total:e.length,owner:[],self:[],others:new Map,unmanaged:[]};for(let i of e){let a=i.labels?.[Ql]?.trim();if(!a){s.unmanaged.push(i.name);continue}if(a===r){s.owner.push(i.name);continue}if(n&&a===n){s.self.push(i.name);continue}let c=s.others.get(a);if(c)c.push(i.name);else s.others.set(a,[i.name])}return s}function Hn(e){let t=e.unmanaged.length;for(let r of e.others.values())t+=r.length;return t}function Uo(e,t){let r=Hn(e),n=[];if(n.push(`Attaching to '${t.ownerSlug}' shares one provider project, so this deploy's credential can write to all ${e.total} server(s) it can see.`),r===0)return n.push("Nothing outside the two projects being joined is reachable with it."),n;n.push(`${r} of them belong to neither project:`);for(let s of[...e.others.keys()].sort())n.push(` ${s}: ${[...e.others.get(s)].sort().join(", ")}`);if(e.unmanaged.length>0)n.push(` not managed by ts-cloud: ${[...e.unmanaged].sort().join(", ")}`);return n.push("A compromised CI run or a mistargeted teardown in this project now reaches those. Keep the app in its own provider project instead if that is not acceptable, which rules out attaching."),n}import{execSync as Ho}from"node:child_process";import{randomBytes as tu}from"node:crypto";import{chmodSync as ru,copyFileSync as nu,existsSync as st,mkdirSync as No,readFileSync as Mo,statSync as su,writeFileSync as Mn}from"node:fs";import{tmpdir as ou}from"node:os";import{basename as iu,dirname as zn,isAbsolute as Fo,join as ge,resolve as au}from"node:path";import{fileURLToPath as zo}from"node:url";function Nn(e){if(!e||typeof e!=="object")return e;return Object.fromEntries(Object.keys(e).map((t)=>[t,""]))}function eu(e){let t=JSON.parse(JSON.stringify(e??{}));if(t.hetzner)delete t.hetzner.apiToken;delete t.aws,delete t.stateDir;for(let r of Object.values(t.sites??{})){if(r?.env)r.env=Nn(r.env);if(r?.environment)r.environment=Nn(r.environment)}for(let r of Object.values(t.environments??{}))if(r?.variables)r.variables=Nn(r.variables);for(let r of Object.values(t.infrastructure?.databases??{}))if(r?.password)r.password="";if(t.infrastructure?.appDatabase?.password)t.infrastructure.appDatabase.password="";if(t.infrastructure?.compute?.database?.password)t.infrastructure.compute.database.password="";if(t.infrastructure?.compute?.managedServices?.vitess?.password)t.infrastructure.compute.managedServices.vitess.password="";return t}function ko(e){let t=eu(e);return["// Generated by ts-cloud for the management dashboard — do not edit.","//","// This is the project's resolved cloud config, inlined so it needs no","// imports on the box. Credentials are deliberately absent.",`export default ${JSON.stringify(t,null,2)}`,""].join(`
441
+ `).filter((t)=>t.startsWith(Et)).map((t)=>t.slice(Et.length).trim())}async function Yh(e){let{box:t}=e;if(e.dryRun)return Zl(e);let r=await new wi(e.client).ensureBox({name:t.name,size:t.size,image:t.image,location:t.location,ports:t.ports,sshPublicKey:e.sshPublicKey,labels:{"ts-cloud/role":"box","ts-cloud/managed-by":"ts-cloud",...t.labels}});await ht(r.publicIp,{identityFile:e.identityFile});let n=new It({user:"root",identityFile:e.identityFile,hostKey:{policy:"pin",knownHostsFile:e.knownHostsFile}}),s=[],i=await n.ensureHostKey(r.publicIp);if(i.pinnedNow)s.push(`pinned host key ${i.fingerprint}`);if(t.resize&&!r.created){let c=await er(e.client,Number(r.id),t.size,t.resize.upgradeDisk!==!1),u=Ao(t,c);if(u==="unavailable")s.push(`${c.targetType.name} is out of stock in ${c.location}; keeping ${c.currentType.name}`);if(u==="resize"){let f=await li({client:e.client,serverId:Number(r.id),targetType:c.targetType.name,upgradeDisk:c.upgradeDisk,attemptUnavailable:t.resize.attemptUnavailable,hooks:{preflight:async()=>{s.push(...nd(await n.exec(r.publicIp,Jl(t))))},onPhase:(h)=>e.onPhase?.(h)}});if(f.status==="completed")s.push(`resized ${c.currentType.name} to ${c.targetType.name}`);else if(f.status==="recovered")s.push(`could not resize to ${c.targetType.name} (${f.error}); back on ${c.currentType.name}`);else if(f.status==="waiting-capacity")s.push(`${c.targetType.name} is out of stock in ${c.location}; keeping ${c.currentType.name}`);await ht(r.publicIp,{identityFile:e.identityFile})}}let a=await n.exec(r.publicIp,Ap(t));return{box:r,report:[...s,...nd(a)]}}async function Zl(e){let{box:t}=e,r=(await e.client.listServers()).find((i)=>i.name===t.name);if(!r)return{box:{provider:"hetzner",id:"",name:t.name,publicIp:"",created:!1},report:[`would create ${t.name} (${t.size})`,"would converge"]};let n={provider:"hetzner",id:String(r.id),name:r.name,publicIp:r.public_net?.ipv4?.ip??"",created:!1},s=[];if(t.resize){let i=await er(e.client,r.id,t.size,t.resize.upgradeDisk!==!1),a=Ao(t,i);if(a==="resize")s.push(`would resize ${i.currentType.name} to ${i.targetType.name}${i.capacityAvailable?"":" (out of stock; asking placement anyway)"}, draining ${Object.entries(t.services??{}).filter(([,c])=>c.drainSignal).map(([c])=>c).join(", ")||"nothing"} first`);else if(a==="unavailable")s.push(`${i.targetType.name} is out of stock in ${i.location}; would keep ${i.currentType.name}`)}else if(r.server_type.name!==t.size)s.push(`runs ${r.server_type.name}, declared ${t.size}; set resize to change it`);return s.push("would converge"),{box:n,report:s}}import{copyFileSync as Hu}from"node:fs";import{tmpdir as Nu}from"node:os";import{join as Mu}from"node:path";var Ql=`${me}/project`;function Lo(e,t){let r=t.ownerSlug.trim(),n=t.selfSlug?.trim(),s={total:e.length,owner:[],self:[],others:new Map,unmanaged:[]};for(let i of e){let a=i.labels?.[Ql]?.trim();if(!a){s.unmanaged.push(i.name);continue}if(a===r){s.owner.push(i.name);continue}if(n&&a===n){s.self.push(i.name);continue}let c=s.others.get(a);if(c)c.push(i.name);else s.others.set(a,[i.name])}return s}function Hn(e){let t=e.unmanaged.length;for(let r of e.others.values())t+=r.length;return t}function Uo(e,t){let r=Hn(e),n=[];if(n.push(`Attaching to '${t.ownerSlug}' shares one provider project, so this deploy's credential can write to all ${e.total} server(s) it can see.`),r===0)return n.push("Nothing outside the two projects being joined is reachable with it."),n;n.push(`${r} of them belong to neither project:`);for(let s of[...e.others.keys()].sort())n.push(` ${s}: ${[...e.others.get(s)].sort().join(", ")}`);if(e.unmanaged.length>0)n.push(` not managed by ts-cloud: ${[...e.unmanaged].sort().join(", ")}`);return n.push("A compromised CI run or a mistargeted teardown in this project now reaches those. Keep the app in its own provider project instead if that is not acceptable, which rules out attaching."),n}import{execSync as Ho}from"node:child_process";import{randomBytes as tu}from"node:crypto";import{chmodSync as ru,copyFileSync as nu,existsSync as st,mkdirSync as No,readFileSync as Mo,statSync as su,writeFileSync as Mn}from"node:fs";import{tmpdir as ou}from"node:os";import{basename as iu,dirname as zn,isAbsolute as Fo,join as Se,resolve as au}from"node:path";import{fileURLToPath as zo}from"node:url";function Nn(e){if(!e||typeof e!=="object")return e;return Object.fromEntries(Object.keys(e).map((t)=>[t,""]))}function eu(e){let t=JSON.parse(JSON.stringify(e??{}));if(t.hetzner)delete t.hetzner.apiToken;delete t.aws,delete t.stateDir;for(let r of Object.values(t.sites??{})){if(r?.env)r.env=Nn(r.env);if(r?.environment)r.environment=Nn(r.environment)}for(let r of Object.values(t.environments??{}))if(r?.variables)r.variables=Nn(r.variables);for(let r of Object.values(t.infrastructure?.databases??{}))if(r?.password)r.password="";if(t.infrastructure?.appDatabase?.password)t.infrastructure.appDatabase.password="";if(t.infrastructure?.compute?.database?.password)t.infrastructure.compute.database.password="";if(t.infrastructure?.compute?.managedServices?.vitess?.password)t.infrastructure.compute.managedServices.vitess.password="";return t}function ko(e){let t=eu(e);return["// Generated by ts-cloud for the management dashboard — do not edit.","//","// This is the project's resolved cloud config, inlined so it needs no","// imports on the box. Credentials are deliberately absent.",`export default ${JSON.stringify(t,null,2)}`,""].join(`
442
442
  `)}var id="dashboard";function ao(){return Q("dashboard-credentials.json")}function cu(){return tu(24).toString("base64url")}function sd(e,t,r){let n=process.env.TS_CLOUD_UI_PASSWORD?.trim();if(n)return{password:n,source:"env"};if(Fn(process.env.TS_CLOUD_UI_PUBLIC))return{password:void 0,source:"public"};let s=ao(),i=l(e,"dashboard-credentials.json");try{if(st(i)){let c=JSON.parse(Mo(i,"utf8"));if(c?.password)return{password:c.password,source:"generated"}}}catch{}let a=cu();try{No(zn(i),{recursive:!0}),Mn(i,`${JSON.stringify({username:t,password:a,generatedAt:new Date().toISOString()},null,2)}
443
443
  `),ru(i,384),r.info(`Management dashboard: generated a password for '${t}' and saved it to ${s} (read it there — it is not printed). Set TS_CLOUD_UI_PASSWORD to pin your own, or TS_CLOUD_UI_PUBLIC=1 to serve without auth.`)}catch(c){r.warn(`Management dashboard: could not persist the generated password (${c?.message??c}). Using it for this deploy only — pass: ${a}
444
- This password is now in your deploy log. Set TS_CLOUD_UI_PASSWORD to a value of your own and redeploy once ${s} is writable.`)}return{password:a,source:"generated"}}var Bo={info:()=>{},warn:()=>{}};function Fn(e){return e!=null&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function lu(){return Q("dashboard-release")}function Ko(){let e=zn(zo(import.meta.url));for(let t of[ge(e,"..","..","package.json"),ge(e,"..","package.json")])try{let r=JSON.parse(Mo(t,"utf8"));if(r.name==="@stacksjs/ts-cloud"&&r.version)return`^${r.version}`}catch{}return"latest"}function uu(){return process.env.TS_CLOUD_UI_VERSION?.trim()||Ko()}function pu(e,t,r){if(!e?.project?.slug)return r.warn("Management dashboard: the cloud config has no project slug — skipping the live dashboard."),null;let n=l(t,"dashboard-release");try{No(n,{recursive:!0}),Mn(ge(n,"cloud.config.ts"),ko(e));let s=uu();if(s.startsWith("file:")){let a=s.slice(5),c=Fo(a)?a:au(t,a);if(!st(c)||!su(c).isFile())s=Ko(),r.warn(`Management dashboard: TS_CLOUD_UI_VERSION points to a missing package file (${c}); using the deploying ts-cloud version ${s} instead.`);else{let u=iu(c),f=ge(n,u);if(c!==f)nu(c,f);s=`file:./${u}`}}let i={name:"ts-cloud-dashboard",private:!0,type:"module",dependencies:{"@stacksjs/ts-cloud":s}};return Mn(ge(n,"package.json"),`${JSON.stringify(i,null,2)}
445
- `),lu()}catch(s){return r.warn(`Management dashboard: could not stage the live release (${s?.message??s}) — skipping.`),null}}function tr(e){if(st(ge(e,"packages","ui","pages"))||st(ge(e,"packages","ui","package.json")))return{uiRoot:"packages/ui/dist",build:"cd packages/ui && bun install && bun run build"};let t=zn(zo(import.meta.url)),r=[ge(t,"ui"),ge(t,"..","ui"),ge(t,"..","..","ui"),ge(t,"..","dist","ui")];for(let n of r)if(st(ge(n,"index.html"))||st(ge(n,"serverless.html")))return{uiRoot:n,build:!1};return null}function Ri(e,t={}){let r=t.logger??Bo,n=t.cwd??process.cwd();if(Fn(process.env.TS_CLOUD_UI_DISABLE))return r.info("Management dashboard: skipped (TS_CLOUD_UI_DISABLE set)."),e;if(e.cloud?.attachTo)return r.info(`Management dashboard: ${e.project.slug} is attached to ${e.cloud.attachTo}; the server owner's dashboard monitors every attached project.`),e;if(pr(e))return e;let s=e.environments&&Object.keys(e.environments)[0],i=process.env.TS_CLOUD_UI_DOMAIN?.trim()||void 0,a=Number(process.env.TS_CLOUD_UI_PORT)||void 0,c={...e.sites??{}};if(!Fn(process.env.TS_CLOUD_UI_STATIC)){let _=pu(e,n,r);if(!_)return e;let y=Zi(e,s??"production",{uiRoot:_,build:!1,domain:i,port:a,live:!0});if(y.length===0)return r.info("Management dashboard: no domain resolved (set TS_CLOUD_UI_DOMAIN or configure a site domain) — skipping."),e;for(let{name:b,site:D}of y)c[b]=D,r.info(`Management dashboard → https://${D.domain} (sign in with your ts-cloud account; the first deploy prints an admin password once)`);return e.sites=c,e}let u=tr(n);if(!u)return r.info("Management dashboard: UI not found (no local ui/ or packaged dist/ui) — skipping auto-deploy."),e;let f=process.env.TS_CLOUD_UI_USERNAME?.trim()||"admin",h=sd(n,f,r),S=Zi(e,s??"production",{uiRoot:u.uiRoot,build:u.build,domain:i,username:f,password:h.password,realm:process.env.TS_CLOUD_UI_REALM?.trim()||void 0,live:!1,port:a});if(S.length===0)return r.info("Management dashboard: no domain resolved (set TS_CLOUD_UI_DOMAIN or configure a site domain) — skipping."),e;let v=h.source==="public"?"NO AUTH — TS_CLOUD_UI_PUBLIC is set (dashboard is publicly reachable)":h.source==="env"?"htpasswd-protected (TS_CLOUD_UI_PASSWORD)":`htpasswd-protected (auto-generated — see ${ao()})`;r.warn("Management dashboard: static mode — one shared password, and no per-site collaborators. Unset TS_CLOUD_UI_STATIC for the live dashboard.");for(let{name:_,site:y}of S)c[_]=y,r.info(`Management dashboard → https://${y.domain} (${v})`);return e.sites=c,e}function Bn(e){return Object.keys(e.sites??{}).filter(mr)}function co(e,t){if(!e?.root)return null;let r=t.cwd??process.cwd(),n=t.logger??Bo;try{if(typeof e.build==="string"&&e.build.trim())n.info(`Management dashboard: building UI (${e.build})`),Ho(e.build,{cwd:r,stdio:"inherit"});let s=Fo(e.root)?e.root:ge(r,e.root);if(!st(s))return n.warn(`Management dashboard: build output not found at ${s} — skipping dashboard artifact.`),null;let i=ge(ou(),`${t.slug}-${t.siteName??id}-${t.sha}.tar.gz`);return Ho(`tar czf "${i}" -C "${s}" .`,{stdio:"inherit"}),i}catch(s){return n.warn(`Management dashboard: failed to build artifact — ${s?.message??s}. Skipping dashboard deploy.`),null}}function du(e){let t=e.split("/");if(!/^[a-zA-Z0-9_./-]+$/.test(e)||e.startsWith("/")||t.some((r)=>!r||r==="."||r==="..")||t.at(-1)!=="bun")throw Error("Stacks backgroundBun must select a safe release-relative Bun executable")}function jo(e,t){if(du(t),!/^\/[a-zA-Z0-9_./-]+$/.test(e)||e.split("/").includes(".."))throw Error("Stacks backgroundBun requires a safe absolute release directory");return`${e}/${t}`}var mu=new Set(["laravel","php","statamic","wordpress"]);function Gr(e){if(e.framework)return e.framework;if(e.type&&mu.has(e.type))return"laravel";return"stacks"}var Go=`eval "$(cd ${p} && pantry env 2>/dev/null)"`,fu="/usr/local/bin/bun",Nr={PATH:"/usr/local/bin:/usr/bin:/bin",BUN_INSTALL:"/root/.bun",APP_ENV:"production",NODE_ENV:"production"};function Kn(e){if(e.backgroundBun===void 0)return fu;return jo(e.current,e.backgroundBun)}function gu(e){let t=e.queue??"default",r=[e.sleep,e.tries,e.timeout,e.processes,e.stopWaitSecs];if(typeof t!=="string"||!/^[a-zA-Z0-9_.:,{}/@+-]+$/.test(t||"default")||r.some((n)=>n!==void 0&&(typeof n!=="number"||!Number.isFinite(n))))throw Error("Stacks background queue options require safe queue names and finite numeric values")}var hu="node_modules/@stacksjs/ts-cloud/dist/bin/stacks-scheduler.js",Su="node_modules/@stacksjs/ts-cloud/dist/bin/stacks-queue-worker.js",Vo={id:"stacks",wrapExec:(e)=>e,execEnv:Nr,executionEnvironment:(e)=>{let t=Kn(e);return e.backgroundBun===void 0?Nr:{...Nr,PATH:`${t.slice(0,t.lastIndexOf("/"))}:${Nr.PATH}`,TS_CLOUD_BACKGROUND_BUN:e.backgroundBun}},schedulerMode:"daemon",schedulerCommand:(e)=>`${Kn(e)} ${hu}`,queueWorkerCommand:(e,t)=>{if(t.backgroundBun!==void 0)gu(e);let{current:r}=t,n=[`--queue=${e.queue||"default"}`,`--sleep=${e.sleep??3}`,`--tries=${e.tries??3}`,`--timeout=${e.timeout??60}`];return`${Kn(t)} ${r}/${Su} ${n.join(" ")}`}},vu={id:"laravel",wrapExec:(e)=>`/bin/sh -lc '${Go}; exec ${e}'`,schedulerMode:"cron",schedulerCommand:({current:e})=>`cd ${e} && ${Go} && php artisan schedule:run`,queueWorkerCommand:(e,{current:t})=>{let r=`${t}/artisan`;if(e.horizon)return`php ${r} horizon`;let n=[e.connection||"default",`--queue=${e.queue||"default"}`,`--sleep=${e.sleep??3}`,`--tries=${e.tries??3}`,`--timeout=${e.timeout??60}`,`--memory=${e.memory??128}`];if(e.maxJobs)n.push(`--max-jobs=${e.maxJobs}`);if(e.maxTime)n.push(`--max-time=${e.maxTime}`);return`php ${r} queue:work ${n.join(" ")}`}},_u={stacks:Vo,laravel:vu};function Wo(e){return _u[e]??Vo}function qo(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $u(e){return`'${e.split("'").join("'\\''")}'`}function Yo(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"unnamed"}function Xo(e,t){return`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E '^${qo(e)}-${qo(t)}-((queue|daemon)-.*|scheduler)\\.service$' || true); do`}function Vn(e){return[Xo(e.slug,e.siteName),' systemctl stop "$unit"',"done"]}function yu(e,t,r){return`${e}-${t}-queue-${r}`}function bu(e,t,r,n){return`${e}-${t}-daemon-${r.name?Yo(r.name):Yo(r.command).slice(0,32)||String(n)}`}function jn(e){let t=["[Unit]",`Description=${e.description}`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${e.workingDir}`,...Object.entries(e.environment??{}).map(([r,n])=>`Environment="${r}=${n}"`),`ExecStart=${e.execStart}`,`Restart=${e.restart||"always"}`,"RestartSec=5","MemoryAccounting=true",`MemoryHigh=${e.memoryHigh??"2G"}`,...e.memoryMax?[`MemoryMax=${e.memoryMax}`]:[]];if(e.isolatedUser)t.push(...Ut(e.isolatedUser));else if(e.user)t.push(`User=${e.user}`);if(typeof e.stopWaitSecs==="number")t.push(`TimeoutStopSec=${e.stopWaitSecs}`);return t.push("","[Install]","WantedBy=multi-user.target"),`${t.join(`
444
+ This password is now in your deploy log. Set TS_CLOUD_UI_PASSWORD to a value of your own and redeploy once ${s} is writable.`)}return{password:a,source:"generated"}}var Bo={info:()=>{},warn:()=>{}};function Fn(e){return e!=null&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function lu(){return Q("dashboard-release")}function Ko(){let e=zn(zo(import.meta.url));for(let t of[Se(e,"..","..","package.json"),Se(e,"..","package.json")])try{let r=JSON.parse(Mo(t,"utf8"));if(r.name==="@stacksjs/ts-cloud"&&r.version)return`^${r.version}`}catch{}return"latest"}function uu(){return process.env.TS_CLOUD_UI_VERSION?.trim()||Ko()}function pu(e,t,r){if(!e?.project?.slug)return r.warn("Management dashboard: the cloud config has no project slug — skipping the live dashboard."),null;let n=l(t,"dashboard-release");try{No(n,{recursive:!0}),Mn(Se(n,"cloud.config.ts"),ko(e));let s=uu();if(s.startsWith("file:")){let a=s.slice(5),c=Fo(a)?a:au(t,a);if(!st(c)||!su(c).isFile())s=Ko(),r.warn(`Management dashboard: TS_CLOUD_UI_VERSION points to a missing package file (${c}); using the deploying ts-cloud version ${s} instead.`);else{let u=iu(c),f=Se(n,u);if(c!==f)nu(c,f);s=`file:./${u}`}}let i={name:"ts-cloud-dashboard",private:!0,type:"module",dependencies:{"@stacksjs/ts-cloud":s}};return Mn(Se(n,"package.json"),`${JSON.stringify(i,null,2)}
445
+ `),lu()}catch(s){return r.warn(`Management dashboard: could not stage the live release (${s?.message??s}) — skipping.`),null}}function tr(e){if(st(Se(e,"packages","ui","pages"))||st(Se(e,"packages","ui","package.json")))return{uiRoot:"packages/ui/dist",build:"cd packages/ui && bun install && bun run build"};let t=zn(zo(import.meta.url)),r=[Se(t,"ui"),Se(t,"..","ui"),Se(t,"..","..","ui"),Se(t,"..","dist","ui")];for(let n of r)if(st(Se(n,"index.html"))||st(Se(n,"serverless.html")))return{uiRoot:n,build:!1};return null}function Ri(e,t={}){let r=t.logger??Bo,n=t.cwd??process.cwd();if(Fn(process.env.TS_CLOUD_UI_DISABLE))return r.info("Management dashboard: skipped (TS_CLOUD_UI_DISABLE set)."),e;if(e.cloud?.attachTo)return r.info(`Management dashboard: ${e.project.slug} is attached to ${e.cloud.attachTo}; the server owner's dashboard monitors every attached project.`),e;if(pr(e))return e;let s=e.environments&&Object.keys(e.environments)[0],i=process.env.TS_CLOUD_UI_DOMAIN?.trim()||void 0,a=Number(process.env.TS_CLOUD_UI_PORT)||void 0,c={...e.sites??{}};if(!Fn(process.env.TS_CLOUD_UI_STATIC)){let _=pu(e,n,r);if(!_)return e;let y=Zi(e,s??"production",{uiRoot:_,build:!1,domain:i,port:a,live:!0});if(y.length===0)return r.info("Management dashboard: no domain resolved (set TS_CLOUD_UI_DOMAIN or configure a site domain) — skipping."),e;for(let{name:T,site:x}of y)c[T]=x,r.info(`Management dashboard → https://${x.domain} (sign in with your ts-cloud account; the first deploy prints an admin password once)`);return e.sites=c,e}let u=tr(n);if(!u)return r.info("Management dashboard: UI not found (no local ui/ or packaged dist/ui) — skipping auto-deploy."),e;let f=process.env.TS_CLOUD_UI_USERNAME?.trim()||"admin",h=sd(n,f,r),S=Zi(e,s??"production",{uiRoot:u.uiRoot,build:u.build,domain:i,username:f,password:h.password,realm:process.env.TS_CLOUD_UI_REALM?.trim()||void 0,live:!1,port:a});if(S.length===0)return r.info("Management dashboard: no domain resolved (set TS_CLOUD_UI_DOMAIN or configure a site domain) — skipping."),e;let v=h.source==="public"?"NO AUTH — TS_CLOUD_UI_PUBLIC is set (dashboard is publicly reachable)":h.source==="env"?"htpasswd-protected (TS_CLOUD_UI_PASSWORD)":`htpasswd-protected (auto-generated — see ${ao()})`;r.warn("Management dashboard: static mode — one shared password, and no per-site collaborators. Unset TS_CLOUD_UI_STATIC for the live dashboard.");for(let{name:_,site:y}of S)c[_]=y,r.info(`Management dashboard → https://${y.domain} (${v})`);return e.sites=c,e}function Bn(e){return Object.keys(e.sites??{}).filter(mr)}function co(e,t){if(!e?.root)return null;let r=t.cwd??process.cwd(),n=t.logger??Bo;try{if(typeof e.build==="string"&&e.build.trim())n.info(`Management dashboard: building UI (${e.build})`),Ho(e.build,{cwd:r,stdio:"inherit"});let s=Fo(e.root)?e.root:Se(r,e.root);if(!st(s))return n.warn(`Management dashboard: build output not found at ${s} — skipping dashboard artifact.`),null;let i=Se(ou(),`${t.slug}-${t.siteName??id}-${t.sha}.tar.gz`);return Ho(`tar czf "${i}" -C "${s}" .`,{stdio:"inherit"}),i}catch(s){return n.warn(`Management dashboard: failed to build artifact — ${s?.message??s}. Skipping dashboard deploy.`),null}}function du(e){let t=e.split("/");if(!/^[a-zA-Z0-9_./-]+$/.test(e)||e.startsWith("/")||t.some((r)=>!r||r==="."||r==="..")||t.at(-1)!=="bun")throw Error("Stacks backgroundBun must select a safe release-relative Bun executable")}function jo(e,t){if(du(t),!/^\/[a-zA-Z0-9_./-]+$/.test(e)||e.split("/").includes(".."))throw Error("Stacks backgroundBun requires a safe absolute release directory");return`${e}/${t}`}var mu=new Set(["laravel","php","statamic","wordpress"]);function Gr(e){if(e.framework)return e.framework;if(e.type&&mu.has(e.type))return"laravel";return"stacks"}var Go=`eval "$(cd ${p} && pantry env 2>/dev/null)"`,fu="/usr/local/bin/bun",Nr={PATH:"/usr/local/bin:/usr/bin:/bin",BUN_INSTALL:"/root/.bun",APP_ENV:"production",NODE_ENV:"production"};function Kn(e){if(e.backgroundBun===void 0)return fu;return jo(e.current,e.backgroundBun)}function gu(e){let t=e.queue??"default",r=[e.sleep,e.tries,e.timeout,e.processes,e.stopWaitSecs];if(typeof t!=="string"||!/^[a-zA-Z0-9_.:,{}/@+-]+$/.test(t||"default")||r.some((n)=>n!==void 0&&(typeof n!=="number"||!Number.isFinite(n))))throw Error("Stacks background queue options require safe queue names and finite numeric values")}var hu="node_modules/@stacksjs/ts-cloud/dist/bin/stacks-scheduler.js",Su="node_modules/@stacksjs/ts-cloud/dist/bin/stacks-queue-worker.js",Vo={id:"stacks",wrapExec:(e)=>e,execEnv:Nr,executionEnvironment:(e)=>{let t=Kn(e);return e.backgroundBun===void 0?Nr:{...Nr,PATH:`${t.slice(0,t.lastIndexOf("/"))}:${Nr.PATH}`,TS_CLOUD_BACKGROUND_BUN:e.backgroundBun}},schedulerMode:"daemon",schedulerCommand:(e)=>`${Kn(e)} ${hu}`,queueWorkerCommand:(e,t)=>{if(t.backgroundBun!==void 0)gu(e);let{current:r}=t,n=[`--queue=${e.queue||"default"}`,`--sleep=${e.sleep??3}`,`--tries=${e.tries??3}`,`--timeout=${e.timeout??60}`];return`${Kn(t)} ${r}/${Su} ${n.join(" ")}`}},vu={id:"laravel",wrapExec:(e)=>`/bin/sh -lc '${Go}; exec ${e}'`,schedulerMode:"cron",schedulerCommand:({current:e})=>`cd ${e} && ${Go} && php artisan schedule:run`,queueWorkerCommand:(e,{current:t})=>{let r=`${t}/artisan`;if(e.horizon)return`php ${r} horizon`;let n=[e.connection||"default",`--queue=${e.queue||"default"}`,`--sleep=${e.sleep??3}`,`--tries=${e.tries??3}`,`--timeout=${e.timeout??60}`,`--memory=${e.memory??128}`];if(e.maxJobs)n.push(`--max-jobs=${e.maxJobs}`);if(e.maxTime)n.push(`--max-time=${e.maxTime}`);return`php ${r} queue:work ${n.join(" ")}`}},_u={stacks:Vo,laravel:vu};function Wo(e){return _u[e]??Vo}function qo(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $u(e){return`'${e.split("'").join("'\\''")}'`}function Yo(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"unnamed"}function Xo(e,t){return`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E '^${qo(e)}-${qo(t)}-((queue|daemon)-.*|scheduler)\\.service$' || true); do`}function Vn(e){return[Xo(e.slug,e.siteName),' systemctl stop "$unit"',"done"]}function yu(e,t,r){return`${e}-${t}-queue-${r}`}function bu(e,t,r,n){return`${e}-${t}-daemon-${r.name?Yo(r.name):Yo(r.command).slice(0,32)||String(n)}`}function jn(e){let t=["[Unit]",`Description=${e.description}`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${e.workingDir}`,...Object.entries(e.environment??{}).map(([r,n])=>`Environment="${r}=${n}"`),`ExecStart=${e.execStart}`,`Restart=${e.restart||"always"}`,"RestartSec=5","MemoryAccounting=true",`MemoryHigh=${e.memoryHigh??"2G"}`,...e.memoryMax?[`MemoryMax=${e.memoryMax}`]:[]];if(e.isolatedUser){if(!e.isolationRoot||!e.isolationSlug)throw Error("Runtime isolation requires its project directory");t.push(...Ut(e.isolatedUser,e.isolationRoot,e.isolationSlug))}else if(e.user)t.push(`User=${e.user}`);if(typeof e.stopWaitSecs==="number")t.push(`TimeoutStopSec=${e.stopWaitSecs}`);return t.push("","[Install]","WantedBy=multi-user.target"),`${t.join(`
446
446
  `)}
447
- `}function Gn(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_UNIT_EOF'`,t.replace(/\n$/,""),"TS_CLOUD_UNIT_EOF"]}function Tu(e,t){return`/etc/cron.d/${e}-${t}-scheduler`}function Wn(e){let t=e.site.isolation&&!["laravel","php","statamic","wordpress"].includes(e.site.type||"")?ut(e.slug):void 0,{slug:r,siteName:n,site:s}=e,i=e.appBase??`/var/www/${n}`,a=`${i}/current`,c=Wo(Gr(s)),u=c.id==="stacks"&&s.backgroundBun!==void 0;if(u&&(!e.releaseId||!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(e.releaseId)))throw Error("Stacks backgroundBun requires a safe physical releaseId");let f=u?`${i}/releases/${e.releaseId}`:a,h={current:f,backgroundBun:s.backgroundBun},S=c.executionEnvironment?.(h)??c.execEnv,v=[],_=[];(s.queues||[]).forEach((I,Y)=>{let W=c.wrapExec(c.queueWorkerCommand(I,h)),K=Math.max(1,I.processes??1);for(let ee=0;ee<K;ee++){let re=yu(r,n,_.length);_.push(re),v.push(...Gn(re,jn({description:`${n} queue worker ${Y}.${ee} (managed by ts-cloud)`,workingDir:f,execStart:W,environment:S,isolatedUser:t,stopWaitSecs:I.stopWaitSecs??90})))}}),(s.daemons||[]).forEach((I,Y)=>{if(t&&I.user&&I.user!==t)throw Error("An isolated runtime daemon cannot change its project identity");let W=Math.max(1,I.processes??1);for(let K=0;K<W;K++){let ee=`${bu(r,n,I,Y)}-${K}`;_.push(ee),v.push(...Gn(ee,jn({description:`${n} daemon ${I.name||I.command} (managed by ts-cloud)`,workingDir:I.directory||a,execStart:c.wrapExec(I.command),environment:c.execEnv,restart:I.restart,user:I.user,isolatedUser:t})))}});let D=s.scheduler,V=D===!0||typeof D==="object"&&D!==null,H=`${r}-${n}-scheduler`;if(V&&c.schedulerMode==="daemon"){_.push(H);let I=typeof D==="object"&&D!==null?D:{};v.push(...Gn(H,jn({description:`${n} scheduler (managed by ts-cloud)`,workingDir:f,execStart:c.wrapExec(c.schedulerCommand(h)),environment:S,isolatedUser:t,memoryHigh:I.memoryHigh,memoryMax:I.memoryMax})),...br(`${H}.service`,{auto:!1,high:Boolean(I.memoryHigh),max:Boolean(I.memoryMax)}))}let x=_.map((I)=>`${I}.service`).join(" ");v.push("systemctl daemon-reload",`TS_CLOUD_DESIRED="${x}"`,Xo(r,n),' case " $TS_CLOUD_DESIRED " in',' *" $unit "*) ;;',' *) systemctl stop "$unit"; systemctl disable "$unit"; rm -f "/etc/systemd/system/$unit" ;;'," esac","done","systemctl daemon-reload");for(let I of _)v.push(`systemctl enable ${I}.service`,`systemctl restart ${I}.service`);let k=Tu(r,n);if(V&&c.schedulerMode==="cron"){let I=typeof D==="object"&&D!==null?D:void 0,Y=`${c.schedulerCommand(h)} >> /dev/null 2>&1`;if(I?.heartbeatUrl){let K=I.heartbeatMethod||"GET",ee=K==="GET"?"":`-X ${K} `;Y+=` && curl -fsS -m 10 ${ee}${$u(I.heartbeatUrl)} >/dev/null 2>&1`}let W=`* * * * * root ${Y}
448
- `.replace(/%/g,"\\%");v.push(`cat > ${k} <<'TS_CLOUD_CRON_EOF'`,W.replace(/\n$/,""),"TS_CLOUD_CRON_EOF",`chmod 644 ${k}`)}else v.push(`rm -f ${k}`);return v}function Jo(e){return!!(e.queues?.length||e.daemons?.length||e.scheduler)}function qn(e){if(e.ssl?.provider)return e.ssl.provider;return e.domain?"letsencrypt":"none"}var Zo={cloudflare:{pkg:"python3-certbot-dns-cloudflare",plugin:"dns-cloudflare"},route53:{pkg:"python3-certbot-dns-route53",plugin:"dns-route53"},digitalocean:{pkg:"python3-certbot-dns-digitalocean",plugin:"dns-digitalocean"},google:{pkg:"python3-certbot-dns-google",plugin:"dns-google"}};function Qo(e){return`/etc/letsencrypt/ts-cloud-${e}.ini`}function wu(e){let t=e?Zo[e.provider]:void 0,r=["certbot","python3-certbot-nginx",...t?[t.pkg]:[]].join(" ");return["export DEBIAN_FRONTEND=noninteractive",t?`apt-get update -y && apt-get install -y ${r}`:`command -v certbot >/dev/null 2>&1 || { apt-get update -y && apt-get install -y ${r}; }`,"mkdir -p /etc/letsencrypt/renewal-hooks/deploy","cat > /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh <<'TS_CLOUD_HOOK_EOF'","#!/bin/sh","systemctl reload ts-cloud-nginx 2>/dev/null || systemctl reload nginx 2>/dev/null || true","TS_CLOUD_HOOK_EOF","chmod +x /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh","systemctl enable certbot.timer 2>/dev/null || true","systemctl start certbot.timer 2>/dev/null || true"]}function Cu(e){if(!e.credentials||Object.keys(e.credentials).length===0)return[];let t=Qo(e.provider),r=Object.entries(e.credentials).map(([n,s])=>`${n} = ${s}`).join(`
447
+ `}function Gn(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_UNIT_EOF'`,t.replace(/\n$/,""),"TS_CLOUD_UNIT_EOF"]}function Tu(e,t){return`/etc/cron.d/${e}-${t}-scheduler`}function Wn(e){let t=e.site.isolation&&!["laravel","php","statamic","wordpress"].includes(e.site.type||"")?ut(e.slug):void 0,{slug:r,siteName:n,site:s}=e,i=e.appBase??`/var/www/${n}`,a=`${i}/current`,c=Wo(Gr(s)),u=c.id==="stacks"&&s.backgroundBun!==void 0;if(u&&(!e.releaseId||!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(e.releaseId)))throw Error("Stacks backgroundBun requires a safe physical releaseId");let f=u?`${i}/releases/${e.releaseId}`:a,h={current:f,backgroundBun:s.backgroundBun},S=c.executionEnvironment?.(h)??c.execEnv,v=[],_=[];(s.queues||[]).forEach((I,V)=>{let q=c.wrapExec(c.queueWorkerCommand(I,h)),K=Math.max(1,I.processes??1);for(let ee=0;ee<K;ee++){let te=yu(r,n,_.length);_.push(te),v.push(...Gn(te,jn({description:`${n} queue worker ${V}.${ee} (managed by ts-cloud)`,workingDir:f,execStart:q,environment:S,isolatedUser:t,isolationRoot:i,isolationSlug:r,stopWaitSecs:I.stopWaitSecs??90})))}}),(s.daemons||[]).forEach((I,V)=>{if(t&&I.user&&I.user!==t)throw Error("An isolated runtime daemon cannot change its project identity");let q=Math.max(1,I.processes??1);for(let K=0;K<q;K++){let ee=`${bu(r,n,I,V)}-${K}`;_.push(ee),v.push(...Gn(ee,jn({description:`${n} daemon ${I.name||I.command} (managed by ts-cloud)`,workingDir:I.directory||a,execStart:c.wrapExec(I.command),environment:c.execEnv,restart:I.restart,user:I.user,isolatedUser:t,isolationRoot:i,isolationSlug:r})))}});let x=s.scheduler,W=x===!0||typeof x==="object"&&x!==null,H=`${r}-${n}-scheduler`;if(W&&c.schedulerMode==="daemon"){_.push(H);let I=typeof x==="object"&&x!==null?x:{};v.push(...Gn(H,jn({description:`${n} scheduler (managed by ts-cloud)`,workingDir:f,execStart:c.wrapExec(c.schedulerCommand(h)),environment:S,isolatedUser:t,isolationRoot:i,isolationSlug:r,memoryHigh:I.memoryHigh,memoryMax:I.memoryMax})),...br(`${H}.service`,{auto:!1,high:Boolean(I.memoryHigh),max:Boolean(I.memoryMax)}))}let R=_.map((I)=>`${I}.service`).join(" ");v.push("systemctl daemon-reload",`TS_CLOUD_DESIRED="${R}"`,Xo(r,n),' case " $TS_CLOUD_DESIRED " in',' *" $unit "*) ;;',' *) systemctl stop "$unit"; systemctl disable "$unit"; rm -f "/etc/systemd/system/$unit" ;;'," esac","done","systemctl daemon-reload");for(let I of _)v.push(`systemctl enable ${I}.service`,`systemctl restart ${I}.service`);let L=Tu(r,n);if(W&&c.schedulerMode==="cron"){let I=typeof x==="object"&&x!==null?x:void 0,V=`${c.schedulerCommand(h)} >> /dev/null 2>&1`;if(I?.heartbeatUrl){let K=I.heartbeatMethod||"GET",ee=K==="GET"?"":`-X ${K} `;V+=` && curl -fsS -m 10 ${ee}${$u(I.heartbeatUrl)} >/dev/null 2>&1`}let q=`* * * * * root ${V}
448
+ `.replace(/%/g,"\\%");v.push(`cat > ${L} <<'TS_CLOUD_CRON_EOF'`,q.replace(/\n$/,""),"TS_CLOUD_CRON_EOF",`chmod 644 ${L}`)}else v.push(`rm -f ${L}`);return v}function Jo(e){return!!(e.queues?.length||e.daemons?.length||e.scheduler)}function qn(e){if(e.ssl?.provider)return e.ssl.provider;return e.domain?"letsencrypt":"none"}var Zo={cloudflare:{pkg:"python3-certbot-dns-cloudflare",plugin:"dns-cloudflare"},route53:{pkg:"python3-certbot-dns-route53",plugin:"dns-route53"},digitalocean:{pkg:"python3-certbot-dns-digitalocean",plugin:"dns-digitalocean"},google:{pkg:"python3-certbot-dns-google",plugin:"dns-google"}};function Qo(e){return`/etc/letsencrypt/ts-cloud-${e}.ini`}function wu(e){let t=e?Zo[e.provider]:void 0,r=["certbot","python3-certbot-nginx",...t?[t.pkg]:[]].join(" ");return["export DEBIAN_FRONTEND=noninteractive",t?`apt-get update -y && apt-get install -y ${r}`:`command -v certbot >/dev/null 2>&1 || { apt-get update -y && apt-get install -y ${r}; }`,"mkdir -p /etc/letsencrypt/renewal-hooks/deploy","cat > /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh <<'TS_CLOUD_HOOK_EOF'","#!/bin/sh","systemctl reload ts-cloud-nginx 2>/dev/null || systemctl reload nginx 2>/dev/null || true","TS_CLOUD_HOOK_EOF","chmod +x /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh","systemctl enable certbot.timer 2>/dev/null || true","systemctl start certbot.timer 2>/dev/null || true"]}function Cu(e){if(!e.credentials||Object.keys(e.credentials).length===0)return[];let t=Qo(e.provider),r=Object.entries(e.credentials).map(([n,s])=>`${n} = ${s}`).join(`
449
449
  `);return[`cat > ${t} <<'TS_CLOUD_DNSCREDS_EOF'`,r,"TS_CLOUD_DNSCREDS_EOF",`chmod 600 ${t}`]}function Pu(e){let t=e.dns,r=e.wildcard?[`*.${e.domain}`,e.domain]:[e.domain,...e.aliases||[]].filter(Boolean),n=["certbot","--non-interactive","--agree-tos","--keep-until-expiring"];if(t){let s=Zo[t.provider].plugin;if(n.push(`--${s}`),t.provider!=="route53"&&t.credentials)n.push(`--${s}-credentials ${Qo(t.provider)}`);if(typeof t.propagationSeconds==="number"&&t.provider!=="route53")n.push(`--${s}-propagation-seconds ${t.propagationSeconds}`);n.push("certonly")}else n.push("--nginx",`--nginx-ctl ${Fe}`,e.redirect===!1?"--no-redirect":"--redirect");if(e.email)n.push(`-m ${e.email}`);else n.push("--register-unsafely-without-email");for(let s of r)n.push(`-d ${s}`);return[n.join(" ")]}function Jn(e){if(qn(e)!=="letsencrypt"||!e.domain)return[];let t=e.ssl,r=t?.dns,n=t?.wildcard===!0;if(n&&!r)return[];return[...wu(r),...r?Cu(r):[],...Pu({domain:e.domain,aliases:e.aliases,email:t?.email,wildcard:n,dns:r})]}function _i(e){let{repository:t,releaseDir:r,commit:n}=e,s=t.branch||"main",i=t.url,a=[`rm -rf ${r}`,`mkdir -p ${r}`];if(t.strategy==="tag")if(t.tag)a.push(`git clone -q --depth 1 --branch ${we(t.tag)} ${we(i)} ${r}`),a.push(`printf '%s' ${we(t.tag)} > ${r}/.ts-cloud-tag`);else{let c=t.tagPattern||"v*";a.push(`TS_CLOUD_TAG="$(git ls-remote --tags --refs --sort=-v:refname ${we(i)} ${we(`refs/tags/${c}`)} | head -n1 | sed 's#.*refs/tags/##')"`,`test -n "$TS_CLOUD_TAG" || { echo "no tags matching" ${we(c)} "found in" ${we(i)} >&2; exit 1; }`,`git clone -q --depth 1 --branch "$TS_CLOUD_TAG" ${we(i)} ${r}`,`printf '%s' "$TS_CLOUD_TAG" > ${r}/.ts-cloud-tag`)}else if(n)a.push(`git -C ${r} init -q`,`git -C ${r} remote add origin ${we(i)}`,`git -C ${r} fetch -q --depth 1 origin ${we(n)}`,`git -C ${r} checkout -q FETCH_HEAD`);else a.push(`git clone -q --depth 1 --branch ${we(s)} ${we(i)} ${r}`);return a.push(`git -C ${r} rev-parse HEAD > ${r}/.ts-cloud-sha`),a}function we(e){return`'${e.split("'").join("'\\''")}'`}var zr="$CREATE_RELEASE",Br="$ACTIVATE_RELEASE",Oi="$RESTART_QUEUES",$i="composer install --no-interaction --prefer-dist --optimize-autoloader --no-dev",Eu=["php artisan migrate --force","php artisan config:cache","php artisan route:cache","php artisan view:cache","php artisan event:cache","php artisan storage:link"];function Ru(e){switch(e){case"laravel":case"statamic":return[zr,$i,...Eu,Br,Oi];case"php":case"wordpress":return[zr,`${$i} || true`,Br];case"static":case"spa":return[zr,Br]}}function Ou(e,t){return e.replace(/^php\s+/,`${t} `).replace(/(\s)php\s+artisan\s+/g,`$1${t} artisan `)}function Du(e,t){let r=fr(t);return[`cat > ${e} <<'TS_CLOUD_ENV_EOF'`,r,"TS_CLOUD_ENV_EOF",`chmod 600 ${e}`]}function Pi(e,t,r){return[`cat > ${e} <<'${r}'`,t.replace(/\n$/,""),r,`chmod 600 ${e}`]}function xu(e,t){if(!t)return[];let r=[];if(t.composerAuth){let n=typeof t.composerAuth==="string"?t.composerAuth:JSON.stringify(t.composerAuth,null,2);r.push(...Pi(`${e}/auth.json`,n,"TS_CLOUD_AUTHJSON_EOF"))}if(t.npmrc)r.push(...Pi(`${e}/.npmrc`,t.npmrc,"TS_CLOUD_NPMRC_EOF"));return r}function xi(e){let t=e.healthCheck?.path;if(!t||!e.domain)return[];let n=`http://127.0.0.1${t.startsWith("/")?t:`/${t}`}`;return[`echo "[ts-cloud] health check ${n} (Host: ${e.domain})"`,"TS_CLOUD_HC_OK=0",`for i in $(seq 1 10); do TS_CLOUD_HC=$(curl -s -o /dev/null -w "%{http_code}" -H "Host: ${e.domain}" -m 10 "${n}" 2>/dev/null || echo 000); case "$TS_CLOUD_HC" in 2*|3*) TS_CLOUD_HC_OK=1; break ;; esac; sleep 3; done`,'[ "$TS_CLOUD_HC_OK" = 1 ] && echo "health check passed ($TS_CLOUD_HC)" || { echo "health check FAILED (last=$TS_CLOUD_HC)" >&2; exit 1; }']}function Li(e){let{siteName:t,site:r,releaseId:n,commit:s}=e;if(!r.repository?.url)throw Error(`Site '${t}' is a PHP/git site but has no repository.url to clone`);let i=e.appBase??`/var/www/${t}`,a="php",c=Zt(i,n),u=r.sharedPaths??gr,f=[...u,...yr(r.env,u)],h=r.keepReleases??Ht,S=r.deployScript?.length?r.deployScript:Ru(r.type??"laravel"),v=["set -euo pipefail",'export HOME="${HOME:-/root}"','export COMPOSER_HOME="${COMPOSER_HOME:-/root/.composer}"',"export COMPOSER_ALLOW_SUPERUSER=1",Oe()];if(v.push(...vr(i,{releaseId:n,commit:s,branch:r.repository.branch,keepLogs:h})),v.push(...Mt(c,f)),r.env&&Object.keys(r.env).length>0)v.push(...Du(`${c.shared}/.env`,r.env));for(let _ of S){let y=_.trim();if(y===zr)v.push(..._i({repository:r.repository,releaseDir:c.release,commit:s})),v.push(...Sr(c,f)),v.push(`cd ${c.release}`),v.push(...xu(c.release,r.credentials)),v.push(`chown -R www-data:www-data ${c.shared}/storage 2>/dev/null || true`,`[ -d ${c.release}/bootstrap/cache ] && chown -R www-data:www-data ${c.release}/bootstrap/cache 2>/dev/null || true`,`chmod -R ug+rwX ${c.shared}/storage 2>/dev/null || true`);else if(y===Br)v.push(...pt(c)),v.push(...dt(c,h)),v.push(`(cd ${p} && pantry restart php-fpm) 2>/dev/null || true`);else if(y===Oi)v.push(`${a} artisan queue:restart || true`);else v.push(Ou(_,a))}return v}var Kr={mysql:{port:3306,binaries:["mysqld","mysql"]},mariadb:{port:3306,binaries:["mariadbd","mariadb","mysqld"]},postgres:{port:5432,binaries:["postgres","psql"]},redis:{port:6379,binaries:["redis-server","redis-cli"]},memcached:{port:11211,binaries:["memcached"]},meilisearch:{port:7700,binaries:["meilisearch"]},vitess:{port:15306,binaries:["vtgate"]}},qt="ts-cloud-service:";function Iu(e){return e===!0||typeof e==="object"&&e!=null}function Ui(e){if(!e)return[];return Object.keys(Kr).filter((t)=>Iu(e[t]))}function Hi(e){if(e.length===0)return[];return[Oe(),"ts_cloud_port_open() {",' if command -v ss >/dev/null 2>&1; then ss -ltn 2>/dev/null | grep -qE "[:.]$1[[:space:]]" && return 0; fi',' if command -v netstat >/dev/null 2>&1; then netstat -ltn 2>/dev/null | grep -qE "[:.]$1[[:space:]]" && return 0; fi'," (exec 3<>/dev/tcp/127.0.0.1/$1) 2>/dev/null && { exec 3<&- 3>&-; return 0; }"," return 1","}","ts_cloud_probe() {",' TS_CLOUD_SVC="$1"; TS_CLOUD_PORT="$2"; shift 2',' for TS_CLOUD_BIN in "$@"; do',` if command -v "$TS_CLOUD_BIN" >/dev/null 2>&1; then echo "${qt}$TS_CLOUD_SVC:present"; return 0; fi`," done",` if ts_cloud_port_open "$TS_CLOUD_PORT"; then echo "${qt}$TS_CLOUD_SVC:present"; return 0; fi`,` echo "${qt}$TS_CLOUD_SVC:missing"`," return 0","}",...e.filter((t)=>Kr[t]).map((t)=>`ts_cloud_probe ${t} ${Kr[t].port} ${Kr[t].binaries.join(" ")}`),"exit 0"]}function Ni(e,t){if(!e)return[];let r=new Map;for(let n of e.split(`
450
450
  `)){let s=n.indexOf(qt);if(s===-1)continue;let[i,a]=n.slice(s+qt.length).trim().split(":");if(i)r.set(i,a)}return t.filter((n)=>r.get(n)==="missing")}function Mi(e,t,r){let n=r?` on ${r}`:"",s=e.map((a)=>`managedServices.${a}`).join(", "),i=e.length===1?`no ${e[0]}`:`none of ${e.join(", ")}`;return`This project declares ${s}, but '${t}' has ${i}${n}. Attach mode does not provision services on the owner's box, so nothing will install ${e.length===1?"it":"them"}. Point the app at an external service, or ask the owner of '${t}' to add ${e.length===1?"it":"them"} to their own config and re-provision.`}var Fi="/var/lib/pantry/php-fpm/pool.d",Au=9100,Lu=400;function Wr(e){return(e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"site").slice(0,28)}function zi(e){return`web_${Wr(e)}`}function Uu(e){let t=Wr(e),r=0;for(let n=0;n<t.length;n++)r=r*31+t.charCodeAt(n)>>>0;return Au+r%Lu}function Qn(e){return`127.0.0.1:${Uu(e)}`}function ku(e){let t=Wr(e.siteName),r=zi(e.siteName),n=e.maxChildren??10;return[`; ts-cloud-managed pool for ${e.siteName} (site isolation)`,`[${t}]`,`user = ${r}`,`group = ${r}`,`listen = ${Qn(e.siteName)}`,"pm = dynamic",`pm.max_children = ${n}`,"pm.start_servers = 2","pm.min_spare_servers = 1","pm.max_spare_servers = 3","pm.max_requests = 500","catch_workers_output = yes",`php_admin_value[open_basedir] = ${e.appBase}:/tmp`,""].join(`
451
- `)}function Bi(e){let t=zi(e.siteName),r=Wr(e.siteName),n=`${Fi}/${r}.conf`;return[`getent group ${t} >/dev/null || groupadd --system ${t}`,`id -u ${t} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin -g ${t} ${t}`,`usermod -aG ${t} www-data 2>/dev/null || true`,`chown -R ${t}:${t} ${e.appBase} || true`,`chmod -R g+rX ${e.appBase} || true`,`chmod 600 ${e.appBase}/shared/.env 2>/dev/null || true`,`mkdir -p ${Fi}`,`cat > ${n} <<'TS_CLOUD_FPMPOOL_EOF'`,ku(e).replace(/\n$/,""),"TS_CLOUD_FPMPOOL_EOF",`(cd ${p} && pantry restart php-fpm) 2>/dev/null || true`]}var Yr={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};function Fu(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function lo(e,t,r=Yr){let{config:n,environment:s,siteName:i,site:a,slug:c,sha:u,runtime:f,localTarballPath:h}=t,S=`releases/${i}/${u}.tar.gz`,v=m(n,s),_=await e.getComputeOutputs({config:n,environment:s}),y=await e.findComputeTargets({slug:c,environment:s,role:"app",stackName:v});if(y.length===0)return{success:!1,error:e.name==="aws"?`Stack '${v}' has no EC2 instances tagged Project=${c} Environment=${s} Role=app, and storage/cloud/state/${v}.json pins no live instance. For a shared box, record its instanceId there.`:`No Hetzner servers labeled ts-cloud/project=${c} ts-cloud/environment=${s} ts-cloud/role=app, and storage/cloud/state/${v}.json pins no live server. For a shared box, record its serverId there.`};let b=_.servicesPrivateIp?Xs(_.servicesPrivateIp,g(n)):ps(g(n)),D=Ji(C(n,{environment:s})),V=n.infrastructure?.compute,H=ni(V?.hostCleanup),x=j({...V,proxy:w(n,{environment:s})})?{HOST:"127.0.0.1"}:{},k=s==="production"?{APP_ENV:"production",NODE_ENV:"production"}:{},I={...b,...D,...x,...a.env||{},...k},Y=Cn(I,a.sharedPaths??[]);if(Y.warning)r.warn(`Site '${i}': ${Y.warning}`);else if(Y.path)r.info(`Site '${i}': sharing '${Y.path}' so the SQLite database survives deploys.`);if(jr(a)){let P=a.phpVersion??V?.php?.default??V?.php?.versions?.[0],R=U(c,i),O=Object.keys(b).length>0?{...a,env:I}:a,J=Li({siteName:i,site:O,releaseId:u,appBase:R,defaultPhpVersion:P}),q=!j(V),Z=qn(a)==="custom"&&a.ssl?.certPath&&a.ssl?.keyPath?{certPath:a.ssl.certPath,keyPath:a.ssl.keyPath}:void 0,le=a.isolation?Bi({siteName:i,appBase:R}):[],E=q?dn({siteName:i,domain:a.domain||i,aliases:a.aliases,type:a.type,appDir:`${R}/current`,webDirectory:a.webDirectory,phpVersion:P,fastcgiPass:a.isolation?Qn(i):void 0,redirects:a.redirects,ssl:Z,auth:a.auth&&a.auth.enabled!==!1&&a.auth.password?{username:a.auth.username||"admin",password:a.auth.password,realm:a.auth.realm}:void 0,serverSnippet:pn(a.nginx,V?.nginxTemplates),clientMaxBodySize:a.nginx?.clientMaxBodySize,hsts:a.ssl?.hsts,tlsProtocols:a.ssl?.tlsProtocols,security:a.security}):[],N=q?Jn(a):[],fe=Jo(a)?Wn({slug:c,siteName:i,site:a,phpVersion:P,appBase:R}):[],ae=q?xi(a):[];r.step(`Deploying PHP site '${i}' to ${y.length} target(s)...`);let Se=await e.runRemoteDeploy({targets:y,commands:[...wn(R,c),...$r(R,c),...J,...le,...E,...N,...fe,...ae,...H],comment:`ts-cloud deploy ${c}/${i}@${u}`,tags:{Project:c,Environment:s,Role:"app"}}),Rt=hs(n.notifications,a.notifications);if(!Se.success)return await Ki(e,y,H,r),await fn(Rt,"deploy-failed",`❌ Deploy of ${c}/${i}@${u} failed: ${Se.error||"unknown error"}`),{success:!1,error:Se.error||"Remote PHP deploy failed",instanceCount:Se.instanceCount,perInstance:Se.perInstance};let Vi=a.domain?` → https://${a.domain}`:"";return await fn(Rt,"deploy",`✅ Deployed ${c}/${i}@${u}${Vi}`),{success:!0,instanceCount:Se.instanceCount,perInstance:Se.perInstance}}if(!h)return{success:!1,error:`Site '${i}' requires a release tarball but none was provided`};let W=await e.uploadRelease({config:n,environment:s,localPath:h,remoteKey:S,targets:y}),K=ai(c,i,u),ee=e.name==="aws"?$c(_.deployBucketName,S,n.project.region||"us-east-1",K):Mc(W.artifactRef,K),re=d(a),te=U(c,i),ie=Wn({slug:c,siteName:i,site:a,appBase:te,releaseId:u}),oe=re==="server-static"?oi({siteName:i,slug:c,appDir:te,artifactFetch:ee,releaseId:u,preStartCommands:a.preStart,postActivateCommands:ie,beforeResetCommands:Vn({slug:c,siteName:i})}):si({siteName:i,slug:c,appDir:te,artifactFetch:ee,releaseId:u,execStart:ii(a.start,f,`${te.replace(/\/+$/,"")}/releases/%i`),envEntries:I,isolation:a.isolation,port:a.port,preStartCommands:a.preStart,postActivateCommands:ie,beforeResetCommands:Vn({slug:c,siteName:i}),sharedPaths:a.sharedPaths,zeroDowntime:a.zeroDowntime!==!1,healthCheckPath:a.healthCheck?.path,liveness:a.liveness,memoryHigh:a.memoryHigh,memoryMax:a.memoryMax,cpuWeight:a.cpuWeight,ioWeight:a.ioWeight,tasksMax:a.tasksMax,stopTimeout:a.stopTimeout}),ne=re==="server-static"&&!j(V)&&!!a.domain,he=ne?dn({siteName:i,domain:a.domain,aliases:a.aliases,type:a.type==="spa"?"spa":"static",appDir:`${te}/current`,webDirectory:"",redirects:a.redirects,auth:a.auth&&a.auth.enabled!==!1&&a.auth.password?{username:a.auth.username||"admin",password:a.auth.password,realm:a.auth.realm}:void 0,serverSnippet:pn(a.nginx,V?.nginxTemplates),clientMaxBodySize:a.nginx?.clientMaxBodySize,hsts:a.ssl?.hsts,tlsProtocols:a.ssl?.tlsProtocols,security:a.security}):[],ye=ne?Jn(a):[],T=[...vr(te,{releaseId:u,commit:u,branch:a.repository?.branch??"main"}),...wn(te,c),...$r(te,c),...oe,...he,...ye,...H];r.step(`Deploying to ${y.length} target(s)...`);let L=await e.runRemoteDeploy({targets:y,commands:T,comment:`ts-cloud deploy ${c}/${i}@${u}`,tags:{Project:c,Environment:s,Role:"app"}});if(!L.success)return await Ki(e,y,H,r),{success:!1,error:L.error||"Remote deploy failed",instanceCount:L.instanceCount,perInstance:L.perInstance};return{success:!0,instanceCount:L.instanceCount,perInstance:L.perInstance}}async function Ki(e,t,r,n){if(r.length===0)return;try{let s=await e.runRemoteDeploy({targets:t,commands:r,comment:"ts-cloud host cleanup after failed deploy"});if(!s.success)n.warn(`Host cleanup after the failed deploy did not complete: ${s.error||"unknown error"}`)}catch(s){n.warn(`Host cleanup after the failed deploy did not run: ${s.message}`)}}function qr(e){return`'${e.replaceAll("'","'\\''")}'`}function zu(e,t,r=!1,n=[]){let s=`${e}-dashboard-`,i=t.map((c)=>`${e}-${c}.service`),a=r?[`export TS_CLOUD_DASHBOARD_KEEP_DOMAINS=${qr(JSON.stringify(n))}`,"rm -f /run/ts-cloud-dashboard-routes-changed",`/usr/local/bin/bun --bun -e ${qr(`
451
+ `)}function Bi(e){let t=zi(e.siteName),r=Wr(e.siteName),n=`${Fi}/${r}.conf`;return[`getent group ${t} >/dev/null || groupadd --system ${t}`,`id -u ${t} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin -g ${t} ${t}`,`usermod -aG ${t} www-data 2>/dev/null || true`,`chown -R ${t}:${t} ${e.appBase} || true`,`chmod -R g+rX ${e.appBase} || true`,`chmod 600 ${e.appBase}/shared/.env 2>/dev/null || true`,`mkdir -p ${Fi}`,`cat > ${n} <<'TS_CLOUD_FPMPOOL_EOF'`,ku(e).replace(/\n$/,""),"TS_CLOUD_FPMPOOL_EOF",`(cd ${p} && pantry restart php-fpm) 2>/dev/null || true`]}var Yr={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};function Fu(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function lo(e,t,r=Yr){let{config:n,environment:s,siteName:i,site:a,slug:c,sha:u,runtime:f,localTarballPath:h}=t,S=`releases/${i}/${u}.tar.gz`,v=m(n,s),_=await e.getComputeOutputs({config:n,environment:s}),y=await e.findComputeTargets({slug:c,environment:s,role:"app",stackName:v});if(y.length===0)return{success:!1,error:e.name==="aws"?`Stack '${v}' has no EC2 instances tagged Project=${c} Environment=${s} Role=app, and storage/cloud/state/${v}.json pins no live instance. For a shared box, record its instanceId there.`:`No Hetzner servers labeled ts-cloud/project=${c} ts-cloud/environment=${s} ts-cloud/role=app, and storage/cloud/state/${v}.json pins no live server. For a shared box, record its serverId there.`};let T=_.servicesPrivateIp?Xs(_.servicesPrivateIp,g(n)):ps(g(n)),x=Ji(C(n,{environment:s})),W=n.infrastructure?.compute,H=ni(W?.hostCleanup),R=j({...W,proxy:w(n,{environment:s})})?{HOST:"127.0.0.1"}:{},L=s==="production"?{APP_ENV:"production",NODE_ENV:"production"}:{},I={...T,...x,...R,...a.env||{},...L},V=Cn(I,a.sharedPaths??[]);if(V.warning)r.warn(`Site '${i}': ${V.warning}`);else if(V.path)r.info(`Site '${i}': sharing '${V.path}' so the SQLite database survives deploys.`);if(jr(a)){let P=a.phpVersion??W?.php?.default??W?.php?.versions?.[0],O=U(c,i),D=Object.keys(T).length>0?{...a,env:I}:a,J=Li({siteName:i,site:D,releaseId:u,appBase:O,defaultPhpVersion:P}),Y=!j(W),Z=qn(a)==="custom"&&a.ssl?.certPath&&a.ssl?.keyPath?{certPath:a.ssl.certPath,keyPath:a.ssl.keyPath}:void 0,le=a.isolation?Bi({siteName:i,appBase:O}):[],E=Y?dn({siteName:i,domain:a.domain||i,aliases:a.aliases,type:a.type,appDir:`${O}/current`,webDirectory:a.webDirectory,phpVersion:P,fastcgiPass:a.isolation?Qn(i):void 0,redirects:a.redirects,ssl:Z,auth:a.auth&&a.auth.enabled!==!1&&a.auth.password?{username:a.auth.username||"admin",password:a.auth.password,realm:a.auth.realm}:void 0,serverSnippet:pn(a.nginx,W?.nginxTemplates),clientMaxBodySize:a.nginx?.clientMaxBodySize,hsts:a.ssl?.hsts,tlsProtocols:a.ssl?.tlsProtocols,security:a.security}):[],N=Y?Jn(a):[],he=Jo(a)?Wn({slug:c,siteName:i,site:a,phpVersion:P,appBase:O}):[],ae=Y?xi(a):[];r.step(`Deploying PHP site '${i}' to ${y.length} target(s)...`);let ve=await e.runRemoteDeploy({targets:y,commands:[...wn(O,c),...$r(O,c),...J,...le,...E,...N,...he,...ae,...H],comment:`ts-cloud deploy ${c}/${i}@${u}`,tags:{Project:c,Environment:s,Role:"app"}}),Rt=hs(n.notifications,a.notifications);if(!ve.success)return await Ki(e,y,H,r),await fn(Rt,"deploy-failed",`❌ Deploy of ${c}/${i}@${u} failed: ${ve.error||"unknown error"}`),{success:!1,error:ve.error||"Remote PHP deploy failed",instanceCount:ve.instanceCount,perInstance:ve.perInstance};let Vi=a.domain?` → https://${a.domain}`:"";return await fn(Rt,"deploy",`✅ Deployed ${c}/${i}@${u}${Vi}`),{success:!0,instanceCount:ve.instanceCount,perInstance:ve.perInstance}}if(!h)return{success:!1,error:`Site '${i}' requires a release tarball but none was provided`};let q=await e.uploadRelease({config:n,environment:s,localPath:h,remoteKey:S,targets:y}),K=ai(c,i,u),ee=e.name==="aws"?$c(_.deployBucketName,S,n.project.region||"us-east-1",K):Mc(q.artifactRef,K),te=d(a),ne=U(c,i),ie=Wn({slug:c,siteName:i,site:a,appBase:ne,releaseId:u}),oe=te==="server-static"?oi({siteName:i,slug:c,appDir:ne,artifactFetch:ee,releaseId:u,preStartCommands:a.preStart,postActivateCommands:ie,beforeResetCommands:Vn({slug:c,siteName:i})}):si({siteName:i,slug:c,appDir:ne,artifactFetch:ee,releaseId:u,execStart:ii(a.start,f,`${ne.replace(/\/+$/,"")}/releases/%i`),envEntries:I,isolation:a.isolation,port:a.port,preStartCommands:a.preStart,postActivateCommands:ie,beforeResetCommands:Vn({slug:c,siteName:i}),sharedPaths:a.sharedPaths,zeroDowntime:a.zeroDowntime!==!1,healthCheckPath:a.healthCheck?.path,liveness:a.liveness,memoryHigh:a.memoryHigh,memoryMax:a.memoryMax,cpuWeight:a.cpuWeight,ioWeight:a.ioWeight,tasksMax:a.tasksMax,stopTimeout:a.stopTimeout}),re=te==="server-static"&&!j(W)&&!!a.domain,pe=re?dn({siteName:i,domain:a.domain,aliases:a.aliases,type:a.type==="spa"?"spa":"static",appDir:`${ne}/current`,webDirectory:"",redirects:a.redirects,auth:a.auth&&a.auth.enabled!==!1&&a.auth.password?{username:a.auth.username||"admin",password:a.auth.password,realm:a.auth.realm}:void 0,serverSnippet:pn(a.nginx,W?.nginxTemplates),clientMaxBodySize:a.nginx?.clientMaxBodySize,hsts:a.ssl?.hsts,tlsProtocols:a.ssl?.tlsProtocols,security:a.security}):[],ge=re?Jn(a):[],b=[...vr(ne,{releaseId:u,commit:u,branch:a.repository?.branch??"main"}),...wn(ne,c),...$r(ne,c),...oe,...pe,...ge,...H];r.step(`Deploying to ${y.length} target(s)...`);let k=await e.runRemoteDeploy({targets:y,commands:b,comment:`ts-cloud deploy ${c}/${i}@${u}`,tags:{Project:c,Environment:s,Role:"app"}});if(!k.success)return await Ki(e,y,H,r),{success:!1,error:k.error||"Remote deploy failed",instanceCount:k.instanceCount,perInstance:k.perInstance};return{success:!0,instanceCount:k.instanceCount,perInstance:k.perInstance}}async function Ki(e,t,r,n){if(r.length===0)return;try{let s=await e.runRemoteDeploy({targets:t,commands:r,comment:"ts-cloud host cleanup after failed deploy"});if(!s.success)n.warn(`Host cleanup after the failed deploy did not complete: ${s.error||"unknown error"}`)}catch(s){n.warn(`Host cleanup after the failed deploy did not run: ${s.message}`)}}function qr(e){return`'${e.replaceAll("'","'\\''")}'`}function zu(e,t,r=!1,n=[]){let s=`${e}-dashboard-`,i=t.map((c)=>`${e}-${c}.service`),a=r?[`export TS_CLOUD_DASHBOARD_KEEP_DOMAINS=${qr(JSON.stringify(n))}`,"rm -f /run/ts-cloud-dashboard-routes-changed",`/usr/local/bin/bun --bun -e ${qr(`
452
452
  const { chmodSync, existsSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } = require('node:fs')
453
453
  const { basename, join } = require('node:path')
454
454
  const root = '/etc/rpx/sites.d'
@@ -476,4 +476,4 @@ This password is now in your deploy log. Set TS_CLOUD_UI_PASSWORD to a value of
476
476
  changed = true
477
477
  }
478
478
  if (changed) writeFileSync('/run/ts-cloud-dashboard-routes-changed', '')
479
- `)}`,"if [ -e /run/ts-cloud-dashboard-routes-changed ]; then"," systemctl restart rpx-gateway.service"," rm -f /run/ts-cloud-dashboard-routes-changed","fi"]:[];return["set -euo pipefail",`TS_CLOUD_DASHBOARD_PREFIX=${qr(s)}`,`TS_CLOUD_DASHBOARD_SERVER_OWNER=${r?"1":"0"}`,`TS_CLOUD_DASHBOARD_DESIRED=${qr(` ${i.join(" ")} `)}`,"for TS_CLOUD_UNIT_FILE in /etc/systemd/system/*.service; do",' [ -e "$TS_CLOUD_UNIT_FILE" ] || continue',' TS_CLOUD_UNIT=$(basename "$TS_CLOUD_UNIT_FILE")',' case "$TS_CLOUD_UNIT" in'," *-dashboard-*.service)",' if [ "$TS_CLOUD_DASHBOARD_SERVER_OWNER" != 1 ]; then',' case "$TS_CLOUD_UNIT" in "$TS_CLOUD_DASHBOARD_PREFIX"*.service) ;; *) continue ;; esac'," fi",' case "$TS_CLOUD_DASHBOARD_DESIRED" in',' *" $TS_CLOUD_UNIT "*) ;;'," *)",' systemctl disable --now "$TS_CLOUD_UNIT" 2>/dev/null || true',' rm -f "$TS_CLOUD_UNIT_FILE"'," ;;"," esac"," ;;"," esac","done","systemctl daemon-reload","systemctl reset-failed",...a]}async function Bu(e,t,r,n){let{config:s,environment:i}=t,a=s.project.slug,c=m(s,i),u=await e.findComputeTargets({slug:a,environment:i,role:"app",stackName:c});if(u.length===0)return!0;let f=await e.runRemoteDeploy({targets:u,commands:zu(a,r,!s.cloud?.attachTo,r.map((h)=>s.sites?.[h]?.domain).filter((h)=>typeof h==="string")),comment:`ts-cloud reconcile management dashboard ${a}`,tags:{Project:a,Environment:i,Role:"app"}});if(!f.success)return n.error(`Management dashboard reconciliation failed: ${f.error||"unknown error"}`),!1;return!0}async function Ku(e,t,r){let{config:n}=t,s=n.cloud?.attachTo;if(!s||!e.listReachableResources)return;let i;try{i=await e.listReachableResources()}catch(u){r.warn(`Could not determine this credential's reach: ${u instanceof Error?u.message:String(u)}`);return}let a=Lo(i,{ownerSlug:s,selfSlug:n.project.slug}),c=Hn(a)>0;for(let u of Uo(a,{ownerSlug:s,selfSlug:n.project.slug}))if(c)r.warn(u);else r.info(u)}async function ju(e,t,r){let{config:n,environment:s}=t,i=n.cloud?.attachTo;if(!i)return!0;let a=Ui(n.infrastructure?.compute?.managedServices);if(a.length===0)return!0;let c=n.project.slug,u=m(n,s),f=await e.findComputeTargets({slug:c,environment:s,role:"app",stackName:u});if(f.length===0)return!0;let h=await e.runRemoteDeploy({targets:f,commands:Hi(a),comment:`ts-cloud preflight managed services ${c}`,tags:{Project:c,Environment:s,Role:"app"}});if(!h.success)return r.warn(`Could not check '${i}' for the declared services: ${h.error||"unknown error"}`),!0;let S=new Set;for(let v of h.perInstance)for(let _ of Ni(v.output,a))S.add(_);if(S.size===0)return!0;return r.error(Mi([...S],i,f[0]?.publicIp)),!1}async function Gu(e,t,r){let{config:n,environment:s}=t;if(!n.cloud?.attachTo)return!0;let i=n.infrastructure?.compute,a=g(n),c=at(a,i?.managedServices??{});if(c.length===0)return!0;let u=n.project.slug,f=m(n,s),h=await e.findComputeTargets({slug:u,environment:s,role:"app",stackName:f});if(h.length===0)return!0;r.step(`Ensuring database '${a?.name}' + role exist on the shared box...`);let S=await e.runRemoteDeploy({targets:h,commands:c,comment:`ts-cloud ensure database ${u}/${a?.name}`,tags:{Project:u,Environment:s,Role:"app"}});if(!S.success)return r.error(`Ensuring database '${a?.name}' failed: ${S.error||"unknown error"}`),!1;return r.success(`Database '${a?.name}' is ready on ${S.instanceCount} target(s)`),!0}async function od(e){let{config:t,environment:r,driver:n,sha:s,runtime:i,tarballForSite:a,logger:c=Yr}=e,u=t.project.slug,f=e.cwd??process.cwd(),h=e.managementDashboard!==!1,S=pr(t);if(h)Ri(t,{cwd:f,logger:{info:c.info,warn:c.warn}});let v=!h||S?[]:Bn(t);if(h&&e.rpxConfig&&e.rpxConfig!==t&&!pr(e.rpxConfig))Ri(e.rpxConfig,{cwd:f,logger:{info:()=>{},warn:()=>{}}});if(h&&!await Bu(n,e,Bn(t),c))return!1;let _=null,y=new Map;if(v.length>0)if(_=co(t.sites?.[v[0]],{cwd:f,slug:u,sha:s,siteName:v[0],logger:{info:c.info,warn:c.warn}}),!_){c.warn("Management dashboard: no artifact available — skipping dashboard site(s) for this deploy.");for(let x of v)if(t.sites)delete t.sites[x]}else for(let x of v){if(x===v[0]){y.set(x,_);continue}try{let k=Mu(Nu(),`${u}-${x}-${s}.tar.gz`);Hu(_,k),y.set(x,k)}catch{y.set(x,_)}}let b=t.sites||{},D=Object.entries(b).filter(([x,k])=>{if(!k)return!1;let I=d(k);if(I==="bucket")return c.warn(`Site '${x}' targets a bucket — skipping (handled by the static-site path, not compute).`),!1;if(I==="redirect")return!1;if(I==="proxy")return!1;return!0});if(D.length===0)return Di(e);if(await Ku(n,e,c),!await ju(n,e,c))return!1;if(!await Gu(n,e,c))return!1;let V=(x)=>y.get(x)??a(x);for(let[x,k]of D){c.step(`Deploying site: ${x}`);let I=jr(k)?void 0:V(x),Y=await lo(n,{config:t,environment:r,siteName:x,site:k,slug:u,sha:s,runtime:i,localTarballPath:I},c);if(!Y.success){if(c.error(`Deploy of '${x}' failed: ${Y.error||"unknown error"}`),Y.perInstance)for(let W of Y.perInstance)c.error(` ${W.instanceId}: ${W.status}${W.error?` — ${W.error}`:""}`);return!1}if(c.success(`Deployed ${u}/${x}@${s} to ${Y.instanceCount} target(s)`),Y.perInstance)for(let W of Y.perInstance)c.info(` ✓ ${W.instanceId}: ${W.status}`)}if(!await Di(e))return!1;return!0}async function Vu(e,t,r){let n=Cp(e);if(!n||n.tls==="off")return n;let s=await je(t,r),i=s?.provider==="ssh"?s.lanIp:void 0;return i?{...n,ip:i}:n}async function Di(e){let{config:t,environment:r,driver:n,logger:s=Yr}=e,i=e.rpxConfig??t,a=w(i,{environment:r})??w(t,{environment:r});if(a?.engine!=="rpx")return!0;let c=i.sites||{},u=t.project.slug,f=m(t,r),h=await n.findComputeTargets({slug:u,environment:r,role:"lb",stackName:f});if(h.length>0){let H=(await n.findComputeTargets({slug:u,environment:r,role:"app",stackName:f})).map((I)=>({privateIp:I.privateIp,publicIp:I.publicIp})),x=rr(c,H,{proxy:a,slug:u});if(x.proxies.length===0)return s.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;s.step(`Reloading the load balancer's rpx gateway with ${x.proxies.length} route(s)...`);let k=await n.runRemoteDeploy({targets:h,commands:Ne({config:x,slug:u,preserveManagementDashboardRoutes:e.managementDashboard===!1}),comment:`ts-cloud rpx gateway reload ${u}`,tags:{Project:u,Environment:r,Role:"lb"}});if(!k.success)return s.error(`rpx gateway reload failed: ${k.error||"unknown error"}`),!1;return s.success(`rpx gateway reloaded on ${k.instanceCount} load balancer(s)`),!0}let S=await Vu(t,f,e.cwd),v=B(c,{proxy:a,slug:u,lan:S,mail:C(t,{environment:r})});if(v.proxies.length===0)return s.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;let _=await n.findComputeTargets({slug:u,environment:r,role:"app",stackName:f});if(_.length===0)return s.warn("rpx gateway: no compute targets found — skipping gateway reload."),!0;let y=Boolean(t.cloud?.attachTo);if(y&&(a.version||a.tlsxVersion))s.warn(`rpx gateway: ignoring proxy.version/tlsxVersion — this project attaches to '${t.cloud?.attachTo}' and the gateway belongs to that box's owner.`);s.step(`Reloading rpx gateway with ${v.proxies.length} route(s)...`);let b=G({proxy:a,config:v,slug:u,tenant:y,profile:Ep(t),preserveManagementDashboardRoutes:e.managementDashboard===!1}),D=await n.runRemoteDeploy({targets:_,commands:b,comment:`ts-cloud rpx gateway reload ${u}`,tags:{Project:u,Environment:r,Role:"app"}});if(!D.success)return s.error(`rpx gateway reload failed: ${D.error||"unknown error"}`),!1;return s.success(`rpx gateway reloaded on ${D.instanceCount} target(s)`),!0}async function ad(e){let{config:t,environment:r,driver:n,logger:s=Yr}=e,i=e.rpxConfig??t,a=w(i,{environment:r})??w(t,{environment:r});if(a?.engine!=="rpx"||!a.onDemandTls)return!0;let c=B(i.sites||{},{proxy:a,slug:t.project.slug,mail:C(t,{environment:r})});if(c.proxies.length===0)return!0;let u=gd(c);if(u.length===0)return!0;let f=t.project.slug,h=m(t,r),S="lb",v=await n.findComputeTargets({slug:f,environment:r,role:S,stackName:h});if(v.length===0)S="app",v=await n.findComputeTargets({slug:f,environment:r,role:S,stackName:h});if(v.length===0)return s.warn("rpx TLS: no gateway targets found - skipping certificate issuance."),!0;s.step("Issuing rpx TLS certificates after DNS reconciliation...");let _=u.map((b)=>`test -s ${Fu(`${c.productionCerts.certsDir}/${b}.crt`)}`).join(" && "),y=await n.runRemoteDeploy({targets:v,commands:[`systemctl start ${ud(f)}`,_],comment:`ts-cloud rpx TLS issuance ${f}`,tags:{Project:f,Environment:r,Role:S}});if(!y.success)return s.error(`rpx TLS issuance failed: ${y.error||"unknown error"}`),!1;return s.success(`rpx TLS certificates reconciled on ${y.instanceCount} gateway target(s)`),!0}var yp="658327ea-f89d-4fab-a63d-7e88639e58f6",Sp="4135ea2d-6df8-44a3-9df3-4b5a84be39ad",Ip="216adef6-5c7f-47e4-b989-5492eafa07d3",es="origin",ji="origin-failover";function Gi(e,t){let r={TargetOriginId:es,ViewerProtocolPolicy:"redirect-to-https",Compress:!0,CachePolicyId:t==="dynamic"?Sp:yp,OriginRequestPolicyId:Ip,SmoothStreaming:!1,FieldLevelEncryptionId:"",TrustedSigners:{Enabled:!1,Quantity:0},TrustedKeyGroups:{Enabled:!1,Quantity:0},LambdaFunctionAssociations:{Quantity:0},FunctionAssociations:{Quantity:0},AllowedMethods:t==="dynamic"?{Quantity:7,Items:["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"],CachedMethods:{Quantity:2,Items:["GET","HEAD"]}}:{Quantity:3,Items:["GET","HEAD","OPTIONS"],CachedMethods:{Quantity:2,Items:["GET","HEAD"]}}};if(e!==null)r.PathPattern=e;return r}function Zh(e){let t=e.aliases;if(t.length===0)throw Error("buildCloudFrontOriginConfig: at least one alias is required");if(t.includes(e.originDomain))throw Error(`buildCloudFrontOriginConfig: originDomain ${e.originDomain} must not be one of the aliases (it would loop)`);if(e.originShield&&!e.originShieldRegion)throw Error("buildCloudFrontOriginConfig: originShieldRegion is required when originShield is enabled");let r=e.failoverOriginDomain;if(r!==void 0){if(t.includes(r))throw Error(`buildCloudFrontOriginConfig: failoverOriginDomain ${r} must not be one of the aliases (it would loop)`);if(r===e.originDomain)throw Error("buildCloudFrontOriginConfig: failoverOriginDomain must differ from originDomain")}else if(e.failoverStatusCodes)throw Error("buildCloudFrontOriginConfig: failoverStatusCodes needs failoverOriginDomain to fail over to");let n=e.originSecretHeader??"X-Origin-Verify",s=e.originSecret?{Quantity:1,Items:[{HeaderName:n,HeaderValue:e.originSecret}]}:{Quantity:0},i=[...e.behaviors??[]].sort((v,_)=>_.pathPattern.length-v.pathPattern.length),a=de(e,"buildCloudFrontOriginConfig"),c=(v,_,y,b={})=>({Id:v,DomainName:_,OriginPath:"",CustomHeaders:s,CustomOriginConfig:{HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only",OriginSslProtocols:{Quantity:1,Items:["TLSv1.2"]},OriginReadTimeout:30,OriginKeepaliveTimeout:5},ConnectionAttempts:b.ConnectionAttempts??3,ConnectionTimeout:b.ConnectionTimeout??10,OriginShield:y,OriginAccessControlId:""}),u=[c(es,e.originDomain,e.originShield?{Enabled:!0,OriginShieldRegion:e.originShieldRegion}:{Enabled:!1},a)],f={Quantity:0},h=Gi(null,"static");if(r!==void 0)u.push(c(ji,r,{Enabled:!1})),f=ln({primaryOriginId:es,secondaryOriginId:ji,statusCodes:e.failoverStatusCodes}),Pt(h.AllowedMethods,"the default cache behavior"),h.TargetOriginId=f.Items[0].Id;let S={CallerReference:e.callerReference??e.originDomain,Comment:e.comment??`Origin-fronted distribution for ${t[0]} → ${e.originDomain}`,Enabled:!0,Aliases:{Quantity:t.length,Items:t},DefaultRootObject:"",Origins:{Quantity:u.length,Items:u},OriginGroups:f,DefaultCacheBehavior:h,CacheBehaviors:{Quantity:i.length,Items:i.map((v)=>Gi(v.pathPattern,v.kind))},ViewerCertificate:{CloudFrontDefaultCertificate:!1,ACMCertificateArn:e.viewerCertificateArn,Certificate:e.viewerCertificateArn,CertificateSource:"acm",SSLSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"},PriceClass:e.priceClass??"PriceClass_All",HttpVersion:"http2and3",IsIPV6Enabled:!0,Restrictions:{GeoRestriction:{RestrictionType:"none",Quantity:0}},Logging:{Enabled:!1,IncludeCookies:!1,Bucket:"",Prefix:""},WebACLId:"",CustomErrorResponses:{Quantity:0}};return kt(S,"buildCloudFrontOriginConfig"),S}export{Ng,Oc,Bg,De,_c,Xn,xg,Lc,Yn,Jt,Or,Xt,Og,_g,Fh,p,ft,Zs,Zn,Yt,_r,Lg,eo,M,Lr,ei,ti,$r,Zt,$g,Mg,Mr,Uh,Qh,Fg,Ug,Hh,Gh,Vh,Fr,ri,Qg,to,ni,ii,si,oi,ai,$c,Mc,ci,Ur,Ie,Fc,ht,Uc,di,Qc,Hc,Qr,Gc,Ve,se,er,Hg,li,Vc,qc,jc,zc,At,qe,je,yt,ui,gi,Pe,ro,no,Gg,Vg,Kc,qg,St,pi,Wc,jg,zg,Jc,It,ke,Xc,Kg,Wg,io,mi,bt,Jg,Xg,Yg,Zg,ep,tp,rp,np,ip,fi,hi,Ai,yi,Si,Ii,bi,sp,op,Hr,F,so,ap,cp,dp,Yc,lp,up,qh,jh,zh,Zc,gp,Kh,Wh,Jh,Ci,Ei,vi,Ti,ed,td,wi,rd,Xh,oo,pp,mp,fp,hp,Ap,nd,Yh,id,ao,sd,tr,Ri,co,Gr,lo,od,Di,ad,yp,Sp,Ip,Zh};
479
+ `)}`,"if [ -e /run/ts-cloud-dashboard-routes-changed ]; then"," systemctl restart rpx-gateway.service"," rm -f /run/ts-cloud-dashboard-routes-changed","fi"]:[];return["set -euo pipefail",`TS_CLOUD_DASHBOARD_PREFIX=${qr(s)}`,`TS_CLOUD_DASHBOARD_SERVER_OWNER=${r?"1":"0"}`,`TS_CLOUD_DASHBOARD_DESIRED=${qr(` ${i.join(" ")} `)}`,"for TS_CLOUD_UNIT_FILE in /etc/systemd/system/*.service; do",' [ -e "$TS_CLOUD_UNIT_FILE" ] || continue',' TS_CLOUD_UNIT=$(basename "$TS_CLOUD_UNIT_FILE")',' case "$TS_CLOUD_UNIT" in'," *-dashboard-*.service)",' if [ "$TS_CLOUD_DASHBOARD_SERVER_OWNER" != 1 ]; then',' case "$TS_CLOUD_UNIT" in "$TS_CLOUD_DASHBOARD_PREFIX"*.service) ;; *) continue ;; esac'," fi",' case "$TS_CLOUD_DASHBOARD_DESIRED" in',' *" $TS_CLOUD_UNIT "*) ;;'," *)",' systemctl disable --now "$TS_CLOUD_UNIT" 2>/dev/null || true',' rm -f "$TS_CLOUD_UNIT_FILE"'," ;;"," esac"," ;;"," esac","done","systemctl daemon-reload","systemctl reset-failed",...a]}async function Bu(e,t,r,n){let{config:s,environment:i}=t,a=s.project.slug,c=m(s,i),u=await e.findComputeTargets({slug:a,environment:i,role:"app",stackName:c});if(u.length===0)return!0;let f=await e.runRemoteDeploy({targets:u,commands:zu(a,r,!s.cloud?.attachTo,r.map((h)=>s.sites?.[h]?.domain).filter((h)=>typeof h==="string")),comment:`ts-cloud reconcile management dashboard ${a}`,tags:{Project:a,Environment:i,Role:"app"}});if(!f.success)return n.error(`Management dashboard reconciliation failed: ${f.error||"unknown error"}`),!1;return!0}async function Ku(e,t,r){let{config:n}=t,s=n.cloud?.attachTo;if(!s||!e.listReachableResources)return;let i;try{i=await e.listReachableResources()}catch(u){r.warn(`Could not determine this credential's reach: ${u instanceof Error?u.message:String(u)}`);return}let a=Lo(i,{ownerSlug:s,selfSlug:n.project.slug}),c=Hn(a)>0;for(let u of Uo(a,{ownerSlug:s,selfSlug:n.project.slug}))if(c)r.warn(u);else r.info(u)}async function ju(e,t,r){let{config:n,environment:s}=t,i=n.cloud?.attachTo;if(!i)return!0;let a=Ui(n.infrastructure?.compute?.managedServices);if(a.length===0)return!0;let c=n.project.slug,u=m(n,s),f=await e.findComputeTargets({slug:c,environment:s,role:"app",stackName:u});if(f.length===0)return!0;let h=await e.runRemoteDeploy({targets:f,commands:Hi(a),comment:`ts-cloud preflight managed services ${c}`,tags:{Project:c,Environment:s,Role:"app"}});if(!h.success)return r.warn(`Could not check '${i}' for the declared services: ${h.error||"unknown error"}`),!0;let S=new Set;for(let v of h.perInstance)for(let _ of Ni(v.output,a))S.add(_);if(S.size===0)return!0;return r.error(Mi([...S],i,f[0]?.publicIp)),!1}async function Gu(e,t,r){let{config:n,environment:s}=t;if(!n.cloud?.attachTo)return!0;let i=n.infrastructure?.compute,a=g(n),c=at(a,i?.managedServices??{});if(c.length===0)return!0;let u=n.project.slug,f=m(n,s),h=await e.findComputeTargets({slug:u,environment:s,role:"app",stackName:f});if(h.length===0)return!0;r.step(`Ensuring database '${a?.name}' + role exist on the shared box...`);let S=await e.runRemoteDeploy({targets:h,commands:c,comment:`ts-cloud ensure database ${u}/${a?.name}`,tags:{Project:u,Environment:s,Role:"app"}});if(!S.success)return r.error(`Ensuring database '${a?.name}' failed: ${S.error||"unknown error"}`),!1;return r.success(`Database '${a?.name}' is ready on ${S.instanceCount} target(s)`),!0}async function od(e){let{config:t,environment:r,driver:n,sha:s,runtime:i,tarballForSite:a,logger:c=Yr}=e,u=t.project.slug,f=e.cwd??process.cwd(),h=e.managementDashboard!==!1,S=pr(t);if(h)Ri(t,{cwd:f,logger:{info:c.info,warn:c.warn}});let v=!h||S?[]:Bn(t);if(h&&e.rpxConfig&&e.rpxConfig!==t&&!pr(e.rpxConfig))Ri(e.rpxConfig,{cwd:f,logger:{info:()=>{},warn:()=>{}}});if(h&&!await Bu(n,e,Bn(t),c))return!1;let _=null,y=new Map;if(v.length>0)if(_=co(t.sites?.[v[0]],{cwd:f,slug:u,sha:s,siteName:v[0],logger:{info:c.info,warn:c.warn}}),!_){c.warn("Management dashboard: no artifact available — skipping dashboard site(s) for this deploy.");for(let R of v)if(t.sites)delete t.sites[R]}else for(let R of v){if(R===v[0]){y.set(R,_);continue}try{let L=Mu(Nu(),`${u}-${R}-${s}.tar.gz`);Hu(_,L),y.set(R,L)}catch{y.set(R,_)}}let T=t.sites||{},x=Object.entries(T).filter(([R,L])=>{if(!L)return!1;let I=d(L);if(I==="bucket")return c.warn(`Site '${R}' targets a bucket — skipping (handled by the static-site path, not compute).`),!1;if(I==="redirect")return!1;if(I==="proxy")return!1;return!0});if(x.length===0)return Di(e);if(await Ku(n,e,c),!await ju(n,e,c))return!1;if(!await Gu(n,e,c))return!1;let W=(R)=>y.get(R)??a(R);for(let[R,L]of x){c.step(`Deploying site: ${R}`);let I=jr(L)?void 0:W(R),V=await lo(n,{config:t,environment:r,siteName:R,site:L,slug:u,sha:s,runtime:i,localTarballPath:I},c);if(!V.success){if(c.error(`Deploy of '${R}' failed: ${V.error||"unknown error"}`),V.perInstance)for(let q of V.perInstance)c.error(` ${q.instanceId}: ${q.status}${q.error?` — ${q.error}`:""}`);return!1}if(c.success(`Deployed ${u}/${R}@${s} to ${V.instanceCount} target(s)`),V.perInstance)for(let q of V.perInstance)c.info(` ✓ ${q.instanceId}: ${q.status}`)}if(!await Di(e))return!1;return!0}async function Vu(e,t,r){let n=Cp(e);if(!n||n.tls==="off")return n;let s=await je(t,r),i=s?.provider==="ssh"?s.lanIp:void 0;return i?{...n,ip:i}:n}async function Di(e){let{config:t,environment:r,driver:n,logger:s=Yr}=e,i=e.rpxConfig??t,a=w(i,{environment:r})??w(t,{environment:r});if(a?.engine!=="rpx")return!0;let c=i.sites||{},u=t.project.slug,f=m(t,r),h=await n.findComputeTargets({slug:u,environment:r,role:"lb",stackName:f});if(h.length>0){let H=(await n.findComputeTargets({slug:u,environment:r,role:"app",stackName:f})).map((I)=>({privateIp:I.privateIp,publicIp:I.publicIp})),R=rr(c,H,{proxy:a,slug:u});if(R.proxies.length===0)return s.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;s.step(`Reloading the load balancer's rpx gateway with ${R.proxies.length} route(s)...`);let L=await n.runRemoteDeploy({targets:h,commands:Ne({config:R,slug:u,preserveManagementDashboardRoutes:e.managementDashboard===!1}),comment:`ts-cloud rpx gateway reload ${u}`,tags:{Project:u,Environment:r,Role:"lb"}});if(!L.success)return s.error(`rpx gateway reload failed: ${L.error||"unknown error"}`),!1;return s.success(`rpx gateway reloaded on ${L.instanceCount} load balancer(s)`),!0}let S=await Vu(t,f,e.cwd),v=B(c,{proxy:a,slug:u,lan:S,mail:C(t,{environment:r})});if(v.proxies.length===0)return s.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;let _=await n.findComputeTargets({slug:u,environment:r,role:"app",stackName:f});if(_.length===0)return s.warn("rpx gateway: no compute targets found — skipping gateway reload."),!0;let y=Boolean(t.cloud?.attachTo);if(y&&(a.version||a.tlsxVersion))s.warn(`rpx gateway: ignoring proxy.version/tlsxVersion — this project attaches to '${t.cloud?.attachTo}' and the gateway belongs to that box's owner.`);s.step(`Reloading rpx gateway with ${v.proxies.length} route(s)...`);let T=G({proxy:a,config:v,slug:u,tenant:y,profile:Ep(t),preserveManagementDashboardRoutes:e.managementDashboard===!1}),x=await n.runRemoteDeploy({targets:_,commands:T,comment:`ts-cloud rpx gateway reload ${u}`,tags:{Project:u,Environment:r,Role:"app"}});if(!x.success)return s.error(`rpx gateway reload failed: ${x.error||"unknown error"}`),!1;return s.success(`rpx gateway reloaded on ${x.instanceCount} target(s)`),!0}async function ad(e){let{config:t,environment:r,driver:n,logger:s=Yr}=e,i=e.rpxConfig??t,a=w(i,{environment:r})??w(t,{environment:r});if(a?.engine!=="rpx"||!a.onDemandTls)return!0;let c=B(i.sites||{},{proxy:a,slug:t.project.slug,mail:C(t,{environment:r})});if(c.proxies.length===0)return!0;let u=gd(c);if(u.length===0)return!0;let f=t.project.slug,h=m(t,r),S="lb",v=await n.findComputeTargets({slug:f,environment:r,role:S,stackName:h});if(v.length===0)S="app",v=await n.findComputeTargets({slug:f,environment:r,role:S,stackName:h});if(v.length===0)return s.warn("rpx TLS: no gateway targets found - skipping certificate issuance."),!0;s.step("Issuing rpx TLS certificates after DNS reconciliation...");let _=u.map((T)=>`test -s ${Fu(`${c.productionCerts.certsDir}/${T}.crt`)}`).join(" && "),y=await n.runRemoteDeploy({targets:v,commands:[`systemctl start ${ud(f)}`,_],comment:`ts-cloud rpx TLS issuance ${f}`,tags:{Project:f,Environment:r,Role:S}});if(!y.success)return s.error(`rpx TLS issuance failed: ${y.error||"unknown error"}`),!1;return s.success(`rpx TLS certificates reconciled on ${y.instanceCount} gateway target(s)`),!0}var yp="658327ea-f89d-4fab-a63d-7e88639e58f6",Sp="4135ea2d-6df8-44a3-9df3-4b5a84be39ad",Ip="216adef6-5c7f-47e4-b989-5492eafa07d3",es="origin",ji="origin-failover";function Gi(e,t){let r={TargetOriginId:es,ViewerProtocolPolicy:"redirect-to-https",Compress:!0,CachePolicyId:t==="dynamic"?Sp:yp,OriginRequestPolicyId:Ip,SmoothStreaming:!1,FieldLevelEncryptionId:"",TrustedSigners:{Enabled:!1,Quantity:0},TrustedKeyGroups:{Enabled:!1,Quantity:0},LambdaFunctionAssociations:{Quantity:0},FunctionAssociations:{Quantity:0},AllowedMethods:t==="dynamic"?{Quantity:7,Items:["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"],CachedMethods:{Quantity:2,Items:["GET","HEAD"]}}:{Quantity:3,Items:["GET","HEAD","OPTIONS"],CachedMethods:{Quantity:2,Items:["GET","HEAD"]}}};if(e!==null)r.PathPattern=e;return r}function Zh(e){let t=e.aliases;if(t.length===0)throw Error("buildCloudFrontOriginConfig: at least one alias is required");if(t.includes(e.originDomain))throw Error(`buildCloudFrontOriginConfig: originDomain ${e.originDomain} must not be one of the aliases (it would loop)`);if(e.originShield&&!e.originShieldRegion)throw Error("buildCloudFrontOriginConfig: originShieldRegion is required when originShield is enabled");let r=e.failoverOriginDomain;if(r!==void 0){if(t.includes(r))throw Error(`buildCloudFrontOriginConfig: failoverOriginDomain ${r} must not be one of the aliases (it would loop)`);if(r===e.originDomain)throw Error("buildCloudFrontOriginConfig: failoverOriginDomain must differ from originDomain")}else if(e.failoverStatusCodes)throw Error("buildCloudFrontOriginConfig: failoverStatusCodes needs failoverOriginDomain to fail over to");let n=e.originSecretHeader??"X-Origin-Verify",s=e.originSecret?{Quantity:1,Items:[{HeaderName:n,HeaderValue:e.originSecret}]}:{Quantity:0},i=[...e.behaviors??[]].sort((v,_)=>_.pathPattern.length-v.pathPattern.length),a=de(e,"buildCloudFrontOriginConfig"),c=(v,_,y,T={})=>({Id:v,DomainName:_,OriginPath:"",CustomHeaders:s,CustomOriginConfig:{HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only",OriginSslProtocols:{Quantity:1,Items:["TLSv1.2"]},OriginReadTimeout:30,OriginKeepaliveTimeout:5},ConnectionAttempts:T.ConnectionAttempts??3,ConnectionTimeout:T.ConnectionTimeout??10,OriginShield:y,OriginAccessControlId:""}),u=[c(es,e.originDomain,e.originShield?{Enabled:!0,OriginShieldRegion:e.originShieldRegion}:{Enabled:!1},a)],f={Quantity:0},h=Gi(null,"static");if(r!==void 0)u.push(c(ji,r,{Enabled:!1})),f=ln({primaryOriginId:es,secondaryOriginId:ji,statusCodes:e.failoverStatusCodes}),Pt(h.AllowedMethods,"the default cache behavior"),h.TargetOriginId=f.Items[0].Id;let S={CallerReference:e.callerReference??e.originDomain,Comment:e.comment??`Origin-fronted distribution for ${t[0]} → ${e.originDomain}`,Enabled:!0,Aliases:{Quantity:t.length,Items:t},DefaultRootObject:"",Origins:{Quantity:u.length,Items:u},OriginGroups:f,DefaultCacheBehavior:h,CacheBehaviors:{Quantity:i.length,Items:i.map((v)=>Gi(v.pathPattern,v.kind))},ViewerCertificate:{CloudFrontDefaultCertificate:!1,ACMCertificateArn:e.viewerCertificateArn,Certificate:e.viewerCertificateArn,CertificateSource:"acm",SSLSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"},PriceClass:e.priceClass??"PriceClass_All",HttpVersion:"http2and3",IsIPV6Enabled:!0,Restrictions:{GeoRestriction:{RestrictionType:"none",Quantity:0}},Logging:{Enabled:!1,IncludeCookies:!1,Bucket:"",Prefix:""},WebACLId:"",CustomErrorResponses:{Quantity:0}};return kt(S,"buildCloudFrontOriginConfig"),S}export{Ng,Oc,Bg,De,_c,Xn,xg,Lc,Yn,Jt,Or,Xt,Og,_g,Fh,p,ft,Zs,Zn,Yt,_r,Lg,eo,M,Lr,ei,ti,$r,Zt,$g,Mg,Mr,Uh,Qh,Fg,Ug,Hh,Gh,Vh,Fr,ri,Qg,to,ni,ii,si,oi,ai,$c,Mc,ci,Ur,Ie,Fc,ht,Uc,di,Qc,Hc,Qr,Gc,Ve,se,er,Hg,li,Vc,qc,jc,zc,At,qe,je,yt,ui,gi,Pe,ro,no,Gg,Vg,Kc,qg,St,pi,Wc,jg,zg,Jc,It,ke,Xc,Kg,Wg,io,mi,bt,Jg,Xg,Yg,Zg,ep,tp,rp,np,ip,fi,hi,Ai,yi,Si,Ii,bi,sp,op,Hr,F,so,ap,cp,dp,Yc,lp,up,qh,jh,zh,Zc,gp,Kh,Wh,Jh,Ci,Ei,vi,Ti,ed,td,wi,rd,Xh,oo,pp,mp,fp,hp,Ap,nd,Yh,id,ao,sd,tr,Ri,co,Gr,lo,od,Di,ad,yp,Sp,Ip,Zh};