@stacksjs/ts-cloud 0.16.54 → 0.16.56

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 (65) hide show
  1. package/dist/bin/{chunk-9de905c6.js → chunk-4sv46rnt.js} +1 -1
  2. package/dist/bin/{chunk-z3f0k8jt.js → chunk-6a1tny5g.js} +83 -83
  3. package/dist/bin/{chunk-gqyfa360.js → chunk-trtxnca4.js} +1 -1
  4. package/dist/bin/cli.js +4 -4
  5. package/dist/bin/dashboard-server.js +1 -1
  6. package/dist/{chunk-07z9bps2.js → chunk-86d69jp3.js} +1 -1
  7. package/dist/{chunk-b11w48de.js → chunk-acxmtx6c.js} +19 -19
  8. package/dist/deploy/index.js +1 -1
  9. package/dist/drivers/index.js +1 -1
  10. package/dist/index.js +1 -1
  11. package/dist/ui/404.html +1 -1
  12. package/dist/ui/accept-invitation.html +1 -1
  13. package/dist/ui/access-denied.html +1 -1
  14. package/dist/ui/account/automation.html +5 -5
  15. package/dist/ui/account/security.html +2 -2
  16. package/dist/ui/applications/compose.html +6 -6
  17. package/dist/ui/applications/new.html +2 -2
  18. package/dist/ui/data/backups.html +6 -6
  19. package/dist/ui/data/services.html +6 -6
  20. package/dist/ui/data/volumes.html +6 -6
  21. package/dist/ui/index.html +5 -5
  22. package/dist/ui/infrastructure/topology.html +5 -5
  23. package/dist/ui/integrations.html +1 -1
  24. package/dist/ui/operations/alerts.html +6 -6
  25. package/dist/ui/operations/configuration.html +5 -5
  26. package/dist/ui/operations/jobs.html +6 -6
  27. package/dist/ui/operations/maintenance.html +6 -6
  28. package/dist/ui/operations/observability.html +6 -6
  29. package/dist/ui/operations/previews.html +5 -5
  30. package/dist/ui/operations/queue.html +6 -6
  31. package/dist/ui/operations/regions.html +5 -5
  32. package/dist/ui/operations/releases.html +6 -6
  33. package/dist/ui/operations/spend.html +6 -6
  34. package/dist/ui/operations/workloads.html +6 -6
  35. package/dist/ui/security.html +1 -1
  36. package/dist/ui/server/actions.html +6 -6
  37. package/dist/ui/server/activity.html +1 -1
  38. package/dist/ui/server/capacity.html +6 -6
  39. package/dist/ui/server/database.html +6 -6
  40. package/dist/ui/server/deployments.html +6 -6
  41. package/dist/ui/server/diagnostics.html +2 -2
  42. package/dist/ui/server/firewall.html +6 -6
  43. package/dist/ui/server/fleet.html +6 -6
  44. package/dist/ui/server/logs.html +6 -6
  45. package/dist/ui/server/metrics.html +6 -6
  46. package/dist/ui/server/security.html +2 -2
  47. package/dist/ui/server/services.html +1 -1
  48. package/dist/ui/server/sites.html +5 -5
  49. package/dist/ui/server/ssh-keys.html +6 -6
  50. package/dist/ui/server/team.html +6 -6
  51. package/dist/ui/server/terminal.html +2 -2
  52. package/dist/ui/serverless/alarms.html +5 -5
  53. package/dist/ui/serverless/assets.html +2 -2
  54. package/dist/ui/serverless/cost.html +2 -2
  55. package/dist/ui/serverless/data.html +6 -6
  56. package/dist/ui/serverless/deployments.html +1 -1
  57. package/dist/ui/serverless/firewall.html +1 -1
  58. package/dist/ui/serverless/functions.html +6 -6
  59. package/dist/ui/serverless/logs.html +6 -6
  60. package/dist/ui/serverless/metrics.html +2 -2
  61. package/dist/ui/serverless/queues.html +6 -6
  62. package/dist/ui/serverless/secrets.html +6 -6
  63. package/dist/ui/serverless/traces.html +6 -6
  64. package/dist/ui/serverless.html +5 -5
  65. package/package.json +3 -3
@@ -14,7 +14,7 @@ ${Xo(c)}`:u}),s=r.length-n.length,i=s>0?[`(+${s} more instance${s===1?"":"s"} fa
14
14
  `)}function $i(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=${we}`,`Group=${we}`,`WorkingDirectory=${e.storagePath}`,`EnvironmentFile=${he}/mail.env`,`Environment="PATH=${Ar}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"`,`ExecStart=${Ar}/mail serve --config ${he}/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} ${he}`,"","[Install]","WantedBy=multi-user.target",""].join(`
15
15
  `)}function wi(e){if(!e.dkim.enabled||e.domains.length===0)return[];let t=[`mkdir -p ${he}/dkim`];for(let r of e.domains){let n=Hr(e,r);t.push(`if [ ! -f ${Ce(n)} ]; then openssl genrsa -out ${Ce(n)} 2048; fi`,`chmod 0600 ${Ce(n)}`,`echo "DKIM ${e.dkim.selector}._domainkey.${r} IN TXT v=DKIM1; k=rsa; p=$(openssl rsa -in ${Ce(n)} -pubout -outform PEM 2>/dev/null | grep -v '^-----' | tr -d '\\n')"`)}return t.push(`chown -R ${we}:${we} ${he}/dkim`),t}function Pi(e){if(e.accounts.length===0)return[];let t=(r)=>`runuser -u ${we} -- env SMTP_DB_PATH="$TS_CLOUD_MAIL_DB" ${Ar}/mail user:local ${r}`;return e.accounts.flatMap((r)=>[t(`create ${Ce(r.address)} ${Ce(r.password)} ${Ce(r.address)}`),...r.passwordPolicy==="managed"?[t(`change-password ${Ce(r.address)} ${Ce(r.password)}`)]:[]])}function Kn(e){if(!e.enabled)return[];return[...Te(Qo(e)),`id -u ${we} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin ${we}`,`mkdir -p ${e.storagePath} ${he}`,`chown -R ${we}:${we} ${e.storagePath}`,`TS_CLOUD_MAIL_DB="$(grep -sE '^SMTP_DB_PATH=' ${he}/mail.env | head -1 | cut -d= -f2- || true)"`,`[ -n "$TS_CLOUD_MAIL_DB" ] || TS_CLOUD_MAIL_DB=${Ce(Bn(e))}`,`cat > ${he}/config.toml <<'TS_CLOUD_MAIL_CONF_EOF'`,Zo(e),"TS_CLOUD_MAIL_CONF_EOF",`cat > ${he}/mail.env <<'TS_CLOUD_MAIL_ENV_EOF'`,_i(e),"TS_CLOUD_MAIL_ENV_EOF",`sed -i "s|^SMTP_DB_PATH=.*|SMTP_DB_PATH=$TS_CLOUD_MAIL_DB|" ${he}/mail.env`,`chmod 0640 ${he}/mail.env`,`chown root:${we} ${he}/mail.env`,...wi(e),`cat > /etc/systemd/system/${Ir}.service <<'TS_CLOUD_MAIL_UNIT_EOF'`,$i(e),"TS_CLOUD_MAIL_UNIT_EOF","systemctl daemon-reload",`systemctl enable ${Ir}`,`systemctl restart ${Ir}`,...Pi(e)]}var ve=`${T}/pantry/.bin`,jr=15306,zr=15991,Ft=15999,jn=16101,Bt=2379,Re="/var/lib/vitess",Gr=100;function bt(e){return e===!0||typeof e==="object"&&e!==null}function Oi(e){return typeof e==="object"&&e!==null?e:{}}function oe(e){return`'${String(e).split("'").join("'\\''")}'`}function Di(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 fe="vitess",xi=`${ve}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`,Qn="/usr/local/lib/vitess",qr=new Map;function Kr(e){return`${Qn}/${e}.sh`}function nt(e,t){return qr.set(e,Li(t)),`/bin/sh ${Kr(e)}`}function Vn(){let e=[`mkdir -p ${Qn}`];for(let[t,r]of qr)e.push(`cat > ${Kr(t)} <<'TS_CLOUD_VITESS_LAUNCHER_EOF'`,r,"TS_CLOUD_VITESS_LAUNCHER_EOF",`chmod 0755 ${Kr(t)}`);return e}function Li(e){return["#!/bin/sh","set -e",`cd ${T}`,`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 ${ve}/mysqld 2>/dev/null)")")"`,`VTROOT="$(dirname "$(dirname "$(readlink -f ${ve}/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
16
  `)}function st(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=${fe}`,`Group=${fe}`,`Environment="PATH=${xi}"`,`Environment="VTDATAROOT=${Re}"`,...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 Gn(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_VITESS_UNIT_EOF'`,t,"TS_CLOUD_VITESS_UNIT_EOF"]}function Ui(e){let t=e.cell??"zone1",r=e.vtgatePort??jr,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 st({description:"Vitess (vtcombo, single-process development stack)",execStart:nt("vtcombo",[`${ve}/vtcombo`,`--cell ${t}`,`--proto-topo ${oe(s)}`,`--mysql-server-port ${r}`,"--mysql-server-bind-address 127.0.0.1","--mysql-auth-server-impl none","--start-mysql",`--port ${zr}`,`--grpc-port ${Ft}`])})}function Hi(){return st({description:"etcd (Vitess topology store)",execStart:nt("etcd",[`${ve}/etcd`,`--data-dir ${Re}/etcd`,`--listen-client-urls http://127.0.0.1:${Bt}`,`--advertise-client-urls http://127.0.0.1:${Bt}`]),execStartPre:[`+/bin/mkdir -p ${Re}/etcd`,`+/bin/chown ${fe}:${fe} ${Re}/etcd`]})}function Wr(e){return["--topo-implementation etcd2",`--topo-global-server-address ${e.etcdEndpoint??`http://127.0.0.1:${Bt}`}`,"--topo-global-root /vitess/global"]}function ki(e){let t=!e.etcdEndpoint;return st({description:"Vitess vtctld (control plane)",after:t?["vitess-etcd.service"]:[],requires:t?["vitess-etcd.service"]:[],execStart:nt("vtctld",[`${ve}/vtctld`,...Wr(e),`--cell ${e.cell??"zone1"}`,"--service-map grpc-vtctl,grpc-vtctld",`--grpc-port ${Ft}`,`--port ${Ft+1}`])})}function Ni(e,t,r){let n=e.cell??"zone1";return st({description:`Vitess vttablet (${t}/${r})`,after:["vitess-vtctld.service","vitess-mysqlctld.service"],requires:["vitess-mysqlctld.service"],execStart:nt("vttablet",[`${ve}/vttablet`,...Wr(e),`--tablet-path ${n}-${String(Gr).padStart(10,"0")}`,`--init-keyspace ${t}`,`--init-shard ${r}`,"--init-tablet-type replica",`--service-map ${oe("grpc-queryservice,grpc-tabletmanager,grpc-updatestream")}`,`--port ${jn}`,`--grpc-port ${jn+1}`,`--db-port ${e.mysqlPort??3306}`,`--mycnf-mysql-port ${e.mysqlPort??3306}`])})}function Mi(e){return st({description:"Vitess mysqlctld (managed mysqld)",execStart:nt("mysqlctld",[`${ve}/mysqlctld`,`--tablet-uid ${Gr}`,`--mysql-port ${e.mysqlPort??3306}`,'--init-db-sql-file "$VTROOT/config/init_db.sql"',"--wait-time 2m"]),execStartPre:[`+/bin/mkdir -p ${Re}`,`+/bin/chown ${fe}:${fe} ${Re}`]})}var es="/etc/vitess/auth.json",$t="/var/lib/vitess/vtgate-auth.sha256";function Fi(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 ${$t} ] && [ "$(cat ${$t})" = "$VTESS_VTGATE_AUTH_SHA" ]; then VTESS_VTGATE_AUTH_CHANGED=0; fi`,`install -o ${fe} -g ${fe} -m 0600 "$VTESS_AUTH_TMP" ${es}`,'rm -f "$VTESS_AUTH_TMP"']}function Bi(e){let t=e.cell??"zone1";return st({description:"Vitess vtgate (query router)",after:["vitess-vtctld.service"],execStart:nt("vtgate",[`${ve}/vtgate`,...Wr(e),`--cell ${t}`,`--cells-to-watch ${t}`,"--tablet-types-to-wait PRIMARY,REPLICA",`--service-map ${oe("grpc-vtgateservice")}`,`--mysql-server-port ${e.vtgatePort??jr}`,`--mysql-server-bind-address ${e.bindAddress??"127.0.0.1"}`,"--mysql-auth-server-impl static",`--mysql-auth-server-static-file ${es}`,`--port ${zr}`,`--grpc-port ${zr+1}`])})}function Ki(e){let t=e.cell??"zone1",r=e.etcdEndpoint??`http://127.0.0.1:${Bt}`,n=`${ve}/vtctldclient --server 127.0.0.1:${Ft}`,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 ${oe(t)}; then`,` ${n} AddCellInfo --root ${oe(`/vitess/${t}`)} --server-address ${oe(r)} ${oe(t)}`,"fi"];for(let i of e.keyspaces??[]){let a=i.sharded?" --sharded":"";s.push(`if ! ${n} GetKeyspace ${oe(i.name)} >/dev/null 2>&1; then`,` ${n} CreateKeyspace${a} ${oe(i.name)}`,"fi");let c=`${t}-${String(Gr).padStart(10,"0")}`;for(let u of i.sharded?["-80","80-"]:["0"]){let m=`${i.name}/${u}`;s.push("for i in $(seq 1 90); do",` if ${n} GetShard ${oe(m)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then break; fi`,` ${n} PlannedReparentShard ${oe(m)} --new-primary ${oe(c)} >/dev/null 2>&1 && break`,` ${n} InitShardPrimary --force ${oe(m)} ${oe(c)} >/dev/null 2>&1 && break`," sleep 2","done",`if ! ${n} GetShard ${oe(m)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then`,` echo "no primary could be elected for ${m}" >&2; exit 1`,"fi")}s.push(`${n} RebuildKeyspaceGraph ${oe(i.name)} >/dev/null`)}return s}function qn(e){let t=e.vtgatePort??jr;return["for i in $(seq 1 60); do",` if (cd ${T} && eval "$(pantry env 2>/dev/null)"; MYSQL_PWD=${oe(e.password??"")} ${ve}/mysql -h 127.0.0.1 -P ${t} -u ${oe(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 Js(e){if(!bt(e))return[];let t=Oi(e),r=t.mode==="combo";qr.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",...Te(Di(t)),`VT_MYSQL_LIB="$(dirname "$(dirname "$(readlink -f ${ve}/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 ${fe} >/dev/null 2>&1 || useradd --system --home-dir ${Re} --shell /usr/sbin/nologin ${fe}`,`mkdir -p ${Re}`,`chown -R ${fe}:${fe} ${Re}`];if(r)return n.push(...Gn("vitess-vtcombo",Ui(t)),...Vn(),"systemctl daemon-reload","systemctl enable --now vitess-vtcombo.service",...qn(t)),n;n.push(...Fi(t));let s=[];if(!t.etcdEndpoint)s.push(["vitess-etcd",Hi()]);s.push(["vitess-vtctld",ki(t)],["vitess-mysqlctld",Mi(t)],["vitess-vtgate",Bi(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")}`,Ni(t,i.name,a)]);for(let[i,a]of s)n.push(...Gn(i,a));n.push(...Vn()),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" > ${$t}; chown ${fe}:${fe} ${$t}; chmod 0600 ${$t}; fi`,...Ki(t),...qn(t)),n}var Vi=new Set(["singlestore","vitess"]);function Xn(e){if(e?.engine&&Vi.has(e.engine))return!1;return!e?.host||e.host==="127.0.0.1"||e.host==="localhost"}function Kt(e,t="psql"){let r=e?.port??5432;if(Xn(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 Oe(e){return e===!0||typeof e==="object"&&e!=null}function Gi(e){let t=[],r=[];if(Oe(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(Oe(e.mariadb))t.push(yt.mariadb),r.push("mariadb");if(Oe(e.postgres))t.push("postgresql.org"),r.push("postgres");if(Oe(e.redis))t.push("redis.io"),r.push("redis");if(Oe(e.memcached))t.push("memcached.org"),r.push("memcached");if(Oe(e.meilisearch))t.push("meilisearch.com"),r.push("meilisearch");return{packages:t,services:r}}function Vt(e={},t={}){let r=Gi(e),n=Js(e.vitess),s=t.mail?Kn(t.mail):[];if(r.packages.length===0)return[...n,...s];return[...Te(r.packages),...Mt(r.services),...n,...s]}function ot(e,t={}){if(!e?.name)return[];if(!Xn(e))return[];let r=e.name,n=e.username||r,s=e.password||"",i=Oe(t.postgres)||e.engine==="postgres",a=Oe(t.mariadb)||e.engine==="mariadb",c=Oe(t.mysql)||e.engine==="mysql";if(i&&!c&&!a){let S=(O)=>`"${O.replace(/"/g,'""')}"`,y=(O)=>`'${O.replace(/'/g,"''")}'`,C=(O,I)=>["DO $$ BEGIN",` IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${y(O)}) THEN`,` CREATE ROLE ${S(O)} LOGIN PASSWORD ${y(I)};`," ELSE",` ALTER ROLE ${S(O)} LOGIN PASSWORD ${y(I)};`," END IF;","END $$;"],A=(O)=>{let I=O.databases&&O.databases.length>0?O.databases:[r],W=[];for(let H of I)if(O.access==="readonly")W.push(`GRANT CONNECT ON DATABASE ${S(H)} TO ${S(O.username)};`,`\\connect ${S(H)}`,`GRANT USAGE ON SCHEMA public TO ${S(O.username)};`,`GRANT SELECT ON ALL TABLES IN SCHEMA public TO ${S(O.username)};`,`ALTER DEFAULT PRIVILEGES FOR ROLE ${S(n)} IN SCHEMA public GRANT SELECT ON TABLES TO ${S(O.username)};`,"\\connect postgres");else W.push(`GRANT ALL PRIVILEGES ON DATABASE ${S(H)} TO ${S(O.username)};`);return W},x=e.users||[],L=e.port??5432;return[Ee(),`for i in $(seq 1 30); do pg_isready -p ${L} -q && break; sleep 2; done`,`${Kt(e)} <<'TS_CLOUD_PG_EOF'`,...C(n,s),`SELECT 'CREATE DATABASE ${S(r)} OWNER ${S(n)}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = ${y(r)})\\gexec`,...x.flatMap((O)=>[...C(O.username,O.password),...A(O)]),"TS_CLOUD_PG_EOF",...qi(e)]}let u=a?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock",m=(S)=>S.replace(/`/g,"``"),f=(S)=>S.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),v=(S)=>{let y=S.databases&&S.databases.length>0?S.databases:[r],C=S.access==="readonly"?"SELECT":"ALL PRIVILEGES",A=[`CREATE USER IF NOT EXISTS '${f(S.username)}'@'%' IDENTIFIED BY '${f(S.password)}';`,`CREATE USER IF NOT EXISTS '${f(S.username)}'@'localhost' IDENTIFIED BY '${f(S.password)}';`,`ALTER USER '${f(S.username)}'@'%' IDENTIFIED BY '${f(S.password)}';`,`ALTER USER '${f(S.username)}'@'localhost' IDENTIFIED BY '${f(S.password)}';`];for(let x of y)A.push(`GRANT ${C} ON \`${m(x)}\`.* TO '${f(S.username)}'@'%';`,`GRANT ${C} ON \`${m(x)}\`.* TO '${f(S.username)}'@'localhost';`);return A},_=e.users||[];return[Ee(),`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 \`${m(r)}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`,...v({username:n,password:s}),..._.flatMap(v),"FLUSH PRIVILEGES;","TS_CLOUD_SQL_EOF"]}function qi(e){return[`${Kt(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 ts(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 Yr="/var/backups/ts-cloud",Wi="/etc/ts-cloud/backups.config.ts",rs="/etc/cron.d/ts-cloud-backups",Nr="/usr/local/bin/ts-cloud-backup.sh";function Yi(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(`
17
+ `)}function Gn(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_VITESS_UNIT_EOF'`,t,"TS_CLOUD_VITESS_UNIT_EOF"]}function Ui(e){let t=e.cell??"zone1",r=e.vtgatePort??jr,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 st({description:"Vitess (vtcombo, single-process development stack)",execStart:nt("vtcombo",[`${ve}/vtcombo`,`--cell ${t}`,`--proto-topo ${oe(s)}`,`--mysql-server-port ${r}`,"--mysql-server-bind-address 127.0.0.1","--mysql-auth-server-impl none","--start-mysql",`--port ${zr}`,`--grpc-port ${Ft}`])})}function Hi(){return st({description:"etcd (Vitess topology store)",execStart:nt("etcd",[`${ve}/etcd`,`--data-dir ${Re}/etcd`,`--listen-client-urls http://127.0.0.1:${Bt}`,`--advertise-client-urls http://127.0.0.1:${Bt}`]),execStartPre:[`+/bin/mkdir -p ${Re}/etcd`,`+/bin/chown ${fe}:${fe} ${Re}/etcd`]})}function Wr(e){return["--topo-implementation etcd2",`--topo-global-server-address ${e.etcdEndpoint??`http://127.0.0.1:${Bt}`}`,"--topo-global-root /vitess/global"]}function ki(e){let t=!e.etcdEndpoint;return st({description:"Vitess vtctld (control plane)",after:t?["vitess-etcd.service"]:[],requires:t?["vitess-etcd.service"]:[],execStart:nt("vtctld",[`${ve}/vtctld`,...Wr(e),`--cell ${e.cell??"zone1"}`,"--service-map grpc-vtctl,grpc-vtctld",`--grpc-port ${Ft}`,`--port ${Ft+1}`])})}function Ni(e,t,r){let n=e.cell??"zone1";return st({description:`Vitess vttablet (${t}/${r})`,after:["vitess-vtctld.service","vitess-mysqlctld.service"],requires:["vitess-mysqlctld.service"],execStart:nt("vttablet",[`${ve}/vttablet`,...Wr(e),`--tablet-path ${n}-${String(Gr).padStart(10,"0")}`,`--init-keyspace ${t}`,`--init-shard ${r}`,"--init-tablet-type replica",`--service-map ${oe("grpc-queryservice,grpc-tabletmanager,grpc-updatestream")}`,`--port ${jn}`,`--grpc-port ${jn+1}`,`--db-port ${e.mysqlPort??3306}`,`--mycnf-mysql-port ${e.mysqlPort??3306}`])})}function Mi(e){return st({description:"Vitess mysqlctld (managed mysqld)",execStart:nt("mysqlctld",[`${ve}/mysqlctld`,`--tablet-uid ${Gr}`,`--mysql-port ${e.mysqlPort??3306}`,'--init-db-sql-file "$VTROOT/config/init_db.sql"',"--wait-time 2m"]),execStartPre:[`+/bin/mkdir -p ${Re}`,`+/bin/chown ${fe}:${fe} ${Re}`]})}var es="/etc/vitess/auth.json",$t="/var/lib/vitess/vtgate-auth.sha256";function Fi(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 ${$t} ] && [ "$(cat ${$t})" = "$VTESS_VTGATE_AUTH_SHA" ]; then VTESS_VTGATE_AUTH_CHANGED=0; fi`,`install -o ${fe} -g ${fe} -m 0600 "$VTESS_AUTH_TMP" ${es}`,'rm -f "$VTESS_AUTH_TMP"']}function Bi(e){let t=e.cell??"zone1";return st({description:"Vitess vtgate (query router)",after:["vitess-vtctld.service"],execStart:nt("vtgate",[`${ve}/vtgate`,...Wr(e),`--cell ${t}`,`--cells-to-watch ${t}`,"--tablet-types-to-wait PRIMARY,REPLICA",`--service-map ${oe("grpc-vtgateservice")}`,`--mysql-server-port ${e.vtgatePort??jr}`,`--mysql-server-bind-address ${e.bindAddress??"127.0.0.1"}`,"--mysql-auth-server-impl static",`--mysql-auth-server-static-file ${es}`,`--port ${zr}`,`--grpc-port ${zr+1}`])})}function Ki(e){let t=e.cell??"zone1",r=e.etcdEndpoint??`http://127.0.0.1:${Bt}`,n=`${ve}/vtctldclient --server 127.0.0.1:${Ft}`,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 ${oe(t)}; then`,` ${n} AddCellInfo --root ${oe(`/vitess/${t}`)} --server-address ${oe(r)} ${oe(t)}`,"fi"];for(let i of e.keyspaces??[]){let a=i.sharded?" --sharded":"";s.push(`if ! ${n} GetKeyspace ${oe(i.name)} >/dev/null 2>&1; then`,` ${n} CreateKeyspace${a} ${oe(i.name)}`,"fi");let c=`${t}-${String(Gr).padStart(10,"0")}`;for(let u of i.sharded?["-80","80-"]:["0"]){let m=`${i.name}/${u}`;s.push("for i in $(seq 1 90); do",` if ${n} GetShard ${oe(m)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then break; fi`,` ${n} PlannedReparentShard ${oe(m)} --new-primary ${oe(c)} >/dev/null 2>&1 && break`,` ${n} InitShardPrimary --force ${oe(m)} ${oe(c)} >/dev/null 2>&1 && break`," sleep 2","done",`if ! ${n} GetShard ${oe(m)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then`,` echo "no primary could be elected for ${m}" >&2; exit 1`,"fi")}s.push(`${n} RebuildKeyspaceGraph ${oe(i.name)} >/dev/null`)}return s}function qn(e){let t=e.vtgatePort??jr;return["for i in $(seq 1 60); do",` if (cd ${T} && eval "$(pantry env 2>/dev/null)"; MYSQL_PWD=${oe(e.password??"")} ${ve}/mysql -h 127.0.0.1 -P ${t} -u ${oe(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 Js(e){if(!bt(e))return[];let t=Oi(e),r=t.mode==="combo";qr.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",...Te(Di(t)),`VT_MYSQL_LIB="$(dirname "$(dirname "$(readlink -f ${ve}/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 ${fe} >/dev/null 2>&1 || useradd --system --home-dir ${Re} --shell /usr/sbin/nologin ${fe}`,`mkdir -p ${Re}`,`chown -R ${fe}:${fe} ${Re}`];if(r)return n.push(...Gn("vitess-vtcombo",Ui(t)),...Vn(),"systemctl daemon-reload","systemctl enable --now vitess-vtcombo.service",...qn(t)),n;n.push(...Fi(t));let s=[];if(!t.etcdEndpoint)s.push(["vitess-etcd",Hi()]);s.push(["vitess-vtctld",ki(t)],["vitess-mysqlctld",Mi(t)],["vitess-vtgate",Bi(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")}`,Ni(t,i.name,a)]);for(let[i,a]of s)n.push(...Gn(i,a));n.push(...Vn()),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" > ${$t}; chown ${fe}:${fe} ${$t}; chmod 0600 ${$t}; fi`,...Ki(t),...qn(t)),n}var Vi=new Set(["singlestore","vitess"]);function Xn(e){if(e?.engine&&Vi.has(e.engine))return!1;return!e?.host||e.host==="127.0.0.1"||e.host==="localhost"}function Kt(e,t="psql"){let r=e?.port??5432;if(Xn(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 Oe(e){return e===!0||typeof e==="object"&&e!=null}function Gi(e){let t=[],r=[];if(Oe(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(Oe(e.mariadb))t.push(yt.mariadb),r.push("mariadb");if(Oe(e.postgres))t.push("postgresql.org"),r.push("postgres");if(Oe(e.redis))t.push("redis.io"),r.push("redis");if(Oe(e.memcached))t.push("memcached.org"),r.push("memcached");if(Oe(e.meilisearch))t.push("meilisearch.com"),r.push("meilisearch");return{packages:t,services:r}}function Vt(e={},t={}){let r=Gi(e),n=Js(e.vitess),s=t.mail?Kn(t.mail):[];if(r.packages.length===0)return[...n,...s];return[...Te(r.packages),...Mt(r.services),...n,...s]}function ot(e,t={}){if(!e?.name)return[];if(!Xn(e))return[];let r=e.name,n=e.username||r,s=e.password||"",i=Oe(t.postgres)||e.engine==="postgres",a=Oe(t.mariadb)||e.engine==="mariadb",c=Oe(t.mysql)||e.engine==="mysql";if(i&&!c&&!a){let S=(O)=>`"${O.replace(/"/g,'""')}"`,y=(O)=>`'${O.replace(/'/g,"''")}'`,C=(O,I)=>["DO $$ BEGIN",` IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${y(O)}) THEN`,` CREATE ROLE ${S(O)} LOGIN PASSWORD ${y(I)};`," ELSE",` ALTER ROLE ${S(O)} LOGIN PASSWORD ${y(I)};`," END IF;","END $$;"],A=(O)=>{let I=O.databases&&O.databases.length>0?O.databases:[r],W=[];for(let k of I)if(O.access==="readonly")W.push(`GRANT CONNECT ON DATABASE ${S(k)} TO ${S(O.username)};`,`\\connect ${S(k)}`,`GRANT USAGE ON SCHEMA public TO ${S(O.username)};`,`GRANT SELECT ON ALL TABLES IN SCHEMA public TO ${S(O.username)};`,`ALTER DEFAULT PRIVILEGES FOR ROLE ${S(n)} IN SCHEMA public GRANT SELECT ON TABLES TO ${S(O.username)};`,"\\connect postgres");else W.push(`GRANT ALL PRIVILEGES ON DATABASE ${S(k)} TO ${S(O.username)};`);return W},x=e.users||[],H=e.port??5432;return[Ee(),`for i in $(seq 1 30); do pg_isready -p ${H} -q && break; sleep 2; done`,`${Kt(e)} <<'TS_CLOUD_PG_EOF'`,...C(n,s),`SELECT 'CREATE DATABASE ${S(r)} OWNER ${S(n)}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = ${y(r)})\\gexec`,...x.flatMap((O)=>[...C(O.username,O.password),...A(O)]),"TS_CLOUD_PG_EOF",...qi(e)]}let u=a?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock",m=(S)=>S.replace(/`/g,"``"),f=(S)=>S.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),v=(S)=>{let y=S.databases&&S.databases.length>0?S.databases:[r],C=S.access==="readonly"?"SELECT":"ALL PRIVILEGES",A=[`CREATE USER IF NOT EXISTS '${f(S.username)}'@'%' IDENTIFIED BY '${f(S.password)}';`,`CREATE USER IF NOT EXISTS '${f(S.username)}'@'localhost' IDENTIFIED BY '${f(S.password)}';`,`ALTER USER '${f(S.username)}'@'%' IDENTIFIED BY '${f(S.password)}';`,`ALTER USER '${f(S.username)}'@'localhost' IDENTIFIED BY '${f(S.password)}';`];for(let x of y)A.push(`GRANT ${C} ON \`${m(x)}\`.* TO '${f(S.username)}'@'%';`,`GRANT ${C} ON \`${m(x)}\`.* TO '${f(S.username)}'@'localhost';`);return A},_=e.users||[];return[Ee(),`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 \`${m(r)}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`,...v({username:n,password:s}),..._.flatMap(v),"FLUSH PRIVILEGES;","TS_CLOUD_SQL_EOF"]}function qi(e){return[`${Kt(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 ts(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 Yr="/var/backups/ts-cloud",Wi="/etc/ts-cloud/backups.config.ts",rs="/etc/cron.d/ts-cloud-backups",Nr="/usr/local/bin/ts-cloud-backup.sh";function Yi(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 Xi(e,t){let r=e?Yi(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: '${Yr}',`," retention: {",` count: ${t.retentionCount??5},`,` maxAge: ${t.retentionDays??30},`," },"," databases: [",...r?[r]:[]," ],",...n,"}","","export default config",""].join(`
19
19
  `)}function Gt(e){let{database:t,backups:r}=e;if(!r.enabled)return[];let n=r.schedule||"0 2 * * *",s=Xi(t,r);return["export DEBIAN_FRONTEND=noninteractive",`mkdir -p /etc/ts-cloud ${Yr}`,"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 > ${Wi} <<'TS_CLOUD_BACKUP_CFG_EOF'`,s.replace(/\n$/,""),"TS_CLOUD_BACKUP_CFG_EOF",`cat > ${Nr} <<'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 ${Nr}`,`cat > ${rs} <<'TS_CLOUD_BACKUP_CRON_EOF'`,`${n} root ${Nr} >> /var/log/ts-cloud-backup.log 2>&1`,"TS_CLOUD_BACKUP_CRON_EOF",`chmod 644 ${rs}`]}function Qi(e){return e==="mariadb"?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock"}function xg(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 ${Yr} -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?`${Kt(e)} -d "${r}"`:`mysql --socket=${Qi(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 Zi(e){return`/etc/ts-cloud/${e}-upgrade.env`}function ea(e){return`${e}-upgrade`}function Xs(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:m="4h",args:f=[]}=n,v=ea(s),_=Zi(s),S=[`--path ${i}`,`--service ${s}`,...c==="canary"?["--canary"]:[],...f].join(" ");t.push(`if [ ! -f ${_} ]; then`,` cat > ${_} <<'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 ${_}`,`cat > /etc/systemd/system/${v}.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=-${_}`,`ExecStart=/bin/sh -c 'if [ "\${ENABLED:-true}" != "true" ]; then echo "auto-update disabled via ${_}"; exit 0; fi; exec ${i} ${a} ${S} $ARGS'`,"TS_CLOUD_APPUPD_SVC_EOF",`cat > /etc/systemd/system/${v}.timer <<'TS_CLOUD_APPUPD_TMR_EOF'`,"[Unit]",`Description=Scheduled ${s} update check`,"","[Timer]",`OnCalendar=${u}`,`RandomizedDelaySec=${m}`,"Persistent=true","","[Install]","WantedBy=timers.target","TS_CLOUD_APPUPD_TMR_EOF"),r.push(`systemctl enable --now ${v}.timer`)}if(r.length===0)return[];return[...t,"systemctl daemon-reload",...r]}function Ue(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 ns=[["nginx",80],["https",443],["phpFpm",9074],["mysql",3306],["postgres",5432],["redis",6379],["meilisearch",7700],["typesense",8108],["smtp",25]];function ta(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 xe(e=!0){let{enabled:t,cpuLoadPerCore:r,memPercent:n,diskPercent:s,bandwidthTb:i,bandwidthPercent:a}=ta(e);if(!t)return[];let c=Math.round(i*1000000000000),u=ns.map(([y,C])=>`SVC_${y.toUpperCase()}=$(probe ${C})`),m=ns.map(([y])=>`"${y}":"$SVC_${y.toUpperCase()}"`).join(","),f=(typeof e==="object"?e.filesystems:void 0)??["/"];if(!f.length)throw Error("monitoring.filesystems must include at least one path");let v=f.map((y)=>typeof y==="string"?{path:y,requiredMount:!1}:y);for(let y of v)if(y.path!=="/"&&(!y.path.startsWith("/")||!y.path.slice(1).split("/").every((C)=>/^[\w-]+$/.test(C))))throw Error(`Invalid monitoring filesystem path: ${y.path}`);let _=v.flatMap((y,C)=>[`DISK_${C}_MOUNTED=true; DISK_${C}_PCT=null`,...y.requiredMount?[`if ! mountpoint -q '${y.path}'; then DISK_${C}_MOUNTED=false; DISK_ALERTS="$DISK_ALERTS missing-mount=${y.path}"; ALERT_KEY="$ALERT_KEY mount:${y.path}"; fi`]:[],`if [ "$DISK_${C}_MOUNTED" = true ]; then`,` DISK_${C}_PCT=$(df -Pk '${y.path}' 2>/dev/null | awk 'NR==2{gsub("%","",$5);print $5}')`,` if [[ "$DISK_${C}_PCT" =~ ^[0-9]+$ ]]; then`,` [ "$DISK_${C}_PCT" -le "$DISK_PCT" ] || DISK_PCT=$DISK_${C}_PCT`,` if [ "$DISK_${C}_PCT" -ge ${s} ]; then DISK_ALERTS="$DISK_ALERTS disk=${y.path}:$DISK_${C}_PCT%"; ALERT_KEY="$ALERT_KEY disk:${y.path}"; fi`,` else DISK_${C}_PCT=null; DISK_ALERTS="$DISK_ALERTS unreadable-disk=${y.path}"; ALERT_KEY="$ALERT_KEY unreadable:${y.path}"; fi`,"fi"]),S=v.map((y,C)=>`{"path":"${y.path}","usedPercent":$DISK_${C}_PCT,"mounted":$DISK_${C}_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}')
@@ -134,21 +134,21 @@ ${y.join(`
134
134
  `)}
135
135
  `}return _+=`
136
136
  echo "ts-cloud bootstrap complete — instance is ready for site deploys"
137
- `,_}var hs="/aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id";function Ss(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 Xe(b(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 _s(e,t){let r={...e.infrastructure?.compute,proxy:w(e,{environment:t})},n=Ye(e,{environment:t}),s=r.proxy?.engine==="rpx"?G({proxy:r.proxy,config:B(e.sites??{},{proxy:r.proxy,slug:e.project.slug,mail:b(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 vs(e){return Buffer.from(e,"utf8").toString("base64")}function ys(e){return e.infrastructure?.compute?.image??null}function Qt(e,t){return`${e}-${t}-app-sg`}function tn(e,t,r="app"){return[{Key:"Project",Value:e},{Key:"Environment",Value:t},{Key:"Role",Value:r},{Key:"ManagedBy",Value:"ts-cloud"}]}function wa(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 $s(e,t){let r=Qt(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 wa(n.Tags,t.slug,t.environment);return!!t.vpcId&&n.VpcId===t.vpcId})}function Pa(e){try{let t=bs(Ca(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 Br{name="aws";usesCloudFormation=!0;region;ec2Client;cfnClient;constructor(e={}){this.region=e.region||"us-east-1",this.ec2Client=e.ec2Client??((t)=>new Qr(t)),this.cfnClient=e.cfnClient??((t)=>new h(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 V=c[0];return{appInstanceId:V.id,appPublicIp:V.publicIp,appPublicIpv6:V.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}let u=ys(t);if(!u){if(u=(await new Be(n).getParameter({Name:hs})).Parameter?.Value??null,!u)throw Error("Could not resolve the Ubuntu 24.04 AMI from SSM")}let m=await a.describeVpcs(),f=(m.Vpcs||[]).find((V)=>V.IsDefault)||(m.Vpcs||[])[0];if(!f?.VpcId)throw Error("No VPC found to launch the instance into");let v=(await a.describeSubnets({Filters:[{Name:"vpc-id",Values:[f.VpcId]}]})).Subnets||[],_=v.find((V)=>V.MapPublicIpOnLaunch)||v[0],S=_?.SubnetId;if(!_?.MapPublicIpOnLaunch)console.warn("ts-cloud: no public subnet found; the instance may not get a public IP (deploys/SSL need one).");let y=Qt(s,r),A=(await a.describeSecurityGroups({Filters:[{Name:"group-name",Values:[y]},{Name:"vpc-id",Values:[f.VpcId]}]})).SecurityGroups?.[0]?.GroupId;if(!A)A=(await a.createSecurityGroup({GroupName:y,Description:`ts-cloud ${s}/${r} app`,VpcId:f.VpcId,TagSpecifications:[{ResourceType:"security-group",Tags:tn(s,r)}]})).GroupId;let x=Ss(t,r);await a.authorizeSecurityGroupIngress({GroupId:A,IpPermissions:x.map((V)=>({IpProtocol:V.protocol,FromPort:V.port,ToPort:V.port,IpRanges:[{CidrIp:V.cidr}]}))}).catch((V)=>{if(!/InvalidPermission\.Duplicate/.test(V instanceof Error?V.message:""))throw V});let L=vs(_s(t,r)),O=i.server?.instanceType||"t3.small",W=(await a.runInstances({ImageId:u,InstanceType:O,MinCount:1,MaxCount:1,SecurityGroupIds:A?[A]:void 0,SubnetId:S,UserData:L,IamInstanceProfile:i.server?.iamInstanceProfile?{Name:i.server.iamInstanceProfile}:void 0,TagSpecifications:[{ResourceType:"instance",Tags:[{Key:"Name",Value:`${s}-${r}-app`},...tn(s,r)]}]})).Instances?.[0]?.InstanceId;if(!W)throw Error("RunInstances did not return an instance id");let H=await a.waitForInstanceState(W,"running");if(!H)throw Error(`Instance ${W} did not reach 'running' before timeout`);return{appInstanceId:W,appPublicIp:H.PublicIpAddress,appPublicIpv6:De(H.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),m;if(u.length>0)m=(await i.describeInstances({InstanceIds:u}).catch(()=>({Reservations:[]}))).Reservations?.flatMap((C)=>C.Instances??[]).find((C)=>C.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 f=Qt(n,r),v=[{Name:"group-name",Values:[f]}];if(m)v.push({Name:"vpc-id",Values:[m]});let _=await i.describeSecurityGroups({Filters:v}).catch(()=>({SecurityGroups:[]})),S=$s(_.SecurityGroups??[],{slug:n,environment:r,vpcId:m});if(S?.GroupId)for(let y=0;y<10;y++)try{await i.deleteSecurityGroup(S.GroupId),a.push(`security group ${f}`);break}catch{await new Promise((C)=>setTimeout(C,3000))}return{destroyed:a}}async getComputeOutputs(e){let t=this.resolveRegion(e.config),r=p(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:bs(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=Pa(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((f)=>setTimeout(f,3000));try{if(c=await e.listCommandInvocations({CommandId:t,Details:!0}),c.length>=r&&c.every((v)=>a.has(v.Status||"")))break}catch{}}let u=c.map((f)=>({instanceId:f.InstanceId,status:f.Status||"Unknown",output:f.StandardOutputContent,error:f.StandardErrorContent})),m=u.length>0&&u.every((f)=>f.status==="Success");return{success:m,instanceCount:u.length,perInstance:u,error:m?void 0:zt(u,"One or more SSM command invocations failed")}}}import{execFileSync as pc,execSync as Ks}from"node:child_process";import{createHash as dc,randomUUID as js}from"node:crypto";import{createReadStream as mc,existsSync as fc,readFileSync as gc}from"node:fs";async function Ts(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 m=(P,D)=>{try{return JSON.parse(r.readFileSync(P,"utf8"))}catch(N){if(N.code==="ENOENT")return D;throw N}},f=(P,D)=>{r.mkdirSync(n.dirname(P),{recursive:!0});let N=`${P}.${process.pid}.tmp`;r.writeFileSync(N,`${JSON.stringify(D,null,2)}
139
- `,{mode:420}),r.renameSync(N,P)},v=(P,D)=>s.execFileSync(P,D,{encoding:"utf8",maxBuffer:16777216}),_=(P,D)=>{let N=s.spawnSync(P,D,{encoding:"utf8"});return N.status===0?N.stdout.trim():""},S=(P)=>!!_("findmnt",["-n","--mountpoint",P]),y=(P,D)=>{try{let N=r.statSync(P),R=r.statSync(D);return N.dev===R.dev&&N.ino===R.ino}catch{return!1}},C=m("/var/lib/ts-cloud/compute-storage-state.json",{entries:[]}),A=e.deploymentStorage,x=e.volumes.find((P)=>P.key===A?.volume),L=(P,D)=>{if(!x)return[];let N=[];for(let R of r.readdirSync(e.webRoot,{withFileTypes:!0})){if(!R.isDirectory()||R.isSymbolicLink())continue;let q=n.join(e.webRoot,R.name);if(P&&q!==P&&q!==n.join(e.webRoot,`${D}-shared`))continue;for(let k of["releases",...A?.includeBackups===!1?[]:["backups"]]){let Y=n.join(q,k);if(!r.existsSync(Y)||!r.lstatSync(Y).isDirectory())continue;N.push({source:Y,destination:n.join(x.mountPath,k,R.name)})}}return N},O=(P)=>{try{return S(P.mountPath)&&r.statSync(P.mountPath).dev===r.statSync(P.device).rdev}catch{return!1}},I=(P)=>{let D=r.statfsSync(P),N=(D.blocks-D.bfree)*D.bsize,R=D.bavail*D.bsize;return{path:P,sizeBytes:D.blocks*D.bsize,usedBytes:N,availableBytes:R,usedPercent:Math.ceil(100*N/(N+R))}},W=()=>{let P=[],D=[I("/")];for(let R of e.volumes)if(!O(R))P.push(`missing or incorrect volume mount: ${R.mountPath}`);else D.push(I(R.mountPath));for(let R of C.entries)if(!S(R.source)||!y(R.source,R.destination))P.push(`missing deployment mount: ${R.source}`);let N=new Set(C.entries.map((R)=>R.source));for(let R of L())if(!N.has(R.source))P.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:D,mounts:C.entries.length,problems:P}};if(u==="plan")return console.log(JSON.stringify({volumes:e.volumes,entries:L(),state:C},null,2));if(u==="status"||u==="check"){let P=W();if(u==="check"){f("/var/lib/ts-cloud/compute-storage-status.json",P);let D="/var/lib/ts-cloud/compute-storage-alert.json",N=m(D,{problems:[]});if(JSON.stringify(N.problems)!==JSON.stringify(P.problems)){let R=P.problems.join("; ")||"all configured mounts are healthy",q=`${P.problems.length?"Storage alert":"Storage recovered"} on ${_("hostname",[])}: ${R}`;v("/usr/local/bin/ts-cloud-notify",[q.length>1800?`${q.slice(0,1600)}... Full report: /var/lib/ts-cloud/compute-storage-status.json`:q])}f(D,{problems:P.problems,timestamp:P.timestamp})}if(console.log(JSON.stringify(P)),P.problems.length)process.exitCode=1;return P}if(process.getuid?.()!==0)throw Error("Compute storage changes require root");let H=()=>{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 q=[];for(let X of e.volumes){let J=v("blkid",["-s","UUID","-o","value",X.device]).trim();if(!J)throw Error(`Volume ${X.name} has no filesystem UUID`);q.push(`UUID=${J} ${X.mountPath} ext4 defaults,noatime,nodev,nosuid,nofail,x-systemd.device-timeout=30s 0 2`)}for(let X of C.entries)q.push(`${X.destination} ${X.source} none bind,nofail,x-systemd.requires-mounts-for=${x.mountPath} 0 0`);let k=`# BEGIN ts-cloud compute storage
137
+ `,_}var hs="/aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id";function Ss(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 Xe(b(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 _s(e,t){let r={...e.infrastructure?.compute,proxy:w(e,{environment:t})},n=Ye(e,{environment:t}),s=r.proxy?.engine==="rpx"?G({proxy:r.proxy,config:B(e.sites??{},{proxy:r.proxy,slug:e.project.slug,mail:b(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 vs(e){return Buffer.from(e,"utf8").toString("base64")}function ys(e){return e.infrastructure?.compute?.image??null}function Qt(e,t){return`${e}-${t}-app-sg`}function tn(e,t,r="app"){return[{Key:"Project",Value:e},{Key:"Environment",Value:t},{Key:"Role",Value:r},{Key:"ManagedBy",Value:"ts-cloud"}]}function wa(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 $s(e,t){let r=Qt(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 wa(n.Tags,t.slug,t.environment);return!!t.vpcId&&n.VpcId===t.vpcId})}function Pa(e){try{let t=bs(Ca(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 Br{name="aws";usesCloudFormation=!0;region;ec2Client;cfnClient;constructor(e={}){this.region=e.region||"us-east-1",this.ec2Client=e.ec2Client??((t)=>new Qr(t)),this.cfnClient=e.cfnClient??((t)=>new h(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 V=c[0];return{appInstanceId:V.id,appPublicIp:V.publicIp,appPublicIpv6:V.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}let u=ys(t);if(!u){if(u=(await new Be(n).getParameter({Name:hs})).Parameter?.Value??null,!u)throw Error("Could not resolve the Ubuntu 24.04 AMI from SSM")}let m=await a.describeVpcs(),f=(m.Vpcs||[]).find((V)=>V.IsDefault)||(m.Vpcs||[])[0];if(!f?.VpcId)throw Error("No VPC found to launch the instance into");let v=(await a.describeSubnets({Filters:[{Name:"vpc-id",Values:[f.VpcId]}]})).Subnets||[],_=v.find((V)=>V.MapPublicIpOnLaunch)||v[0],S=_?.SubnetId;if(!_?.MapPublicIpOnLaunch)console.warn("ts-cloud: no public subnet found; the instance may not get a public IP (deploys/SSL need one).");let y=Qt(s,r),A=(await a.describeSecurityGroups({Filters:[{Name:"group-name",Values:[y]},{Name:"vpc-id",Values:[f.VpcId]}]})).SecurityGroups?.[0]?.GroupId;if(!A)A=(await a.createSecurityGroup({GroupName:y,Description:`ts-cloud ${s}/${r} app`,VpcId:f.VpcId,TagSpecifications:[{ResourceType:"security-group",Tags:tn(s,r)}]})).GroupId;let x=Ss(t,r);await a.authorizeSecurityGroupIngress({GroupId:A,IpPermissions:x.map((V)=>({IpProtocol:V.protocol,FromPort:V.port,ToPort:V.port,IpRanges:[{CidrIp:V.cidr}]}))}).catch((V)=>{if(!/InvalidPermission\.Duplicate/.test(V instanceof Error?V.message:""))throw V});let H=vs(_s(t,r)),O=i.server?.instanceType||"t3.small",W=(await a.runInstances({ImageId:u,InstanceType:O,MinCount:1,MaxCount:1,SecurityGroupIds:A?[A]:void 0,SubnetId:S,UserData:H,IamInstanceProfile:i.server?.iamInstanceProfile?{Name:i.server.iamInstanceProfile}:void 0,TagSpecifications:[{ResourceType:"instance",Tags:[{Key:"Name",Value:`${s}-${r}-app`},...tn(s,r)]}]})).Instances?.[0]?.InstanceId;if(!W)throw Error("RunInstances did not return an instance id");let k=await a.waitForInstanceState(W,"running");if(!k)throw Error(`Instance ${W} did not reach 'running' before timeout`);return{appInstanceId:W,appPublicIp:k.PublicIpAddress,appPublicIpv6:De(k.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),m;if(u.length>0)m=(await i.describeInstances({InstanceIds:u}).catch(()=>({Reservations:[]}))).Reservations?.flatMap((C)=>C.Instances??[]).find((C)=>C.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 f=Qt(n,r),v=[{Name:"group-name",Values:[f]}];if(m)v.push({Name:"vpc-id",Values:[m]});let _=await i.describeSecurityGroups({Filters:v}).catch(()=>({SecurityGroups:[]})),S=$s(_.SecurityGroups??[],{slug:n,environment:r,vpcId:m});if(S?.GroupId)for(let y=0;y<10;y++)try{await i.deleteSecurityGroup(S.GroupId),a.push(`security group ${f}`);break}catch{await new Promise((C)=>setTimeout(C,3000))}return{destroyed:a}}async getComputeOutputs(e){let t=this.resolveRegion(e.config),r=p(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:bs(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=Pa(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((f)=>setTimeout(f,3000));try{if(c=await e.listCommandInvocations({CommandId:t,Details:!0}),c.length>=r&&c.every((v)=>a.has(v.Status||"")))break}catch{}}let u=c.map((f)=>({instanceId:f.InstanceId,status:f.Status||"Unknown",output:f.StandardOutputContent,error:f.StandardErrorContent})),m=u.length>0&&u.every((f)=>f.status==="Success");return{success:m,instanceCount:u.length,perInstance:u,error:m?void 0:zt(u,"One or more SSM command invocations failed")}}}import{execFileSync as pc,execSync as Ks}from"node:child_process";import{createHash as dc,randomUUID as js}from"node:crypto";import{createReadStream as mc,existsSync as fc,readFileSync as gc}from"node:fs";async function Ts(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 m=(P,D)=>{try{return JSON.parse(r.readFileSync(P,"utf8"))}catch(K){if(K.code==="ENOENT")return D;throw K}},f=(P,D)=>{r.mkdirSync(n.dirname(P),{recursive:!0});let K=`${P}.${process.pid}.tmp`;r.writeFileSync(K,`${JSON.stringify(D,null,2)}
139
+ `,{mode:420}),r.renameSync(K,P)},v=(P,D)=>s.execFileSync(P,D,{encoding:"utf8",maxBuffer:16777216}),_=(P,D)=>{let K=s.spawnSync(P,D,{encoding:"utf8"});return K.status===0?K.stdout.trim():""},S=(P)=>!!_("findmnt",["-n","--mountpoint",P]),y=(P,D)=>{try{let K=r.statSync(P),R=r.statSync(D);return K.dev===R.dev&&K.ino===R.ino}catch{return!1}},C=m("/var/lib/ts-cloud/compute-storage-state.json",{entries:[]}),A=e.deploymentStorage,x=e.volumes.find((P)=>P.key===A?.volume),H=(P,D)=>{if(!x)return[];let K=[];for(let R of r.readdirSync(e.webRoot,{withFileTypes:!0})){if(!R.isDirectory()||R.isSymbolicLink())continue;let q=n.join(e.webRoot,R.name);if(P&&q!==P&&q!==n.join(e.webRoot,`${D}-shared`))continue;for(let N of["releases",...A?.includeBackups===!1?[]:["backups"]]){let Y=n.join(q,N);if(!r.existsSync(Y)||!r.lstatSync(Y).isDirectory())continue;K.push({source:Y,destination:n.join(x.mountPath,N,R.name)})}}return K},O=(P)=>{try{return S(P.mountPath)&&r.statSync(P.mountPath).dev===r.statSync(P.device).rdev}catch{return!1}},I=(P)=>{let D=r.statfsSync(P),K=(D.blocks-D.bfree)*D.bsize,R=D.bavail*D.bsize;return{path:P,sizeBytes:D.blocks*D.bsize,usedBytes:K,availableBytes:R,usedPercent:Math.ceil(100*K/(K+R))}},W=()=>{let P=[],D=[I("/")];for(let R of e.volumes)if(!O(R))P.push(`missing or incorrect volume mount: ${R.mountPath}`);else D.push(I(R.mountPath));for(let R of C.entries)if(!S(R.source)||!y(R.source,R.destination))P.push(`missing deployment mount: ${R.source}`);let K=new Set(C.entries.map((R)=>R.source));for(let R of H())if(!K.has(R.source))P.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:D,mounts:C.entries.length,problems:P}};if(u==="plan")return console.log(JSON.stringify({volumes:e.volumes,entries:H(),state:C},null,2));if(u==="status"||u==="check"){let P=W();if(u==="check"){f("/var/lib/ts-cloud/compute-storage-status.json",P);let D="/var/lib/ts-cloud/compute-storage-alert.json",K=m(D,{problems:[]});if(JSON.stringify(K.problems)!==JSON.stringify(P.problems)){let R=P.problems.join("; ")||"all configured mounts are healthy",q=`${P.problems.length?"Storage alert":"Storage recovered"} on ${_("hostname",[])}: ${R}`;v("/usr/local/bin/ts-cloud-notify",[q.length>1800?`${q.slice(0,1600)}... Full report: /var/lib/ts-cloud/compute-storage-status.json`:q])}f(D,{problems:P.problems,timestamp:P.timestamp})}if(console.log(JSON.stringify(P)),P.problems.length)process.exitCode=1;return P}if(process.getuid?.()!==0)throw Error("Compute storage changes require root");let k=()=>{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 q=[];for(let X of e.volumes){let J=v("blkid",["-s","UUID","-o","value",X.device]).trim();if(!J)throw Error(`Volume ${X.name} has no filesystem UUID`);q.push(`UUID=${J} ${X.mountPath} ext4 defaults,noatime,nodev,nosuid,nofail,x-systemd.device-timeout=30s 0 2`)}for(let X of C.entries)q.push(`${X.destination} ${X.source} none bind,nofail,x-systemd.requires-mounts-for=${x.mountPath} 0 0`);let N=`# BEGIN ts-cloud compute storage
140
140
  ${q.join(`
141
141
  `)}
142
- # END ts-cloud compute storage`,Y;if(R.includes("# BEGIN ts-cloud compute storage")){let X=R.indexOf("# BEGIN ts-cloud compute storage"),J=R.indexOf("# END ts-cloud compute storage",X);if(J<0)throw Error("Incomplete managed storage block in fstab");Y=R.slice(0,X)+k+R.slice(J+30)}else Y=`${R.trimEnd()}
143
- ${k}
144
- `;r.writeFileSync("/etc/fstab.ts-cloud-new",Y),r.renameSync("/etc/fstab.ts-cloud-new","/etc/fstab")},V=()=>{for(let P of e.volumes){if(!r.existsSync(P.device)||!r.statSync(P.device).isBlockDevice())throw Error(`Volume device missing: ${P.device}`);let D=_("blkid",["-s","TYPE","-o","value",P.device]);if(!D){if(!P.allowFormat)throw Error(`Refusing to format adopted volume ${P.name}; no recognized filesystem`);v("mkfs.ext4",["-m","1",P.device]),D="ext4"}if(D!=="ext4")throw Error(`Refusing to replace ${D} filesystem on ${P.name}`);if(r.mkdirSync(P.mountPath,{recursive:!0}),S(P.mountPath)&&!O(P))throw Error(`Another filesystem occupies ${P.mountPath}`);if(!S(P.mountPath)&&r.readdirSync(P.mountPath).length)throw Error(`Refusing to hide existing files beneath ${P.mountPath}`);if(!S(P.mountPath))v("mount",["-o","noatime,nodev,nosuid",P.device,P.mountPath]);if(!O(P))throw Error(`Volume identity verification failed: ${P.name}`);v("resize2fs",[P.device]),P.allowFormat=!1}f("/etc/ts-cloud/compute-storage.json",e),H(),v("systemctl",["daemon-reload"])},{dlopen:te}=await import("bun:ffi"),ue=te("libc.so.6",{flock:{args:["i32","i32"],returns:"i32"}}),me=[],Z=(P)=>{r.mkdirSync(n.dirname(P),{recursive:!0});let D=r.openSync(P,r.constants.O_CREAT|r.constants.O_RDWR|r.constants.O_NOFOLLOW,384);if(ue.symbols.flock(D,2)!==0)throw r.closeSync(D),Error(`Could not acquire lock: ${P}`);me.push(D)},pe=()=>{let P=[];for(let D of r.readdirSync("/proc").filter((N)=>/^\d+$/.test(N))){let N=[];try{N=r.readdirSync(`/proc/${D}/fd`)}catch{continue}for(let R of["cwd","exe",...N.map((q)=>`fd/${q}`)]){let q=`/proc/${D}/${R}`;try{let k=r.readlinkSync(q);if(!k.startsWith(`${e.webRoot}/`)||!k.includes("/releases/"))continue;let Y=!1;if(R.startsWith("fd/")){let X=r.readFileSync(`/proc/${D}/fdinfo/${R.slice(3)}`,"utf8").match(/^flags:\s+(\d+)/m);Y=!!X&&(Number.parseInt(X[1],8)&3)!==0&&r.statSync(q).isFile()}P.push({file:k,write:Y,device:r.statSync(q).dev})}catch{}}}return P},ne=async(P,D)=>{r.mkdirSync(P.destination,{recursive:!0});let N=["rsync","-aHAXx","--numeric-ids","--delete",...D?["--checksum"]:[],`${P.source}/`,`${P.destination}/`],q=await Bun.spawn(N,{stdout:"inherit",stderr:"inherit"}).exited;if(q!==0&&!(q===24&&!D))throw Error(`rsync failed (${q}): ${P.source}`)},ee=async()=>{let P=v("systemctl",["list-units","--type=service","--state=running","--no-legend","--plain"]).split(`
142
+ # END ts-cloud compute storage`,Y;if(R.includes("# BEGIN ts-cloud compute storage")){let X=R.indexOf("# BEGIN ts-cloud compute storage"),J=R.indexOf("# END ts-cloud compute storage",X);if(J<0)throw Error("Incomplete managed storage block in fstab");Y=R.slice(0,X)+N+R.slice(J+30)}else Y=`${R.trimEnd()}
143
+ ${N}
144
+ `;r.writeFileSync("/etc/fstab.ts-cloud-new",Y),r.renameSync("/etc/fstab.ts-cloud-new","/etc/fstab")},V=()=>{for(let P of e.volumes){if(!r.existsSync(P.device)||!r.statSync(P.device).isBlockDevice())throw Error(`Volume device missing: ${P.device}`);let D=_("blkid",["-s","TYPE","-o","value",P.device]);if(!D){if(!P.allowFormat)throw Error(`Refusing to format adopted volume ${P.name}; no recognized filesystem`);v("mkfs.ext4",["-m","1",P.device]),D="ext4"}if(D!=="ext4")throw Error(`Refusing to replace ${D} filesystem on ${P.name}`);if(r.mkdirSync(P.mountPath,{recursive:!0}),S(P.mountPath)&&!O(P))throw Error(`Another filesystem occupies ${P.mountPath}`);if(!S(P.mountPath)&&r.readdirSync(P.mountPath).length)throw Error(`Refusing to hide existing files beneath ${P.mountPath}`);if(!S(P.mountPath))v("mount",["-o","noatime,nodev,nosuid",P.device,P.mountPath]);if(!O(P))throw Error(`Volume identity verification failed: ${P.name}`);v("resize2fs",[P.device]),P.allowFormat=!1}f("/etc/ts-cloud/compute-storage.json",e),k(),v("systemctl",["daemon-reload"])},{dlopen:te}=await import("bun:ffi"),ue=te("libc.so.6",{flock:{args:["i32","i32"],returns:"i32"}}),me=[],Z=(P)=>{r.mkdirSync(n.dirname(P),{recursive:!0});let D=r.openSync(P,r.constants.O_CREAT|r.constants.O_RDWR|r.constants.O_NOFOLLOW,384);if(ue.symbols.flock(D,2)!==0)throw r.closeSync(D),Error(`Could not acquire lock: ${P}`);me.push(D)},pe=()=>{let P=[];for(let D of r.readdirSync("/proc").filter((K)=>/^\d+$/.test(K))){let K=[];try{K=r.readdirSync(`/proc/${D}/fd`)}catch{continue}for(let R of["cwd","exe",...K.map((q)=>`fd/${q}`)]){let q=`/proc/${D}/${R}`;try{let N=r.readlinkSync(q);if(!N.startsWith(`${e.webRoot}/`)||!N.includes("/releases/"))continue;let Y=!1;if(R.startsWith("fd/")){let X=r.readFileSync(`/proc/${D}/fdinfo/${R.slice(3)}`,"utf8").match(/^flags:\s+(\d+)/m);Y=!!X&&(Number.parseInt(X[1],8)&3)!==0&&r.statSync(q).isFile()}P.push({file:N,write:Y,device:r.statSync(q).dev})}catch{}}}return P},ne=async(P,D)=>{r.mkdirSync(P.destination,{recursive:!0});let K=["rsync","-aHAXx","--numeric-ids","--delete",...D?["--checksum"]:[],`${P.source}/`,`${P.destination}/`],q=await Bun.spawn(K,{stdout:"inherit",stderr:"inherit"}).exited;if(q!==0&&!(q===24&&!D))throw Error(`rsync failed (${q}): ${P.source}`)},ee=async()=>{let P=v("systemctl",["list-units","--type=service","--state=running","--no-legend","--plain"]).split(`
145
145
  `).map((Y)=>Y.trim().split(/\s+/)[0]).filter(Boolean),D={};if(P.length){let Y=v("systemctl",["show",...P,"-p","Id","-p","MainPID","-p","WorkingDirectory"]);for(let X of Y.split(`
146
146
 
147
147
  `)){let J=Object.fromEntries(X.split(`
148
- `).filter(Boolean).map((E)=>{let K=E.indexOf("=");return[E.slice(0,K),E.slice(K+1)]}));if(J.WorkingDirectory?.startsWith(`${e.webRoot}/`)||/^(?:mail|rpx-gateway|postgresql|mysql|redis)[@.]/.test(J.Id??""))D[J.Id]=Number(J.MainPID)}}let N=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 J of X.proxies??[]){if(typeof J.to!=="string"||!/^[a-zA-Z0-9.-]+$/.test(J.to))continue;let E=typeof J.path==="string"&&J.path.startsWith("/")?J.path:"/";N.set(`${J.to}${E}`,{domain:J.to,path:E})}}let R=[...N.values()],q=[],k=0;return await Promise.all(Array.from({length:Math.min(8,R.length)},async()=>{while(k<R.length){let Y=R[k++],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"}),[J,,E]=await Promise.all([new Response(X.stdout).text(),new Response(X.stderr).text(),X.exited]),K=Number(J);q.push({...Y,status:K,ok:E===0&&K>=200&&K<500})}})),{routes:q.sort((Y,X)=>`${Y.domain}${Y.path}`.localeCompare(`${X.domain}${X.path}`)),services:D}},ge=()=>{let P=[x.mountPath,...C.entries.map((N)=>N.source)],D=new Set(["rpx-gateway.service","host-app-backup.service","host-app-backup-retry.service","host-backup-check.service","mail-host-maintenance.service"]);for(let N of r.readdirSync("/etc/systemd/system")){if(!N.endsWith(".service"))continue;try{if(r.readFileSync(`/etc/systemd/system/${N}`,"utf8").includes(e.webRoot))D.add(N)}catch{}}for(let N of D){let R=`/etc/systemd/system/${N}.d`;r.mkdirSync(R,{recursive:!0}),r.writeFileSync(`${R}/ts-cloud-storage.conf`,`[Unit]
148
+ `).filter(Boolean).map((E)=>{let L=E.indexOf("=");return[E.slice(0,L),E.slice(L+1)]}));if(J.WorkingDirectory?.startsWith(`${e.webRoot}/`)||/^(?:mail|rpx-gateway|postgresql|mysql|redis)[@.]/.test(J.Id??""))D[J.Id]=Number(J.MainPID)}}let K=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 J of X.proxies??[]){if(typeof J.to!=="string"||!/^[a-zA-Z0-9.-]+$/.test(J.to))continue;let E=typeof J.path==="string"&&J.path.startsWith("/")?J.path:"/";K.set(`${J.to}${E}`,{domain:J.to,path:E})}}let R=[...K.values()],q=[],N=0;return await Promise.all(Array.from({length:Math.min(8,R.length)},async()=>{while(N<R.length){let Y=R[N++],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"}),[J,,E]=await Promise.all([new Response(X.stdout).text(),new Response(X.stderr).text(),X.exited]),L=Number(J);q.push({...Y,status:L,ok:E===0&&L>=200&&L<500})}})),{routes:q.sort((Y,X)=>`${Y.domain}${Y.path}`.localeCompare(`${X.domain}${X.path}`)),services:D}},ge=()=>{let P=[x.mountPath,...C.entries.map((K)=>K.source)],D=new Set(["rpx-gateway.service",...A?.dependentUnits??[]]);for(let K of r.readdirSync("/etc/systemd/system")){if(!K.endsWith(".service"))continue;try{if(r.readFileSync(`/etc/systemd/system/${K}`,"utf8").includes(e.webRoot))D.add(K)}catch{}}for(let K of D){let R=`/etc/systemd/system/${K}.d`;r.mkdirSync(R,{recursive:!0}),r.writeFileSync(`${R}/ts-cloud-storage.conf`,`[Unit]
149
149
  RequiresMountsFor=${P.join(" ")}
150
- `)}v("systemctl",["daemon-reload"])};try{Z("/run/lock/ts-cloud-compute-storage.lock"),C=m("/var/lib/ts-cloud/compute-storage-state.json",{entries:[]});let P=m("/etc/ts-cloud/compute-storage.json",null);if(P){for(let E of P.volumes)if(!e.volumes.some((K)=>K.id===E.id&&K.key===E.key&&K.mountPath===E.mountPath))throw Error(`Refusing to remove or relocate managed volume ${E.name}; migrate its data explicitly first`);if(JSON.stringify(P.deploymentStorage)!==JSON.stringify(e.deploymentStorage)&&C.entries.length)throw Error("Refusing to change an active deployment-storage policy; migrate its data explicitly first")}if(u==="apply")V();for(let E of e.volumes)if(!O(E))throw Error(`Required volume is not mounted: ${E.name}`);if(!A||!x)return{volumes:e.volumes};if(u==="ensure-site"){let[E,K]=t.slice(1);if(!E?.startsWith(`${e.webRoot}/`)||!/^[\w-]+$/.test(n.basename(E))||E.includes("..")||!/^[\w-]+$/.test(K??""))throw Error("Invalid deployment site path or project slug");if(r.mkdirSync(n.join(E,"releases"),{recursive:!0}),A.includeBackups!==!1)r.mkdirSync(n.join(e.webRoot,`${K}-shared`,"backups"),{recursive:!0})}let D=(u==="reclaim"?[]:L(u==="ensure-site"?t[1]:void 0,t[2])).filter((E)=>!C.entries.some((K)=>K.source===E.source));for(let E of C.entries)if(!S(E.source)||!y(E.source,E.destination))throw Error(`Recorded deployment mount is missing: ${E.source}`);if(!D.length&&u==="ensure-site")return{inherited:!0,volume:x.name};if(!A.migrateExisting&&D.some((E)=>r.readdirSync(E.source).length>0))throw Error("Existing deployments require deploymentStorage.migrateExisting: true");if(D.length){let E=v("du",["-scx","--block-size=1",...D.map((ie)=>ie.source)]).trim().split(`
151
- `).at(-1)?.split(/\s+/)[0],K=r.statfsSync(x.mountPath);if(Number(E)>K.bavail*K.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(!S("/run/ts-cloud-root-web"))v("mount",["--bind",e.webRoot,"/run/ts-cloud-root-web"]);for(let E=0;E<D.length;E++){if(S(D[E].source)&&y(D[E].source,D[E].destination))continue;console.log(`copy ${E+1}/${D.length}: ${D[E].source}`),await ne(D[E],!1)}for(let E of["mail-host-maintenance","host-backup","ts-cloud-host-cleanup"])Z(`/run/lock/${E}.lock`);for(let E of r.readdirSync(e.webRoot,{withFileTypes:!0}).filter((K)=>K.isDirectory()).sort((K,ie)=>K.name.localeCompare(ie.name)))Z(n.join(e.webRoot,E.name,".ts-cloud/deploy.lock"));for(let E of u==="reclaim"?[]:L(u==="ensure-site"?t[1]:void 0,t[2]))if(!C.entries.some((K)=>K.source===E.source)&&!D.some((K)=>K.source===E.source))D.push(E);if(D.length)console.log("Checking application services and HTTPS routes before activation");let N=D.length?await ee():void 0;if(N)f("/var/lib/ts-cloud/compute-storage-health-before.json",N);let R=pe().filter((E)=>E.write);if(R.length)throw Error(`Live writable files must be shared before migration: ${R.map((E)=>E.file).join(", ")}`);let q={entries:[...C.entries],fstab:r.readFileSync("/etc/fstab","utf8")};if(D.length)v("sync",[]);let k=[];try{for(let E=0;E<D.length;E++){let K=D[E];if(S(K.source)){if(!y(K.source,K.destination))throw Error(`Unrecorded mount occupies ${K.source}`);C.entries.push(K),f("/var/lib/ts-cloud/compute-storage-state.json",C);continue}if(console.log(`verify and mount ${E+1}/${D.length}: ${K.source}`),await ne(K,!0),v("mount",["--bind",K.destination,K.source]),!y(K.source,K.destination))throw Error(`Bind verification failed: ${K.source}`);k.push(K),C.entries.push(K),f("/var/lib/ts-cloud/compute-storage-state.json",C),H()}if(H(),v("findmnt",["--verify"]),C.activatedAt=new Date().toISOString(),f("/var/lib/ts-cloud/compute-storage-state.json",C),ge(),N){console.log("Checking application services and HTTPS routes after activation");let E=await ee();f("/var/lib/ts-cloud/compute-storage-health-after.json",E);let K=N.routes.filter((re)=>re.ok&&!E.routes.some((Le)=>Le.domain===re.domain&&Le.path===re.path&&Le.ok)),ie=Object.keys(N.services).filter((re)=>!E.services[re]);if(K.length||ie.length)throw Error(`Application verification failed: ${K.map((re)=>re.domain+re.path).concat(ie).join(", ")}`);console.log(`Verified ${E.routes.length} routes and ${Object.keys(E.services).length} services`)}}catch(E){let K=[];for(let ie of k.reverse())try{v("umount",[ie.source])}catch{K.push(ie),console.error(`Rollback mount busy, original data retained: ${ie.source}`)}if(C.entries=[...q.entries,...K],r.writeFileSync("/etc/fstab",q.fstab),K.length)H();throw f("/var/lib/ts-cloud/compute-storage-state.json",C),v("systemctl",["daemon-reload"]),E}let Y=r.statSync(e.webRoot).dev,X=pe().filter((E)=>E.device===Y).map((E)=>E.file);for(let E of C.entries){if(!S(E.source)||!y(E.source,E.destination))throw Error(`Lost deployment mount: ${E.source}`);let K=n.join("/run/ts-cloud-root-web",n.relative(e.webRoot,E.source));if(!r.existsSync(K))continue;let ie="";try{ie=n.basename(r.realpathSync(n.join(n.dirname(E.source),"current")))}catch{}for(let re of r.readdirSync(K,{withFileTypes:!0})){let Le=n.join(K,re.name);if(n.basename(E.source)==="backups"){if(re.isFile()&&r.existsSync(n.join(E.destination,re.name)))r.unlinkSync(Le)}else if(re.isDirectory()&&!re.isSymbolicLink()&&re.name!==ie&&!X.some((kt)=>kt===n.join(E.source,re.name)||kt.startsWith(`${n.join(E.source,re.name)}/`)))r.rmSync(Le,{recursive:!0})}}v("sync",[]);let J=W();return f("/var/lib/ts-cloud/compute-storage-status.json",J),console.log(JSON.stringify(J)),J}finally{for(let P of me.reverse())ue.symbols.flock(P,8),r.closeSync(P);ue.close()}}var rn="/etc/ts-cloud/compute-storage.json",Me="/usr/local/lib/ts-cloud/compute-storage.mjs";function Yn(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;if(n&&!r.some((s)=>s.key===n.volume))throw Error(`deploymentStorage.volume references an undeclared compute volume: ${n.volume}`);return r}function Zt(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function Zn(e){let t=`${rn}.candidate`,r=`#!/usr/bin/env bun
150
+ `)}v("systemctl",["daemon-reload"])};try{Z("/run/lock/ts-cloud-compute-storage.lock"),C=m("/var/lib/ts-cloud/compute-storage-state.json",{entries:[]});let P=m("/etc/ts-cloud/compute-storage.json",null);if(P){for(let E of P.volumes)if(!e.volumes.some((L)=>L.id===E.id&&L.key===E.key&&L.mountPath===E.mountPath))throw Error(`Refusing to remove or relocate managed volume ${E.name}; migrate its data explicitly first`);if(C.entries.length&&(P.deploymentStorage?.volume!==A?.volume||P.deploymentStorage?.includeBackups!==!1!==(A?.includeBackups!==!1)))throw Error("Refusing to change an active deployment-storage policy; migrate its data explicitly first")}if(u==="apply")V();for(let E of e.volumes)if(!O(E))throw Error(`Required volume is not mounted: ${E.name}`);if(!A||!x)return{volumes:e.volumes};if(u==="ensure-site"){let[E,L]=t.slice(1);if(!E?.startsWith(`${e.webRoot}/`)||!/^[\w-]+$/.test(n.basename(E))||E.includes("..")||!/^[\w-]+$/.test(L??""))throw Error("Invalid deployment site path or project slug");if(r.mkdirSync(n.join(E,"releases"),{recursive:!0}),A.includeBackups!==!1)r.mkdirSync(n.join(e.webRoot,`${L}-shared`,"backups"),{recursive:!0})}let D=(u==="reclaim"?[]:H(u==="ensure-site"?t[1]:void 0,t[2])).filter((E)=>!C.entries.some((L)=>L.source===E.source));for(let E of C.entries)if(!S(E.source)||!y(E.source,E.destination))throw Error(`Recorded deployment mount is missing: ${E.source}`);if(!D.length&&u==="ensure-site")return{inherited:!0,volume:x.name};if(!A.migrateExisting&&D.some((E)=>r.readdirSync(E.source).length>0))throw Error("Existing deployments require deploymentStorage.migrateExisting: true");if(D.length){let E=v("du",["-scx","--block-size=1",...D.map((ie)=>ie.source)]).trim().split(`
151
+ `).at(-1)?.split(/\s+/)[0],L=r.statfsSync(x.mountPath);if(Number(E)>L.bavail*L.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(!S("/run/ts-cloud-root-web"))v("mount",["--bind",e.webRoot,"/run/ts-cloud-root-web"]);v("mount",["--make-private","/run/ts-cloud-root-web"]);let K=r.statSync(e.webRoot).dev;for(let E of C.entries){let L=n.join("/run/ts-cloud-root-web",n.relative(e.webRoot,E.source));if(r.existsSync(L)&&(r.statSync(L).dev!==K||y(L,E.destination)))throw Error(`Root recovery view contains a deployment mount: ${L}`)}for(let E=0;E<D.length;E++){if(S(D[E].source)&&y(D[E].source,D[E].destination))continue;console.log(`copy ${E+1}/${D.length}: ${D[E].source}`),await ne(D[E],!1)}for(let E of new Set([...A.locks??[],"/run/lock/ts-cloud-host-cleanup.lock"]))Z(E);for(let E of r.readdirSync(e.webRoot,{withFileTypes:!0}).filter((L)=>L.isDirectory()).sort((L,ie)=>L.name.localeCompare(ie.name)))Z(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(!C.entries.some((L)=>L.source===E.source)&&!D.some((L)=>L.source===E.source))D.push(E);if(D.length)console.log("Checking application services and HTTPS routes before activation");let R=D.length?await ee():void 0;if(R)f("/var/lib/ts-cloud/compute-storage-health-before.json",R);let q=pe().filter((E)=>E.write);if(q.length)throw Error(`Live writable files must be shared before migration: ${q.map((E)=>E.file).join(", ")}`);let N={entries:[...C.entries],fstab:r.readFileSync("/etc/fstab","utf8")};if(D.length)v("sync",[]);let Y=[];try{for(let E=0;E<D.length;E++){let L=D[E];if(S(L.source)){if(!y(L.source,L.destination))throw Error(`Unrecorded mount occupies ${L.source}`);C.entries.push(L),f("/var/lib/ts-cloud/compute-storage-state.json",C);continue}if(console.log(`verify and mount ${E+1}/${D.length}: ${L.source}`),await ne(L,!0),v("mount",["--bind",L.destination,L.source]),!y(L.source,L.destination))throw Error(`Bind verification failed: ${L.source}`);Y.push(L),C.entries.push(L),f("/var/lib/ts-cloud/compute-storage-state.json",C),k()}if(k(),v("findmnt",["--verify"]),C.activatedAt=new Date().toISOString(),f("/var/lib/ts-cloud/compute-storage-state.json",C),ge(),R){console.log("Checking application services and HTTPS routes after activation");let E=await ee();f("/var/lib/ts-cloud/compute-storage-health-after.json",E);let L=R.routes.filter((re)=>re.ok&&!E.routes.some((Le)=>Le.domain===re.domain&&Le.path===re.path&&Le.ok)),ie=Object.keys(R.services).filter((re)=>!E.services[re]);if(L.length||ie.length)throw Error(`Application verification failed: ${L.map((re)=>re.domain+re.path).concat(ie).join(", ")}`);console.log(`Verified ${E.routes.length} routes and ${Object.keys(E.services).length} services`)}}catch(E){let L=[];for(let ie of Y.reverse())try{v("umount",[ie.source])}catch{L.push(ie),console.error(`Rollback mount busy, original data retained: ${ie.source}`)}if(C.entries=[...N.entries,...L],r.writeFileSync("/etc/fstab",N.fstab),L.length)k();throw f("/var/lib/ts-cloud/compute-storage-state.json",C),v("systemctl",["daemon-reload"]),E}let X=pe().filter((E)=>E.device===K).map((E)=>E.file);for(let E of C.entries){if(!S(E.source)||!y(E.source,E.destination))throw Error(`Lost deployment mount: ${E.source}`);let L=n.join("/run/ts-cloud-root-web",n.relative(e.webRoot,E.source));if(!r.existsSync(L))continue;if(r.statSync(L).dev!==K||y(L,E.destination))throw Error(`Refusing to clean a deployment volume through the root recovery view: ${L}`);let ie="";try{ie=n.basename(r.realpathSync(n.join(n.dirname(E.source),"current")))}catch{}for(let re of r.readdirSync(L,{withFileTypes:!0})){let Le=n.join(L,re.name);if(n.basename(E.source)==="backups"){if(re.isFile()&&r.existsSync(n.join(E.destination,re.name)))r.unlinkSync(Le)}else if(re.isDirectory()&&!re.isSymbolicLink()&&re.name!==ie&&!X.some((kt)=>kt===n.join(E.source,re.name)||kt.startsWith(`${n.join(E.source,re.name)}/`)))r.rmSync(Le,{recursive:!0})}}v("sync",[]);let J=W();return f("/var/lib/ts-cloud/compute-storage-status.json",J),console.log(JSON.stringify(J)),J}finally{for(let P of me.reverse())ue.symbols.flock(P,8),r.closeSync(P);ue.close()}}var rn="/etc/ts-cloud/compute-storage.json",Me="/usr/local/lib/ts-cloud/compute-storage.mjs";function Yn(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 Zt(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function Zn(e){let t=`${rn}.candidate`,r=`#!/usr/bin/env bun
152
152
  await (${Ts.toString()})(JSON.parse(await Bun.file(process.env.TS_CLOUD_STORAGE_POLICY || ${JSON.stringify(rn)}).text()), process.argv.slice(2));
153
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 ${Zt(Buffer.from(r).toString("base64"))} | base64 -d > ${Me}.new`,`chmod 0755 ${Me}.new && mv ${Me}.new ${Me}`,`printf %s ${Zt(JSON.stringify(e))} > ${t}`,`chmod 0644 ${t}`,`TS_CLOUD_STORAGE_POLICY=${t} bun ${Me} 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 ${Me} 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 ${Me} 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 xr(e,t){return[`if [ -f ${rn} ]; then bun ${Me} ensure-site ${Zt(e)} ${Zt(t)}; fi`]}function er(e){return Object.entries(e).map(([t,r])=>`${t}=${Ea(String(r))}`).join(`
154
154
  `)}function Ea(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}var tr=["storage",".env"],Pt=4;function Ie(e){return`${e.replace(/\/+$/,"")}/.ts-cloud`}function Ra(e){return`${Ie(e)}/deploy-history.log`}function Oa(e,t){return`${Ie(e)}/deploys/${t}.log`}function ws(e){return`${Ie(e)}/shared-paths`}function rr(e){return`${e.shared}/stx-images`}function Wt(e,t){let r=e.replace(/\/+$/,"");return{base:r,releases:`${r}/releases`,shared:`${r}/shared`,current:`${r}/current`,release:`${r}/releases/${t}`}}function Cs(e){let t=e.split("/").pop()||e;if(t===".env"||t.startsWith(".env."))return!0;return/\.[a-z0-9]+$/i.test(t)}function nn(e){return typeof e==="string"?e:e.path}function Ps(e){let t=new Map;for(let r of e)t.set(nn(r),r);return[...t.values()]}function Es(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 Da(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 Et(e,t=tr){let r=[`mkdir -p ${e.releases} ${e.shared} ${rr(e)}`,...Da(e)],n=t.map((i)=>Es(e,i));for(let{path:i,target:a,seed:c}of n){if(!c)continue;if(r.push(`ts_cloud_adopt_shared '${i}' '${a}'`),Cs(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=ws(e.base);return r.push(`mkdir -p ${Ie(e.base)}`,`cat > ${s} <<'TS_CLOUD_SHARED_PATHS_EOF'`,...n.map((i)=>`${i.path} ${i.target}`),"TS_CLOUD_SHARED_PATHS_EOF"),r}function sn(e,t=900){let r=`${Ie(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 on(e){let t=`${e.release}.incoming`;return[`rm -rf ${t}`,`mkdir -p ${t}`,...xa(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 an(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 xa(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 ln(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 Ia(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 nr(e,t=tr){let r=[];for(let n of t){let{path:s,target:i,seed:a}=Es(e,n),c=`${e.release}/${s}`,u=[`rm -rf ${c}`,`mkdir -p "$(dirname ${c})"`,`ln -sfn ${i} ${c}`];if(a){if(s!==".env"&&Cs(s))r.push(...Ia(c,i));r.push(...u);continue}r.push(`if [ -e ${i} ]; then`,...u.map((m)=>` ${m}`),"fi")}return r}function Aa(e,t){let r=ws(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 ct(e){return[`ln -sfn ${e.release} ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`]}function un(e){return`${Ie(e)}/previous-release`}function pn(e,t="TS_CLOUD_PREV_CURRENT"){let r=un(e.base);return[`if [ -n "\${${t}:-}" ] && [ -d "$${t}" ] && [ "$(readlink -f "$${t}")" != "$(readlink -f ${e.release})" ]; then mkdir -p ${Ie(e.base)}; basename "$${t}" > ${r}; fi`]}function Rs(e,t){let r=un(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 Og(e,t={}){return[...Rs(e,t.to),'echo "would roll back from $(basename "${TS_CLOUD_CURRENT:-none}") to $TS_CLOUD_RB_ID (dry run: nothing changed)"']}function _g(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 ${un(e.base)}`,'echo "rolled back to $TS_CLOUD_RB_ID"'],i=[...Rs(e,t.to),...Aa(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 lt(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 La(e){return`${Ie(e)}/owner`}function dn(e,t){let r=La(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 sr(e,t){let r=Ie(e),n=Oa(e,t.releaseId),s=Ra(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 Ua=new Set(["sqlite","sqlite3"]),Ha=new Set([":memory:","memory"]);function ka(e){let t=e?.DB_CONNECTION?.trim().toLowerCase();return t!=null&&Ua.has(t)}function Na(e){let t=e.trim().replace(/^\.\//,"");if(t===""||t.startsWith("/")||t.startsWith("~"))return;if(t.split("/").includes(".."))return;return t.replace(/\/+$/,"")}function mn(e,t=[]){if(!ka(e))return{};let r=e?.DB_DATABASE_PATH?.trim()||e?.DB_DATABASE?.trim();if(r&&Ha.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=Na(r);if(!n)return{};if(t.some((s)=>nn(s)===n))return{};return{path:n}}function or(e,t=[]){let{path:r}=mn(e,t);return r?[r]:[]}var Or="/var/ts-cloud/artifacts",Bh="/usr/local/bin/ts-cloud-host-cleanup.sh",xh="ts-cloud-host-cleanup";var Lg=Object.freeze({stagingMaxAgeMinutes:60,artifactMaxAgeDays:2,artifactUploadMaxAgeMinutes:60,bunCacheMaxAgeDays:7,journalMaxAgeDays:14,journalMaxSizeMb:512,containerImageMaxAgeHours:168}),$g=Object.freeze({artifactMaxAgeDays:0,bunCacheMaxAgeDays:1,journalMaxAgeDays:3,journalMaxSizeMb:256,containerImageMaxAgeHours:24}),Oh=50,_h=85,Lh="daily";function Os(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function Je(e,t,r=0){if(!Number.isInteger(t)||t<r)throw Error(`hostCleanup: ${e} must be a whole number >= ${r} (got ${t})`)}function Ds(e,t){for(let[r,n]of Object.entries(t))Je(`${e}.${r}`,n);Je(`${e}.stagingMaxAgeMinutes`,t.stagingMaxAgeMinutes,15),Je(`${e}.artifactUploadMaxAgeMinutes`,t.artifactUploadMaxAgeMinutes,15),Je(`${e}.journalMaxSizeMb`,t.journalMaxSizeMb,1)}function Ma(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(Je(`${r}.maxAgeDays`,e.maxAgeDays),e.type!==void 0&&e.type!=="file"&&e.type!=="directory")throw Error(`${r}.type must be 'file' or 'directory'`)}function _r(e){let t=typeof e==="object"&&e!==null?e:{},r=e!==!1,n={...Lg,...xs(t.retention)};Ds("hostCleanup.retention",n);let s=null;if(t.pressure!==!1){let c=typeof t.pressure==="object"?t.pressure:{},u=c.lowWaterPercent??50,m=c.highWaterPercent??85;if(Je("hostCleanup.pressure.lowWaterPercent",u),Je("hostCleanup.pressure.highWaterPercent",m,1),m>100||u>=m)throw Error(`hostCleanup.pressure: need 0 <= lowWaterPercent < highWaterPercent <= 100 (got ${u} and ${m})`);let f={...$g,...xs(c.escalated)},v=Object.fromEntries(Object.keys(n).map((_)=>[_,Math.min(n[_],f[_]??n[_])]));Ds("hostCleanup.pressure.escalated",v),s={lowWaterPercent:u,highWaterPercent:m,escalated:v}}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(Ma),{enabled:r,timer:r&&t.timer!==!1,schedule:i,retention:n,pressure:s,paths:a}}function xs(e){return Object.fromEntries(Object.entries(e??{}).filter(([,t])=>t!==void 0))}var Rt={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 fn(e){return Object.keys(Rt).map((t)=>`${Rt[t]}=${e[t]}`).join(" ")}var Fe=(e)=>`"$${Rt[e]}"`;function Is(e){return[`find /var/ts-cloud/staging -xdev -maxdepth 1 -type f -mmin +${Fe("stagingMaxAgeMinutes")} -delete 2>/dev/null || true`,`find /tmp -xdev -maxdepth 1 -type f -name "*-release.tar.gz" -mmin +${Fe("stagingMaxAgeMinutes")} -delete 2>/dev/null || true`,`find /var/ts-cloud/artifacts -xdev -maxdepth 1 -type f -name "*.tar.gz" -mtime +${Fe("artifactMaxAgeDays")} -delete 2>/dev/null || true`,`find /var/ts-cloud/artifacts -xdev -maxdepth 1 -type f -name ".*.tmp" -mmin +${Fe("artifactUploadMaxAgeMinutes")} -delete 2>/dev/null || true`,...e.map(Fa),`journalctl --vacuum-time=${Fe("journalMaxAgeDays")}d --vacuum-size=${Fe("journalMaxSizeMb")}M >/dev/null 2>&1 || true`]}function Fa(e){let t=Os(e.path.replace(/\/+$/,"")),r=Os(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 As(){return[`find /root/.bun/install/cache -xdev -type f -mtime +${Fe("bunCacheMaxAgeDays")} -delete 2>/dev/null || true`,`find /root/.bun/install/cache -xdev -depth -type d -empty -mtime +${Fe("bunCacheMaxAgeDays")} -delete 2>/dev/null || true`,`if command -v docker >/dev/null 2>&1; then docker image prune --all --force --filter "until=\${${Rt.containerImageMaxAgeHours}}h" >/dev/null 2>&1 || true; fi`,`if command -v podman >/dev/null 2>&1; then podman image prune --all --force --filter "until=\${${Rt.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 Ls(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 ei(e){let{retention:t,pressure:r,paths:n}=_r(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)"',fn(t),...Is(n),...As(),'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)"',...Ls("TS_CLOUD_HC_BEFORE"),"TS_CLOUD_HC_TIER=normal",fn(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",` ${fn(u)}`,` echo "[ts-cloud] warning: / at \${TS_CLOUD_HC_BEFORE}% (at or above ${c}%), host cleanup is using shortened retention windows" >&2`,"fi",...Is(n),'if [ "$TS_CLOUD_HC_TIER" != light ]; then',...As().map((m)=>` ${m}`),"fi",'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"',...Ls("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 Mg(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",...ei(e),"exit 0"]}function gn(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 Ys(e){let t=_r(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=gn("/usr/local/bin/ts-cloud-host-cleanup.sh",Mg(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",...gn("/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"),...gn("/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 ti(e){let t=Ys(e);if(!_r(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 za=/\.(?:[cm]?[jt]sx?)$/;function ri(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&&!za.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 Us(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.
@@ -156,7 +156,7 @@ await (${Ts.toString()})(JSON.parse(await Bun.file(process.env.TS_CLOUD_STORAGE_
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)"',...Sn()]}function ir(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 Sn(){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 Ba(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 Ot(e,t,r){return typeof e==="number"&&Number.isFinite(e)?Math.max(r,Math.floor(e)):t}function Hs(e){let{unitBase:t,unitPattern:r,port:n}=e,s=e.path&&e.path.startsWith("/")?e.path:Qe.path,i=Ot(e.intervalSeconds,Qe.intervalSeconds,10),a=Ot(e.failuresBeforeRestart,Qe.failuresBeforeRestart,1),c=Ot(e.timeoutSeconds,Qe.timeoutSeconds,1),u=Ot(e.startupGraceSeconds,Qe.startupGraceSeconds,0),m=Ot(e.maxBackoffSeconds,Qe.maxBackoffSeconds,0),f=Math.min(Qe.backoffBaseSeconds,m),v=`/usr/local/sbin/${t}-liveness`,_=`/run/${t}-liveness`,S=`${t}-liveness`,y=`127.0.0.1:${n}${s}`,A=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 > ${v} <<'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=${m}s`,"set -eu",`TS_CLOUD_STATE=${_}`,'exec 9>"$TS_CLOUD_STATE.lock"',"flock -n 9 || exit 0",A,'[ -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 ${m} ] || 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 ${S} "$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 ${S} "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=${f}`," TS_CLOUD_I=1",` while [ "$TS_CLOUD_I" -lt "$TS_CLOUD_STREAK" ] && [ "$TS_CLOUD_WAIT" -lt ${m} ]; do TS_CLOUD_WAIT=$((TS_CLOUD_WAIT * 2)); TS_CLOUD_I=$((TS_CLOUD_I + 1)); done`,` [ "$TS_CLOUD_WAIT" -le ${m} ] || TS_CLOUD_WAIT=${m}`," TS_CLOUD_ELAPSED=$((TS_CLOUD_NOW - TS_CLOUD_LAST))",' if [ "$TS_CLOUD_ELAPSED" -lt "$TS_CLOUD_WAIT" ]; then',` logger -t ${S} "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 ${S} "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 ${v}`,`rm -f ${_}.fail ${_}.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=${v}`,"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 ks=20,hn=3,Ka=5,ja=60;function Va(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,m=u?`curl -sf -o /dev/null --max-time ${Ka} "http://127.0.0.1:${s}${u}"`:null,f=(v)=>`{ echo "[ts-cloud] release ${n} ${v}" >&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} || ${f("failed its health gate on the free port")}; done`," else",` ${f("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 ${ja}); 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 ${hn}`," done",` [ "$TS_CLOUD_BOUND" -eq 1 ] || ${f(`never took :${s}`)}`,"else",' echo "[ts-cloud] cannot read listener PIDs on this host — the response probes run without the bind check" >&2',"fi",...m?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${ks}); do if ${m}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${hn}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${f(`never answered ${u}`)}`]:[],...ct(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 ] || ${f(`is active but never bound :${s}`)}`,...m?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${ks}); do if ${m}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${hn}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${f(`stopped answering ${u} once it served alone`)}`]:[],...pn(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 ni(e){let{siteName:t,slug:r,artifactFetch:n,releaseId:s,execStart:i,envEntries:a,port:c,keepReleases:u=Pt,preStartCommands:m=[],healthCheckPath:f,healthGateSeconds:v=5,liveness:_,memoryHigh:S="auto",memoryMax:y,cpuWeight:C,ioWeight:A,tasksMax:x,stopTimeout:L}=e,O=[...C!=null?[`CPUWeight=${C}`]:[],...A!=null?[`IOWeight=${A}`]:[],...x!=null?[`TasksMax=${x}`]:[],...L?[`TimeoutStopSec=${L}`]:[]],I=e.zeroDowntime??c!=null,W=e.appDir??`/var/www/${t}`,H=Wt(W,s),V=`${r}-${t}`,te=`${V}.service`,ue=si(r,t,s),me=e.sharedPaths??[],Z=Ps([".env",...me,...or(a,me)]),pe=er(a),ne=m.length>0?[`cd ${H.release}`,...m]:[],ee=["set -euo pipefail",...sn(H),an(H),...n,...Et(H,Z),...on(H),`tar xzf ${ue} -C "$TS_CLOUD_STAGED"`,`rm -f ${ue}`,`cat > ${H.shared}/.env <<'TS_CLOUD_ENV_EOF'`,pe,"TS_CLOUD_ENV_EOF",`chmod 600 ${H.shared}/.env`,...ln(H),`find ${H.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' ${H.shared}/.env 2>/dev/null || true`,...nr(H,Z),...ne];if(I&&c!=null){let ge=`${V}@${s}.service`,P=f?f.startsWith("/")?f:`/${f}`:null;return[...ee,`cat > /etc/systemd/system/${V}@.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} release %i (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${H.releases}/%i`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...S&&S!=="auto"?[`MemoryHigh=${S}`]:[],...y?[`MemoryMax=${y}`]:[],...O,`EnvironmentFile=${H.releases}/%i/.env`,`Environment=PORT=${c}`,`Environment=STX_IMAGE_CACHE_DIR=${rr(H)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...S==="auto"?Us(`${V}@.service`):[...ir(`${V}@.service`),...Sn()],...Ba(ge),...Va({paths:H,unitBase:V,releaseId:s,port:c,healthCheckPath:P,healthGateSeconds:v}),...lt(H,u),..._===!1?[]:Hs({..._,unitBase:V,unitPattern:`${V}@*.service`,port:c,path:_?.path??f})]}return[...ee,`cat > /etc/systemd/system/${te} <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${H.current}`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...S&&S!=="auto"?[`MemoryHigh=${S}`]:[],...y?[`MemoryMax=${y}`]:[],...O,`EnvironmentFile=${H.current}/.env`,...c?[`Environment=PORT=${c}`]:[],`Environment=STX_IMAGE_CACHE_DIR=${rr(H)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...ir(te,{auto:S!=="auto",high:S!=="auto",max:Boolean(y)}),...S==="auto"?Us(te):Sn(),`systemctl enable ${te}`,`TS_CLOUD_PREV_CURRENT="$(readlink ${H.current} 2>/dev/null || true)"`,...ct(H),`systemctl restart ${te}`,`for TS_CLOUD_I in $(seq 1 ${Math.max(1,v)}); 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 ${H.release})" ]; then ln -sfn "$TS_CLOUD_PREV_CURRENT" ${H.current}.tmp && mv -Tf ${H.current}.tmp ${H.current}; systemctl restart ${te} || true; fi; exit 1; }; done`,...pn(H),...lt(H,u),..._===!1||!c?[]:Hs({..._,unitBase:V,unitPattern:te,port:c,path:_?.path??f})]}function ii(e){let{siteName:t,artifactFetch:r,releaseId:n,keepReleases:s=Pt,preStartCommands:i=[]}=e,a=e.appDir??`/var/www/${t}`,c=Wt(a,n),u=si(e.slug,t,n),m=i.length>0?[`cd ${c.release}`,...i]:[];return["set -euo pipefail",...sn(c),an(c),...r,...Et(c,[]),...on(c),`tar xzf ${u} -C "$TS_CLOUD_STAGED"`,...ln(c),`rm -f ${u}`,...m,...ct(c),...lt(c,s)]}function si(e,t,r){return`/tmp/${[e,t,r].filter(Boolean).join("-")}-release.tar.gz`}function xc(e,t,r,n){return[`aws s3 cp "s3://${e}/${t}" ${n} --region ${r}`]}function Oc(e,t){return[`mv "${e}" ${t}`]}function ut(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function ar(e,t,r){return["set -euo pipefail",`chmod 600 ${ut(e)}`,`mv -f -- ${ut(e)} ${ut(t)}`,`cp -- ${ut(t)} ${ut(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)"',...Sn()]}function ir(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 Sn(){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 Ba(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 Ot(e,t,r){return typeof e==="number"&&Number.isFinite(e)?Math.max(r,Math.floor(e)):t}function Hs(e){let{unitBase:t,unitPattern:r,port:n}=e,s=e.path&&e.path.startsWith("/")?e.path:Qe.path,i=Ot(e.intervalSeconds,Qe.intervalSeconds,10),a=Ot(e.failuresBeforeRestart,Qe.failuresBeforeRestart,1),c=Ot(e.timeoutSeconds,Qe.timeoutSeconds,1),u=Ot(e.startupGraceSeconds,Qe.startupGraceSeconds,0),m=Ot(e.maxBackoffSeconds,Qe.maxBackoffSeconds,0),f=Math.min(Qe.backoffBaseSeconds,m),v=`/usr/local/sbin/${t}-liveness`,_=`/run/${t}-liveness`,S=`${t}-liveness`,y=`127.0.0.1:${n}${s}`,A=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 > ${v} <<'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=${m}s`,"set -eu",`TS_CLOUD_STATE=${_}`,'exec 9>"$TS_CLOUD_STATE.lock"',"flock -n 9 || exit 0",A,'[ -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 ${m} ] || 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 ${S} "$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 ${S} "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=${f}`," TS_CLOUD_I=1",` while [ "$TS_CLOUD_I" -lt "$TS_CLOUD_STREAK" ] && [ "$TS_CLOUD_WAIT" -lt ${m} ]; do TS_CLOUD_WAIT=$((TS_CLOUD_WAIT * 2)); TS_CLOUD_I=$((TS_CLOUD_I + 1)); done`,` [ "$TS_CLOUD_WAIT" -le ${m} ] || TS_CLOUD_WAIT=${m}`," TS_CLOUD_ELAPSED=$((TS_CLOUD_NOW - TS_CLOUD_LAST))",' if [ "$TS_CLOUD_ELAPSED" -lt "$TS_CLOUD_WAIT" ]; then',` logger -t ${S} "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 ${S} "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 ${v}`,`rm -f ${_}.fail ${_}.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=${v}`,"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 ks=20,hn=3,Ka=5,ja=60;function Va(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,m=u?`curl -sf -o /dev/null --max-time ${Ka} "http://127.0.0.1:${s}${u}"`:null,f=(v)=>`{ echo "[ts-cloud] release ${n} ${v}" >&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} || ${f("failed its health gate on the free port")}; done`," else",` ${f("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 ${ja}); 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 ${hn}`," done",` [ "$TS_CLOUD_BOUND" -eq 1 ] || ${f(`never took :${s}`)}`,"else",' echo "[ts-cloud] cannot read listener PIDs on this host — the response probes run without the bind check" >&2',"fi",...m?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${ks}); do if ${m}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${hn}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${f(`never answered ${u}`)}`]:[],...ct(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 ] || ${f(`is active but never bound :${s}`)}`,...m?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${ks}); do if ${m}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${hn}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${f(`stopped answering ${u} once it served alone`)}`]:[],...pn(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 ni(e){let{siteName:t,slug:r,artifactFetch:n,releaseId:s,execStart:i,envEntries:a,port:c,keepReleases:u=Pt,preStartCommands:m=[],healthCheckPath:f,healthGateSeconds:v=5,liveness:_,memoryHigh:S="auto",memoryMax:y,cpuWeight:C,ioWeight:A,tasksMax:x,stopTimeout:H}=e,O=[...C!=null?[`CPUWeight=${C}`]:[],...A!=null?[`IOWeight=${A}`]:[],...x!=null?[`TasksMax=${x}`]:[],...H?[`TimeoutStopSec=${H}`]:[]],I=e.zeroDowntime??c!=null,W=e.appDir??`/var/www/${t}`,k=Wt(W,s),V=`${r}-${t}`,te=`${V}.service`,ue=si(r,t,s),me=e.sharedPaths??[],Z=Ps([".env",...me,...or(a,me)]),pe=er(a),ne=m.length>0?[`cd ${k.release}`,...m]:[],ee=["set -euo pipefail",...sn(k),an(k),...n,...Et(k,Z),...on(k),`tar xzf ${ue} -C "$TS_CLOUD_STAGED"`,`rm -f ${ue}`,`cat > ${k.shared}/.env <<'TS_CLOUD_ENV_EOF'`,pe,"TS_CLOUD_ENV_EOF",`chmod 600 ${k.shared}/.env`,...ln(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`,...nr(k,Z),...ne];if(I&&c!=null){let ge=`${V}@${s}.service`,P=f?f.startsWith("/")?f:`/${f}`:null;return[...ee,`cat > /etc/systemd/system/${V}@.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} release %i (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${k.releases}/%i`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...S&&S!=="auto"?[`MemoryHigh=${S}`]:[],...y?[`MemoryMax=${y}`]:[],...O,`EnvironmentFile=${k.releases}/%i/.env`,`Environment=PORT=${c}`,`Environment=STX_IMAGE_CACHE_DIR=${rr(k)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...S==="auto"?Us(`${V}@.service`):[...ir(`${V}@.service`),...Sn()],...Ba(ge),...Va({paths:k,unitBase:V,releaseId:s,port:c,healthCheckPath:P,healthGateSeconds:v}),...lt(k,u),..._===!1?[]:Hs({..._,unitBase:V,unitPattern:`${V}@*.service`,port:c,path:_?.path??f})]}return[...ee,`cat > /etc/systemd/system/${te} <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${k.current}`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...S&&S!=="auto"?[`MemoryHigh=${S}`]:[],...y?[`MemoryMax=${y}`]:[],...O,`EnvironmentFile=${k.current}/.env`,...c?[`Environment=PORT=${c}`]:[],`Environment=STX_IMAGE_CACHE_DIR=${rr(k)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...ir(te,{auto:S!=="auto",high:S!=="auto",max:Boolean(y)}),...S==="auto"?Us(te):Sn(),`systemctl enable ${te}`,`TS_CLOUD_PREV_CURRENT="$(readlink ${k.current} 2>/dev/null || true)"`,...ct(k),`systemctl restart ${te}`,`for TS_CLOUD_I in $(seq 1 ${Math.max(1,v)}); 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`,...pn(k),...lt(k,u),..._===!1||!c?[]:Hs({..._,unitBase:V,unitPattern:te,port:c,path:_?.path??f})]}function ii(e){let{siteName:t,artifactFetch:r,releaseId:n,keepReleases:s=Pt,preStartCommands:i=[]}=e,a=e.appDir??`/var/www/${t}`,c=Wt(a,n),u=si(e.slug,t,n),m=i.length>0?[`cd ${c.release}`,...i]:[];return["set -euo pipefail",...sn(c),an(c),...r,...Et(c,[]),...on(c),`tar xzf ${u} -C "$TS_CLOUD_STAGED"`,...ln(c),`rm -f ${u}`,...m,...ct(c),...lt(c,s)]}function si(e,t,r){return`/tmp/${[e,t,r].filter(Boolean).join("-")}-release.tar.gz`}function xc(e,t,r,n){return[`aws s3 cp "s3://${e}/${t}" ${n} --region ${r}`]}function Oc(e,t){return[`mv "${e}" ${t}`]}function ut(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function ar(e,t,r){return["set -euo pipefail",`chmod 600 ${ut(e)}`,`mv -f -- ${ut(e)} ${ut(t)}`,`cp -- ${ut(t)} ${ut(r)}`].join(`
160
160
  `)}function lr(e){return`rm -f -- ${ut(e)} 2>/dev/null || true`}function _n(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 Ns(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 vn(e){let t=e.infrastructure?.compute??{},r=g(e);return[...Vt(t.managedServices??{mysql:!0,redis:!0},{bindPrivate:!0}),...ot(r,t.managedServices??{mysql:!0}),...Ue(!0),...xe(!0),...it(t.sshKeys),...We(e.notifications),...t.backups?.enabled?[...Gt({database:r,backups:t.backups})]:[]]}function oi(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 Lr(e,t,r={}){let n=Bun.spawn(["ssh",...oi(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 Se(e,t,r={}){let n=await Lr(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 _c(e,t,r,n={}){let s=Bun.spawn(["scp",...oi(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 ai(e,t={}){let r=t.timeoutMs??180000,n=t.pollIntervalMs??5000,s=Date.now();while(Date.now()-s<r){let i=await Lr(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 Lc(e,t={}){let r=t.timeoutMs??300000,n=t.pollIntervalMs??5000,s=Date.now();while(Date.now()-s<r){let i=await Lr(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 ci(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
161
  `)}var $c=ci();import{homedir as Ga}from"node:os";import{join as qa}from"node:path";var ur={location:"fsn1",image:"ubuntu-24.04",sshUser:"root",sshPrivateKeyPath:"~/.ssh/id_ed25519"};function pr(e){return e.startsWith("~/")?qa(Ga(),e.slice(2)):e}function pt(...e){for(let t of e){let r=process.env[t]?.trim();if(r)return r}return}function dt(...e){for(let t of e){let r=t?.trim();if(r)return r}return}function Dt(e,t){return dt(e,t?.hetzner?.apiToken,pt("HCLOUD_TOKEN","HETZNER_API_TOKEN"))}function Mc(e,t){return dt(t,e?.hetzner?.location,pt("HCLOUD_LOCATION","HETZNER_LOCATION"))??ur.location}function xt(e,t){let r=e?.infrastructure?.compute;return dt(t,r?.image,e?.hetzner?.image,pt("HCLOUD_IMAGE","HETZNER_IMAGE"))??ur.image}function Wa(e,t){return dt(t,e?.hetzner?.sshUser,pt("HCLOUD_SSH_USER","HETZNER_SSH_USER"))??ur.sshUser}function Ms(e,t){return pr(dt(t,e?.hetzner?.sshPrivateKeyPath,pt("HCLOUD_SSH_KEY","HETZNER_SSH_KEY"))??ur.sshPrivateKeyPath)}function Ya(e,t,r){let n=dt(t,e?.hetzner?.sshPublicKeyPath,pt("HCLOUD_SSH_PUBLIC_KEY","HETZNER_SSH_PUBLIC_KEY"));if(n)return pr(n);return`${r??Ms(e)}.pub`}function Fs(e,t={}){let r=Ms(e,t.sshPrivateKeyPath);return{apiToken:Dt(t.apiToken,e),location:Mc(e,t.location),image:xt(e,t.image),sshUser:Wa(e,t.sshUser),sshPrivateKeyPath:r,sshPublicKeyPath:Ya(e,t.sshPublicKeyPath,r)}}var Xa="https://api.hetzner.cloud/v1";class mr 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 fr extends Error{action;constructor(e,t){super(e);this.action=t;this.name="HetznerActionError"}}class $r{name="hetzner";apiToken;baseUrl;fetchImpl;constructor(e){this.apiToken=e.apiToken,this.baseUrl=e.baseUrl??Xa,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 mr(`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});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: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 fr(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 Fc(e,t){let r=Dt(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 zs(e){if(!e)return"";return e.endsWith(`
162
162
  `)?e:`${e}
@@ -276,9 +276,9 @@ 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 ic(e,t){let r=Buffer.from(t.join(`
279
- `)).toString("base64");await Se(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 Gc(e,t,r,n={recovered:!1}){if(await ai(e.host,{...e,timeoutMs:e.sshTimeoutMs??600000}),!n.recovered)await oc(e);if(r)await ic(e,r.runningServices);let s=await Qc(e),i=[],a=r?St(r.runningServices,s.runningServices):[],c=r?St(r.releaseLinks,s.releaseLinks):[],u=r?St(r.routeFragments,s.routeFragments):[],m=r?St(r.routeIds,s.routeIds):[],f=r?.persistentData.map((I)=>I.split("=")[0])??[],v=s.persistentData.map((I)=>I.split("=")[0]),_=St(f,v),S=r?St(r.dataCatalog,s.dataCatalog):[],y=s.routeProbes.filter((I)=>!I.ok),C=n.recovered&&r?r.cpuCores:t.cores??0,A=n.recovered&&r?r.memoryBytes:sc(t),x=s.cpuCores>=C,L=s.memoryBytes>=A*0.9,O=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(m.length>0)i.push(`Routes disappeared: ${m.join(", ")}`);if(_.length>0)i.push(`Persistent data paths disappeared: ${_.join(", ")}`);if(S.length>0)i.push(`Databases or volumes disappeared: ${S.join(", ")}`);if(y.length>0)i.push(`Unhealthy routes: ${y.map((I)=>I.domain).join(", ")}`);if(!x)i.push(`Expected at least ${C} CPU cores, found ${s.cpuCores}`);if(!L)i.push(`Expected at least ${A} bytes of RAM`);if(!O)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((I)=>I.ok).length,persistentDataPaths:s.persistentData.length,databasesAndVolumes:s.dataCatalog.length,failedUnits:s.failedUnits.length},failures:i}}import{mkdir as ac,readFile as cc,rename as lc,writeFile as uc}from"node:fs/promises";import{join as Bs}from"node:path";var Vc="storage/cloud/state";function mt(e=process.cwd()){return rl()?l(e,"state"):Bs(e,Vc)}function qe(e,t=process.cwd()){return Bs(mt(t),`${e}.json`)}async function je(e,t=process.cwd()){try{let r=await cc(qe(e,t),"utf8");return JSON.parse(r)}catch{return null}}async function ft(e,t,r=process.cwd()){let n=qe(e,r);await ac(mt(r),{recursive:!0});let s=`${n}.${process.pid}.tmp`;await uc(s,`${JSON.stringify(t,null,2)}
279
+ `)).toString("base64");await Se(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 Gc(e,t,r,n={recovered:!1}){if(await ai(e.host,{...e,timeoutMs:e.sshTimeoutMs??600000}),!n.recovered)await oc(e);if(r)await ic(e,r.runningServices);let s=await Qc(e),i=[],a=r?St(r.runningServices,s.runningServices):[],c=r?St(r.releaseLinks,s.releaseLinks):[],u=r?St(r.routeFragments,s.routeFragments):[],m=r?St(r.routeIds,s.routeIds):[],f=r?.persistentData.map((I)=>I.split("=")[0])??[],v=s.persistentData.map((I)=>I.split("=")[0]),_=St(f,v),S=r?St(r.dataCatalog,s.dataCatalog):[],y=s.routeProbes.filter((I)=>!I.ok),C=n.recovered&&r?r.cpuCores:t.cores??0,A=n.recovered&&r?r.memoryBytes:sc(t),x=s.cpuCores>=C,H=s.memoryBytes>=A*0.9,O=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(m.length>0)i.push(`Routes disappeared: ${m.join(", ")}`);if(_.length>0)i.push(`Persistent data paths disappeared: ${_.join(", ")}`);if(S.length>0)i.push(`Databases or volumes disappeared: ${S.join(", ")}`);if(y.length>0)i.push(`Unhealthy routes: ${y.map((I)=>I.domain).join(", ")}`);if(!x)i.push(`Expected at least ${C} CPU cores, found ${s.cpuCores}`);if(!H)i.push(`Expected at least ${A} bytes of RAM`);if(!O)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((I)=>I.ok).length,persistentDataPaths:s.persistentData.length,databasesAndVolumes:s.dataCatalog.length,failedUnits:s.failedUnits.length},failures:i}}import{mkdir as ac,readFile as cc,rename as lc,writeFile as uc}from"node:fs/promises";import{join as Bs}from"node:path";var Vc="storage/cloud/state";function mt(e=process.cwd()){return rl()?l(e,"state"):Bs(e,Vc)}function qe(e,t=process.cwd()){return Bs(mt(t),`${e}.json`)}async function je(e,t=process.cwd()){try{let r=await cc(qe(e,t),"utf8");return JSON.parse(r)}catch{return null}}async function ft(e,t,r=process.cwd()){let n=qe(e,r);await ac(mt(r),{recursive:!0});let s=`${n}.${process.pid}.tmp`;await uc(s,`${JSON.stringify(t,null,2)}
280
280
  `,"utf8"),await lc(s,n)}async function Ze(e){return je(e)}async function et(e,t){await ft(e,t)}async function di(e,t,r){let n=r.length?await e.listVolumes():[];return r.map((s)=>{let i=n.filter((m)=>m.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 li(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 Tn=268435456;function It(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function hc(e){let t=dc("sha256");for await(let r of mc(e))t.update(r);return t.digest("hex")}class Pe{name="hetzner";usesCloudFormation=!1;client;sshPrivateKeyPath;sshPublicKeyPath;sshUser;location;stateOnly;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=Yn(t,r),i=_n(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 di(this.client,c,s),m=n?.resize&&n.size?await Zs(this.client,c.id,ze(n.size),n.resize.upgradeDisk!==!1):void 0,f={serverId:String(c.id),changes:u.flatMap((y)=>y.actions.map((C)=>({resource:y.declaration.name,action:C,detail:`${y.declaration.size} GB at ${y.declaration.mountPath}`})))};if(n?.deploymentStorage)f.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(m&&!m.alreadyComplete)if(!m.capacityAvailable){if(n?.resize?.whenUnavailable!=="keep-current")throw Error(`${m.targetType.name} is unavailable in ${m.location}`);f.waitingForCapacity=`${m.targetType.name} unavailable in ${m.location}; keeping ${c.server_type.name} running`}else f.changes.push({resource:c.name,action:"resize",detail:`${c.server_type.name} to ${m.targetType.name}`});if(e.dryRun)return f;if(f.waitingForCapacity)console.warn(`[ts-cloud] ${f.waitingForCapacity}`);let v=await li(this.client,c,u),_=[{id:String(c.id),name:c.name,publicIp:c.public_net.ipv4?.ip}],S=[...We(t.notifications),...n?.volumes||n?.deploymentStorage?Zn({volumes:v,deploymentStorage:n?.deploymentStorage,webRoot:"/var/www"}):[],...n?.monitoring!==!1?xe(n?.monitoring):[]];if(S.length){let y=await this.runRemoteDeploy({targets:_,commands:S,timeoutSeconds:7200,comment:"ts-cloud apply configured compute storage"});if(!y.success)throw Error(y.error||y.perInstance.map((C)=>C.error||C.output).join(`
281
- `))}if(m?.capacityAvailable&&!m.alreadyComplete){let y={host:_[0].publicIp,user:this.sshUser,identityFile:this.sshPrivateKeyPath},C=await Uc({client:this.client,serverId:c.id,targetType:m.targetType.name,upgradeDisk:m.upgradeDisk,hooks:{preflight:()=>Hc(y),afterBoot:(A,x,L,O)=>Gc(y,x,L,O)}});if(C.status!=="completed"&&C.status!=="already-complete")throw Error(`Resize did not complete: ${C.status}`)}return f}constructor(e={}){let t=Dt(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 $r({apiToken:t??""});let r=Fs(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=p(t,r),a=`${n}-${r}-app`,c=s.runtime==="php"||!!s.php,u=_n(s);if(u.dedicatedServices||u.appServers>1)return c?this.provisionFleet(e,u):this.provisionBunFleet(e,u);let m=le(n,r,"app"),f=t.sites||{},v=j(s)?[]:this.collectUpstreamPorts(f),_=`${n}-${r}-app-fw`,{firewall:S}=await this.ensureFirewall(_,m,gr({allowSsh:s.allowSsh!==!1,sitePorts:v,allowedPorts:[...s.firewall?.allowedPorts??[],...gs(t.infrastructure?.sftp),...Xe(b(t,{environment:r}))]})),y=await this.ensureSshKey(n,r,m),C=await Ze(i);if(C?.serverId){let ee=await this.tryGetServer(C.serverId);if(ee&&ee.status!=="off"){if(s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(C,ee)}}let A=await this.findExistingServer(n,r,a);if(A&&A.status!=="off"){let ee={provider:"hetzner",stackName:i,serverId:A.id,serverName:A.name,publicIp:A.public_net.ipv4?.ip,publicIpv6:De(A.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};if(await et(i,ee),s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(ee,A)}let x=w(t,{environment:r}),L=x?.engine==="rpx"?G({proxy:x,config:B(f,{proxy:x,slug:t.project.slug,mail:b(t,{environment:r})}),slug:t.project.slug,bunBin:s.runtime==="node"||s.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,O=Ye(t,{environment:r}),I=s.bakedImage===!0,W=M({runtime:O.runtime,runtimeVersion:O.runtimeVersion,systemPackages:s.systemPackages,database:t.infrastructure?.database,phpProvision:O.phpProvision,servicesProvision:O.servicesProvision,rpxProvision:L,baked:I,swapGb:s.swapGb}),H=se(W),V=ze(s.size),te=xt(t),{server:ue,action:me}=await this.client.createServer({name:a,serverType:V,image:te,location:t.hetzner?.location||this.location,userData:H,labels:m,sshKeys:y?[y]:void 0,firewalls:[{firewall:S.id}]});await this.client.waitForAction(me.id);let Z=await this.client.waitForServerRunning(ue.id),pe={provider:"hetzner",stackName:i,serverId:Z.id,serverName:Z.name,firewallId:S.id,publicIp:Z.public_net.ipv4?.ip,publicIpv6:De(Z.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};await et(i,pe);let ne=Z.public_net.ipv4?.ip;if(ne&&this.waitForBoot)await this.waitForSshReady(ne),await this.waitForCloudInit(ne);if(s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(pe,Z)}async provisionFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,i=r.infrastructure.compute,a=p(r,n),c=ze(i.size),u=xt(r),m=r.hetzner?.location||this.location,f=i.bakedImage===!0,v=await Ze(a);if(v?.loadBalancerId){let q=(await this.client.listLoadBalancers().catch(()=>[])).find((k)=>k.id===v.loadBalancerId);if(q)return{appPublicIp:q.public_net?.ipv4?.ip,loadBalancerIp:q.public_net?.ipv4?.ip,servicesPrivateIp:v.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}let _=await this.ensureSshKey(s,n,le(s,n,"app")),S=`${s}-${n}-net`,C=(await this.client.listNetworks().catch(()=>[])).find((R)=>R.name===S)??await this.client.createNetwork({name:S,labels:le(s,n,"app")}),{firewall:A}=await this.ensureFirewall(`${s}-${n}-app-fw`,le(s,n,"app"),gr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),{firewall:x}=await this.ensureFirewall(`${s}-${n}-services-fw`,le(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:[C.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[C.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[C.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[C.ip_range]}]),L=vn(r),O=se(M({runtime:"php",servicesProvision:L,baked:f,swapGb:i.swapGb})),I=await this.client.listServers().catch(()=>[]),W=[],H=I.find((R)=>_e(R.labels,s,n,"services"));if(!H){let{server:R,action:q}=await this.client.createServer({name:`${s}-${n}-services`,serverType:ze(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:u,location:m,userData:O,labels:le(s,n,"services"),sshKeys:_?[_]:void 0,firewalls:[{firewall:x.id}],networks:[C.id]});await this.client.waitForAction(q.id),H=await this.client.waitForServerRunning(R.id),W.push(R.id)}let V=H.id,te=H.private_net?.[0]?.ip??(await this.client.getServer(V)).private_net?.[0]?.ip,ue=[...Ue(!0),...xe(!0),...it(i.sshKeys),...We(r.notifications)],me=qt({versions:i.php?.versions,default:i.php?.default,extensions:i.php?.extensions,installNginx:!j(i),optimizeForProduction:i.php?.optimizeForProduction,ini:i.php?.ini}),Z=se(M({runtime:"php",phpProvision:me,servicesProvision:ue,baked:f,swapGb:i.swapGb})),pe=I.filter((R)=>_e(R.labels,s,n,"app")),ne=pe.map((R)=>R.id);if(pe.length>t.appServers)for(let R of pe.slice(t.appServers))await this.client.deleteServer(R.id).catch(()=>{}),ne.splice(ne.indexOf(R.id),1);for(let R=pe.length;R<t.appServers;R++){let{server:q,action:k}=await this.client.createServer({name:`${s}-${n}-app-${R+1}`,serverType:c,image:u,location:m,userData:Z,labels:le(s,n,"app"),sshKeys:_?[_]:void 0,firewalls:[{firewall:A.id}],networks:[C.id]});await this.client.waitForAction(k.id),ne.push(q.id),W.push(q.id)}if(this.waitForBoot&&W.length>0)await Promise.all(W.map(async(R)=>{let k=(await this.client.waitForServerRunning(R)).public_net.ipv4?.ip;if(k)await this.waitForSshReady(k),await this.waitForCloudInit(k)}));let ee=`${s}-${n}-lb`,ge,P;if(t.loadBalancer){let q=(await this.client.listLoadBalancers().catch(()=>[])).find((k)=>k.name===ee)??await this.client.createLoadBalancer({name:ee,location:m,network:C.id,labels:le(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}]});P=q.id,ge=q.public_net?.ipv4?.ip}let D=ge??(await this.client.getServer(ne[0]).catch(()=>{return}))?.public_net.ipv4?.ip,N={provider:"hetzner",stackName:a,networkId:C.id,loadBalancerId:P,servicesServerId:V,servicesPrivateIp:te,publicIp:D,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await et(a,N),{appPublicIp:D,loadBalancerIp:ge,servicesPrivateIp:te,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=p(r,n),c=ze(i.size),u=xt(r),m=r.hetzner?.location||this.location,f=i.bakedImage===!0,v=r.sites||{},_=await Ze(a);if(_?.lbServerId){let k=await this.tryGetServer(_.lbServerId);if(k&&k.status!=="off"){let Y=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"},X=await this.findComputeTargets({slug:s,environment:n,role:"app",stackName:a});return this.refreshLbRoutes(k,v,X.map((J)=>({privateIp:J.privateIp,publicIp:J.publicIp})),Y,s),{appPublicIp:k.public_net.ipv4?.ip??_.publicIp,loadBalancerIp:k.public_net.ipv4?.ip??_.publicIp,servicesPrivateIp:_.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}}let S=await this.ensureSshKey(s,n,le(s,n,"app")),y=`${s}-${n}-net`,A=(await this.client.listNetworks().catch(()=>[])).find((k)=>k.name===y)??await this.client.createNetwork({name:y,labels:le(s,n,"app")}),x=this.collectUpstreamPorts(v),{firewall:L}=await this.ensureFirewall(`${s}-${n}-app-fw`,le(s,n,"app"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},...x.map((k)=>({direction:"in",protocol:"tcp",port:String(k),source_ips:[A.ip_range],description:`ts-cloud port ${k} (private, LB-only)`}))]),{firewall:O}=await this.ensureFirewall(`${s}-${n}-lb-fw`,le(s,n,"lb"),gr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),I=await this.client.listServers().catch(()=>[]),W=[],H,V,te=!!i.servicesServer||!!i.managedServices,ue=t.dedicatedServices&&te;if(ue){let{firewall:k}=await this.ensureFirewall(`${s}-${n}-services-fw`,le(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:[A.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[A.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[A.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[A.ip_range]}]),Y=vn(r),X=se(M({runtime:"bun",servicesProvision:Y,baked:f,swapGb:i.swapGb})),J=I.find((E)=>_e(E.labels,s,n,"services"));if(!J){let{server:E,action:K}=await this.client.createServer({name:`${s}-${n}-services`,serverType:ze(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:u,location:m,userData:X,labels:le(s,n,"services"),sshKeys:S?[S]:void 0,firewalls:[{firewall:k.id}],networks:[A.id]});await this.client.waitForAction(K.id),J=await this.client.waitForServerRunning(E.id),W.push(E.id)}H=J.id,V=J.private_net?.[0]?.ip??(await this.client.getServer(H)).private_net?.[0]?.ip}let me=ue?{...i,managedServices:void 0,backups:void 0}:i,Z=Ye({...r,infrastructure:{...r.infrastructure,compute:me}},{environment:n}),pe=se(M({runtime:Z.runtime,runtimeVersion:Z.runtimeVersion,systemPackages:i.systemPackages,database:r.infrastructure?.database,servicesProvision:Z.servicesProvision,baked:f,swapGb:i.swapGb})),ne=I.filter((k)=>_e(k.labels,s,n,"app")),ee=ne.map((k)=>k.id);if(ne.length>t.appServers)for(let k of ne.slice(t.appServers))await this.client.deleteServer(k.id).catch(()=>{}),ee.splice(ee.indexOf(k.id),1);for(let k=ne.length;k<t.appServers;k++){let{server:Y,action:X}=await this.client.createServer({name:`${s}-${n}-app-${k+1}`,serverType:c,image:u,location:m,userData:pe,labels:le(s,n,"app"),sshKeys:S?[S]:void 0,firewalls:[{firewall:L.id}],networks:[A.id]});await this.client.waitForAction(X.id),ee.push(Y.id),W.push(Y.id)}if(this.waitForBoot&&W.length>0)await Promise.all(W.map(async(k)=>{let X=(await this.client.waitForServerRunning(k)).public_net.ipv4?.ip;if(X)await this.waitForSshReady(X),await this.waitForCloudInit(X)}));let ge=[];for(let k of ee){let Y=I.find((X)=>X.id===k);if(!Y||!Y.private_net?.[0]?.ip)Y=await this.client.getServer(k).catch(()=>Y);ge.push({privateIp:Y?.private_net?.[0]?.ip,publicIp:Y?.public_net.ipv4?.ip})}let P=`${s}-${n}-lb`,D,N;if(t.loadBalancer){let k=I.find((X)=>_e(X.labels,s,n,"lb")),Y=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"};if(!k){let X=G({proxy:Y,config:Xt(v,ge,{proxy:Y,slug:s}),slug:s,bunBin:Z.runtime==="node"||Z.runtime==="deno"?void 0:"/usr/local/bin/bun"}),J=se(M({runtime:"bun",rpxProvision:X,baked:!1})),E=typeof i.loadBalancer==="object"?i.loadBalancer.size:void 0,{server:K,action:ie}=await this.client.createServer({name:P,serverType:ze(E??"micro"),image:u,location:m,userData:J,labels:le(s,n,"lb"),sshKeys:S?[S]:void 0,firewalls:[{firewall:O.id}],networks:[A.id]});if(await this.client.waitForAction(ie.id),k=await this.client.waitForServerRunning(K.id),this.waitForBoot){let re=k.public_net.ipv4?.ip;if(re)await this.waitForSshReady(re),await this.waitForCloudInit(re)}}else this.refreshLbRoutes(k,v,ge,Y,s);D=k.id,N=k.public_net.ipv4?.ip}let R=N??(await this.client.getServer(ee[0]).catch(()=>{return}))?.public_net.ipv4?.ip,q={provider:"hetzner",stackName:a,networkId:A.id,lbServerId:D,appServerIds:ee,servicesServerId:H,servicesPrivateIp:V,publicIp:R,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await et(a,q),{appPublicIp:R,loadBalancerIp:N,servicesPrivateIp:V,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async destroyCompute(e){let{config:t,environment:r}=e,n=t.project.slug,s=p(t,r),i=await Ze(s),a=[],c=`${n}-${r}-lb`,m=(await this.client.listLoadBalancers().catch(()=>[])).find((L)=>L.name===c);if(m)try{await this.client.deleteLoadBalancer(m.id),a.push(`load balancer ${c}`)}catch{}let f=await this.client.listServers().catch(()=>[]),v=new Set;for(let L of f)if(_e(L.labels,n,r,"app")||_e(L.labels,n,r,"services")||_e(L.labels,n,r,"lb"))v.add(L.id);if(i?.serverId)v.add(i.serverId);if(i?.servicesServerId)v.add(i.servicesServerId);if(i?.lbServerId)v.add(i.lbServerId);for(let L of i?.appServerIds??[])v.add(L);for(let L of v)try{await this.client.deleteServer(L),a.push(`server ${L}`)}catch{}let _=await this.client.listFirewalls().catch(()=>[]);for(let L of[`${n}-${r}-app-fw`,`${n}-${r}-services-fw`,`${n}-${r}-lb-fw`]){let O=_.find((I)=>I.name===L);if(!O)continue;for(let I=0;I<12;I++)try{await this.client.deleteFirewall(O.id),a.push(`firewall ${L}`);break}catch{await this.sleep(3000)}}let S=`${n}-${r}-net`,C=(await this.client.listNetworks().catch(()=>[])).find((L)=>L.name===S);if(C)for(let L=0;L<12;L++)try{await this.client.deleteNetwork(C.id),a.push(`network ${S}`);break}catch{await this.sleep(3000)}let x=(await this.client.listSshKeys().catch(()=>[])).filter((L)=>$n(L.labels,n,r));for(let L of x)try{await this.client.deleteSshKey(L.id),a.push(`ssh key ${L.name}`)}catch{}return await et(s,{provider:"hetzner",stackName:s}).catch(()=>{}),{destroyed:a}}async getComputeOutputs(e){let t=p(e.config,e.environment),r=await Ze(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:p(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:p(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,"-")}-${js()}.tar.gz`}`,i=await hc(e.localPath),a=Or,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 m=["set -euo pipefail",`mkdir -p ${It(a)} /var/ts-cloud/staging`,`test -s ${It(c)}`,`cp -- ${It(c)} ${It(s)}`].join(`
281
+ `))}if(m?.capacityAvailable&&!m.alreadyComplete){let y={host:_[0].publicIp,user:this.sshUser,identityFile:this.sshPrivateKeyPath},C=await Uc({client:this.client,serverId:c.id,targetType:m.targetType.name,upgradeDisk:m.upgradeDisk,hooks:{preflight:()=>Hc(y),afterBoot:(A,x,H,O)=>Gc(y,x,H,O)}});if(C.status!=="completed"&&C.status!=="already-complete")throw Error(`Resize did not complete: ${C.status}`)}return f}constructor(e={}){let t=Dt(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 $r({apiToken:t??""});let r=Fs(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=p(t,r),a=`${n}-${r}-app`,c=s.runtime==="php"||!!s.php,u=_n(s);if(u.dedicatedServices||u.appServers>1)return c?this.provisionFleet(e,u):this.provisionBunFleet(e,u);let m=le(n,r,"app"),f=t.sites||{},v=j(s)?[]:this.collectUpstreamPorts(f),_=`${n}-${r}-app-fw`,{firewall:S}=await this.ensureFirewall(_,m,gr({allowSsh:s.allowSsh!==!1,sitePorts:v,allowedPorts:[...s.firewall?.allowedPorts??[],...gs(t.infrastructure?.sftp),...Xe(b(t,{environment:r}))]})),y=await this.ensureSshKey(n,r,m),C=await Ze(i);if(C?.serverId){let ee=await this.tryGetServer(C.serverId);if(ee&&ee.status!=="off"){if(s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(C,ee)}}let A=await this.findExistingServer(n,r,a);if(A&&A.status!=="off"){let ee={provider:"hetzner",stackName:i,serverId:A.id,serverName:A.name,publicIp:A.public_net.ipv4?.ip,publicIpv6:De(A.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};if(await et(i,ee),s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(ee,A)}let x=w(t,{environment:r}),H=x?.engine==="rpx"?G({proxy:x,config:B(f,{proxy:x,slug:t.project.slug,mail:b(t,{environment:r})}),slug:t.project.slug,bunBin:s.runtime==="node"||s.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,O=Ye(t,{environment:r}),I=s.bakedImage===!0,W=M({runtime:O.runtime,runtimeVersion:O.runtimeVersion,systemPackages:s.systemPackages,database:t.infrastructure?.database,phpProvision:O.phpProvision,servicesProvision:O.servicesProvision,rpxProvision:H,baked:I,swapGb:s.swapGb}),k=se(W),V=ze(s.size),te=xt(t),{server:ue,action:me}=await this.client.createServer({name:a,serverType:V,image:te,location:t.hetzner?.location||this.location,userData:k,labels:m,sshKeys:y?[y]:void 0,firewalls:[{firewall:S.id}]});await this.client.waitForAction(me.id);let Z=await this.client.waitForServerRunning(ue.id),pe={provider:"hetzner",stackName:i,serverId:Z.id,serverName:Z.name,firewallId:S.id,publicIp:Z.public_net.ipv4?.ip,publicIpv6:De(Z.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};await et(i,pe);let ne=Z.public_net.ipv4?.ip;if(ne&&this.waitForBoot)await this.waitForSshReady(ne),await this.waitForCloudInit(ne);if(s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(pe,Z)}async provisionFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,i=r.infrastructure.compute,a=p(r,n),c=ze(i.size),u=xt(r),m=r.hetzner?.location||this.location,f=i.bakedImage===!0,v=await Ze(a);if(v?.loadBalancerId){let q=(await this.client.listLoadBalancers().catch(()=>[])).find((N)=>N.id===v.loadBalancerId);if(q)return{appPublicIp:q.public_net?.ipv4?.ip,loadBalancerIp:q.public_net?.ipv4?.ip,servicesPrivateIp:v.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}let _=await this.ensureSshKey(s,n,le(s,n,"app")),S=`${s}-${n}-net`,C=(await this.client.listNetworks().catch(()=>[])).find((R)=>R.name===S)??await this.client.createNetwork({name:S,labels:le(s,n,"app")}),{firewall:A}=await this.ensureFirewall(`${s}-${n}-app-fw`,le(s,n,"app"),gr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),{firewall:x}=await this.ensureFirewall(`${s}-${n}-services-fw`,le(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:[C.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[C.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[C.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[C.ip_range]}]),H=vn(r),O=se(M({runtime:"php",servicesProvision:H,baked:f,swapGb:i.swapGb})),I=await this.client.listServers().catch(()=>[]),W=[],k=I.find((R)=>_e(R.labels,s,n,"services"));if(!k){let{server:R,action:q}=await this.client.createServer({name:`${s}-${n}-services`,serverType:ze(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:u,location:m,userData:O,labels:le(s,n,"services"),sshKeys:_?[_]:void 0,firewalls:[{firewall:x.id}],networks:[C.id]});await this.client.waitForAction(q.id),k=await this.client.waitForServerRunning(R.id),W.push(R.id)}let V=k.id,te=k.private_net?.[0]?.ip??(await this.client.getServer(V)).private_net?.[0]?.ip,ue=[...Ue(!0),...xe(!0),...it(i.sshKeys),...We(r.notifications)],me=qt({versions:i.php?.versions,default:i.php?.default,extensions:i.php?.extensions,installNginx:!j(i),optimizeForProduction:i.php?.optimizeForProduction,ini:i.php?.ini}),Z=se(M({runtime:"php",phpProvision:me,servicesProvision:ue,baked:f,swapGb:i.swapGb})),pe=I.filter((R)=>_e(R.labels,s,n,"app")),ne=pe.map((R)=>R.id);if(pe.length>t.appServers)for(let R of pe.slice(t.appServers))await this.client.deleteServer(R.id).catch(()=>{}),ne.splice(ne.indexOf(R.id),1);for(let R=pe.length;R<t.appServers;R++){let{server:q,action:N}=await this.client.createServer({name:`${s}-${n}-app-${R+1}`,serverType:c,image:u,location:m,userData:Z,labels:le(s,n,"app"),sshKeys:_?[_]:void 0,firewalls:[{firewall:A.id}],networks:[C.id]});await this.client.waitForAction(N.id),ne.push(q.id),W.push(q.id)}if(this.waitForBoot&&W.length>0)await Promise.all(W.map(async(R)=>{let N=(await this.client.waitForServerRunning(R)).public_net.ipv4?.ip;if(N)await this.waitForSshReady(N),await this.waitForCloudInit(N)}));let ee=`${s}-${n}-lb`,ge,P;if(t.loadBalancer){let q=(await this.client.listLoadBalancers().catch(()=>[])).find((N)=>N.name===ee)??await this.client.createLoadBalancer({name:ee,location:m,network:C.id,labels:le(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}]});P=q.id,ge=q.public_net?.ipv4?.ip}let D=ge??(await this.client.getServer(ne[0]).catch(()=>{return}))?.public_net.ipv4?.ip,K={provider:"hetzner",stackName:a,networkId:C.id,loadBalancerId:P,servicesServerId:V,servicesPrivateIp:te,publicIp:D,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await et(a,K),{appPublicIp:D,loadBalancerIp:ge,servicesPrivateIp:te,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=p(r,n),c=ze(i.size),u=xt(r),m=r.hetzner?.location||this.location,f=i.bakedImage===!0,v=r.sites||{},_=await Ze(a);if(_?.lbServerId){let N=await this.tryGetServer(_.lbServerId);if(N&&N.status!=="off"){let Y=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"},X=await this.findComputeTargets({slug:s,environment:n,role:"app",stackName:a});return this.refreshLbRoutes(N,v,X.map((J)=>({privateIp:J.privateIp,publicIp:J.publicIp})),Y,s),{appPublicIp:N.public_net.ipv4?.ip??_.publicIp,loadBalancerIp:N.public_net.ipv4?.ip??_.publicIp,servicesPrivateIp:_.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}}let S=await this.ensureSshKey(s,n,le(s,n,"app")),y=`${s}-${n}-net`,A=(await this.client.listNetworks().catch(()=>[])).find((N)=>N.name===y)??await this.client.createNetwork({name:y,labels:le(s,n,"app")}),x=this.collectUpstreamPorts(v),{firewall:H}=await this.ensureFirewall(`${s}-${n}-app-fw`,le(s,n,"app"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},...x.map((N)=>({direction:"in",protocol:"tcp",port:String(N),source_ips:[A.ip_range],description:`ts-cloud port ${N} (private, LB-only)`}))]),{firewall:O}=await this.ensureFirewall(`${s}-${n}-lb-fw`,le(s,n,"lb"),gr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),I=await this.client.listServers().catch(()=>[]),W=[],k,V,te=!!i.servicesServer||!!i.managedServices,ue=t.dedicatedServices&&te;if(ue){let{firewall:N}=await this.ensureFirewall(`${s}-${n}-services-fw`,le(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:[A.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[A.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[A.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[A.ip_range]}]),Y=vn(r),X=se(M({runtime:"bun",servicesProvision:Y,baked:f,swapGb:i.swapGb})),J=I.find((E)=>_e(E.labels,s,n,"services"));if(!J){let{server:E,action:L}=await this.client.createServer({name:`${s}-${n}-services`,serverType:ze(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:u,location:m,userData:X,labels:le(s,n,"services"),sshKeys:S?[S]:void 0,firewalls:[{firewall:N.id}],networks:[A.id]});await this.client.waitForAction(L.id),J=await this.client.waitForServerRunning(E.id),W.push(E.id)}k=J.id,V=J.private_net?.[0]?.ip??(await this.client.getServer(k)).private_net?.[0]?.ip}let me=ue?{...i,managedServices:void 0,backups:void 0}:i,Z=Ye({...r,infrastructure:{...r.infrastructure,compute:me}},{environment:n}),pe=se(M({runtime:Z.runtime,runtimeVersion:Z.runtimeVersion,systemPackages:i.systemPackages,database:r.infrastructure?.database,servicesProvision:Z.servicesProvision,baked:f,swapGb:i.swapGb})),ne=I.filter((N)=>_e(N.labels,s,n,"app")),ee=ne.map((N)=>N.id);if(ne.length>t.appServers)for(let N of ne.slice(t.appServers))await this.client.deleteServer(N.id).catch(()=>{}),ee.splice(ee.indexOf(N.id),1);for(let N=ne.length;N<t.appServers;N++){let{server:Y,action:X}=await this.client.createServer({name:`${s}-${n}-app-${N+1}`,serverType:c,image:u,location:m,userData:pe,labels:le(s,n,"app"),sshKeys:S?[S]:void 0,firewalls:[{firewall:H.id}],networks:[A.id]});await this.client.waitForAction(X.id),ee.push(Y.id),W.push(Y.id)}if(this.waitForBoot&&W.length>0)await Promise.all(W.map(async(N)=>{let X=(await this.client.waitForServerRunning(N)).public_net.ipv4?.ip;if(X)await this.waitForSshReady(X),await this.waitForCloudInit(X)}));let ge=[];for(let N of ee){let Y=I.find((X)=>X.id===N);if(!Y||!Y.private_net?.[0]?.ip)Y=await this.client.getServer(N).catch(()=>Y);ge.push({privateIp:Y?.private_net?.[0]?.ip,publicIp:Y?.public_net.ipv4?.ip})}let P=`${s}-${n}-lb`,D,K;if(t.loadBalancer){let N=I.find((X)=>_e(X.labels,s,n,"lb")),Y=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"};if(!N){let X=G({proxy:Y,config:Xt(v,ge,{proxy:Y,slug:s}),slug:s,bunBin:Z.runtime==="node"||Z.runtime==="deno"?void 0:"/usr/local/bin/bun"}),J=se(M({runtime:"bun",rpxProvision:X,baked:!1})),E=typeof i.loadBalancer==="object"?i.loadBalancer.size:void 0,{server:L,action:ie}=await this.client.createServer({name:P,serverType:ze(E??"micro"),image:u,location:m,userData:J,labels:le(s,n,"lb"),sshKeys:S?[S]:void 0,firewalls:[{firewall:O.id}],networks:[A.id]});if(await this.client.waitForAction(ie.id),N=await this.client.waitForServerRunning(L.id),this.waitForBoot){let re=N.public_net.ipv4?.ip;if(re)await this.waitForSshReady(re),await this.waitForCloudInit(re)}}else this.refreshLbRoutes(N,v,ge,Y,s);D=N.id,K=N.public_net.ipv4?.ip}let R=K??(await this.client.getServer(ee[0]).catch(()=>{return}))?.public_net.ipv4?.ip,q={provider:"hetzner",stackName:a,networkId:A.id,lbServerId:D,appServerIds:ee,servicesServerId:k,servicesPrivateIp:V,publicIp:R,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await et(a,q),{appPublicIp:R,loadBalancerIp:K,servicesPrivateIp:V,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async destroyCompute(e){let{config:t,environment:r}=e,n=t.project.slug,s=p(t,r),i=await Ze(s),a=[],c=`${n}-${r}-lb`,m=(await this.client.listLoadBalancers().catch(()=>[])).find((H)=>H.name===c);if(m)try{await this.client.deleteLoadBalancer(m.id),a.push(`load balancer ${c}`)}catch{}let f=await this.client.listServers().catch(()=>[]),v=new Set;for(let H of f)if(_e(H.labels,n,r,"app")||_e(H.labels,n,r,"services")||_e(H.labels,n,r,"lb"))v.add(H.id);if(i?.serverId)v.add(i.serverId);if(i?.servicesServerId)v.add(i.servicesServerId);if(i?.lbServerId)v.add(i.lbServerId);for(let H of i?.appServerIds??[])v.add(H);for(let H of v)try{await this.client.deleteServer(H),a.push(`server ${H}`)}catch{}let _=await this.client.listFirewalls().catch(()=>[]);for(let H of[`${n}-${r}-app-fw`,`${n}-${r}-services-fw`,`${n}-${r}-lb-fw`]){let O=_.find((I)=>I.name===H);if(!O)continue;for(let I=0;I<12;I++)try{await this.client.deleteFirewall(O.id),a.push(`firewall ${H}`);break}catch{await this.sleep(3000)}}let S=`${n}-${r}-net`,C=(await this.client.listNetworks().catch(()=>[])).find((H)=>H.name===S);if(C)for(let H=0;H<12;H++)try{await this.client.deleteNetwork(C.id),a.push(`network ${S}`);break}catch{await this.sleep(3000)}let x=(await this.client.listSshKeys().catch(()=>[])).filter((H)=>$n(H.labels,n,r));for(let H of x)try{await this.client.deleteSshKey(H.id),a.push(`ssh key ${H.name}`)}catch{}return await et(s,{provider:"hetzner",stackName:s}).catch(()=>{}),{destroyed:a}}async getComputeOutputs(e){let t=p(e.config,e.environment),r=await Ze(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:p(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:p(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,"-")}-${js()}.tar.gz`}`,i=await hc(e.localPath),a=Or,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 m=["set -euo pipefail",`mkdir -p ${It(a)} /var/ts-cloud/staging`,`test -s ${It(c)}`,`cp -- ${It(c)} ${It(s)}`].join(`
282
282
  `);try{this.sshExec(u.publicIp,m);continue}catch{}let f=`${a}/.${i}-${js()}.tmp`;try{this.scpToHost(u.publicIp,e.localPath,f),this.sshExec(u.publicIp,ar(f,c,s))}catch(v){try{this.sshExec(u.publicIp,lr(f))}catch{}throw v}}return{artifactRef:s}}async findComputeTargets(e){let t=e.role||"app",r=(i)=>({id:String(i.id),name:i.name,publicIp:i.public_net.ipv4?.ip,publicIpv6:De(i.public_net.ipv6?.ip),privateIp:i.private_net?.[0]?.ip,status:i.status});if(t==="app"||t==="lb"||t==="services"){let i=await Ze(e.stackName??`${e.slug}-${e.environment}`),a=[...new Set(t==="app"?[i?.serverId,...i?.appServerIds??[]]:t==="lb"?[i?.lbServerId]:[i?.servicesServerId])].filter((m)=>typeof m==="number");if(this.stateOnly){if(a.length>0&&i?.publicIp)return a.map((m)=>({id:String(m),name:m===i.serverId?i.serverName:void 0,publicIp:i.publicIp,publicIpv6:i.publicIpv6,status:"running"}));if(t!=="app")return[];throw Error(`Hetzner API token required because '${e.stackName??`${e.slug}-${e.environment}`}' has no complete local compute state pin.`)}let c=await this.client.listServers();if(a.length>0){let m=[];for(let f of a){let v=c.find((_)=>_.id===f)??await this.tryGetServer(f);if(f===i?.serverId&&i.serverName&&v?.name!==i.serverName)continue;if(v&&v.status!=="off")m.push(v)}if(m.length>0)return m.map(r)}let u=c.filter((m)=>_e(m.labels,e.slug,e.environment,t));if(u.length>0)return u.map(r);if(t==="app"){let m=c.filter((f)=>f.status!=="off"&&f.labels?.[`${ae}/managed-by`]==="ts-cloud"&&f.labels?.[`${ae}/environment`]===e.environment&&f.labels?.[`${ae}/role`]==="app");if(m.length===1)return m.map(r)}return[]}if(this.stateOnly)throw Error(`Hetzner API token required to discover '${t}' compute targets.`);let s=(await this.client.listServers()).filter((i)=>_e(i.labels,e.slug,e.environment,t));if(s.length>0)return s.map(r);return[]}async attachToComputeInfrastructure(e,t,r){let n=await this.client.listServers(),s=(_)=>n.filter((S)=>S.status!=="off"&&_e(S.labels,e,r,_)),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],m=a??u,f=p(t,r),v={provider:"hetzner",stackName:f,serverId:u.id,serverName:u.name,appServerIds:i.map((_)=>_.id),lbServerId:a?.id,servicesServerId:c?.id,servicesPrivateIp:c?.private_net?.[0]?.ip,publicIp:m.public_net.ipv4?.ip,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await et(f,v),this.outputsFromState(v)}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);Pr(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:zt(r,"One or more SSH deploy commands failed")}}async ensureSshKey(e,t,r){if(!fc(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=gc(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=Xt(t,a,{proxy:n,slug:s});this.sshExec(i,Ne({config:c,slug:s}).join(`
284
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?.[`${ae}/managed-by`]==="ts-cloud"&&a.labels?.[`${ae}/environment`]===t&&a.labels?.[`${ae}/role`]==="app");if(i.length===1){let a=i[0],c=a.labels?.[`${ae}/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{Ks(`ssh ${this.sshBaseArgs(e,["-o","ConnectTimeout=5"]).map(It).join(" ")} true`,{stdio:"pipe",maxBuffer:Tn});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}:
@@ -317,7 +317,7 @@ 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 ${tt(e)})" /var/ts-cloud/artifacts /var/ts-cloud/staging
320
- `}function Ac(e){let t=tt(e),r=`/home/${e}`;return[`chown -R ${t}:"$(id -gn ${t})" ${tt(`${r}/.ssh`)}`,`chmod 700 ${tt(`${r}/.ssh`)}`]}function gi(e){let{config:t,environment:r,profile:n,sudoUser:s}=e;to(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",...Qs(e)?{ip:Qs(e)}:{}}:void 0,m=i.proxy?.engine==="rpx"?B(a,{proxy:i.proxy,slug:c,lan:u,mail:b(t,{environment:e.environment,environmentType:e.environment})}):void 0,f=i.proxy?.engine==="rpx"&&m?G({proxy:i.proxy,config:m,slug:c,profile:n,bunBin:i.runtime==="node"||i.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,v=i.proxy?.engine==="rpx"&&m?Ne({config:m,slug:c}):void 0,_=s?`/home/${s}/.ssh/authorized_keys`:void 0,S=Ye(t,{environment:r,authorizedKeysPath:_}),y=s?[...S.servicesProvision??[],...Ac(s)]:S.servicesProvision,C=[...new Set([...i.systemPackages??[],"psmisc","ca-certificates"])],A=i.swapGb??(n==="raspberry-pi"?jg:void 0),x=M({runtime:S.runtime,runtimeVersion:S.runtimeVersion,systemPackages:C,database:t.infrastructure?.database,phpProvision:S.phpProvision,servicesProvision:y,rpxProvision:f,swapGb:A}).replace(/^#!\/bin\/bash\nset -euo pipefail\n/,""),L=qg(),O=m?.localCa?` lan=${m.localCa.hosts.join(",")} tls=local-ca`:u?` lan=${u.hostname??`${c}.local`} tls=${u.tls??"local-ca"}`:"",I=`#!/bin/bash
320
+ `}function Ac(e){let t=tt(e),r=`/home/${e}`;return[`chown -R ${t}:"$(id -gn ${t})" ${tt(`${r}/.ssh`)}`,`chmod 700 ${tt(`${r}/.ssh`)}`]}function gi(e){let{config:t,environment:r,profile:n,sudoUser:s}=e;to(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",...Qs(e)?{ip:Qs(e)}:{}}:void 0,m=i.proxy?.engine==="rpx"?B(a,{proxy:i.proxy,slug:c,lan:u,mail:b(t,{environment:e.environment,environmentType:e.environment})}):void 0,f=i.proxy?.engine==="rpx"&&m?G({proxy:i.proxy,config:m,slug:c,profile:n,bunBin:i.runtime==="node"||i.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,v=i.proxy?.engine==="rpx"&&m?Ne({config:m,slug:c}):void 0,_=s?`/home/${s}/.ssh/authorized_keys`:void 0,S=Ye(t,{environment:r,authorizedKeysPath:_}),y=s?[...S.servicesProvision??[],...Ac(s)]:S.servicesProvision,C=[...new Set([...i.systemPackages??[],"psmisc","ca-certificates"])],A=i.swapGb??(n==="raspberry-pi"?jg:void 0),x=M({runtime:S.runtime,runtimeVersion:S.runtimeVersion,systemPackages:C,database:t.infrastructure?.database,phpProvision:S.phpProvision,servicesProvision:y,rpxProvision:f,swapGb:A}).replace(/^#!\/bin\/bash\nset -euo pipefail\n/,""),H=qg(),O=m?.localCa?` lan=${m.localCa.hosts.join(",")} tls=local-ca`:u?` lan=${u.hostname??`${c}.local`} tls=${u.tls??"local-ca"}`:"",I=`#!/bin/bash
321
321
  set -euo pipefail
322
322
  # ts-cloud ssh bootstrap v${ke} profile=${n}${O}
323
323
 
@@ -325,7 +325,7 @@ set -euo pipefail
325
325
  # adopt, a deploy): once this version has been applied, only the gateway's
326
326
  # route fragment is refreshed, so a rerun cannot re-download the runtime or
327
327
  # re-create swap on every boot.
328
- if [ -e ${tt(L)} ]; then
328
+ if [ -e ${tt(H)} ]; then
329
329
  echo "[ts-cloud] bootstrap v${ke} already applied; refreshing the gateway fragment only"
330
330
  `;if(v){let W=v[0]==="set -euo pipefail"?v.slice(1):v;I+=`${W.join(`
331
331
  `)}
@@ -334,7 +334,7 @@ fi
334
334
  `,I+=Rc(),n==="raspberry-pi")I+=Dc();if(s)I+=Ic(s);if(I+=`
335
335
  ${x}`,I+=`
336
336
  install -d -m 0755 ${tt(Wc)}
337
- date -u +%Y-%m-%dT%H:%M:%SZ > ${tt(L)}
337
+ date -u +%Y-%m-%dT%H:%M:%SZ > ${tt(H)}
338
338
  echo "[ts-cloud] bootstrap v${ke} applied (${n}); gateway fragment at ${z}/${c}.json"
339
339
  `,m?.localCa)I+=`echo "[ts-cloud] LAN certificate authority for ${m.localCa.hosts.join(", ")} at ${co(m.localCa.dir)} (copy it to a client to trust this box)"
340
340
  `;return I}var At={user:"root",port:22,privateKeyPath:"~/.ssh/id_ed25519",hostKey:"pin",profile:"generic",publicIp:"auto"},oo=["pin","accept-new","insecure"],ao=["raspberry-pi","generic"];function _t(...e){for(let t of e){let r=process.env[t]?.trim();if(r)return r}return}function Lt(...e){for(let t of e){let r=t?.trim();if(r)return r}return}function zg(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 Kg(e,t){return Lt(t,e?.user,_t("TS_CLOUD_SSH_USER"))??At.user}function Wg(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 At.port}function Jg(e,t){return pr(Lt(t,e?.privateKeyPath,_t("TS_CLOUD_SSH_KEY"))??At.privateKeyPath)}function Xg(e,t){let r=Lt(t,e?.ssh?.hostKey,_t("TS_CLOUD_SSH_HOST_KEY"))??At.hostKey;if(!oo.includes(r))throw Error(`Invalid ssh.hostKey '${r}'. Use one of: ${oo.join(", ")}.`);return r}function Yg(e,t=At.user,r){return r??e?.ssh?.sudo??t!=="root"}function Zg(e,t){let r=Lt(t,e?.ssh?.profile,_t("TS_CLOUD_SSH_PROFILE"))??At.profile;if(!ao.includes(r))throw Error(`Invalid ssh.profile '${r}'. Use one of: ${ao.join(", ")}.`);return r}function ep(e,t){return Lt(t,e?.ssh?.publicIp)??At.publicIp}function tp(e,t){return t??e?.ssh?.lan}function pi(e,t={}){let r=zg(e,t.hosts).map((n)=>({host:n.host,user:Kg(n,t.user),port:Wg(n,t.port),privateKeyPath:Jg(n,t.privateKeyPath),role:n.role??"app"}));return{hosts:r,hostKey:Xg(e,t.hostKey),sudo:Yg(e,r[0]?.user,t.sudo),profile:Zg(e,t.profile),publicIp:ep(e,t.publicIp),lan:tp(e,t.lan)}}var mi=`set -u
@@ -429,11 +429,11 @@ console.log(JSON.stringify({
429
429
  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 Rn(e){return e!=null&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function Ul(){return Q("dashboard-release")}function To(){let e=On($o(import.meta.url));for(let t of[de(e,"..","..","package.json"),de(e,"..","package.json")])try{let r=JSON.parse(vo(t,"utf8"));if(r.name==="@stacksjs/ts-cloud"&&r.version)return`^${r.version}`}catch{}return"latest"}function Hl(){return process.env.TS_CLOUD_UI_VERSION?.trim()||To()}function kl(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{_o(n,{recursive:!0}),En(de(n,"cloud.config.ts"),ho(e));let s=Hl();if(s.startsWith("file:")){let a=s.slice(5),c=yo(a)?a:Al(t,a);if(!rt(c)||!Dl(c).isFile())s=To(),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=Il(c),m=de(n,u);if(c!==m)Ol(c,m);s=`file:./${u}`}}let i={name:"ts-cloud-dashboard",private:!0,type:"module",dependencies:{"@stacksjs/ts-cloud":s}};return En(de(n,"package.json"),`${JSON.stringify(i,null,2)}
430
430
  `),Ul()}catch(s){return r.warn(`Management dashboard: could not stage the live release (${s?.message??s}) — skipping.`),null}}function Jt(e){if(rt(de(e,"packages","ui","pages"))||rt(de(e,"packages","ui","package.json")))return{uiRoot:"packages/ui/dist",build:"cd packages/ui && bun install && bun run build"};let t=On($o(import.meta.url)),r=[de(t,"ui"),de(t,"..","ui"),de(t,"..","..","ui"),de(t,"..","dist","ui")];for(let n of r)if(rt(de(n,"index.html"))||rt(de(n,"serverless.html")))return{uiRoot:n,build:!1};return null}function vi(e,t={}){let r=t.logger??bo,n=t.cwd??process.cwd();if(Rn(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(cr(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(!Rn(process.env.TS_CLOUD_UI_STATIC)){let S=kl(e,n,r);if(!S)return e;let y=Ji(e,s??"production",{uiRoot:S,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:C,site:A}of y)c[C]=A,r.info(`Management dashboard → https://${A.domain} (sign in with your ts-cloud account; the first deploy prints an admin password once)`);return e.sites=c,e}let u=Jt(n);if(!u)return r.info("Management dashboard: UI not found (no local ui/ or packaged dist/ui) — skipping auto-deploy."),e;let m=process.env.TS_CLOUD_UI_USERNAME?.trim()||"admin",f=nd(n,m,r),v=Ji(e,s??"production",{uiRoot:u.uiRoot,build:u.build,domain:i,username:m,password:f.password,realm:process.env.TS_CLOUD_UI_REALM?.trim()||void 0,live:!1,port:a});if(v.length===0)return r.info("Management dashboard: no domain resolved (set TS_CLOUD_UI_DOMAIN or configure a site domain) — skipping."),e;let _=f.source==="public"?"NO AUTH — TS_CLOUD_UI_PUBLIC is set (dashboard is publicly reachable)":f.source==="env"?"htpasswd-protected (TS_CLOUD_UI_PASSWORD)":`htpasswd-protected (auto-generated — see ${no()})`;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:S,site:y}of v)c[S]=y,r.info(`Management dashboard → https://${y.domain} (${_})`);return e.sites=c,e}function Dn(e){return Object.keys(e.sites??{}).filter(dr)}function io(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})`),So(e.build,{cwd:r,stdio:"inherit"});let s=yo(e.root)?e.root:de(r,e.root);if(!rt(s))return n.warn(`Management dashboard: build output not found at ${s} — skipping dashboard artifact.`),null;let i=de(xl(),`${t.slug}-${t.siteName??rd}-${t.sha}.tar.gz`);return So(`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}}var Nl=new Set(["laravel","php","statamic","wordpress"]);function Ur(e){if(e.framework)return e.framework;if(e.type&&Nl.has(e.type))return"laravel";return"stacks"}var wo=`eval "$(cd ${T} && pantry env 2>/dev/null)"`,Co="/usr/local/bin/bun",Ml="node_modules/@stacksjs/ts-cloud/dist/bin/stacks-scheduler.js",Fl="node_modules/@stacksjs/ts-cloud/dist/bin/stacks-queue-worker.js",Po={id:"stacks",wrapExec:(e)=>e,execEnv:{PATH:"/usr/local/bin:/usr/bin:/bin",BUN_INSTALL:"/root/.bun",APP_ENV:"production",NODE_ENV:"production"},schedulerMode:"daemon",schedulerCommand:()=>`${Co} ${Ml}`,queueWorkerCommand:(e,{current:t})=>{let r=[`--queue=${e.queue||"default"}`,`--sleep=${e.sleep??3}`,`--tries=${e.tries??3}`,`--timeout=${e.timeout??60}`];return`${Co} ${t}/${Fl} ${r.join(" ")}`}},zl={id:"laravel",wrapExec:(e)=>`/bin/sh -lc '${wo}; exec ${e}'`,schedulerMode:"cron",schedulerCommand:({current:e})=>`cd ${e} && ${wo} && 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(" ")}`}},Bl={stacks:Po,laravel:zl};function Eo(e){return Bl[e]??Po}function Ro(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Kl(e){return`'${e.split("'").join("'\\''")}'`}function Oo(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"unnamed"}function jl(e,t,r){return`${e}-${t}-queue-${r}`}function Vl(e,t,r,n){return`${e}-${t}-daemon-${r.name?Oo(r.name):Oo(r.command).slice(0,32)||String(n)}`}function xn(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.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(`
431
431
  `)}
432
- `}function In(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_UNIT_EOF'`,t.replace(/\n$/,""),"TS_CLOUD_UNIT_EOF"]}function Gl(e,t){return`/etc/cron.d/${e}-${t}-scheduler`}function An(e){let{slug:t,siteName:r,site:n}=e,i=`${e.appBase??`/var/www/${r}`}/current`,a=Eo(Ur(n)),c={current:i},u=[],m=[];(n.queues||[]).forEach((x,L)=>{let O=Math.max(1,x.processes??1);for(let I=0;I<O;I++){let W=jl(t,r,m.length);m.push(W),u.push(...In(W,xn({description:`${r} queue worker ${L}.${I} (managed by ts-cloud)`,workingDir:i,execStart:a.wrapExec(a.queueWorkerCommand(x,c)),environment:a.execEnv,stopWaitSecs:x.stopWaitSecs??90})))}}),(n.daemons||[]).forEach((x,L)=>{let O=Math.max(1,x.processes??1);for(let I=0;I<O;I++){let W=`${Vl(t,r,x,L)}-${I}`;m.push(W),u.push(...In(W,xn({description:`${r} daemon ${x.name||x.command} (managed by ts-cloud)`,workingDir:x.directory||i,execStart:a.wrapExec(x.command),environment:a.execEnv,restart:x.restart,user:x.user})))}});let _=n.scheduler,S=_===!0||typeof _==="object"&&_!==null,y=`${t}-${r}-scheduler`;if(S&&a.schedulerMode==="daemon"){m.push(y);let x=typeof _==="object"&&_!==null?_:{};u.push(...In(y,xn({description:`${r} scheduler (managed by ts-cloud)`,workingDir:i,execStart:a.wrapExec(a.schedulerCommand(c)),environment:a.execEnv,memoryHigh:x.memoryHigh,memoryMax:x.memoryMax})),...ir(`${y}.service`,{auto:!1,high:Boolean(x.memoryHigh),max:Boolean(x.memoryMax)}))}let C=m.map((x)=>`${x}.service`).join(" ");u.push("systemctl daemon-reload",`TS_CLOUD_DESIRED="${C}"`,`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E '^${Ro(t)}-${Ro(r)}-((queue|daemon)-.*|scheduler)\\.service$' || true); do`,' case " $TS_CLOUD_DESIRED " in',' *" $unit "*) ;;',' *) systemctl stop "$unit" 2>/dev/null || true; systemctl disable "$unit" 2>/dev/null || true; rm -f "/etc/systemd/system/$unit" ;;'," esac","done","systemctl daemon-reload");for(let x of m)u.push(`systemctl enable ${x}.service`,`systemctl restart ${x}.service`);let A=Gl(t,r);if(S&&a.schedulerMode==="cron"){let x=typeof _==="object"&&_!==null?_:void 0,L=`${a.schedulerCommand(c)} >> /dev/null 2>&1`;if(x?.heartbeatUrl){let I=x.heartbeatMethod||"GET",W=I==="GET"?"":`-X ${I} `;L+=` && curl -fsS -m 10 ${W}${Kl(x.heartbeatUrl)} >/dev/null 2>&1`}let O=`* * * * * root ${L}
432
+ `}function In(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_UNIT_EOF'`,t.replace(/\n$/,""),"TS_CLOUD_UNIT_EOF"]}function Gl(e,t){return`/etc/cron.d/${e}-${t}-scheduler`}function An(e){let{slug:t,siteName:r,site:n}=e,i=`${e.appBase??`/var/www/${r}`}/current`,a=Eo(Ur(n)),c={current:i},u=[],m=[];(n.queues||[]).forEach((x,H)=>{let O=Math.max(1,x.processes??1);for(let I=0;I<O;I++){let W=jl(t,r,m.length);m.push(W),u.push(...In(W,xn({description:`${r} queue worker ${H}.${I} (managed by ts-cloud)`,workingDir:i,execStart:a.wrapExec(a.queueWorkerCommand(x,c)),environment:a.execEnv,stopWaitSecs:x.stopWaitSecs??90})))}}),(n.daemons||[]).forEach((x,H)=>{let O=Math.max(1,x.processes??1);for(let I=0;I<O;I++){let W=`${Vl(t,r,x,H)}-${I}`;m.push(W),u.push(...In(W,xn({description:`${r} daemon ${x.name||x.command} (managed by ts-cloud)`,workingDir:x.directory||i,execStart:a.wrapExec(x.command),environment:a.execEnv,restart:x.restart,user:x.user})))}});let _=n.scheduler,S=_===!0||typeof _==="object"&&_!==null,y=`${t}-${r}-scheduler`;if(S&&a.schedulerMode==="daemon"){m.push(y);let x=typeof _==="object"&&_!==null?_:{};u.push(...In(y,xn({description:`${r} scheduler (managed by ts-cloud)`,workingDir:i,execStart:a.wrapExec(a.schedulerCommand(c)),environment:a.execEnv,memoryHigh:x.memoryHigh,memoryMax:x.memoryMax})),...ir(`${y}.service`,{auto:!1,high:Boolean(x.memoryHigh),max:Boolean(x.memoryMax)}))}let C=m.map((x)=>`${x}.service`).join(" ");u.push("systemctl daemon-reload",`TS_CLOUD_DESIRED="${C}"`,`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E '^${Ro(t)}-${Ro(r)}-((queue|daemon)-.*|scheduler)\\.service$' || true); do`,' case " $TS_CLOUD_DESIRED " in',' *" $unit "*) ;;',' *) systemctl stop "$unit" 2>/dev/null || true; systemctl disable "$unit" 2>/dev/null || true; rm -f "/etc/systemd/system/$unit" ;;'," esac","done","systemctl daemon-reload");for(let x of m)u.push(`systemctl enable ${x}.service`,`systemctl restart ${x}.service`);let A=Gl(t,r);if(S&&a.schedulerMode==="cron"){let x=typeof _==="object"&&_!==null?_:void 0,H=`${a.schedulerCommand(c)} >> /dev/null 2>&1`;if(x?.heartbeatUrl){let I=x.heartbeatMethod||"GET",W=I==="GET"?"":`-X ${I} `;H+=` && curl -fsS -m 10 ${W}${Kl(x.heartbeatUrl)} >/dev/null 2>&1`}let O=`* * * * * root ${H}
433
433
  `.replace(/%/g,"\\%");u.push(`cat > ${A} <<'TS_CLOUD_CRON_EOF'`,O.replace(/\n$/,""),"TS_CLOUD_CRON_EOF",`chmod 644 ${A}`)}else u.push(`rm -f ${A}`);return u}function Ln(e){return!!(e.queues?.length||e.daemons?.length||e.scheduler)}function Un(e){if(e.ssl?.provider)return e.ssl.provider;return e.domain?"letsencrypt":"none"}var Do={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 xo(e){return`/etc/letsencrypt/ts-cloud-${e}.ini`}function ql(e){let t=e?Do[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 Wl(e){if(!e.credentials||Object.keys(e.credentials).length===0)return[];let t=xo(e.provider),r=Object.entries(e.credentials).map(([n,s])=>`${n} = ${s}`).join(`
434
434
  `);return[`cat > ${t} <<'TS_CLOUD_DNSCREDS_EOF'`,r,"TS_CLOUD_DNSCREDS_EOF",`chmod 600 ${t}`]}function Yl(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=Do[t.provider].plugin;if(n.push(`--${s}`),t.provider!=="route53"&&t.credentials)n.push(`--${s}-credentials ${xo(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 ${He}`,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 Hn(e){if(Un(e)!=="letsencrypt"||!e.domain)return[];let t=e.ssl,r=t?.dns,n=t?.wildcard===!0;if(n&&!r)return[];return[...ql(r),...r?Wl(r):[],...Yl({domain:e.domain,aliases:e.aliases,email:t?.email,wildcard:n,dns:r})]}function Io(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 ${$e(t.tag)} ${$e(i)} ${r}`),a.push(`printf '%s' ${$e(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 ${$e(i)} ${$e(`refs/tags/${c}`)} | head -n1 | sed 's#.*refs/tags/##')"`,`test -n "$TS_CLOUD_TAG" || { echo "no tags matching" ${$e(c)} "found in" ${$e(i)} >&2; exit 1; }`,`git clone -q --depth 1 --branch "$TS_CLOUD_TAG" ${$e(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 ${$e(i)}`,`git -C ${r} fetch -q --depth 1 origin ${$e(n)}`,`git -C ${r} checkout -q FETCH_HEAD`);else a.push(`git clone -q --depth 1 --branch ${$e(s)} ${$e(i)} ${r}`);return a.push(`git -C ${r} rev-parse HEAD > ${r}/.ts-cloud-sha`),a}function $e(e){return`'${e.split("'").join("'\\''")}'`}var yr="$CREATE_RELEASE",br="$ACTIVATE_RELEASE",Uo="$RESTART_QUEUES",Ao="composer install --no-interaction --prefer-dist --optimize-autoloader --no-dev",Xl=["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 Jl(e){switch(e){case"laravel":case"statamic":return[yr,Ao,...Xl,br,Uo];case"php":case"wordpress":return[yr,`${Ao} || true`,br];case"static":case"spa":return[yr,br]}}function Ql(e,t){return e.replace(/^php\s+/,`${t} `).replace(/(\s)php\s+artisan\s+/g,`$1${t} artisan `)}function Zl(e,t){let r=er(t);return[`cat > ${e} <<'TS_CLOUD_ENV_EOF'`,r,"TS_CLOUD_ENV_EOF",`chmod 600 ${e}`]}function Lo(e,t,r){return[`cat > ${e} <<'${r}'`,t.replace(/\n$/,""),r,`chmod 600 ${e}`]}function eu(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(...Lo(`${e}/auth.json`,n,"TS_CLOUD_AUTHJSON_EOF"))}if(t.npmrc)r.push(...Lo(`${e}/.npmrc`,t.npmrc,"TS_CLOUD_NPMRC_EOF"));return r}function Ho(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 ko(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=Wt(i,n),u=r.sharedPaths??tr,m=[...u,...or(r.env,u)],f=r.keepReleases??Pt,v=r.deployScript?.length?r.deployScript:Jl(r.type??"laravel"),_=["set -euo pipefail",'export HOME="${HOME:-/root}"','export COMPOSER_HOME="${COMPOSER_HOME:-/root/.composer}"',"export COMPOSER_ALLOW_SUPERUSER=1",Ee()];if(_.push(...sr(i,{releaseId:n,commit:s,branch:r.repository.branch,keepLogs:f})),_.push(...Et(c,m)),r.env&&Object.keys(r.env).length>0)_.push(...Zl(`${c.shared}/.env`,r.env));for(let S of v){let y=S.trim();if(y===yr)_.push(...Io({repository:r.repository,releaseDir:c.release,commit:s})),_.push(...nr(c,m)),_.push(`cd ${c.release}`),_.push(...eu(c.release,r.credentials)),_.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)_.push(...ct(c)),_.push(...lt(c,f)),_.push(`(cd ${T} && pantry restart php-fpm) 2>/dev/null || true`);else if(y===Uo)_.push(`${a} artisan queue:restart || true`);else _.push(Ql(S,a))}return _}var Tr={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"]}},Ht="ts-cloud-service:";function tu(e){return e===!0||typeof e==="object"&&e!=null}function No(e){if(!e)return[];return Object.keys(Tr).filter((t)=>tu(e[t]))}function Mo(e){if(e.length===0)return[];return[Ee(),"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 "${Ht}$TS_CLOUD_SVC:present"; return 0; fi`," done",` if ts_cloud_port_open "$TS_CLOUD_PORT"; then echo "${Ht}$TS_CLOUD_SVC:present"; return 0; fi`,` echo "${Ht}$TS_CLOUD_SVC:missing"`," return 0","}",...e.filter((t)=>Tr[t]).map((t)=>`ts_cloud_probe ${t} ${Tr[t].port} ${Tr[t].binaries.join(" ")}`),"exit 0"]}function Fo(e,t){if(!e)return[];let r=new Map;for(let n of e.split(`
435
435
  `)){let s=n.indexOf(Ht);if(s===-1)continue;let[i,a]=n.slice(s+Ht.length).trim().split(":");if(i)r.set(i,a)}return t.filter((n)=>r.get(n)==="missing")}function zo(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 Bo="/var/lib/pantry/php-fpm/pool.d",ru=9100,nu=400;function wr(e){return(e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"site").slice(0,28)}function Ko(e){return`web_${wr(e)}`}function su(e){let t=wr(e),r=0;for(let n=0;n<t.length;n++)r=r*31+t.charCodeAt(n)>>>0;return ru+r%nu}function kn(e){return`127.0.0.1:${su(e)}`}function ou(e){let t=wr(e.siteName),r=Ko(e.siteName),n=e.maxChildren??10;return[`; ts-cloud-managed pool for ${e.siteName} (site isolation)`,`[${t}]`,`user = ${r}`,`group = ${r}`,`listen = ${kn(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(`
436
- `)}function jo(e){let t=Ko(e.siteName),r=wr(e.siteName),n=`${Bo}/${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 ${Bo}`,`cat > ${n} <<'TS_CLOUD_FPMPOOL_EOF'`,ou(e).replace(/\n$/,""),"TS_CLOUD_FPMPOOL_EOF",`(cd ${T} && pantry restart php-fpm) 2>/dev/null || true`]}var Er={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};function lu(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function so(e,t,r=Er){let{config:n,environment:s,siteName:i,site:a,slug:c,sha:u,runtime:m,localTarballPath:f}=t,v=`releases/${i}/${u}.tar.gz`,_=p(n,s),S=await e.getComputeOutputs({config:n,environment:s}),y=await e.findComputeTargets({slug:c,environment:s,role:"app",stackName:_});if(y.length===0)return{success:!1,error:e.name==="aws"?`Stack '${_}' has no EC2 instances tagged Project=${c} Environment=${s} Role=app, and storage/cloud/state/${_}.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/${_}.json pins no live server. For a shared box, record its serverId there.`};let C=S.servicesPrivateIp?Ns(S.servicesPrivateIp,g(n)):ts(g(n)),A=zi(b(n,{environment:s})),x=n.infrastructure?.compute,L=ti(x?.hostCleanup),O=j({...x,proxy:w(n,{environment:s})})?{HOST:"127.0.0.1"}:{},I=s==="production"?{APP_ENV:"production",NODE_ENV:"production"}:{},W={...C,...A,...O,...a.env||{},...I},H=mn(W,a.sharedPaths??[]);if(H.warning)r.warn(`Site '${i}': ${H.warning}`);else if(H.path)r.info(`Site '${i}': sharing '${H.path}' so the SQLite database survives deploys.`);if(Vr(a)){let R=a.phpVersion??x?.php?.default??x?.php?.versions?.[0],q=U(c,i),k=Object.keys(C).length>0?{...a,env:W}:a,Y=ko({siteName:i,site:k,releaseId:u,appBase:q,defaultPhpVersion:R}),X=!j(x),E=Un(a)==="custom"&&a.ssl?.certPath&&a.ssl?.keyPath?{certPath:a.ssl.certPath,keyPath:a.ssl.keyPath}:void 0,K=a.isolation?jo({siteName:i,appBase:q}):[],ie=X?Jr({siteName:i,domain:a.domain||i,aliases:a.aliases,type:a.type,appDir:`${q}/current`,webDirectory:a.webDirectory,phpVersion:R,fastcgiPass:a.isolation?kn(i):void 0,redirects:a.redirects,ssl:E,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:Xr(a.nginx,x?.nginxTemplates),clientMaxBodySize:a.nginx?.clientMaxBodySize,hsts:a.ssl?.hsts,tlsProtocols:a.ssl?.tlsProtocols,security:a.security}):[],re=X?Hn(a):[],Le=Ln(a)?An({slug:c,siteName:i,site:a,phpVersion:R,appBase:q}):[],kt=X?Ho(a):[];r.step(`Deploying PHP site '${i}' to ${y.length} target(s)...`);let Ke=await e.runRemoteDeploy({targets:y,commands:[...dn(q,c),...xr(q,c),...Y,...K,...ie,...re,...Le,...kt,...L],comment:`ts-cloud deploy ${c}/${i}@${u}`,tags:{Project:c,Environment:s,Role:"app"}}),Mn=is(n.notifications,a.notifications);if(!Ke.success)return await Vo(e,y,L,r),await en(Mn,"deploy-failed",`❌ Deploy of ${c}/${i}@${u} failed: ${Ke.error||"unknown error"}`),{success:!1,error:Ke.error||"Remote PHP deploy failed",instanceCount:Ke.instanceCount,perInstance:Ke.perInstance};let Wo=a.domain?` → https://${a.domain}`:"";return await en(Mn,"deploy",`✅ Deployed ${c}/${i}@${u}${Wo}`),{success:!0,instanceCount:Ke.instanceCount,perInstance:Ke.perInstance}}if(!f)return{success:!1,error:`Site '${i}' requires a release tarball but none was provided`};let V=await e.uploadRelease({config:n,environment:s,localPath:f,remoteKey:v,targets:y}),te=si(c,i,u),ue=e.name==="aws"?xc(S.deployBucketName,v,n.project.region||"us-east-1",te):Oc(V.artifactRef,te),me=d(a),Z=U(c,i),pe=me==="server-static"?ii({siteName:i,slug:c,appDir:Z,artifactFetch:ue,releaseId:u,preStartCommands:a.preStart}):ni({siteName:i,slug:c,appDir:Z,artifactFetch:ue,releaseId:u,execStart:ri(a.start,m,`${Z.replace(/\/+$/,"")}/releases/%i`),envEntries:W,port:a.port,preStartCommands:a.preStart,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=me==="server-static"&&!j(x)&&!!a.domain,ee=ne?Jr({siteName:i,domain:a.domain,aliases:a.aliases,type:a.type==="spa"?"spa":"static",appDir:`${Z}/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:Xr(a.nginx,x?.nginxTemplates),clientMaxBodySize:a.nginx?.clientMaxBodySize,hsts:a.ssl?.hsts,tlsProtocols:a.ssl?.tlsProtocols,security:a.security}):[],ge=ne?Hn(a):[],P=Ln(a)?An({slug:c,siteName:i,site:a,appBase:Z}):[],D=[...sr(Z,{releaseId:u,commit:u,branch:a.repository?.branch??"main"}),...dn(Z,c),...xr(Z,c),...pe,...ee,...ge,...P,...L];r.step(`Deploying to ${y.length} target(s)...`);let N=await e.runRemoteDeploy({targets:y,commands:D,comment:`ts-cloud deploy ${c}/${i}@${u}`,tags:{Project:c,Environment:s,Role:"app"}});if(!N.success)return await Vo(e,y,L,r),{success:!1,error:N.error||"Remote deploy failed",instanceCount:N.instanceCount,perInstance:N.perInstance};return{success:!0,instanceCount:N.instanceCount,perInstance:N.perInstance}}async function Vo(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 Cr(e){return`'${e.replaceAll("'","'\\''")}'`}function uu(e,t,r=!1,n=[]){let s=`${e}-dashboard-`,i=t.map((c)=>`${e}-${c}.service`),a=r?[`export TS_CLOUD_DASHBOARD_KEEP_DOMAINS=${Cr(JSON.stringify(n))}`,"rm -f /run/ts-cloud-dashboard-routes-changed",`/usr/local/bin/bun --bun -e ${Cr(`
436
+ `)}function jo(e){let t=Ko(e.siteName),r=wr(e.siteName),n=`${Bo}/${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 ${Bo}`,`cat > ${n} <<'TS_CLOUD_FPMPOOL_EOF'`,ou(e).replace(/\n$/,""),"TS_CLOUD_FPMPOOL_EOF",`(cd ${T} && pantry restart php-fpm) 2>/dev/null || true`]}var Er={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};function lu(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function so(e,t,r=Er){let{config:n,environment:s,siteName:i,site:a,slug:c,sha:u,runtime:m,localTarballPath:f}=t,v=`releases/${i}/${u}.tar.gz`,_=p(n,s),S=await e.getComputeOutputs({config:n,environment:s}),y=await e.findComputeTargets({slug:c,environment:s,role:"app",stackName:_});if(y.length===0)return{success:!1,error:e.name==="aws"?`Stack '${_}' has no EC2 instances tagged Project=${c} Environment=${s} Role=app, and storage/cloud/state/${_}.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/${_}.json pins no live server. For a shared box, record its serverId there.`};let C=S.servicesPrivateIp?Ns(S.servicesPrivateIp,g(n)):ts(g(n)),A=zi(b(n,{environment:s})),x=n.infrastructure?.compute,H=ti(x?.hostCleanup),O=j({...x,proxy:w(n,{environment:s})})?{HOST:"127.0.0.1"}:{},I=s==="production"?{APP_ENV:"production",NODE_ENV:"production"}:{},W={...C,...A,...O,...a.env||{},...I},k=mn(W,a.sharedPaths??[]);if(k.warning)r.warn(`Site '${i}': ${k.warning}`);else if(k.path)r.info(`Site '${i}': sharing '${k.path}' so the SQLite database survives deploys.`);if(Vr(a)){let R=a.phpVersion??x?.php?.default??x?.php?.versions?.[0],q=U(c,i),N=Object.keys(C).length>0?{...a,env:W}:a,Y=ko({siteName:i,site:N,releaseId:u,appBase:q,defaultPhpVersion:R}),X=!j(x),E=Un(a)==="custom"&&a.ssl?.certPath&&a.ssl?.keyPath?{certPath:a.ssl.certPath,keyPath:a.ssl.keyPath}:void 0,L=a.isolation?jo({siteName:i,appBase:q}):[],ie=X?Jr({siteName:i,domain:a.domain||i,aliases:a.aliases,type:a.type,appDir:`${q}/current`,webDirectory:a.webDirectory,phpVersion:R,fastcgiPass:a.isolation?kn(i):void 0,redirects:a.redirects,ssl:E,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:Xr(a.nginx,x?.nginxTemplates),clientMaxBodySize:a.nginx?.clientMaxBodySize,hsts:a.ssl?.hsts,tlsProtocols:a.ssl?.tlsProtocols,security:a.security}):[],re=X?Hn(a):[],Le=Ln(a)?An({slug:c,siteName:i,site:a,phpVersion:R,appBase:q}):[],kt=X?Ho(a):[];r.step(`Deploying PHP site '${i}' to ${y.length} target(s)...`);let Ke=await e.runRemoteDeploy({targets:y,commands:[...dn(q,c),...xr(q,c),...Y,...L,...ie,...re,...Le,...kt,...H],comment:`ts-cloud deploy ${c}/${i}@${u}`,tags:{Project:c,Environment:s,Role:"app"}}),Mn=is(n.notifications,a.notifications);if(!Ke.success)return await Vo(e,y,H,r),await en(Mn,"deploy-failed",`❌ Deploy of ${c}/${i}@${u} failed: ${Ke.error||"unknown error"}`),{success:!1,error:Ke.error||"Remote PHP deploy failed",instanceCount:Ke.instanceCount,perInstance:Ke.perInstance};let Wo=a.domain?` → https://${a.domain}`:"";return await en(Mn,"deploy",`✅ Deployed ${c}/${i}@${u}${Wo}`),{success:!0,instanceCount:Ke.instanceCount,perInstance:Ke.perInstance}}if(!f)return{success:!1,error:`Site '${i}' requires a release tarball but none was provided`};let V=await e.uploadRelease({config:n,environment:s,localPath:f,remoteKey:v,targets:y}),te=si(c,i,u),ue=e.name==="aws"?xc(S.deployBucketName,v,n.project.region||"us-east-1",te):Oc(V.artifactRef,te),me=d(a),Z=U(c,i),pe=me==="server-static"?ii({siteName:i,slug:c,appDir:Z,artifactFetch:ue,releaseId:u,preStartCommands:a.preStart}):ni({siteName:i,slug:c,appDir:Z,artifactFetch:ue,releaseId:u,execStart:ri(a.start,m,`${Z.replace(/\/+$/,"")}/releases/%i`),envEntries:W,port:a.port,preStartCommands:a.preStart,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=me==="server-static"&&!j(x)&&!!a.domain,ee=ne?Jr({siteName:i,domain:a.domain,aliases:a.aliases,type:a.type==="spa"?"spa":"static",appDir:`${Z}/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:Xr(a.nginx,x?.nginxTemplates),clientMaxBodySize:a.nginx?.clientMaxBodySize,hsts:a.ssl?.hsts,tlsProtocols:a.ssl?.tlsProtocols,security:a.security}):[],ge=ne?Hn(a):[],P=Ln(a)?An({slug:c,siteName:i,site:a,appBase:Z}):[],D=[...sr(Z,{releaseId:u,commit:u,branch:a.repository?.branch??"main"}),...dn(Z,c),...xr(Z,c),...pe,...ee,...ge,...P,...H];r.step(`Deploying to ${y.length} target(s)...`);let K=await e.runRemoteDeploy({targets:y,commands:D,comment:`ts-cloud deploy ${c}/${i}@${u}`,tags:{Project:c,Environment:s,Role:"app"}});if(!K.success)return await Vo(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 Vo(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 Cr(e){return`'${e.replaceAll("'","'\\''")}'`}function uu(e,t,r=!1,n=[]){let s=`${e}-dashboard-`,i=t.map((c)=>`${e}-${c}.service`),a=r?[`export TS_CLOUD_DASHBOARD_KEEP_DOMAINS=${Cr(JSON.stringify(n))}`,"rm -f /run/ts-cloud-dashboard-routes-changed",`/usr/local/bin/bun --bun -e ${Cr(`
437
437
  const { chmodSync, existsSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } = require('node:fs')
438
438
  const { basename, join } = require('node:path')
439
439
  const root = '/etc/rpx/sites.d'
@@ -461,4 +461,4 @@ This password is now in your deploy log. Set TS_CLOUD_UI_PASSWORD to a value of
461
461
  changed = true
462
462
  }
463
463
  if (changed) writeFileSync('/run/ts-cloud-dashboard-routes-changed', '')
464
- `)}`,"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=${Cr(s)}`,`TS_CLOUD_DASHBOARD_SERVER_OWNER=${r?"1":"0"}`,`TS_CLOUD_DASHBOARD_DESIRED=${Cr(` ${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 pu(e,t,r,n){let{config:s,environment:i}=t,a=s.project.slug,c=p(s,i),u=await e.findComputeTargets({slug:a,environment:i,role:"app",stackName:c});if(u.length===0)return!0;let m=await e.runRemoteDeploy({targets:u,commands:uu(a,r,!s.cloud?.attachTo,r.map((f)=>s.sites?.[f]?.domain).filter((f)=>typeof f==="string")),comment:`ts-cloud reconcile management dashboard ${a}`,tags:{Project:a,Environment:i,Role:"app"}});if(!m.success)return n.error(`Management dashboard reconciliation failed: ${m.error||"unknown error"}`),!1;return!0}async function du(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=fo(i,{ownerSlug:s,selfSlug:n.project.slug}),c=Cn(a)>0;for(let u of go(a,{ownerSlug:s,selfSlug:n.project.slug}))if(c)r.warn(u);else r.info(u)}async function mu(e,t,r){let{config:n,environment:s}=t,i=n.cloud?.attachTo;if(!i)return!0;let a=No(n.infrastructure?.compute?.managedServices);if(a.length===0)return!0;let c=n.project.slug,u=p(n,s),m=await e.findComputeTargets({slug:c,environment:s,role:"app",stackName:u});if(m.length===0)return!0;let f=await e.runRemoteDeploy({targets:m,commands:Mo(a),comment:`ts-cloud preflight managed services ${c}`,tags:{Project:c,Environment:s,Role:"app"}});if(!f.success)return r.warn(`Could not check '${i}' for the declared services: ${f.error||"unknown error"}`),!0;let v=new Set;for(let _ of f.perInstance)for(let S of Fo(_.output,a))v.add(S);if(v.size===0)return!0;return r.error(zo([...v],i,m[0]?.publicIp)),!1}async function fu(e,t,r){let{config:n,environment:s}=t;if(!n.cloud?.attachTo)return!0;let i=n.infrastructure?.compute,a=g(n),c=ot(a,i?.managedServices??{});if(c.length===0)return!0;let u=n.project.slug,m=p(n,s),f=await e.findComputeTargets({slug:u,environment:s,role:"app",stackName:m});if(f.length===0)return!0;r.step(`Ensuring database '${a?.name}' + role exist on the shared box...`);let v=await e.runRemoteDeploy({targets:f,commands:c,comment:`ts-cloud ensure database ${u}/${a?.name}`,tags:{Project:u,Environment:s,Role:"app"}});if(!v.success)return r.error(`Ensuring database '${a?.name}' failed: ${v.error||"unknown error"}`),!1;return r.success(`Database '${a?.name}' is ready on ${v.instanceCount} target(s)`),!0}async function id(e){let{config:t,environment:r,driver:n,sha:s,runtime:i,tarballForSite:a,logger:c=Er}=e,u=t.project.slug,m=e.cwd??process.cwd(),f=e.managementDashboard!==!1,v=cr(t);if(f)vi(t,{cwd:m,logger:{info:c.info,warn:c.warn}});let _=!f||v?[]:Dn(t);if(f&&e.rpxConfig&&e.rpxConfig!==t&&!cr(e.rpxConfig))vi(e.rpxConfig,{cwd:m,logger:{info:()=>{},warn:()=>{}}});if(f&&!await pu(n,e,Dn(t),c))return!1;let S=null,y=new Map;if(_.length>0)if(S=io(t.sites?.[_[0]],{cwd:m,slug:u,sha:s,siteName:_[0],logger:{info:c.info,warn:c.warn}}),!S){c.warn("Management dashboard: no artifact available — skipping dashboard site(s) for this deploy.");for(let O of _)if(t.sites)delete t.sites[O]}else for(let O of _){if(O===_[0]){y.set(O,S);continue}try{let I=cu(au(),`${u}-${O}-${s}.tar.gz`);iu(S,I),y.set(O,I)}catch{y.set(O,S)}}let C=t.sites||{},A=Object.entries(C).filter(([O,I])=>{if(!I)return!1;let W=d(I);if(W==="bucket")return c.warn(`Site '${O}' targets a bucket — skipping (handled by the static-site path, not compute).`),!1;if(W==="redirect")return!1;if(W==="proxy")return!1;return!0});if(A.length===0)return Ti(e);if(await du(n,e,c),!await mu(n,e,c))return!1;if(!await fu(n,e,c))return!1;let x=(O)=>y.get(O)??a(O);for(let[O,I]of A){c.step(`Deploying site: ${O}`);let W=Vr(I)?void 0:x(O),H=await so(n,{config:t,environment:r,siteName:O,site:I,slug:u,sha:s,runtime:i,localTarballPath:W},c);if(!H.success){if(c.error(`Deploy of '${O}' failed: ${H.error||"unknown error"}`),H.perInstance)for(let V of H.perInstance)c.error(` ${V.instanceId}: ${V.status}${V.error?` — ${V.error}`:""}`);return!1}if(c.success(`Deployed ${u}/${O}@${s} to ${H.instanceCount} target(s)`),H.perInstance)for(let V of H.perInstance)c.info(` ✓ ${V.instanceId}: ${V.status}`)}if(!await Ti(e))return!1;return!0}async function gu(e,t,r){let n=mp(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 Ti(e){let{config:t,environment:r,driver:n,logger:s=Er}=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,m=p(t,r),f=await n.findComputeTargets({slug:u,environment:r,role:"lb",stackName:m});if(f.length>0){let L=(await n.findComputeTargets({slug:u,environment:r,role:"app",stackName:m})).map((W)=>({privateIp:W.privateIp,publicIp:W.publicIp})),O=Xt(c,L,{proxy:a,slug:u});if(O.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 ${O.proxies.length} route(s)...`);let I=await n.runRemoteDeploy({targets:f,commands:Ne({config:O,slug:u,preserveManagementDashboardRoutes:e.managementDashboard===!1}),comment:`ts-cloud rpx gateway reload ${u}`,tags:{Project:u,Environment:r,Role:"lb"}});if(!I.success)return s.error(`rpx gateway reload failed: ${I.error||"unknown error"}`),!1;return s.success(`rpx gateway reloaded on ${I.instanceCount} load balancer(s)`),!0}let v=await gu(t,m,e.cwd),_=B(c,{proxy:a,slug:u,lan:v,mail:b(t,{environment:r})});if(_.proxies.length===0)return s.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;let S=await n.findComputeTargets({slug:u,environment:r,role:"app",stackName:m});if(S.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 ${_.proxies.length} route(s)...`);let C=G({proxy:a,config:_,slug:u,tenant:y,profile:fp(t),preserveManagementDashboardRoutes:e.managementDashboard===!1}),A=await n.runRemoteDeploy({targets:S,commands:C,comment:`ts-cloud rpx gateway reload ${u}`,tags:{Project:u,Environment:r,Role:"app"}});if(!A.success)return s.error(`rpx gateway reload failed: ${A.error||"unknown error"}`),!1;return s.success(`rpx gateway reloaded on ${A.instanceCount} target(s)`),!0}async function sd(e){let{config:t,environment:r,driver:n,logger:s=Er}=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:b(t,{environment:r})});if(c.proxies.length===0)return!0;let u=ld(c);if(u.length===0)return!0;let m=t.project.slug,f=p(t,r),v="lb",_=await n.findComputeTargets({slug:m,environment:r,role:v,stackName:f});if(_.length===0)v="app",_=await n.findComputeTargets({slug:m,environment:r,role:v,stackName:f});if(_.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 S=u.map((C)=>`test -s ${lu(`${c.productionCerts.certsDir}/${C}.crt`)}`).join(" && "),y=await n.runRemoteDeploy({targets:_,commands:[`systemctl start ${dd(m)}`,S],comment:`ts-cloud rpx TLS issuance ${m}`,tags:{Project:m,Environment:r,Role:v}});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 lp="658327ea-f89d-4fab-a63d-7e88639e58f6",up="4135ea2d-6df8-44a3-9df3-4b5a84be39ad",gp="216adef6-5c7f-47e4-b989-5492eafa07d3",Nn="origin",Go="origin-failover";function qo(e,t){let r={TargetOriginId:Nn,ViewerProtocolPolicy:"redirect-to-https",Compress:!0,CachePolicyId:t==="dynamic"?up:lp,OriginRequestPolicyId:gp,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 Vh(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((_,S)=>S.pathPattern.length-_.pathPattern.length),a=ce(e,"buildCloudFrontOriginConfig"),c=(_,S,y,C={})=>({Id:_,DomainName:S,OriginPath:"",CustomHeaders:s,CustomOriginConfig:{HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only",OriginSslProtocols:{Quantity:1,Items:["TLSv1.2"]},OriginReadTimeout:30,OriginKeepaliveTimeout:5},ConnectionAttempts:C.ConnectionAttempts??3,ConnectionTimeout:C.ConnectionTimeout??10,OriginShield:y,OriginAccessControlId:""}),u=[c(Nn,e.originDomain,e.originShield?{Enabled:!0,OriginShieldRegion:e.originShieldRegion}:{Enabled:!1},a)],m={Quantity:0},f=qo(null,"static");if(r!==void 0)u.push(c(Go,r,{Enabled:!1})),m=cn({primaryOriginId:Nn,secondaryOriginId:Go,statusCodes:e.failoverStatusCodes}),Tt(f.AllowedMethods,"the default cache behavior"),f.TargetOriginId=m.Items[0].Id;let v={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:m,DefaultCacheBehavior:f,CacheBehaviors:{Quantity:i.length,Items:i.map((_)=>qo(_.pathPattern,_.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 wt(v,"buildCloudFrontOriginConfig"),v}export{Dg,kc,Pg,De,Nc,Wn,kg,Bc,Jn,jt,Pr,zt,Ng,Bg,Nh,T,kr,Js,Xn,Kt,Nr,xg,Xs,M,Br,Yn,Zn,xr,Wt,Og,_g,Or,Bh,xh,Lg,$g,Oh,_h,Lh,_r,ei,Mg,Ys,ti,ri,ni,ii,si,xc,Oc,oi,Lr,Se,_c,ai,Lc,ci,$c,Mc,$r,Fc,Ve,se,Zs,Fg,Uc,Qc,Hc,Gc,Vc,mt,qe,je,ft,di,li,Pe,eo,qc,Ug,Qg,jc,Hg,ht,ui,zc,Gg,Vg,Kc,Mr,ke,Wc,qg,jg,to,gi,At,zg,Kg,Wg,Jg,Xg,Yg,Zg,ep,tp,pi,mi,fi,hi,Ai,yi,Si,rp,np,Fr,F,ro,ip,sp,op,Jc,ap,cp,$h,Mh,Fh,Xc,dp,Uh,Qh,Hh,Ii,bi,Ci,Ei,Yc,Zc,ed,td,Gh,rd,no,nd,Jt,vi,io,Ur,so,id,Ti,sd,lp,up,gp,Vh};
464
+ `)}`,"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=${Cr(s)}`,`TS_CLOUD_DASHBOARD_SERVER_OWNER=${r?"1":"0"}`,`TS_CLOUD_DASHBOARD_DESIRED=${Cr(` ${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 pu(e,t,r,n){let{config:s,environment:i}=t,a=s.project.slug,c=p(s,i),u=await e.findComputeTargets({slug:a,environment:i,role:"app",stackName:c});if(u.length===0)return!0;let m=await e.runRemoteDeploy({targets:u,commands:uu(a,r,!s.cloud?.attachTo,r.map((f)=>s.sites?.[f]?.domain).filter((f)=>typeof f==="string")),comment:`ts-cloud reconcile management dashboard ${a}`,tags:{Project:a,Environment:i,Role:"app"}});if(!m.success)return n.error(`Management dashboard reconciliation failed: ${m.error||"unknown error"}`),!1;return!0}async function du(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=fo(i,{ownerSlug:s,selfSlug:n.project.slug}),c=Cn(a)>0;for(let u of go(a,{ownerSlug:s,selfSlug:n.project.slug}))if(c)r.warn(u);else r.info(u)}async function mu(e,t,r){let{config:n,environment:s}=t,i=n.cloud?.attachTo;if(!i)return!0;let a=No(n.infrastructure?.compute?.managedServices);if(a.length===0)return!0;let c=n.project.slug,u=p(n,s),m=await e.findComputeTargets({slug:c,environment:s,role:"app",stackName:u});if(m.length===0)return!0;let f=await e.runRemoteDeploy({targets:m,commands:Mo(a),comment:`ts-cloud preflight managed services ${c}`,tags:{Project:c,Environment:s,Role:"app"}});if(!f.success)return r.warn(`Could not check '${i}' for the declared services: ${f.error||"unknown error"}`),!0;let v=new Set;for(let _ of f.perInstance)for(let S of Fo(_.output,a))v.add(S);if(v.size===0)return!0;return r.error(zo([...v],i,m[0]?.publicIp)),!1}async function fu(e,t,r){let{config:n,environment:s}=t;if(!n.cloud?.attachTo)return!0;let i=n.infrastructure?.compute,a=g(n),c=ot(a,i?.managedServices??{});if(c.length===0)return!0;let u=n.project.slug,m=p(n,s),f=await e.findComputeTargets({slug:u,environment:s,role:"app",stackName:m});if(f.length===0)return!0;r.step(`Ensuring database '${a?.name}' + role exist on the shared box...`);let v=await e.runRemoteDeploy({targets:f,commands:c,comment:`ts-cloud ensure database ${u}/${a?.name}`,tags:{Project:u,Environment:s,Role:"app"}});if(!v.success)return r.error(`Ensuring database '${a?.name}' failed: ${v.error||"unknown error"}`),!1;return r.success(`Database '${a?.name}' is ready on ${v.instanceCount} target(s)`),!0}async function id(e){let{config:t,environment:r,driver:n,sha:s,runtime:i,tarballForSite:a,logger:c=Er}=e,u=t.project.slug,m=e.cwd??process.cwd(),f=e.managementDashboard!==!1,v=cr(t);if(f)vi(t,{cwd:m,logger:{info:c.info,warn:c.warn}});let _=!f||v?[]:Dn(t);if(f&&e.rpxConfig&&e.rpxConfig!==t&&!cr(e.rpxConfig))vi(e.rpxConfig,{cwd:m,logger:{info:()=>{},warn:()=>{}}});if(f&&!await pu(n,e,Dn(t),c))return!1;let S=null,y=new Map;if(_.length>0)if(S=io(t.sites?.[_[0]],{cwd:m,slug:u,sha:s,siteName:_[0],logger:{info:c.info,warn:c.warn}}),!S){c.warn("Management dashboard: no artifact available — skipping dashboard site(s) for this deploy.");for(let O of _)if(t.sites)delete t.sites[O]}else for(let O of _){if(O===_[0]){y.set(O,S);continue}try{let I=cu(au(),`${u}-${O}-${s}.tar.gz`);iu(S,I),y.set(O,I)}catch{y.set(O,S)}}let C=t.sites||{},A=Object.entries(C).filter(([O,I])=>{if(!I)return!1;let W=d(I);if(W==="bucket")return c.warn(`Site '${O}' targets a bucket — skipping (handled by the static-site path, not compute).`),!1;if(W==="redirect")return!1;if(W==="proxy")return!1;return!0});if(A.length===0)return Ti(e);if(await du(n,e,c),!await mu(n,e,c))return!1;if(!await fu(n,e,c))return!1;let x=(O)=>y.get(O)??a(O);for(let[O,I]of A){c.step(`Deploying site: ${O}`);let W=Vr(I)?void 0:x(O),k=await so(n,{config:t,environment:r,siteName:O,site:I,slug:u,sha:s,runtime:i,localTarballPath:W},c);if(!k.success){if(c.error(`Deploy of '${O}' failed: ${k.error||"unknown error"}`),k.perInstance)for(let V of k.perInstance)c.error(` ${V.instanceId}: ${V.status}${V.error?` — ${V.error}`:""}`);return!1}if(c.success(`Deployed ${u}/${O}@${s} to ${k.instanceCount} target(s)`),k.perInstance)for(let V of k.perInstance)c.info(` ✓ ${V.instanceId}: ${V.status}`)}if(!await Ti(e))return!1;return!0}async function gu(e,t,r){let n=mp(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 Ti(e){let{config:t,environment:r,driver:n,logger:s=Er}=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,m=p(t,r),f=await n.findComputeTargets({slug:u,environment:r,role:"lb",stackName:m});if(f.length>0){let H=(await n.findComputeTargets({slug:u,environment:r,role:"app",stackName:m})).map((W)=>({privateIp:W.privateIp,publicIp:W.publicIp})),O=Xt(c,H,{proxy:a,slug:u});if(O.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 ${O.proxies.length} route(s)...`);let I=await n.runRemoteDeploy({targets:f,commands:Ne({config:O,slug:u,preserveManagementDashboardRoutes:e.managementDashboard===!1}),comment:`ts-cloud rpx gateway reload ${u}`,tags:{Project:u,Environment:r,Role:"lb"}});if(!I.success)return s.error(`rpx gateway reload failed: ${I.error||"unknown error"}`),!1;return s.success(`rpx gateway reloaded on ${I.instanceCount} load balancer(s)`),!0}let v=await gu(t,m,e.cwd),_=B(c,{proxy:a,slug:u,lan:v,mail:b(t,{environment:r})});if(_.proxies.length===0)return s.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;let S=await n.findComputeTargets({slug:u,environment:r,role:"app",stackName:m});if(S.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 ${_.proxies.length} route(s)...`);let C=G({proxy:a,config:_,slug:u,tenant:y,profile:fp(t),preserveManagementDashboardRoutes:e.managementDashboard===!1}),A=await n.runRemoteDeploy({targets:S,commands:C,comment:`ts-cloud rpx gateway reload ${u}`,tags:{Project:u,Environment:r,Role:"app"}});if(!A.success)return s.error(`rpx gateway reload failed: ${A.error||"unknown error"}`),!1;return s.success(`rpx gateway reloaded on ${A.instanceCount} target(s)`),!0}async function sd(e){let{config:t,environment:r,driver:n,logger:s=Er}=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:b(t,{environment:r})});if(c.proxies.length===0)return!0;let u=ld(c);if(u.length===0)return!0;let m=t.project.slug,f=p(t,r),v="lb",_=await n.findComputeTargets({slug:m,environment:r,role:v,stackName:f});if(_.length===0)v="app",_=await n.findComputeTargets({slug:m,environment:r,role:v,stackName:f});if(_.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 S=u.map((C)=>`test -s ${lu(`${c.productionCerts.certsDir}/${C}.crt`)}`).join(" && "),y=await n.runRemoteDeploy({targets:_,commands:[`systemctl start ${dd(m)}`,S],comment:`ts-cloud rpx TLS issuance ${m}`,tags:{Project:m,Environment:r,Role:v}});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 lp="658327ea-f89d-4fab-a63d-7e88639e58f6",up="4135ea2d-6df8-44a3-9df3-4b5a84be39ad",gp="216adef6-5c7f-47e4-b989-5492eafa07d3",Nn="origin",Go="origin-failover";function qo(e,t){let r={TargetOriginId:Nn,ViewerProtocolPolicy:"redirect-to-https",Compress:!0,CachePolicyId:t==="dynamic"?up:lp,OriginRequestPolicyId:gp,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 Vh(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((_,S)=>S.pathPattern.length-_.pathPattern.length),a=ce(e,"buildCloudFrontOriginConfig"),c=(_,S,y,C={})=>({Id:_,DomainName:S,OriginPath:"",CustomHeaders:s,CustomOriginConfig:{HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only",OriginSslProtocols:{Quantity:1,Items:["TLSv1.2"]},OriginReadTimeout:30,OriginKeepaliveTimeout:5},ConnectionAttempts:C.ConnectionAttempts??3,ConnectionTimeout:C.ConnectionTimeout??10,OriginShield:y,OriginAccessControlId:""}),u=[c(Nn,e.originDomain,e.originShield?{Enabled:!0,OriginShieldRegion:e.originShieldRegion}:{Enabled:!1},a)],m={Quantity:0},f=qo(null,"static");if(r!==void 0)u.push(c(Go,r,{Enabled:!1})),m=cn({primaryOriginId:Nn,secondaryOriginId:Go,statusCodes:e.failoverStatusCodes}),Tt(f.AllowedMethods,"the default cache behavior"),f.TargetOriginId=m.Items[0].Id;let v={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:m,DefaultCacheBehavior:f,CacheBehaviors:{Quantity:i.length,Items:i.map((_)=>qo(_.pathPattern,_.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 wt(v,"buildCloudFrontOriginConfig"),v}export{Dg,kc,Pg,De,Nc,Wn,kg,Bc,Jn,jt,Pr,zt,Ng,Bg,Nh,T,kr,Js,Xn,Kt,Nr,xg,Xs,M,Br,Yn,Zn,xr,Wt,Og,_g,Or,Bh,xh,Lg,$g,Oh,_h,Lh,_r,ei,Mg,Ys,ti,ri,ni,ii,si,xc,Oc,oi,Lr,Se,_c,ai,Lc,ci,$c,Mc,$r,Fc,Ve,se,Zs,Fg,Uc,Qc,Hc,Gc,Vc,mt,qe,je,ft,di,li,Pe,eo,qc,Ug,Qg,jc,Hg,ht,ui,zc,Gg,Vg,Kc,Mr,ke,Wc,qg,jg,to,gi,At,zg,Kg,Wg,Jg,Xg,Yg,Zg,ep,tp,pi,mi,fi,hi,Ai,yi,Si,rp,np,Fr,F,ro,ip,sp,op,Jc,ap,cp,$h,Mh,Fh,Xc,dp,Uh,Qh,Hh,Ii,bi,Ci,Ei,Yc,Zc,ed,td,Gh,rd,no,nd,Jt,vi,io,Ur,so,id,Ti,sd,lp,up,gp,Vh};