@stacksjs/ts-cloud 0.16.55 → 0.16.57
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.
- package/dist/bin/{chunk-akv3qkam.js → chunk-gx5wqrgh.js} +1 -1
- package/dist/bin/{chunk-fw1j79zq.js → chunk-mn3x457v.js} +1 -1
- package/dist/bin/{chunk-3hnczw70.js → chunk-s59x3psv.js} +88 -88
- package/dist/bin/cli.js +4 -4
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/{chunk-m0vnrgdz.js → chunk-r3qpx6xp.js} +1 -1
- package/dist/{chunk-fdr2cr9r.js → chunk-y2dej583.js} +80 -80
- package/dist/deploy/index.js +1 -1
- package/dist/drivers/index.js +1 -1
- package/dist/drivers/shared/remote-exec.d.ts +2 -0
- package/dist/index.js +1 -1
- package/dist/ui/404.html +1 -1
- package/dist/ui/accept-invitation.html +1 -1
- package/dist/ui/access-denied.html +1 -1
- package/dist/ui/account/automation.html +5 -5
- package/dist/ui/account/security.html +2 -2
- package/dist/ui/applications/compose.html +6 -6
- package/dist/ui/applications/new.html +2 -2
- package/dist/ui/data/backups.html +6 -6
- package/dist/ui/data/services.html +6 -6
- package/dist/ui/data/volumes.html +6 -6
- package/dist/ui/index.html +6 -6
- package/dist/ui/infrastructure/topology.html +5 -5
- package/dist/ui/integrations.html +2 -2
- package/dist/ui/operations/alerts.html +6 -6
- package/dist/ui/operations/configuration.html +5 -5
- package/dist/ui/operations/jobs.html +5 -5
- package/dist/ui/operations/maintenance.html +6 -6
- package/dist/ui/operations/observability.html +6 -6
- package/dist/ui/operations/previews.html +6 -6
- package/dist/ui/operations/queue.html +5 -5
- package/dist/ui/operations/regions.html +6 -6
- package/dist/ui/operations/releases.html +6 -6
- package/dist/ui/operations/spend.html +5 -5
- package/dist/ui/operations/workloads.html +6 -6
- package/dist/ui/security.html +2 -2
- package/dist/ui/server/actions.html +6 -6
- package/dist/ui/server/activity.html +1 -1
- package/dist/ui/server/capacity.html +6 -6
- package/dist/ui/server/database.html +6 -6
- package/dist/ui/server/deployments.html +6 -6
- package/dist/ui/server/diagnostics.html +2 -2
- package/dist/ui/server/firewall.html +6 -6
- package/dist/ui/server/fleet.html +6 -6
- package/dist/ui/server/logs.html +6 -6
- package/dist/ui/server/metrics.html +6 -6
- package/dist/ui/server/security.html +1 -1
- package/dist/ui/server/services.html +2 -2
- package/dist/ui/server/sites.html +6 -6
- package/dist/ui/server/ssh-keys.html +6 -6
- package/dist/ui/server/team.html +6 -6
- package/dist/ui/server/terminal.html +1 -1
- package/dist/ui/serverless/alarms.html +6 -6
- package/dist/ui/serverless/assets.html +2 -2
- package/dist/ui/serverless/cost.html +1 -1
- package/dist/ui/serverless/data.html +6 -6
- package/dist/ui/serverless/deployments.html +2 -2
- package/dist/ui/serverless/firewall.html +1 -1
- package/dist/ui/serverless/functions.html +6 -6
- package/dist/ui/serverless/logs.html +6 -6
- package/dist/ui/serverless/metrics.html +2 -2
- package/dist/ui/serverless/queues.html +6 -6
- package/dist/ui/serverless/secrets.html +6 -6
- package/dist/ui/serverless/traces.html +6 -6
- package/dist/ui/serverless.html +6 -6
- package/package.json +3 -3
|
@@ -1,30 +1,30 @@
|
|
|
1
|
-
import{rl,Q,l,g,b,Xe,zi,w,be,p,ce,cn,Tt,wt,cr,dr,Ji}from"./chunk-zvcd6x45.js";import{o}from"./chunk-jyvnfny6.js";import{U,Vr,d}from"./chunk-2hma3g5q.js";import{co,ad,mp,fp,B,Xt,j,z,dd,ld,G,Ne}from"./chunk-yt8qgn5d.js";import{Ri}from"./chunk-wbbbpt4v.js";import{Qr,Be}from"./chunk-80bgb48v.js";import{h}from"./chunk-d245va6b.js";import{ji}from"./chunk-qjp3f5y8.js";import{readFileSync as
|
|
1
|
+
import{rl,Q,l,g,b,Xe,zi,w,be,p,ce,cn,Tt,wt,cr,dr,Ji}from"./chunk-zvcd6x45.js";import{o}from"./chunk-jyvnfny6.js";import{U,Vr,d}from"./chunk-2hma3g5q.js";import{co,ad,mp,fp,B,Xt,j,z,dd,ld,G,Ne}from"./chunk-yt8qgn5d.js";import{Ri}from"./chunk-wbbbpt4v.js";import{Qr,Be}from"./chunk-80bgb48v.js";import{h}from"./chunk-d245va6b.js";import{ji}from"./chunk-qjp3f5y8.js";import{readFileSync as Ts}from"node:fs";import{join as Pa}from"node:path";function Dg(e={}){let t=new Set;for(let r of Object.values(e)){if(!r.domain)continue;if(!(r.redirect||r.deploy==="server"||r.start))continue;t.add(r.domain);for(let n of r.aliases??[]){let s=String(n).trim().toLowerCase();if(s)t.add(s)}}return t}function Dr(e){return e.replace(/\.$/,"").toLowerCase()}function zn(e,t,r){let n=Dr(e.name),s=Dr(t),i=Dr(r),a=i===s?"@":i.endsWith(`.${s}`)?i.slice(0,-(s.length+1)):i;return n===i||n===a||a==="@"&&(n===""||n===s)}async function kc(e,t,r,n,s="A"){let i=await e.listRecords(t);if(!i.success)return[`could not list ${s} records: ${i.message||"unknown provider error"}`];let a=i.records.filter((m)=>m.type===s&&zn(m,t,r)),c=a.findIndex((m)=>m.content===n);if(a.length<=1||c===-1)return[];let u=[];for(let[m,f]of a.entries()){if(m===c)continue;let v=await e.deleteRecord(t,f);if(!v.success)u.push(`could not remove stale ${f.name} ${s} ${f.content}: ${v.message||"unknown provider error"}`)}return u}async function Pg(e,t,r){let n=await e.listRecords(t);if(!n.success)return{removed:[],warnings:[`could not list records for ${t}: ${n.message||"unknown provider error"}`]};let s=[],i=[];for(let a of n.records){if(a.type!=="A"&&a.type!=="AAAA"||!zn(a,t,r))continue;let c=await e.deleteRecord(t,a);if(c.success)s.push(a);else i.push(`could not remove ${a.type} ${r} ${a.content}: ${c.message||"unknown provider error"}`)}return{removed:s,warnings:i}}function De(e){if(!e)return;let t=e.trim();if(!t)return;if(!t.includes("/"))return t;let[r]=t.split("/");if(!r.endsWith("::"))return r||void 0;return`${r}1`}var Nc=new Set(["mail","smtp","imap","mx"]);function Wn(e){return!Nc.has(e.split(".")[0]??"")}async function kg(e){let{provider:t,zone:r,fqdn:n,ipv4:s,ipv6:i,ttl:a=600}=e,c={published:[],warnings:[]},u=[{type:"A",content:s}];if(i&&Wn(n))u.push({type:"AAAA",content:i});for(let{type:m,content:f}of u){let v=await t.upsertRecord(r,{name:n,type:m,content:f,ttl:a});if(v?.success===!1){c.warnings.push(`${n} → ${f} failed: ${v.error||v.message||"unknown error"}`);continue}if(c.warnings.push(...(await kc(t,r,n,f,m)).map((_)=>`${n} cleanup: ${_}`)),await Bc(t,r,n,f,m))c.published.push({fqdn:n,type:m,content:f});else c.warnings.push(`${n} → ${f} reported success at ${t.name} but no matching ${m} record exists — create it manually: ${m} ${n} → ${f}`)}return c}async function Bc(e,t,r,n,s){try{if(typeof e?.listRecords!=="function")return!0;let i=await e.listRecords(t);if(!i?.success||!Array.isArray(i.records))return!0;return i.records.some((a)=>{let c=typeof a?.name==="string"?a.name.replace(/\.$/,""):"";return a?.type===s&&c===r&&a?.content===n})}catch{return!0}}function Ir(e){return(Buffer.isBuffer(e)?e.toString("utf8"):typeof e==="string"?e:"").replace(/(^|\n)(\s*(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*=).*$/gm,"$1$2[redacted]").replace(/encrypted:[A-Za-z0-9+/=]+/g,"encrypted:[redacted]").trim().slice(-8000)}function Jn(e,t){let r=Ir(e?.stderr),n=/line (\d+): syntax error/.exec(r);if(!n)return"";let s=Number(n[1]),i=t.split(`
|
|
2
2
|
`),a=Math.max(1,s-12),c=Math.min(i.length,s+2),u=i.slice(a-1,c).map((m,f)=>{let v=a+f,_=/^[A-Z_][A-Z0-9_]*=/.test(m)?m.replace(/=.*/,"=<redacted>"):m;return` ${String(v).padStart(4)}${v===s?" >":" "} ${_}`});return["",`The deploy script bash rejected is ${i.length} lines; it stopped at ${s}.`,...u].join(`
|
|
3
|
-
`)}function jt(e){let t=e,r=typeof t?.status==="number"?` (exit ${t.status})`:"",n=t?.signal?` (signal ${t.signal})`:"",s=[
|
|
3
|
+
`)}function jt(e){let t=e,r=typeof t?.status==="number"?` (exit ${t.status})`:"",n=t?.signal?` (signal ${t.signal})`:"",s=[Ir(t?.stderr),Ir(t?.stdout)].filter(Boolean).join(`
|
|
4
4
|
`);return`Remote SSH command failed${r}${n}${s?`
|
|
5
5
|
${s}`:""}`}function Pr(e){for(let t of e.split(`
|
|
6
|
-
`)){let r=t.trim();if(!r.startsWith("[ts-cloud]"))continue;console.warn(r)}}var
|
|
7
|
-
${e.slice(-
|
|
8
|
-
${
|
|
9
|
-
`)}function
|
|
6
|
+
`)){let r=t.trim();if(!r.startsWith("[ts-cloud]"))continue;console.warn(r)}}var Bn=4000,Xo=3;function Jo(e){return e.length>Bn?`…
|
|
7
|
+
${e.slice(-Bn)}`:e}function zt(e,t){let r=e.filter((a)=>a.status!=="Success");if(r.length===0)return t;let n=r.slice(0,Xo).map((a)=>{let c=(a.error||a.output||"").trim(),u=`${a.instanceId}: ${a.status}`;return c?`${u}
|
|
8
|
+
${Jo(c)}`:u}),s=r.length-n.length,i=s>0?[`(+${s} more instance${s===1?"":"s"} failed)`]:[];return[t,...n,...i].join(`
|
|
9
|
+
`)}function Qo(e){let t=2166136261,r=16777619;for(let n=0;n<e.length;n++){let s=e.charCodeAt(n);t=Math.imul(t^s,16777619)>>>0,r=Math.imul(r+s,2246822507)>>>0}return`${t.toString(36)}${r.toString(36)}`.padEnd(12,"0").slice(0,12)}function Ng(e,t,r={}){let n=r.mode??"testing",s=r.maxAge??604800,i=r.mx?.length?r.mx:[e.hostname],a=`${["version: STSv1",`mode: ${n}`,...i.map((u)=>`mx: ${u}`),`max_age: ${s}`].join(`\r
|
|
10
10
|
`)}\r
|
|
11
|
-
`,c=
|
|
12
|
-
`)}var yt={php:"php.net",nginx:"nginx.org",composer:"getcomposer.org",mysql:"mysql.com",mariadb:"mariadb.com/server",postgres:"postgresql.org",vitess:"vitess.io",etcd:"etcd.io",redis:"redis.io",memcached:"memcached.org",meilisearch:"meilisearch.com",mail:"github.com/mail-os/mail",git:"git-scm.com",certbot:"certbot.eff.org",bun:"bun.sh",node:"nodejs.org",deno:"deno.land"};var T="/opt/pantry";function
|
|
13
|
-
`)}function
|
|
14
|
-
`)}function
|
|
15
|
-
`)}function
|
|
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=${
|
|
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(`
|
|
18
|
-
`)}function
|
|
19
|
-
`)}function
|
|
11
|
+
`,c=Qo(a);return{host:`mta-sts.${t}`,body:a,id:c,txt:`v=STSv1; id=${c}`}}var Bg=8461;function Nh(e,t=Bg){return[`const policy = ${JSON.stringify(e.body)}`,"Bun.serve({",` port: ${t},`," hostname: '127.0.0.1',"," fetch(req) {"," const { pathname } = new URL(req.url)"," if (pathname !== '/.well-known/mta-sts.txt') return new Response('Not Found', { status: 404 })"," return new Response(policy, { headers: { 'content-type': 'text/plain; charset=utf-8' } })"," },","})"].join(`
|
|
12
|
+
`)}var yt={php:"php.net",nginx:"nginx.org",composer:"getcomposer.org",mysql:"mysql.com",mariadb:"mariadb.com/server",postgres:"postgresql.org",vitess:"vitess.io",etcd:"etcd.io",redis:"redis.io",memcached:"memcached.org",meilisearch:"meilisearch.com",mail:"github.com/mail-os/mail",git:"git-scm.com",certbot:"certbot.eff.org",bun:"bun.sh",node:"nodejs.org",deno:"deno.land"};var T="/opt/pantry";function Mt(e){return`'${e.split("'").join("'\\''")}'`}function kr(e={}){return["export DEBIAN_FRONTEND=noninteractive","export PANTRY_SERVICE_SCOPE=system","export PANTRY_INSTALL_DIR=/usr/local/bin",e.version?`export PANTRY_VERSION=${Mt(e.version)}`:'export PANTRY_VERSION="${PANTRY_VERSION:-latest}"',"command -v curl >/dev/null 2>&1 || (apt-get update -y && apt-get install -y curl ca-certificates)","command -v unzip >/dev/null 2>&1 || (apt-get update -y && apt-get install -y unzip)",'OS=$(uname -s | tr \'[:upper:]\' \'[:lower:]\'); ARCH=$(uname -m); case "$ARCH" in x86_64|amd64) ARCH=x64 ;; arm64|aarch64) ARCH=arm64 ;; esac; ZIP="pantry-${OS}-${ARCH}.zip"; if [ "${PANTRY_VERSION:-latest}" = latest ]; then REL=\'latest/download\'; else REL="download/v${PANTRY_VERSION}"; fi; TMP=$(mktemp -d); curl -fsSL -o "${TMP}/${ZIP}" "https://github.com/pantry-pm/pantry/releases/${REL}/${ZIP}"; unzip -o "${TMP}/${ZIP}" -d /usr/local/bin; chmod +x /usr/local/bin/pantry; rm -rf "${TMP}"','export PATH="/usr/local/bin:$PATH"',"mkdir -p /opt/pantry"]}function Ee(){return'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true'}function Te(e){if(e.length===0)return[];return[`(cd /opt/pantry && pantry install ${[...new Set(e)].map(Mt).join(" ")})`]}function Ft(e){return[...new Set(e)].flatMap((t)=>[`(cd /opt/pantry && pantry start ${Mt(t)})`,`(cd /opt/pantry && pantry enable ${Mt(t)})`])}var he="/etc/mail",we="mail-server",Ar="mail",Hr=`${T}/pantry/.bin`;function Ce(e){return`'${String(e).split("'").join("'\\''")}'`}function Ge(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function Zo(e){return[e.version?`${yt.mail}@${e.version}`:yt.mail]}function zr(e,t){return`${he}/dkim/${t}.${e.dkim.selector}.pem`}function Kn(e){return`${e.storagePath}/smtp.db`}function _i(e){let t=["# Generated by ts-cloud. Edits are overwritten on the next deploy —","# change `services.mail` in the cloud config instead.","","[server]",`host = ${Ge(e.bindAddress)}`,`port = ${e.ports.smtp}`,`hostname = ${Ge(e.hostname)}`];if(e.domains.length>0)t.push(`local_domains = ${Ge(e.domains.join(", "))}`);if(e.mode==="catcher")t.push("catch_all = true");if(t.push(`max_message_size = ${e.maxMessageSize}`,"","[tls]",`enabled = ${e.tls.enabled}`),e.tls.certPath)t.push(`cert_path = ${Ge(e.tls.certPath)}`);if(e.tls.keyPath)t.push(`key_path = ${Ge(e.tls.keyPath)}`);if(t.push("","[auth]",`enabled = ${e.mode==="server"}`,"","[antispam]",`dnsbl = ${e.spam.dnsbl}`,`greylist = ${e.spam.greylist}`,`spam_filter = ${e.spam.enabled}`,`junk_score = ${e.spam.junkScore}`,`reject_score = ${e.spam.rejectScore}`,"","[dkim]",`rotation_enabled = ${e.dkim.enabled&&e.dkim.rotate}`,`rotation_interval_days = ${e.dkim.rotateIntervalDays}`,"","[acme]",`enabled = ${e.tls.acme}`),e.tls.acmeEmail)t.push(`email = ${Ge(e.tls.acmeEmail)}`);if(t.push("","[webhook]",`enabled = ${!!e.webhookUrl}`),e.webhookUrl)t.push(`url = ${Ge(e.webhookUrl)}`);return t.push(""),t.join(`
|
|
13
|
+
`)}function $i(e){let t=["# Generated by ts-cloud. See /etc/mail/config.toml for the rest.",`SMTP_DB_PATH=${Kn(e)}`,`SMTP_DELIVERY_METHOD=${e.delivery==="ses"?"ses":"direct"}`];if(e.delivery==="ses")t.push(`SMTP_SES_REGION=${e.sesRegion}`);if(e.ports.submission)t.push(`SUBMISSION_PORT=${e.ports.submission}`);if(e.ports.submissions)t.push(`SMTPS_PORT=${e.ports.submissions}`);if(e.ports.imap)t.push("IMAP_ENABLED=1",`IMAP_PORT=${e.ports.imap}`);if(e.webmail.enabled)t.push("SMTP_ENABLE_WEBMAIL=true",`SMTP_WEBMAIL_PORT=${e.webmail.port}`,`SMTP_WEBMAIL_TLS=${e.webmail.tls}`,`SMTP_WEBMAIL_SECURE_COOKIES=${e.webmail.secureCookies}`,`SMTP_WEBMAIL_ATTACHMENT_MAX_FILE=${e.webmail.attachmentMaxFileBytes}`,`SMTP_WEBMAIL_ATTACHMENT_MAX_TOTAL=${e.webmail.attachmentMaxTotalBytes}`,`SMTP_WEBMAIL_ATTACHMENT_MAX_COUNT=${e.webmail.attachmentMaxCount}`,`SMTP_WEBMAIL_UNDO_SEND_SECONDS=${e.webmail.undoSendSeconds}`);if(e.tls.requireForAuth)t.push("SMTP_REQUIRE_TLS_FOR_AUTH=true");if(e.dkim.enabled&&e.domains.length>0){let[r,...n]=e.domains;if(t.push(`DKIM_DOMAIN=${r}`,`DKIM_SELECTOR=${e.dkim.selector}`,`DKIM_PRIVATE_KEY_PATH=${zr(e,r)}`),n.length>0){let s=n.map((i)=>`${i}:${e.dkim.selector}:${zr(e,i)}`);t.push(`DKIM_EXTRA_KEYS=${s.join(",")}`)}}return t.push(""),t.join(`
|
|
14
|
+
`)}function wi(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=${Hr}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"`,`ExecStart=${Hr}/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
|
+
`)}function Pi(e){if(!e.dkim.enabled||e.domains.length===0)return[];let t=[`mkdir -p ${he}/dkim`];for(let r of e.domains){let n=zr(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 Oi(e){if(e.accounts.length===0)return[];let t=(r)=>`runuser -u ${we} -- env SMTP_DB_PATH="$TS_CLOUD_MAIL_DB" ${Hr}/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 jn(e){if(!e.enabled)return[];return[...Te(Zo(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(Kn(e))}`,`cat > ${he}/config.toml <<'TS_CLOUD_MAIL_CONF_EOF'`,_i(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`,...Pi(e),`cat > /etc/systemd/system/${Ar}.service <<'TS_CLOUD_MAIL_UNIT_EOF'`,wi(e),"TS_CLOUD_MAIL_UNIT_EOF","systemctl daemon-reload",`systemctl enable ${Ar}`,`systemctl restart ${Ar}`,...Oi(e)]}var ve=`${T}/pantry/.bin`,Gr=15306,Kr=15991,Bt=15999,Vn=16101,Vt=2379,Re="/var/lib/vitess",qr=100;function bt(e){return e===!0||typeof e==="object"&&e!==null}function Di(e){return typeof e==="object"&&e!==null?e:{}}function oe(e){return`'${String(e).split("'").join("'\\''")}'`}function xi(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",Li=`${ve}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`,es="/usr/local/lib/vitess",Wr=new Map;function jr(e){return`${es}/${e}.sh`}function nt(e,t){return Wr.set(e,Ui(t)),`/bin/sh ${jr(e)}`}function Gn(){let e=[`mkdir -p ${es}`];for(let[t,r]of Wr)e.push(`cat > ${jr(t)} <<'TS_CLOUD_VITESS_LAUNCHER_EOF'`,r,"TS_CLOUD_VITESS_LAUNCHER_EOF",`chmod 0755 ${jr(t)}`);return e}function Ui(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
|
+
`)}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=${Li}"`,`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 qn(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_VITESS_UNIT_EOF'`,t,"TS_CLOUD_VITESS_UNIT_EOF"]}function Hi(e){let t=e.cell??"zone1",r=e.vtgatePort??Gr,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 ${Kr}`,`--grpc-port ${Bt}`])})}function ki(){return st({description:"etcd (Vitess topology store)",execStart:nt("etcd",[`${ve}/etcd`,`--data-dir ${Re}/etcd`,`--listen-client-urls http://127.0.0.1:${Vt}`,`--advertise-client-urls http://127.0.0.1:${Vt}`]),execStartPre:[`+/bin/mkdir -p ${Re}/etcd`,`+/bin/chown ${fe}:${fe} ${Re}/etcd`]})}function Yr(e){return["--topo-implementation etcd2",`--topo-global-server-address ${e.etcdEndpoint??`http://127.0.0.1:${Vt}`}`,"--topo-global-root /vitess/global"]}function Ni(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`,...Yr(e),`--cell ${e.cell??"zone1"}`,"--service-map grpc-vtctl,grpc-vtctld",`--grpc-port ${Bt}`,`--port ${Bt+1}`])})}function Mi(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`,...Yr(e),`--tablet-path ${n}-${String(qr).padStart(10,"0")}`,`--init-keyspace ${t}`,`--init-shard ${r}`,"--init-tablet-type replica",`--service-map ${oe("grpc-queryservice,grpc-tabletmanager,grpc-updatestream")}`,`--port ${Vn}`,`--grpc-port ${Vn+1}`,`--db-port ${e.mysqlPort??3306}`,`--mycnf-mysql-port ${e.mysqlPort??3306}`])})}function Fi(e){return st({description:"Vitess mysqlctld (managed mysqld)",execStart:nt("mysqlctld",[`${ve}/mysqlctld`,`--tablet-uid ${qr}`,`--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 ts="/etc/vitess/auth.json",$t="/var/lib/vitess/vtgate-auth.sha256";function Bi(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" ${ts}`,'rm -f "$VTESS_AUTH_TMP"']}function Ki(e){let t=e.cell??"zone1";return st({description:"Vitess vtgate (query router)",after:["vitess-vtctld.service"],execStart:nt("vtgate",[`${ve}/vtgate`,...Yr(e),`--cell ${t}`,`--cells-to-watch ${t}`,"--tablet-types-to-wait PRIMARY,REPLICA",`--service-map ${oe("grpc-vtgateservice")}`,`--mysql-server-port ${e.vtgatePort??Gr}`,`--mysql-server-bind-address ${e.bindAddress??"127.0.0.1"}`,"--mysql-auth-server-impl static",`--mysql-auth-server-static-file ${ts}`,`--port ${Kr}`,`--grpc-port ${Kr+1}`])})}function Vi(e){let t=e.cell??"zone1",r=e.etcdEndpoint??`http://127.0.0.1:${Vt}`,n=`${ve}/vtctldclient --server 127.0.0.1:${Bt}`,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(qr).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??Gr;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=Di(e),r=t.mode==="combo";Wr.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(xi(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(...qn("vitess-vtcombo",Hi(t)),...Gn(),"systemctl daemon-reload","systemctl enable --now vitess-vtcombo.service",...Qn(t)),n;n.push(...Bi(t));let s=[];if(!t.etcdEndpoint)s.push(["vitess-etcd",ki()]);s.push(["vitess-vtctld",Ni(t)],["vitess-mysqlctld",Fi(t)],["vitess-vtgate",Ki(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")}`,Mi(t,i.name,a)]);for(let[i,a]of s)n.push(...qn(i,a));n.push(...Gn()),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`,...Vi(t),...Qn(t)),n}var Gi=new Set(["singlestore","vitess"]);function Xn(e){if(e?.engine&&Gi.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 qi(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 Gt(e={},t={}){let r=qi(e),n=Js(e.vitess),s=t.mail?jn(t.mail):[];if(r.packages.length===0)return[...n,...s];return[...Te(r.packages),...Ft(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",...Wi(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 Wi(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 rs(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 Xr="/var/backups/ts-cloud",Yi="/etc/ts-cloud/backups.config.ts",ns="/etc/cron.d/ts-cloud-backups",Nr="/usr/local/bin/ts-cloud-backup.sh";function Xi(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
|
+
`)}function Qi(e,t){let r=e?Xi(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: '${Xr}',`," retention: {",` count: ${t.retentionCount??5},`,` maxAge: ${t.retentionDays??30},`," },"," databases: [",...r?[r]:[]," ],",...n,"}","","export default config",""].join(`
|
|
19
|
+
`)}function qt(e){let{database:t,backups:r}=e;if(!r.enabled)return[];let n=r.schedule||"0 2 * * *",s=Qi(t,r);return["export DEBIAN_FRONTEND=noninteractive",`mkdir -p /etc/ts-cloud ${Xr}`,"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 > ${Yi} <<'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 > ${ns} <<'TS_CLOUD_BACKUP_CRON_EOF'`,`${n} root ${Nr} >> /var/log/ts-cloud-backup.log 2>&1`,"TS_CLOUD_BACKUP_CRON_EOF",`chmod 644 ${ns}`]}function Zi(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 ${Xr} -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=${Zi(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 ea(e){return`/etc/ts-cloud/${e}-upgrade.env`}function ta(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=ta(s),_=ea(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 ss=[["nginx",80],["https",443],["phpFpm",9074],["mysql",3306],["postgres",5432],["redis",6379],["meilisearch",7700],["typesense",8108],["smtp",25]];function ra(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}=ra(e);if(!t)return[];let c=Math.round(i*1000000000000),u=ss.map(([y,C])=>`SVC_${y.toUpperCase()}=$(probe ${C})`),m=ss.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}')
|
|
21
|
-
EOF`,'DISK_PCT=0; DISK_ALERTS=""; ALERT_KEY=""',..._,"UPTIME_SEC=$(cut -d' ' -f1 /proc/uptime | cut -d. -f1)",`RX_BYTES=$(awk -F'[: ]+' 'NR>2 && $2!="lo"{rx+=$3} END{print rx+0}' /proc/net/dev)`,`TX_BYTES=$(awk -F'[: ]+' 'NR>2 && $2!="lo"{tx+=$11} END{print tx+0}' /proc/net/dev)`,"NOW_EPOCH=$(date -u +%s); TODAY=$(date -u +%Y-%m-%d); MONTH=$(date -u +%Y-%m)","if [ -r /var/lib/ts-cloud/bandwidth-state ]; then . /var/lib/ts-cloud/bandwidth-state; fi","PREV_EPOCH=${PREV_EPOCH:-0}; PREV_RX=${PREV_RX:-0}; PREV_TX=${PREV_TX:-0}","DAY_KEY=${DAY_KEY:-$TODAY}; MONTH_KEY=${MONTH_KEY:-$MONTH}","DAY_RX=${DAY_RX:-0}; DAY_TX=${DAY_TX:-0}; MONTH_RX=${MONTH_RX:-0}; MONTH_TX=${MONTH_TX:-0}","ELAPSED=$(( NOW_EPOCH - PREV_EPOCH ))",'if [ "$PREV_EPOCH" -le 0 ] || [ "$ELAPSED" -le 0 ] || [ "$RX_BYTES" -lt "$PREV_RX" ] || [ "$TX_BYTES" -lt "$PREV_TX" ]; then'," DELTA_RX=0; DELTA_TX=0; ELAPSED=0","else"," DELTA_RX=$(( RX_BYTES - PREV_RX )); DELTA_TX=$(( TX_BYTES - PREV_TX ))","fi",'if [ "$DAY_KEY" != "$TODAY" ]; then DAY_KEY=$TODAY; DAY_RX=0; DAY_TX=0; fi','if [ "$MONTH_KEY" != "$MONTH" ]; then MONTH_KEY=$MONTH; MONTH_RX=0; MONTH_TX=0; fi',"DAY_RX=$(( DAY_RX + DELTA_RX )); DAY_TX=$(( DAY_TX + DELTA_TX ))","MONTH_RX=$(( MONTH_RX + DELTA_RX )); MONTH_TX=$(( MONTH_TX + DELTA_TX ))",'if [ "$ELAPSED" -gt 0 ]; then RX_RATE=$(( DELTA_RX / ELAPSED )); TX_RATE=$(( DELTA_TX / ELAPSED )); else RX_RATE=0; TX_RATE=0; fi',"cat > /var/lib/ts-cloud/bandwidth-state.tmp <<BWSTATE","PREV_EPOCH=$NOW_EPOCH","PREV_RX=$RX_BYTES","PREV_TX=$TX_BYTES","RX_RATE=$RX_RATE","TX_RATE=$TX_RATE","DAY_KEY=$DAY_KEY","DAY_RX=$DAY_RX","DAY_TX=$DAY_TX","MONTH_KEY=$MONTH_KEY","MONTH_RX=$MONTH_RX","MONTH_TX=$MONTH_TX","BWSTATE","mv -f /var/lib/ts-cloud/bandwidth-state.tmp /var/lib/ts-cloud/bandwidth-state","probe(){ (exec 3<>/dev/tcp/127.0.0.1/$1) 2>/dev/null && echo up || echo down; }",...u,"LOAD=${LOAD:-0}; CPUS=${CPUS:-1}; MEM_TOTAL=${MEM_TOTAL:-0}; MEM_USED=${MEM_USED:-0}","SWAP_TOTAL=${SWAP_TOTAL:-0}; SWAP_USED=${SWAP_USED:-0}; DISK_PCT=${DISK_PCT:-0}","UPTIME_SEC=${UPTIME_SEC:-0}; RX_BYTES=${RX_BYTES:-0}; TX_BYTES=${TX_BYTES:-0}","MEM_PCT=$(( MEM_TOTAL > 0 ? MEM_USED * 100 / MEM_TOTAL : 0 ))","cat > /var/lib/ts-cloud/metrics.json.tmp <<JSON",`{"load":$LOAD,"cpus":$CPUS,"memTotalMb":$MEM_TOTAL,"memUsedMb":$MEM_USED,"memUsedPct":$MEM_PCT,"swapTotalMb":$SWAP_TOTAL,"swapUsedMb":$SWAP_USED,"diskUsedPct":$DISK_PCT,"uptimeSec":$UPTIME_SEC,"disks":[${S}],"network":{"rxBytes":$RX_BYTES,"txBytes":$TX_BYTES,"rxBytesPerSec":$RX_RATE,"txBytesPerSec":$TX_RATE,"dayKey":"$DAY_KEY","rxBytesToday":$DAY_RX,"txBytesToday":$DAY_TX,"monthKey":"$MONTH_KEY","rxBytesMonth":$MONTH_RX,"txBytesMonth":$MONTH_TX,"budgetBytes":${c}},"services":{`+m+"}}","JSON","mv -f /var/lib/ts-cloud/metrics.json.tmp /var/lib/ts-cloud/metrics.json",'ALERTS="$DISK_ALERTS"',`if awk -v l="$LOAD" -v c="$CPUS" -v t=${r} 'BEGIN{exit !(c>0 && l/c > t)}'; then ALERTS="$ALERTS load=$LOAD/${r}xCPU"; ALERT_KEY="$ALERT_KEY cpu"; fi`,`if [ "\${MEM_PCT:-0}" -ge ${n} ]; then ALERTS="$ALERTS mem=\${MEM_PCT}%"; ALERT_KEY="$ALERT_KEY memory"; fi`,"PREV=$(cat /var/lib/ts-cloud/alert-state 2>/dev/null || echo ok)",'if [ -n "$ALERTS" ]; then',` if [ "$PREV" != "$ALERT_KEY" ] && [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "⚠️ $(hostname): resource alert:$ALERTS"; then printf '%s\\n' "$ALERT_KEY" > ${"/var/lib/ts-cloud/alert-state"}; fi`,"else",` if [ "$PREV" != ok ] && [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "✅ $(hostname): resource usage back to normal"; then echo ok > ${"/var/lib/ts-cloud/alert-state"}; fi`,"fi",...c>0?["BW_TOTAL=$(( MONTH_RX + MONTH_TX ))",`BW_PCT=$(( BW_TOTAL * 100 / ${c} ))`,"BW_PREV=$(cat /var/lib/ts-cloud/bandwidth-alert-state 2>/dev/null || echo ok)",`if [ "$BW_PCT" -ge ${a} ]; then`,` if [ "$BW_PREV" != alert ] && [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "⚠️ $(hostname): bandwidth at \${BW_PCT}% of the ${i} TB monthly allowance ($MONTH_KEY)"; then echo alert > ${"/var/lib/ts-cloud/bandwidth-alert-state"}; fi`,"else",` if [ "$BW_PREV" = alert ] && [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "✅ $(hostname): bandwidth back under the monthly allowance (\${BW_PCT}%)"; then echo ok > ${"/var/lib/ts-cloud/bandwidth-alert-state"}; fi`,"fi"]:[],"TS_CLOUD_METRICS_EOF","chmod +x /usr/local/bin/ts-cloud-metrics.sh","cat > /etc/systemd/system/ts-cloud-metrics.service <<'TS_CLOUD_METRICS_SVC_EOF'","[Unit]","Description=ts-cloud metrics collector","","[Service]","Type=oneshot","ExecStart=/usr/local/bin/ts-cloud-metrics.sh","TS_CLOUD_METRICS_SVC_EOF","cat > /etc/systemd/system/ts-cloud-metrics.timer <<'TS_CLOUD_METRICS_TMR_EOF'","[Unit]","Description=Run ts-cloud metrics collector every minute","","[Timer]","OnCalendar=*-*-* *:*:00","AccuracySec=1s","RandomizedDelaySec=5s","Persistent=true","","[Install]","WantedBy=timers.target","TS_CLOUD_METRICS_TMR_EOF","systemctl daemon-reload","systemctl enable --now ts-cloud-metrics.timer","systemctl start ts-cloud-metrics.service"]}var ra={"opcache.enable":"1","opcache.enable_cli":"1","opcache.memory_consumption":"256","opcache.interned_strings_buffer":"16","opcache.max_accelerated_files":"20000","opcache.validate_timestamps":"0","opcache.revalidate_freq":"0","opcache.save_comments":"1","opcache.fast_shutdown":"1",realpath_cache_size:"4096K",realpath_cache_ttl:"600"},na="127.0.0.1:9074";function ss(e){return na}function sa(e={}){let t=e.versions?.length?e.versions:["8.3"];return e.default&&t.includes(e.default)?e.default:t[0]}function oa(e={}){return{...e.optimizeForProduction===!1?{}:{...ra},...e.ini||{}}}function ia(e={}){let t=oa(e),r=Object.keys(t);if(r.length===0)return[];let n=r.map((i)=>`${i}=${t[i]}`),s="ts-cloud-managed";return[Ee(),"TS_CLOUD_SCAN_DIR=$(php -i 2>/dev/null | awk -F' => ' '/^Scan this dir for additional .ini files/{print $2}' | head -1)",`TS_CLOUD_LOADED_INI=$(php -r 'echo php_ini_loaded_file() ?: "";' 2>/dev/null)`,'if [ -n "$TS_CLOUD_SCAN_DIR" ] && [ "$TS_CLOUD_SCAN_DIR" != "(none)" ]; then',' mkdir -p "$TS_CLOUD_SCAN_DIR"',' TS_CLOUD_PHP_INI="$TS_CLOUD_SCAN_DIR/zz-ts-cloud.ini"',` cat > "$TS_CLOUD_PHP_INI" <<'TS_CLOUD_PHPINI_EOF'`,`; ${s} — production PHP tuning`,...n,"TS_CLOUD_PHPINI_EOF","else",' if [ -z "$TS_CLOUD_LOADED_INI" ]; then'," TS_CLOUD_INI_DIR=$(php -i 2>/dev/null | awk -F' => ' '/^Configuration File \\(php.ini\\) Path/{print $2}' | head -1)",' TS_CLOUD_LOADED_INI="$TS_CLOUD_INI_DIR/php.ini"',' mkdir -p "$TS_CLOUD_INI_DIR"',' touch "$TS_CLOUD_LOADED_INI"'," fi",` sed -i '/; ${s} BEGIN/,/; ${s} END/d' "$TS_CLOUD_LOADED_INI"`,` cat >> "$TS_CLOUD_LOADED_INI" <<'TS_CLOUD_PHPINI_EOF'`,`; ${s} BEGIN`,...n,`; ${s} END`,"TS_CLOUD_PHPINI_EOF","fi",`(cd ${T} && pantry restart php-fpm) 2>/dev/null || true`]}function qt(e={}){let t=sa(e),r=e.installNginx!==!1,n=e.installComposer!==!1,s=[`php.net@${t}`];if(n)s.push("getcomposer.org");if(r)s.push("nginx.org");return[...Te(s),...Mt(["php-fpm"]),...ia(e)]}function Xr(e,t){if(!e)return[];let r=[];if(e.template&&t?.[e.template])r.push(...t[e.template]);if(e.serverSnippet)r.push(...e.serverSnippet);return r}function aa(e){if(!e)return"";let t=typeof e==="object"?e:{},n=[`max-age=${t.maxAge??31536000}`];if(t.includeSubDomains??!0)n.push("includeSubDomains");if(t.preload)n.push("preload");return` add_header Strict-Transport-Security "${n.join("; ")}" always;`}function ca(e){if(!e||!e.allow?.length&&!e.deny?.length)return[];let t=[];for(let r of e.deny||[])t.push(` deny ${r};`);if(e.allow?.length){for(let r of e.allow)t.push(` allow ${r};`);t.push(" deny all;")}return t}function os(e){return`/etc/nginx/.htpasswd-${e}`}var la=new Set(["laravel","php","statamic","wordpress"]);function ua(e){return la.has(e)}function pa(e){return e==="laravel"||e==="statamic"?"public":""}function da(e,t){let r=e.replace(/\/+$/,""),n=t.replace(/^\/+|\/+$/g,"");return n?`${r}/${n}`:r}function ma(e){let t=e.type??"laravel",r=e.webDirectory??pa(t),n=da(e.appDir,r),s=ua(t),i=e.phpVersion??"8.3",a=[` root ${n};`,"",' add_header X-Frame-Options "SAMEORIGIN";',' add_header X-Content-Type-Options "nosniff";'],c=aa(e.hsts);if(c)a.push(c);for(let u of ca(e.security))a.push(u);if(a.push("",` index ${s?"index.php index.html":"index.html index.htm"};`,""," charset utf-8;",""),e.clientMaxBodySize)a.push(` client_max_body_size ${e.clientMaxBodySize};`,"");if(e.auth)a.push(` auth_basic "${e.auth.realm||"Restricted"}";`,` auth_basic_user_file ${os(e.siteName)};`,"");for(let[u,m]of Object.entries(e.redirects||{}))a.push(` location = ${u} { return 301 ${m}; }`);if(Object.keys(e.redirects||{}).length>0)a.push("");if(s){if(a.push(" location / {"," try_files $uri $uri/ /index.php?$query_string;"," }",""," location = /favicon.ico { access_log off; log_not_found off; }"," location = /robots.txt { access_log off; log_not_found off; }",""," error_page 404 /index.php;",""," location ~ \\.php$ {",` fastcgi_pass ${e.fastcgiPass??ss(i)};`," fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;"," include fastcgi_params;"," }",""," location ~ /\\.(?!well-known).* {"," deny all;"," }"),t==="wordpress")a.push(""," location = /xmlrpc.php { deny all; }"," location ~* /(?:wp-config\\.php|readme\\.html|license\\.txt)$ { deny all; }"," location ~* /wp-content/uploads/.*\\.php$ { deny all; }")}else if(t==="spa")a.push(" location / {"," try_files $uri $uri/ /index.html;"," }");else a.push(" location / {"," try_files $uri $uri/ =404;"," }");if(e.serverSnippet&&e.serverSnippet.length>0){a.push("");for(let u of e.serverSnippet)a.push(u?` ${u}`:"")}return a}function fa(e){let t=[e.domain,...e.aliases||[]].filter(Boolean);for(let i of t)if(!/^(?=.{1,253}$)(?:\*\.)?[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i.test(i.trim()))throw Error(`Refusing to build a vhost: '${i}' is not a valid hostname.`);if(!t.length)throw Error("Refusing to build a vhost: no server_name (domain) was given.");let r=t.join(" "),n=ma(e);if(e.ssl){let i=["server {"," listen 80;"," listen [::]:80;",` server_name ${r};`," return 301 https://$host$request_uri;","}"],a=["server {"," listen 443 ssl;"," listen [::]:443 ssl;",` server_name ${r};`,` ssl_certificate ${e.ssl.certPath};`,` ssl_certificate_key ${e.ssl.keyPath};`,...e.tlsProtocols?.length?[` ssl_protocols ${e.tlsProtocols.join(" ")};`]:[],"",...n,"}"];return`${[...i,"",...a].join(`
|
|
21
|
+
EOF`,'DISK_PCT=0; DISK_ALERTS=""; ALERT_KEY=""',..._,"UPTIME_SEC=$(cut -d' ' -f1 /proc/uptime | cut -d. -f1)",`RX_BYTES=$(awk -F'[: ]+' 'NR>2 && $2!="lo"{rx+=$3} END{print rx+0}' /proc/net/dev)`,`TX_BYTES=$(awk -F'[: ]+' 'NR>2 && $2!="lo"{tx+=$11} END{print tx+0}' /proc/net/dev)`,"NOW_EPOCH=$(date -u +%s); TODAY=$(date -u +%Y-%m-%d); MONTH=$(date -u +%Y-%m)","if [ -r /var/lib/ts-cloud/bandwidth-state ]; then . /var/lib/ts-cloud/bandwidth-state; fi","PREV_EPOCH=${PREV_EPOCH:-0}; PREV_RX=${PREV_RX:-0}; PREV_TX=${PREV_TX:-0}","DAY_KEY=${DAY_KEY:-$TODAY}; MONTH_KEY=${MONTH_KEY:-$MONTH}","DAY_RX=${DAY_RX:-0}; DAY_TX=${DAY_TX:-0}; MONTH_RX=${MONTH_RX:-0}; MONTH_TX=${MONTH_TX:-0}","ELAPSED=$(( NOW_EPOCH - PREV_EPOCH ))",'if [ "$PREV_EPOCH" -le 0 ] || [ "$ELAPSED" -le 0 ] || [ "$RX_BYTES" -lt "$PREV_RX" ] || [ "$TX_BYTES" -lt "$PREV_TX" ]; then'," DELTA_RX=0; DELTA_TX=0; ELAPSED=0","else"," DELTA_RX=$(( RX_BYTES - PREV_RX )); DELTA_TX=$(( TX_BYTES - PREV_TX ))","fi",'if [ "$DAY_KEY" != "$TODAY" ]; then DAY_KEY=$TODAY; DAY_RX=0; DAY_TX=0; fi','if [ "$MONTH_KEY" != "$MONTH" ]; then MONTH_KEY=$MONTH; MONTH_RX=0; MONTH_TX=0; fi',"DAY_RX=$(( DAY_RX + DELTA_RX )); DAY_TX=$(( DAY_TX + DELTA_TX ))","MONTH_RX=$(( MONTH_RX + DELTA_RX )); MONTH_TX=$(( MONTH_TX + DELTA_TX ))",'if [ "$ELAPSED" -gt 0 ]; then RX_RATE=$(( DELTA_RX / ELAPSED )); TX_RATE=$(( DELTA_TX / ELAPSED )); else RX_RATE=0; TX_RATE=0; fi',"cat > /var/lib/ts-cloud/bandwidth-state.tmp <<BWSTATE","PREV_EPOCH=$NOW_EPOCH","PREV_RX=$RX_BYTES","PREV_TX=$TX_BYTES","RX_RATE=$RX_RATE","TX_RATE=$TX_RATE","DAY_KEY=$DAY_KEY","DAY_RX=$DAY_RX","DAY_TX=$DAY_TX","MONTH_KEY=$MONTH_KEY","MONTH_RX=$MONTH_RX","MONTH_TX=$MONTH_TX","BWSTATE","mv -f /var/lib/ts-cloud/bandwidth-state.tmp /var/lib/ts-cloud/bandwidth-state","probe(){ (exec 3<>/dev/tcp/127.0.0.1/$1) 2>/dev/null && echo up || echo down; }",...u,"LOAD=${LOAD:-0}; CPUS=${CPUS:-1}; MEM_TOTAL=${MEM_TOTAL:-0}; MEM_USED=${MEM_USED:-0}","SWAP_TOTAL=${SWAP_TOTAL:-0}; SWAP_USED=${SWAP_USED:-0}; DISK_PCT=${DISK_PCT:-0}","UPTIME_SEC=${UPTIME_SEC:-0}; RX_BYTES=${RX_BYTES:-0}; TX_BYTES=${TX_BYTES:-0}","MEM_PCT=$(( MEM_TOTAL > 0 ? MEM_USED * 100 / MEM_TOTAL : 0 ))","cat > /var/lib/ts-cloud/metrics.json.tmp <<JSON",`{"load":$LOAD,"cpus":$CPUS,"memTotalMb":$MEM_TOTAL,"memUsedMb":$MEM_USED,"memUsedPct":$MEM_PCT,"swapTotalMb":$SWAP_TOTAL,"swapUsedMb":$SWAP_USED,"diskUsedPct":$DISK_PCT,"uptimeSec":$UPTIME_SEC,"disks":[${S}],"network":{"rxBytes":$RX_BYTES,"txBytes":$TX_BYTES,"rxBytesPerSec":$RX_RATE,"txBytesPerSec":$TX_RATE,"dayKey":"$DAY_KEY","rxBytesToday":$DAY_RX,"txBytesToday":$DAY_TX,"monthKey":"$MONTH_KEY","rxBytesMonth":$MONTH_RX,"txBytesMonth":$MONTH_TX,"budgetBytes":${c}},"services":{`+m+"}}","JSON","mv -f /var/lib/ts-cloud/metrics.json.tmp /var/lib/ts-cloud/metrics.json",'ALERTS="$DISK_ALERTS"',`if awk -v l="$LOAD" -v c="$CPUS" -v t=${r} 'BEGIN{exit !(c>0 && l/c > t)}'; then ALERTS="$ALERTS load=$LOAD/${r}xCPU"; ALERT_KEY="$ALERT_KEY cpu"; fi`,`if [ "\${MEM_PCT:-0}" -ge ${n} ]; then ALERTS="$ALERTS mem=\${MEM_PCT}%"; ALERT_KEY="$ALERT_KEY memory"; fi`,"PREV=$(cat /var/lib/ts-cloud/alert-state 2>/dev/null || echo ok)",'if [ -n "$ALERTS" ]; then',` if [ "$PREV" != "$ALERT_KEY" ] && [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "⚠️ $(hostname): resource alert:$ALERTS"; then printf '%s\\n' "$ALERT_KEY" > ${"/var/lib/ts-cloud/alert-state"}; fi`,"else",` if [ "$PREV" != ok ] && [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "✅ $(hostname): resource usage back to normal"; then echo ok > ${"/var/lib/ts-cloud/alert-state"}; fi`,"fi",...c>0?["BW_TOTAL=$(( MONTH_RX + MONTH_TX ))",`BW_PCT=$(( BW_TOTAL * 100 / ${c} ))`,"BW_PREV=$(cat /var/lib/ts-cloud/bandwidth-alert-state 2>/dev/null || echo ok)",`if [ "$BW_PCT" -ge ${a} ]; then`,` if [ "$BW_PREV" != alert ] && [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "⚠️ $(hostname): bandwidth at \${BW_PCT}% of the ${i} TB monthly allowance ($MONTH_KEY)"; then echo alert > ${"/var/lib/ts-cloud/bandwidth-alert-state"}; fi`,"else",` if [ "$BW_PREV" = alert ] && [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "✅ $(hostname): bandwidth back under the monthly allowance (\${BW_PCT}%)"; then echo ok > ${"/var/lib/ts-cloud/bandwidth-alert-state"}; fi`,"fi"]:[],"TS_CLOUD_METRICS_EOF","chmod +x /usr/local/bin/ts-cloud-metrics.sh","cat > /etc/systemd/system/ts-cloud-metrics.service <<'TS_CLOUD_METRICS_SVC_EOF'","[Unit]","Description=ts-cloud metrics collector","","[Service]","Type=oneshot","ExecStart=/usr/local/bin/ts-cloud-metrics.sh","TS_CLOUD_METRICS_SVC_EOF","cat > /etc/systemd/system/ts-cloud-metrics.timer <<'TS_CLOUD_METRICS_TMR_EOF'","[Unit]","Description=Run ts-cloud metrics collector every minute","","[Timer]","OnCalendar=*-*-* *:*:00","AccuracySec=1s","RandomizedDelaySec=5s","Persistent=true","","[Install]","WantedBy=timers.target","TS_CLOUD_METRICS_TMR_EOF","systemctl daemon-reload","systemctl enable --now ts-cloud-metrics.timer","systemctl start ts-cloud-metrics.service"]}var na={"opcache.enable":"1","opcache.enable_cli":"1","opcache.memory_consumption":"256","opcache.interned_strings_buffer":"16","opcache.max_accelerated_files":"20000","opcache.validate_timestamps":"0","opcache.revalidate_freq":"0","opcache.save_comments":"1","opcache.fast_shutdown":"1",realpath_cache_size:"4096K",realpath_cache_ttl:"600"},sa="127.0.0.1:9074";function os(e){return sa}function oa(e={}){let t=e.versions?.length?e.versions:["8.3"];return e.default&&t.includes(e.default)?e.default:t[0]}function ia(e={}){return{...e.optimizeForProduction===!1?{}:{...na},...e.ini||{}}}function aa(e={}){let t=ia(e),r=Object.keys(t);if(r.length===0)return[];let n=r.map((i)=>`${i}=${t[i]}`),s="ts-cloud-managed";return[Ee(),"TS_CLOUD_SCAN_DIR=$(php -i 2>/dev/null | awk -F' => ' '/^Scan this dir for additional .ini files/{print $2}' | head -1)",`TS_CLOUD_LOADED_INI=$(php -r 'echo php_ini_loaded_file() ?: "";' 2>/dev/null)`,'if [ -n "$TS_CLOUD_SCAN_DIR" ] && [ "$TS_CLOUD_SCAN_DIR" != "(none)" ]; then',' mkdir -p "$TS_CLOUD_SCAN_DIR"',' TS_CLOUD_PHP_INI="$TS_CLOUD_SCAN_DIR/zz-ts-cloud.ini"',` cat > "$TS_CLOUD_PHP_INI" <<'TS_CLOUD_PHPINI_EOF'`,`; ${s} — production PHP tuning`,...n,"TS_CLOUD_PHPINI_EOF","else",' if [ -z "$TS_CLOUD_LOADED_INI" ]; then'," TS_CLOUD_INI_DIR=$(php -i 2>/dev/null | awk -F' => ' '/^Configuration File \\(php.ini\\) Path/{print $2}' | head -1)",' TS_CLOUD_LOADED_INI="$TS_CLOUD_INI_DIR/php.ini"',' mkdir -p "$TS_CLOUD_INI_DIR"',' touch "$TS_CLOUD_LOADED_INI"'," fi",` sed -i '/; ${s} BEGIN/,/; ${s} END/d' "$TS_CLOUD_LOADED_INI"`,` cat >> "$TS_CLOUD_LOADED_INI" <<'TS_CLOUD_PHPINI_EOF'`,`; ${s} BEGIN`,...n,`; ${s} END`,"TS_CLOUD_PHPINI_EOF","fi",`(cd ${T} && pantry restart php-fpm) 2>/dev/null || true`]}function Yt(e={}){let t=oa(e),r=e.installNginx!==!1,n=e.installComposer!==!1,s=[`php.net@${t}`];if(n)s.push("getcomposer.org");if(r)s.push("nginx.org");return[...Te(s),...Ft(["php-fpm"]),...aa(e)]}function Jr(e,t){if(!e)return[];let r=[];if(e.template&&t?.[e.template])r.push(...t[e.template]);if(e.serverSnippet)r.push(...e.serverSnippet);return r}function ca(e){if(!e)return"";let t=typeof e==="object"?e:{},n=[`max-age=${t.maxAge??31536000}`];if(t.includeSubDomains??!0)n.push("includeSubDomains");if(t.preload)n.push("preload");return` add_header Strict-Transport-Security "${n.join("; ")}" always;`}function la(e){if(!e||!e.allow?.length&&!e.deny?.length)return[];let t=[];for(let r of e.deny||[])t.push(` deny ${r};`);if(e.allow?.length){for(let r of e.allow)t.push(` allow ${r};`);t.push(" deny all;")}return t}function is(e){return`/etc/nginx/.htpasswd-${e}`}var ua=new Set(["laravel","php","statamic","wordpress"]);function pa(e){return ua.has(e)}function da(e){return e==="laravel"||e==="statamic"?"public":""}function ma(e,t){let r=e.replace(/\/+$/,""),n=t.replace(/^\/+|\/+$/g,"");return n?`${r}/${n}`:r}function fa(e){let t=e.type??"laravel",r=e.webDirectory??da(t),n=ma(e.appDir,r),s=pa(t),i=e.phpVersion??"8.3",a=[` root ${n};`,"",' add_header X-Frame-Options "SAMEORIGIN";',' add_header X-Content-Type-Options "nosniff";'],c=ca(e.hsts);if(c)a.push(c);for(let u of la(e.security))a.push(u);if(a.push("",` index ${s?"index.php index.html":"index.html index.htm"};`,""," charset utf-8;",""),e.clientMaxBodySize)a.push(` client_max_body_size ${e.clientMaxBodySize};`,"");if(e.auth)a.push(` auth_basic "${e.auth.realm||"Restricted"}";`,` auth_basic_user_file ${is(e.siteName)};`,"");for(let[u,m]of Object.entries(e.redirects||{}))a.push(` location = ${u} { return 301 ${m}; }`);if(Object.keys(e.redirects||{}).length>0)a.push("");if(s){if(a.push(" location / {"," try_files $uri $uri/ /index.php?$query_string;"," }",""," location = /favicon.ico { access_log off; log_not_found off; }"," location = /robots.txt { access_log off; log_not_found off; }",""," error_page 404 /index.php;",""," location ~ \\.php$ {",` fastcgi_pass ${e.fastcgiPass??os(i)};`," fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;"," include fastcgi_params;"," }",""," location ~ /\\.(?!well-known).* {"," deny all;"," }"),t==="wordpress")a.push(""," location = /xmlrpc.php { deny all; }"," location ~* /(?:wp-config\\.php|readme\\.html|license\\.txt)$ { deny all; }"," location ~* /wp-content/uploads/.*\\.php$ { deny all; }")}else if(t==="spa")a.push(" location / {"," try_files $uri $uri/ /index.html;"," }");else a.push(" location / {"," try_files $uri $uri/ =404;"," }");if(e.serverSnippet&&e.serverSnippet.length>0){a.push("");for(let u of e.serverSnippet)a.push(u?` ${u}`:"")}return a}function ga(e){let t=[e.domain,...e.aliases||[]].filter(Boolean);for(let i of t)if(!/^(?=.{1,253}$)(?:\*\.)?[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i.test(i.trim()))throw Error(`Refusing to build a vhost: '${i}' is not a valid hostname.`);if(!t.length)throw Error("Refusing to build a vhost: no server_name (domain) was given.");let r=t.join(" "),n=fa(e);if(e.ssl){let i=["server {"," listen 80;"," listen [::]:80;",` server_name ${r};`," return 301 https://$host$request_uri;","}"],a=["server {"," listen 443 ssl;"," listen [::]:443 ssl;",` server_name ${r};`,` ssl_certificate ${e.ssl.certPath};`,` ssl_certificate_key ${e.ssl.keyPath};`,...e.tlsProtocols?.length?[` ssl_protocols ${e.tlsProtocols.join(" ")};`]:[],"",...n,"}"];return`${[...i,"",...a].join(`
|
|
22
22
|
`)}
|
|
23
23
|
`}return`${["server {"," listen 80;"," listen [::]:80;",` server_name ${r};`,...n,"}"].join(`
|
|
24
24
|
`)}
|
|
25
|
-
`}function
|
|
26
|
-
`);s.push(`cat >> ${r} <<'TS_CLOUD_KEYS_EOF'`,i,"TS_CLOUD_KEYS_EOF",`chmod 600 ${r}`)}return s}function
|
|
27
|
-
`))} > ${y}`,`chmod 644 ${y}`),f.push(`--user ${v}:${y}`)}return m.push(`chown -R ${u}:${u} ${at(s)} /etc/ts-sftp`,`cat > /etc/systemd/system/${n}.service <<TSCLOUD_SFTP_UNIT`,"[Unit]","Description=ts-sftp file transfer server","After=network.target","","[Service]",`User=${u}`,`ExecStart=$BUN_BIN /opt/ts-sftp/node_modules/ts-sftp/dist/bin/cli.js serve --root ${s} --host-key /etc/ts-sftp/host_key --port ${i}${r.readOnly?" --read-only":""} ${f.join(" ")}`,"Restart=always","RestartSec=2","NoNewPrivileges=true","PrivateTmp=true","ProtectSystem=strict",`ReadWritePaths=${s}`,"","[Install]","WantedBy=multi-user.target","TSCLOUD_SFTP_UNIT","systemctl daemon-reload",`systemctl enable ${n}.service`,`systemctl restart ${n}.service`),m}function
|
|
25
|
+
`}function Zr(e){let t=`/etc/nginx/sites-available/${e.siteName}`,r=`/etc/nginx/sites-enabled/${e.siteName}`,n=ga(e),s=[...en()];if(e.auth){let i=is(e.siteName),a=(m)=>m.split("'").join("'\\''"),c=a(e.auth.password),u=a(e.auth.username);s.push(`TS_CLOUD_HTPASS=$(openssl passwd -apr1 '${c}')`,`printf '%s:%s\\n' '${u}' "$TS_CLOUD_HTPASS" > ${i}`,`chmod 640 ${i}`,`chown root:www-data ${i} 2>/dev/null || true`)}return s.push(`cat > ${t} <<'TS_CLOUD_NGINX_EOF'`,n.replace(/\n$/,""),"TS_CLOUD_NGINX_EOF",`ln -sf ${t} ${r}`,"rm -f /etc/nginx/sites-enabled/default",`${He} -t`,"systemctl reload ts-cloud-nginx 2>/dev/null || systemctl restart ts-cloud-nginx 2>/dev/null || true"),s}var He="/usr/local/bin/ts-cloud-nginx";function en(e="/opt/pantry"){return[...kr(),...Te(["nginx.org"]),"mkdir -p /etc/nginx/sites-available /etc/nginx/sites-enabled /var/log/nginx /var/lib/nginx/body /var/lib/nginx/proxy /var/lib/nginx/fastcgi /var/lib/nginx/uwsgi /var/lib/nginx/scgi","getent passwd www-data >/dev/null || useradd --system --no-create-home --shell /usr/sbin/nologin www-data","chown -R www-data:www-data /var/lib/nginx /var/log/nginx",`cat > ${He} <<'TS_CLOUD_NGINXBIN_EOF'`,"#!/bin/sh",`eval "$(cd ${e} && pantry env 2>/dev/null)"`,"NGINX_BIN=/opt/pantry/pantry/.bin/nginx",'if [ ! -x "$NGINX_BIN" ]; then NGINX_BIN=$(command -v nginx || true); fi','if [ -z "$NGINX_BIN" ]; then echo "nginx binary not found; run pantry install nginx.org or install nginx explicitly" >&2; exit 1; fi','exec "$NGINX_BIN" -c /etc/nginx/nginx.conf "$@"',"TS_CLOUD_NGINXBIN_EOF",`chmod +x ${He}`,"cat > /etc/nginx/fastcgi_params <<'TS_CLOUD_FCGI_EOF'","fastcgi_param QUERY_STRING $query_string;","fastcgi_param REQUEST_METHOD $request_method;","fastcgi_param CONTENT_TYPE $content_type;","fastcgi_param CONTENT_LENGTH $content_length;","fastcgi_param SCRIPT_NAME $fastcgi_script_name;","fastcgi_param REQUEST_URI $request_uri;","fastcgi_param DOCUMENT_URI $document_uri;","fastcgi_param DOCUMENT_ROOT $document_root;","fastcgi_param SERVER_PROTOCOL $server_protocol;","fastcgi_param REQUEST_SCHEME $scheme;","fastcgi_param HTTPS $https if_not_empty;","fastcgi_param GATEWAY_INTERFACE CGI/1.1;","fastcgi_param SERVER_SOFTWARE nginx/$nginx_version;","fastcgi_param REMOTE_ADDR $remote_addr;","fastcgi_param REMOTE_PORT $remote_port;","fastcgi_param SERVER_ADDR $server_addr;","fastcgi_param SERVER_PORT $server_port;","fastcgi_param SERVER_NAME $server_name;","fastcgi_param REDIRECT_STATUS 200;","TS_CLOUD_FCGI_EOF","cat > /etc/nginx/nginx.conf <<'TS_CLOUD_NGINXCONF_EOF'","user www-data;","worker_processes auto;","pid /run/nginx.pid;","error_log /var/log/nginx/error.log;","events { worker_connections 1024; }","http {"," default_type application/octet-stream;"," types {"," text/html html htm;"," text/css css;"," application/javascript js;"," application/json json;"," image/svg+xml svg;"," image/png png;"," image/jpeg jpg jpeg;"," image/gif gif;"," image/x-icon ico;"," image/webp webp;"," font/woff2 woff2;"," font/woff woff;"," text/plain txt;"," }"," access_log /var/log/nginx/access.log;"," sendfile on;"," tcp_nopush on;"," keepalive_timeout 65;"," server_tokens off;"," client_max_body_size 100m;"," client_body_temp_path /var/lib/nginx/body;"," proxy_temp_path /var/lib/nginx/proxy;"," fastcgi_temp_path /var/lib/nginx/fastcgi;"," uwsgi_temp_path /var/lib/nginx/uwsgi;"," scgi_temp_path /var/lib/nginx/scgi;"," server {"," listen 80 default_server;"," listen [::]:80 default_server;"," server_name _;"," return 444;"," }"," include /etc/nginx/sites-enabled/*;","}","TS_CLOUD_NGINXCONF_EOF","cat > /etc/systemd/system/ts-cloud-nginx.service <<'TS_CLOUD_NGINXUNIT_EOF'","[Unit]","Description=ts-cloud nginx (pantry)","After=network.target","","[Service]","Type=simple",`ExecStartPre=${He} -t`,`ExecStart=${He} -g 'daemon off;'`,`ExecReload=${He} -s reload`,"Restart=always","RestartSec=3","","[Install]","WantedBy=multi-user.target","TS_CLOUD_NGINXUNIT_EOF","systemctl daemon-reload","systemctl enable ts-cloud-nginx","ls /etc/nginx/sites-enabled/* >/dev/null 2>&1 && systemctl restart ts-cloud-nginx || true"]}import{readFileSync as ha}from"node:fs";function Sa(e){if(typeof e==="string")return e;if(!/^\/[\w./-]+$/.test(e.envFile)||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e.variable))throw Error("Invalid notification env-file reference");let r=ha(e.envFile,"utf8").split(/\r?\n/).map((n)=>n.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/)).find((n)=>n?.[1]===e.variable)?.[2];if(!r)throw Error(`Notification variable ${e.variable} is missing`);return r.replace(/^(['"])(.*)\1$/,"$2")}function Ct(e,t){return!e.events||e.events.includes(t)}async function tn(e,t,r,n={}){if(!e)return[];let s=n.fetchImpl??globalThis.fetch,i=[],a=[],c=async(u,m)=>{try{return await s(Sa(u),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m)})}catch{return}};if(e.slack?.webhookUrl&&Ct(e,t))i.push("slack"),a.push(c(e.slack.webhookUrl,{text:r}));if(e.discord?.webhookUrl&&Ct(e,t))i.push("discord"),a.push(c(e.discord.webhookUrl,{content:r}));if(e.telegram?.botToken&&e.telegram.chatId&&Ct(e,t)){i.push("telegram");let u=`https://api.telegram.org/bot${e.telegram.botToken}/sendMessage`;a.push(c(u,{chat_id:e.telegram.chatId,text:r}))}if(e.webhook?.url&&Ct(e,t))if(i.push("webhook"),(e.webhook.method||"POST")==="GET"){let u=e.webhook.url.includes("?")?"&":"?",m=`${e.webhook.url}${u}event=${encodeURIComponent(t)}&message=${encodeURIComponent(r)}`;a.push(s(m,{method:"GET"}).catch(()=>{return}))}else a.push(c(e.webhook.url,{event:t,message:r}));if(e.email?.to&&Ct(e,t))i.push("email"),a.push(_a(e.email,t,r));return await Promise.all(a),i}async function _a(e,t,r){try{let n=await import("./chunk-27ny16g8.js");await n.email.send({to:e.to,from:e.from,subject:`[ts-cloud] ${t}`,text:r})}catch{}}function as(e,t){return t??e}function We(e){if(!e)return[];let t=(s)=>"'"+s.replaceAll("'",`'"'"'`)+"'",r=(s)=>{if(typeof s==="string")return t(s);if(!/^\/[\w./-]+$/.test(s.envFile)||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(s.variable))throw Error("Invalid notification env-file reference");return'"$(read_env '+t(s.envFile)+" "+t(s.variable)+')"'},n=[];for(let[s,i]of[["slack","text"],["discord","content"]]){let a=e[s]?.webhookUrl;if(a)n.push("URL="+r(a),'post "$URL" '+t(i))}if(e.telegram?.botToken&&e.telegram.chatId)n.push("curl -fsS --max-time 30 -X POST "+t("https://api.telegram.org/bot"+e.telegram.botToken+"/sendMessage")+" --data-urlencode "+t("chat_id="+e.telegram.chatId)+' --data-urlencode "text=$MSG" >/dev/null || FAILED=1');if(e.webhook?.url)if(e.webhook.method==="GET")n.push("curl -fsS --max-time 30 -G "+t(e.webhook.url)+' --data-urlencode "message=$MSG" >/dev/null || FAILED=1');else n.push("post "+t(e.webhook.url)+" message");if(!n.length)return[];return["cat > /usr/local/bin/ts-cloud-notify.new <<'TS_CLOUD_NOTIFY_EOF'","#!/bin/bash","set -uo pipefail",'MSG="${1:-}"; FAILED=0',String.raw`read_env(){ awk -v key="$2" '$0 ~ "^[[:space:]]*(export[[:space:]]+)?" key "[[:space:]]*=" { sub("^[^=]*=[[:space:]]*", ""); sub(/[\r[:space:]]+$/, ""); if (($0 ~ /^".*"$/) || ($0 ~ /^\047.*\047$/)) $0=substr($0,2,length($0)-2); print; exit }' "$1"; }`,String.raw`ESCAPED=$(printf %s "$MSG" | LC_ALL=C awk 'BEGIN{ORS=""; for(i=1;i<32;i++) esc[sprintf("%c",i)]=sprintf("\\u%04x",i)} {if(NR>1) printf "\\n"; for(i=1;i<=length($0);i++){ c=substr($0,i,1); if(c=="\\") printf "\\\\"; else if(c=="\"") printf "\\\""; else if(c in esc) printf "%s",esc[c]; else printf "%s",c }}')`,String.raw`post(){ if [ -z "$1" ]; then FAILED=1; return; fi; curl -fsS --max-time 30 -X POST -H 'Content-Type: application/json' --data "{\"$2\":\"$ESCAPED\"}" "$1" >/dev/null || FAILED=1; }`,...n,'exit "$FAILED"',"TS_CLOUD_NOTIFY_EOF","chmod 0700 /usr/local/bin/ts-cloud-notify.new","mv -f /usr/local/bin/ts-cloud-notify.new /usr/local/bin/ts-cloud-notify"]}function it(e=[],t={}){let r=t.path??"/root/.ssh/authorized_keys",s=[`mkdir -p ${r.replace(/\/[^/]*$/,"")}`,`touch ${r}`,`sed -i '/^${cs("# >>> ts-cloud managed keys >>>")}$/,/^${cs("# <<< ts-cloud managed keys <<<")}$/d' ${r}`];if(e.length>0){let i=["# >>> ts-cloud managed keys >>>",...e.map((a)=>`${a.publicKey.trim()} ${a.name}`),"# <<< ts-cloud managed keys <<<"].join(`
|
|
26
|
+
`);s.push(`cat >> ${r} <<'TS_CLOUD_KEYS_EOF'`,i,"TS_CLOUD_KEYS_EOF",`chmod 600 ${r}`)}return s}function cs(e){return e.replace(/[.*[\]\\/^$]/g,"\\$&")}function us(e,t){let r=`/tmp/ts-cloud-${e}.sh`,n=`TS_CLOUD_${e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}_EOF`;return[`cat > ${r} <<'${n}'`,t.replace(/\n$/,""),n,`chmod +x ${r}`,`bash ${r} || echo "ts-cloud: ${e} setup did not complete; continuing" >&2`,`rm -f ${r}`]}function ps(e,t){if(e===!1)return;if(e===!0||e===void 0)return t;return e}var ls={enabled:!0,ports:[80,443]},va={mode:"detection",paranoiaLevel:1};function ya(e=!0,t=[]){let r=ps(e,ls);if(!r||r.enabled===!1)return[];let n=[...new Set([...r.ports??ls.ports??[],...t])].sort((s,i)=>s-i);return us("ddos",ji({...r,ports:n}))}function $a(e=!0){let t=ps(e,va);if(!t||t.mode==="off")return[];return us("waf",Ri(t))}function ds(e={},t=[]){return[...ya(e.ddos,t),...$a(e.waf)]}function ba(e){return`${e}-sftp`}function ms(e){return e.port??2222}function Ta(e){let t=e.sftp.storage;if(t?.type==="efs"&&t.path)return t.path;return`/var/sftp/${e.slug}`}function at(e){return`'${e.split("'").join("'\\''")}'`}function fs(e,t){if(t==="aws")return;let r=e.storage;if(r?.type==="s3"||!r&&!!e.bucket)throw Error(`sftp: bucket-backed storage is only available on the aws provider (Transfer Family). On ${t}, use storage: { type: 'efs' } to serve a directory on the server.`);for(let[s,i]of Object.entries(e.users))if(!i.sshPublicKeys?.length)throw Error(`sftp: user ${s} needs at least one SSH public key`)}function gs(e){let{slug:t,sftp:r}=e,n=ba(t),s=Ta(e),i=ms(r),a="/etc/ts-sftp/host_key",c="/etc/ts-sftp/users",u=r.serviceUser??"ts-sftp",m=[`# --- ts-sftp (${n}) ---`,`id -u ${u} >/dev/null 2>&1 || useradd --system --home-dir ${at(s)} --shell /usr/sbin/nologin ${u}`,'export HOME="${HOME:-/root}"','command -v bun >/dev/null 2>&1 || (curl -fsSL https://bun.sh/install | bash && ln -sf "$HOME/.bun/bin/bun" /usr/local/bin/bun)',`mkdir -p ${at(s)} /etc/ts-sftp /etc/ts-sftp/users /opt/ts-sftp`,"chmod 750 /etc/ts-sftp",`cd /opt/ts-sftp && [ -f package.json ] || printf '{"name":"ts-sftp-host","private":true}' > package.json`,`cd /opt/ts-sftp && bun add ts-sftp@${r.version??"latest"} --no-save --production || bun add ts-sftp@${r.version??"latest"}`,`[ -f /etc/ts-sftp/host_key ] || bun /opt/ts-sftp/node_modules/ts-sftp/dist/bin/cli.js keygen --out /etc/ts-sftp/host_key --comment ${at(`${t}-sftp`)}`,"chmod 600 /etc/ts-sftp/host_key",'BUN_REAL=$(readlink -f "$(command -v bun)")','case "$BUN_REAL" in /root/*) install -m 0755 "$BUN_REAL" /usr/local/bin/ts-sftp-bun; BUN_BIN=/usr/local/bin/ts-sftp-bun;; *) BUN_BIN="$BUN_REAL";; esac'],f=[];for(let[v,_]of Object.entries(r.users)){let S=(_.homeDirectory??v).replace(/^\/+|\/+$/g,"");if(!S||S.split("/").includes(".."))throw Error(`sftp: invalid homeDirectory for user ${v}`);let y=`/etc/ts-sftp/users/${v}.pub`;m.push(`mkdir -p ${at(`${s}/${S}`)}`,`printf '%s\\n' ${at(_.sshPublicKeys.join(`
|
|
27
|
+
`))} > ${y}`,`chmod 644 ${y}`),f.push(`--user ${v}:${y}`)}return m.push(`chown -R ${u}:${u} ${at(s)} /etc/ts-sftp`,`cat > /etc/systemd/system/${n}.service <<TSCLOUD_SFTP_UNIT`,"[Unit]","Description=ts-sftp file transfer server","After=network.target","","[Service]",`User=${u}`,`ExecStart=$BUN_BIN /opt/ts-sftp/node_modules/ts-sftp/dist/bin/cli.js serve --root ${s} --host-key /etc/ts-sftp/host_key --port ${i}${r.readOnly?" --read-only":""} ${f.join(" ")}`,"Restart=always","RestartSec=2","NoNewPrivileges=true","PrivateTmp=true","ProtectSystem=strict",`ReadWritePaths=${s}`,"","[Install]","WantedBy=multi-user.target","TSCLOUD_SFTP_UNIT","systemctl daemon-reload",`systemctl enable ${n}.service`,`systemctl restart ${n}.service`),m}function hs(e){return e?[ms(e)]:[]}var wa=[80,443];function Qt(e={}){if(e.enabled===!1)return[];let t=[...new Set([...wa,...e.allowedPorts||[]])].filter((n)=>Number.isInteger(n)&&n>=1&&n<=65535).sort((n,s)=>n-s),r=["export DEBIAN_FRONTEND=noninteractive","command -v ufw >/dev/null 2>&1 || apt-get install -y ufw","ufw --force reset","ufw default deny incoming","ufw default allow outgoing","ufw allow OpenSSH"];for(let n of t)r.push(`ufw allow ${n}/tcp`);return r.push("ufw --force enable"),r}function Ye(e,t){let r=e.infrastructure?.compute??{},n=r.runtime==="php"||!!r.php,s=b(e,{environment:t?.environment}),i=n||!!r.managedServices,a=i?kr():[],c=!j({...r,proxy:w(e,{environment:t?.environment})}),u=n?[...a,...Yt({versions:r.php?.versions,default:r.php?.default,extensions:r.php?.extensions,installNginx:c,optimizeForProduction:r.php?.optimizeForProduction,ini:r.php?.ini}),...c?en():[]]:void 0,m=[],f=g(e);if(!n&&i)m.push(...a);if(m.push(...We(e.notifications)),r.managedServices)m.push(...Gt(r.managedServices,{mail:s.enabled?s:void 0}),...ot(f,r.managedServices));let v=e.infrastructure?.sftp;if(v)fs(v,be(e)),m.push(...gs({slug:e.project.slug,sftp:v}));let _=r.firewall??(n?{enabled:!0}:{enabled:!1}),S=Xe(s);if(m.push(...Qt(S.length>0?{..._,allowedPorts:[..._.allowedPorts??[],...S]}:_)),m.push(...ds({ddos:r.ddos,waf:r.waf},[...r.firewall?.allowedPorts??[],...S])),m.push(...Ue(r.autoUpdates??n)),m.push(...Xs(r.appUpdates)),m.push(...xe(r.monitoring??n)),m.push(...it(r.sshKeys,{path:t?.authorizedKeysPath})),r.backups?.enabled)m.push(...qt({database:f,backups:r.backups}));return{runtime:r.runtime||"bun",runtimeVersion:r.runtimeVersion||"latest",phpBox:n,phpProvision:u,servicesProvision:m.length>0?m:void 0}}function M(e={}){let{runtime:t="bun",runtimeVersion:r="latest",systemPackages:n=[],database:s,phpProvision:i,servicesProvision:a,caddyfile:c,rpxProvision:u,baked:m=!1,swapGb:f=2}=e,v=new Set(n);if(s==="sqlite")v.add("sqlite3");else if(s==="mysql")v.add("mysql-client");else if(s==="postgres")v.add("postgresql-client");let _=`#!/bin/bash
|
|
28
28
|
set -euo pipefail
|
|
29
29
|
`,S=Math.floor(f);if(S>0)_+=`
|
|
30
30
|
# Swap: a swapless box under memory pressure lets the kernel OOM killer choose
|
|
@@ -134,36 +134,36 @@ ${y.join(`
|
|
|
134
134
|
`)}
|
|
135
135
|
`}return _+=`
|
|
136
136
|
echo "ts-cloud bootstrap complete — instance is ready for site deploys"
|
|
137
|
-
`,_}var
|
|
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
|
|
139
|
-
`,{mode:420}),r.renameSync(
|
|
137
|
+
`,_}var Ss="/aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id";function _s(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 vs(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 ys(e){return Buffer.from(e,"utf8").toString("base64")}function $s(e){return e.infrastructure?.compute?.image??null}function Zt(e,t){return`${e}-${t}-app-sg`}function rn(e,t,r="app"){return[{Key:"Project",Value:e},{Key:"Environment",Value:t},{Key:"Role",Value:r},{Key:"ManagedBy",Value:"ts-cloud"}]}function Ca(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 bs(e,t){let r=Zt(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 Ca(n.Tags,t.slug,t.environment);return!!t.vpcId&&n.VpcId===t.vpcId})}function Ea(e){try{let t=Ts(Pa(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=$s(t);if(!u){if(u=(await new Be(n).getParameter({Name:Ss})).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=Zt(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:rn(s,r)}]})).GroupId;let x=_s(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=ys(vs(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`},...rn(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=Zt(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=bs(_.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:Ts(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=Ea(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 dc,execSync as js}from"node:child_process";import{createHash as mc,randomUUID as Vs}from"node:crypto";import{createReadStream as fc,existsSync as gc,readFileSync as hc}from"node:fs";async function ws(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)+
|
|
143
|
-
${
|
|
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),
|
|
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
|
|
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((
|
|
151
|
-
`).at(-1)?.split(/\s+/)[0],
|
|
152
|
-
await (${
|
|
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 ${
|
|
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.
|
|
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((Nt)=>Nt===n.join(E.source,re.name)||Nt.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 nn="/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 er(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function Zn(e){let t=`${nn}.candidate`,r=`#!/usr/bin/env bun
|
|
152
|
+
await (${ws.toString()})(JSON.parse(await Bun.file(process.env.TS_CLOUD_STORAGE_POLICY || ${JSON.stringify(nn)}).text()), process.argv.slice(2));
|
|
153
|
+
`;return['command -v bun >/dev/null 2>&1 || { echo "Configured compute storage requires Bun on the host" >&2; exit 1; }',"install -d -m 0755 /etc/ts-cloud /usr/local/lib/ts-cloud /var/lib/ts-cloud",`printf %s ${er(Buffer.from(r).toString("base64"))} | base64 -d > ${Me}.new`,`chmod 0755 ${Me}.new && mv ${Me}.new ${Me}`,`printf %s ${er(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 ${nn} ]; then bun ${Me} ensure-site ${er(e)} ${er(t)}; fi`]}function tr(e){return Object.entries(e).map(([t,r])=>`${t}=${Ra(String(r))}`).join(`
|
|
154
|
+
`)}function Ra(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}var rr=["storage",".env"],Pt=4;function Ie(e){return`${e.replace(/\/+$/,"")}/.ts-cloud`}function Oa(e){return`${Ie(e)}/deploy-history.log`}function Da(e,t){return`${Ie(e)}/deploys/${t}.log`}function Cs(e){return`${Ie(e)}/shared-paths`}function nr(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 Ps(e){let t=e.split("/").pop()||e;if(t===".env"||t.startsWith(".env."))return!0;return/\.[a-z0-9]+$/i.test(t)}function sn(e){return typeof e==="string"?e:e.path}function Es(e){let t=new Map;for(let r of e)t.set(sn(r),r);return[...t.values()]}function Rs(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 xa(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=rr){let r=[`mkdir -p ${e.releases} ${e.shared} ${nr(e)}`,...xa(e)],n=t.map((i)=>Rs(e,i));for(let{path:i,target:a,seed:c}of n){if(!c)continue;if(r.push(`ts_cloud_adopt_shared '${i}' '${a}'`),Ps(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=Cs(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 on(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 an(e){let t=`${e.release}.incoming`;return[`rm -rf ${t}`,`mkdir -p ${t}`,...Ia(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 ln(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 Ia(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 un(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 Aa(e,t){return[`if [ -f ${e} ] && [ ! -L ${e} ] && [ -s ${e} ] && [ ! -s ${t} ]; then`,` cp -a ${e} ${t}`,` echo "[ts-cloud] seeded shared/ from the release's own copy of the file"`,"fi"]}function sr(e,t=rr){let r=[];for(let n of t){let{path:s,target:i,seed:a}=Rs(e,n),c=`${e.release}/${s}`,u=[`rm -rf ${c}`,`mkdir -p "$(dirname ${c})"`,`ln -sfn ${i} ${c}`];if(a){if(s!==".env"&&Ps(s))r.push(...Aa(c,i));r.push(...u);continue}r.push(`if [ -e ${i} ]; then`,...u.map((m)=>` ${m}`),"fi")}return r}function La(e,t){let r=Cs(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 pn(e){return`${Ie(e)}/previous-release`}function dn(e,t="TS_CLOUD_PREV_CURRENT"){let r=pn(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 Os(e,t){let r=pn(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[...Os(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 ${pn(e.base)}`,'echo "rolled back to $TS_CLOUD_RB_ID"'],i=[...Os(e,t.to),...La(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 Ua(e){return`${Ie(e)}/owner`}function mn(e,t){let r=Ua(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 or(e,t){let r=Ie(e),n=Da(e,t.releaseId),s=Oa(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 Ha=new Set(["sqlite","sqlite3"]),ka=new Set([":memory:","memory"]);function Na(e){let t=e?.DB_CONNECTION?.trim().toLowerCase();return t!=null&&Ha.has(t)}function Ma(e){let t=e.trim().replace(/^\.\//,"");if(t===""||t.startsWith("/")||t.startsWith("~"))return;if(t.split("/").includes(".."))return;return t.replace(/\/+$/,"")}function fn(e,t=[]){if(!Na(e))return{};let r=e?.DB_DATABASE_PATH?.trim()||e?.DB_DATABASE?.trim();if(r&&ka.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=Ma(r);if(!n)return{};if(t.some((s)=>sn(s)===n))return{};return{path:n}}function ir(e,t=[]){let{path:r}=fn(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 Ds(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 xs(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 Fa(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,...Is(t.retention)};xs("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,...Is(c.escalated)},v=Object.fromEntries(Object.keys(n).map((_)=>[_,Math.min(n[_],f[_]??n[_])]));xs("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(Fa),{enabled:r,timer:r&&t.timer!==!1,schedule:i,retention:n,pressure:s,paths:a}}function Is(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 gn(e){return Object.keys(Rt).map((t)=>`${Rt[t]}=${e[t]}`).join(" ")}var Fe=(e)=>`"$${Rt[e]}"`;function As(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(za),`journalctl --vacuum-time=${Fe("journalMaxAgeDays")}d --vacuum-size=${Fe("journalMaxSizeMb")}M >/dev/null 2>&1 || true`]}function za(e){let t=Ds(e.path.replace(/\/+$/,"")),r=Ds(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 Ls(){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 Us(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)"',gn(t),...As(n),...Ls(),'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)"',...Us("TS_CLOUD_HC_BEFORE"),"TS_CLOUD_HC_TIER=normal",gn(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",` ${gn(u)}`,` echo "[ts-cloud] warning: / at \${TS_CLOUD_HC_BEFORE}% (at or above ${c}%), host cleanup is using shortened retention windows" >&2`,"fi",...As(n),'if [ "$TS_CLOUD_HC_TIER" != light ]; then',...Ls().map((m)=>` ${m}`),"fi",'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"',...Us("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 hn(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=hn("/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",...hn("/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"),...hn("/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 Ba=/\.(?:[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&&!Ba.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 Hs(e){return["TS_CLOUD_MEM_MB=$(awk '/^MemTotal:/{print int($2/1024)}' /proc/meminfo)","TS_CLOUD_HIGH_MB=$((TS_CLOUD_MEM_MB / 8))",'[ "$TS_CLOUD_HIGH_MB" -lt 512 ] && TS_CLOUD_HIGH_MB=512','[ "$TS_CLOUD_HIGH_MB" -gt 4096 ] && TS_CLOUD_HIGH_MB=4096',`mkdir -p /etc/systemd/system/${e}.d`,`printf '# Written by ts-cloud: memoryHigh resolved from this box.
|
|
155
155
|
# An eighth of %sMB RAM. Set memoryHigh in config to override.
|
|
156
156
|
[Service]
|
|
157
157
|
MemoryAccounting=true
|
|
158
158
|
MemoryHigh=%sM
|
|
159
|
-
' "$TS_CLOUD_MEM_MB" "$TS_CLOUD_HIGH_MB" > /etc/systemd/system/${e}.d/50-ts-cloud-memory.conf`,"systemctl daemon-reload",'echo "[ts-cloud] memoryHigh=auto resolved to ${TS_CLOUD_HIGH_MB}M (one eighth of ${TS_CLOUD_MEM_MB}M)"',...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(`
|
|
160
|
-
`)}function
|
|
161
|
-
`)}var $c=ci();import{homedir as
|
|
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)"',..._n()]}function ar(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 _n(){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 Ka(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 ks(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 Ns=20,Sn=3,ja=5,Va=60;function Ga(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 ${ja} "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 ${Va}); 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 ${Sn}`," 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 ${Ns}); do if ${m}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${Sn}; 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 ${Ns}); do if ${m}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${Sn}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${f(`stopped answering ${u} once it served alone`)}`]:[],...dn(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=Es([".env",...me,...ir(a,me)]),pe=tr(a),ne=m.length>0?[`cd ${k.release}`,...m]:[],ee=["set -euo pipefail",...on(k),ln(k),...n,...Et(k,Z),...an(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`,...un(k),`find ${k.release} -maxdepth 1 \\( -type f -o -type l \\) -name '.env*' ! -name '.env.example' ! -name '*.example' -delete`,`sed -i -E '/^[[:space:]]*(PORT|PORT_BACKEND|PORT_ADMIN|PORT_FRONTEND)[[:space:]]*=/d' ${k.shared}/.env 2>/dev/null || true`,...sr(k,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=${nr(k)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...S==="auto"?Hs(`${V}@.service`):[...ar(`${V}@.service`),..._n()],...Ka(ge),...Ga({paths:k,unitBase:V,releaseId:s,port:c,healthCheckPath:P,healthGateSeconds:v}),...lt(k,u),..._===!1?[]:ks({..._,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=${nr(k)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...ar(te,{auto:S!=="auto",high:S!=="auto",max:Boolean(y)}),...S==="auto"?Hs(te):_n(),`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`,...dn(k),...lt(k,u),..._===!1||!c?[]:ks({..._,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",...on(c),ln(c),...r,...Et(c,[]),...an(c),`tar xzf ${u} -C "$TS_CLOUD_STAGED"`,...un(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 lr(e,t,r){return["set -euo pipefail",`chmod 600 ${ut(e)}`,`mv -f -- ${ut(e)} ${ut(t)}`,`cp -- ${ut(t)} ${ut(r)}`].join(`
|
|
160
|
+
`)}function ur(e){return`rm -f -- ${ut(e)} 2>/dev/null || true`}function vn(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 Ms(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 yn(e){let t=e.infrastructure?.compute??{},r=g(e);return[...Gt(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?[...qt({database:r,backups:t.backups})]:[]]}var Dt=["-S","ssh"];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",...Dt,...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
|
+
`)}var $c=ci();import{homedir as qa}from"node:os";import{join as Wa}from"node:path";var pr={location:"fsn1",image:"ubuntu-24.04",sshUser:"root",sshPrivateKeyPath:"~/.ssh/id_ed25519"};function mr(e){return e.startsWith("~/")?Wa(qa(),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 xt(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"))??pr.location}function It(e,t){let r=e?.infrastructure?.compute;return dt(t,r?.image,e?.hetzner?.image,pt("HCLOUD_IMAGE","HETZNER_IMAGE"))??pr.image}function Ya(e,t){return dt(t,e?.hetzner?.sshUser,pt("HCLOUD_SSH_USER","HETZNER_SSH_USER"))??pr.sshUser}function Fs(e,t){return mr(dt(t,e?.hetzner?.sshPrivateKeyPath,pt("HCLOUD_SSH_KEY","HETZNER_SSH_KEY"))??pr.sshPrivateKeyPath)}function Xa(e,t,r){let n=dt(t,e?.hetzner?.sshPublicKeyPath,pt("HCLOUD_SSH_PUBLIC_KEY","HETZNER_SSH_PUBLIC_KEY"));if(n)return mr(n);return`${r??Fs(e)}.pub`}function zs(e,t={}){let r=Fs(e,t.sshPrivateKeyPath);return{apiToken:xt(t.apiToken,e),location:Mc(e,t.location),image:It(e,t.image),sshUser:Ya(e,t.sshUser),sshPrivateKeyPath:r,sshPublicKeyPath:Xa(e,t.sshPublicKeyPath,r)}}var Ja="https://api.hetzner.cloud/v1";class fr 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 gr 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??Ja,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 fr(`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 gr(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=xt(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 Bs(e){if(!e)return"";return e.endsWith(`
|
|
162
162
|
`)?e:`${e}
|
|
163
163
|
`}function se(e,t={}){let r=t.scriptPath??"/var/lib/cloud/ts-cloud-bootstrap.sh",n=t.permissions??"0755",s=e.split(`
|
|
164
164
|
`).map((i)=>` ${i}`).join(`
|
|
165
165
|
`);return`#cloud-config
|
|
166
|
-
${
|
|
166
|
+
${Bs(t.before)}write_files:
|
|
167
167
|
- path: ${r}
|
|
168
168
|
permissions: '${n}'
|
|
169
169
|
owner: root:root
|
|
@@ -171,7 +171,7 @@ ${zs(t.before)}write_files:
|
|
|
171
171
|
${s}
|
|
172
172
|
runcmd:
|
|
173
173
|
- [ bash, ${r} ]
|
|
174
|
-
${
|
|
174
|
+
${Bs(t.after)}`}function hr(e){let t=new Set([80,443,...e.sitePorts,...e.allowedPorts??[]]);if(e.allowSsh)t.add(22);return[...t].map((r)=>({direction:"in",protocol:"tcp",port:String(r),source_ips:["0.0.0.0/0","::/0"],description:`ts-cloud port ${r}`}))}var $n={micro:"cpx11",small:"cx23",medium:"cx33",large:"cx43",xlarge:"cx53","2xlarge":"ccx33"};function ze(e){if(!e)return $n.micro;if(e in $n)return $n[e];return e}var ae="ts-cloud";function le(e,t,r="app"){return{[`${ae}/project`]:e,[`${ae}/environment`]:t,[`${ae}/role`]:r,[`${ae}/managed-by`]:"ts-cloud"}}function _e(e,t,r,n="app"){return bn(e,t,r)&&e[`${ae}/role`]===n}function bn(e,t,r){if(!e)return!1;return e[`${ae}/project`]===t&&e[`${ae}/environment`]===r}function Qa(e){return e.location?.name??e.datacenter?.location.name??"unknown"}function gt(e){return typeof e==="number"&&Number.isFinite(e)?e:0}function Za(e,t){if(e.architecture&&t.architecture&&e.architecture!==t.architecture)throw Error(`Cannot resize ${e.name} (${e.architecture}) to ${t.name} (${t.architecture}) in place.`);let r=[];if(gt(t.cores)<gt(e.cores))r.push("CPU");if(gt(t.memory)<gt(e.memory))r.push("memory");if(gt(t.disk)<gt(e.disk))r.push("disk");if(r.length>0)throw Error(`Refusing an in-place downgrade from ${e.name} to ${t.name}: ${r.join(", ")} would shrink.`)}async function Zs(e,t,r,n=!0){let[s,i]=await Promise.all([e.getServer(t),e.getServerType(r)]);if(!i)throw Error(`Hetzner server type ${r} was not found.`);let a=s.server_type,c=a.name===i.name;if(!c)Za(a,i);let u=Qa(s),m=i.locations?.find((f)=>f.name===u);return{serverId:t,serverName:s.name,location:u,currentType:a,targetType:i,capacityAvailable:m?.available!==!1,alreadyComplete:c,upgradeDisk:n}}function Fg(e){if(e instanceof fr&&e.code==="resource_unavailable")return!0;if(e instanceof gr){if(e.action.error?.code==="resource_unavailable")return!0;if(/no fitting vhost|placement|free resources/i.test(e.action.error?.message??""))return!0}return/resource_unavailable|no fitting vhost|error during placement|free resources/i.test(e instanceof Error?e.message:String(e))}async function Ae(e,t,r){await e?.onPhase?.(t,r)}async function Tn(e,t,r){await e.waitForAction(t.id,{pollIntervalMs:r.actionPollIntervalMs,maxWaitMs:r.actionTimeoutMs})}var Sr=async({client:e,hooks:t,actionPollIntervalMs:r,actionTimeoutMs:n,serverPollIntervalMs:s,serverTimeoutMs:i},a,c,u)=>{let m=await e.getServer(a.serverId);if(m.status!=="running"){await Ae(t,u?"recovering":"powering-on",{serverId:a.serverId});let v=await e.powerOnServer(a.serverId);await Tn(e,v,{actionPollIntervalMs:r,actionTimeoutMs:n}),m=await e.waitForServerRunning(a.serverId,{pollIntervalMs:s,maxWaitMs:i})}await Ae(t,"verifying",{serverId:a.serverId,recovered:u});let f=await t?.afterBoot?.(m,a.targetType,c,{recovered:u});return{server:m,verification:f}};async function Uc(e){let{client:t,hooks:r}=e,n=e.upgradeDisk??!0;await Ae(r,"planning",{serverId:e.serverId,targetType:e.targetType});let s=await Zs(t,e.serverId,e.targetType,n),i=await t.getServer(s.serverId);if(s.alreadyComplete){let u=await Sr(e,s,e.manifest,!1);return await Ae(r,"complete",{alreadyComplete:!0}),{status:"already-complete",plan:s,verification:u.verification}}if(!s.capacityAvailable&&!e.attemptUnavailable)return await Ae(r,"waiting-capacity",{location:s.location,targetType:s.targetType.name}),{status:"waiting-capacity",plan:s};let a=e.manifest;if(i.status==="off"&&!e.resumeFromOff){let u=await Sr(e,s,void 0,!0);return{status:"recovered",plan:s,server:u.server,verification:u.verification,retryable:!0,error:"Server was already off without a resumable resize checkpoint; powered it back on."}}if(i.status==="running"){await Ae(r,"preflight",{serverId:s.serverId}),a=await r?.preflight?.(i,s.targetType),await Ae(r,"shutting-down",{serverId:s.serverId});let u=await t.shutdownServer(s.serverId);await Tn(t,u,e),i=await t.waitForServerStatus(s.serverId,"off",{pollIntervalMs:e.serverPollIntervalMs,maxWaitMs:e.serverTimeoutMs})}try{await Ae(r,"resizing",{serverId:s.serverId,from:s.currentType.name,to:s.targetType.name,upgradeDisk:n});let u=await t.changeServerType(s.serverId,s.targetType.name,n);await Tn(t,u,e)}catch(u){let m=await Sr(e,s,a,!0);return{status:"recovered",plan:s,server:m.server,manifest:a,verification:m.verification,retryable:Fg(u),error:u instanceof Error?u.message:String(u)}}let c=await Sr(e,s,a,!1);if(c.verification&&!c.verification.ok)throw Error(`Resize completed but verification failed: ${(c.verification.failures??[]).join("; ")}`);return await Ae(r,"complete",{serverId:s.serverId,targetType:s.targetType.name}),{status:"completed",plan:s,server:c.server,manifest:a,verification:c.verification}}var ec=String.raw`
|
|
175
175
|
const { readdir, readFile, readlink, stat } = await import('node:fs/promises')
|
|
176
176
|
|
|
177
177
|
const text = (command) => {
|
|
@@ -263,7 +263,7 @@ console.log(JSON.stringify({
|
|
|
263
263
|
persistentData: persistentData.sort(),
|
|
264
264
|
dataCatalog: dataCatalog.sort(),
|
|
265
265
|
}))
|
|
266
|
-
`;function
|
|
266
|
+
`;function tc(e){return`printf %s ${Buffer.from(e).toString("base64")} | base64 -d | bun -`}async function rc(e){let t=await Se(e.host,tc(ec),e);return JSON.parse(t)}async function nc(e,t){let r="";for(let n=1;n<=3;n++){let s=Bun.spawn(["curl","--location","--silent","--show-error","--output","/dev/null","--max-time",String(Math.max(1,Math.ceil(t/1000))),"--write-out","%{http_code}",`https://${e}/`],{stdout:"pipe",stderr:"pipe"}),[i,a,c]=await Promise.all([new Response(s.stdout).text(),new Response(s.stderr).text(),s.exited]),u=Number.parseInt(i.trim(),10);if(c===0&&u>0)return{domain:e,ok:u<500,status:u};if(r=a.trim()||`curl exited ${c}`,n<3)await Bun.sleep(500*n)}return{domain:e,ok:!1,error:r}}async function sc(e,t){let r=[],n=0,s=Array.from({length:Math.min(4,e.length)},async()=>{for(;;){let i=n++,a=e[i];if(!a)return;r[i]=await nc(a,t)}});return await Promise.all(s),r}async function Qc(e){let t=await rc(e),r=await sc(t.routeDomains,e.routeTimeoutMs??15000);return{...t,routeProbes:r}}async function Hc(e){let t=await Qc(e),r=t.routeProbes.filter((n)=>!n.ok);if(t.failedUnits.length>0)throw Error(`Preflight found failed services: ${t.failedUnits.join(", ")}`);if(r.length>0)throw Error(`Preflight found unhealthy routes: ${r.map((n)=>n.domain).join(", ")}`);return await Se(e.host,String.raw`systemctl list-units --type=service --state=running --no-legend --plain | awk '{print $1}' | while read -r unit; do if systemctl cat "$unit" 2>/dev/null | grep -Eq '/var/www|/usr/local/bin/rpx|/opt/ts-cloud'; then systemctl enable "$unit" >/dev/null 2>&1 || true; fi; done; systemctl daemon-reload; sync`,e),t}function St(e,t){let r=new Set(t);return e.filter((n)=>!r.has(n))}function oc(e){return Math.floor((e.memory??0)*1024*1024*1024)}async function ic(e){await Se(e.host,String.raw`set -e
|
|
267
267
|
root_source="$(findmnt -n -o SOURCE /)"
|
|
268
268
|
root_fs="$(findmnt -n -o FSTYPE /)"
|
|
269
269
|
parent="$(lsblk -n -o PKNAME "$root_source" | head -1)"
|
|
@@ -275,18 +275,18 @@ case "$root_fs" in
|
|
|
275
275
|
ext2|ext3|ext4) resize2fs "$root_source" ;;
|
|
276
276
|
xfs) xfs_growfs / ;;
|
|
277
277
|
*) echo "Unsupported root filesystem: $root_fs" >&2; exit 1 ;;
|
|
278
|
-
esac`,e)}async function
|
|
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
|
|
280
|
-
`,"utf8"),await
|
|
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(`
|
|
282
|
-
`);try{this.sshExec(u.publicIp,m);continue}catch{}let f=`${a}/.${i}-${
|
|
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(!
|
|
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{
|
|
285
|
-
${s}`);if(/status:\s*(?:done|degraded)/.test(s))return}catch(s){if(s instanceof Error&&/cloud-init reported an error/.test(s.message))throw s}await this.sleep(t)}throw Error(`Timed out waiting for cloud-init to finish on ${e} after ${r}ms`)}outputsFromState(e,t){return{deployStoragePath:e.deployStoragePath||"/var/ts-cloud/staging",appInstanceId:e.serverId?String(e.serverId):void 0,appPublicIp:t?.public_net.ipv4?.ip||e.publicIp,appPublicIpv6:De(t?.public_net.ipv6?.ip)||e.publicIpv6,sshUser:e.sshUser||this.sshUser,servicesPrivateIp:e.servicesPrivateIp}}static SSH_HOST_KEY_OPTS=["-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR"];static SSH_KEEPALIVE_OPTS=["-o","ConnectTimeout=30","-o","ServerAliveInterval=15","-o","ServerAliveCountMax=4"];sshBaseArgs(e,t=[]){return["-i",this.sshPrivateKeyPath,...Pe.SSH_HOST_KEY_OPTS,...Pe.SSH_KEEPALIVE_OPTS,"-o","BatchMode=yes",...t,`${this.sshUser}@${e}`]}scpToHost(e,t,r){let n=["scp","-i",this.sshPrivateKeyPath,...Pe.SSH_HOST_KEY_OPTS,...Pe.SSH_KEEPALIVE_OPTS,"-o","BatchMode=yes",t,`${this.sshUser}@${e}:${r}`].map((i)=>`"${i.replace(/"/g,"\\\"")}"`).join(" "),s=3;for(let i=1;i<=3;i++)try{
|
|
286
|
-
`);try{let r=Bun.spawn(["bash","-c",t],{stdout:"pipe",stderr:"pipe",env:process.env}),[n,s,i]=await Promise.all([new Response(r.stdout).text(),new Response(r.stderr).text(),r.exited]);return{success:i===0,instanceCount:1,perInstance:[{instanceId:"localhost",status:i===0?"Success":"Failed",output:n,error:s}]}}catch(r){return{success:!1,instanceCount:1,perInstance:[{instanceId:"localhost",status:"Failed",error:r?.message??String(r)}],error:r?.message??String(r)}}}}function qc(){let e=process.env.TS_CLOUD_DASHBOARD_BOX;return e!=null&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}import{createHash as
|
|
278
|
+
esac`,e)}async function ac(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 ic(e);if(r)await ac(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:oc(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 cc,readFile as lc,rename as uc,writeFile as pc}from"node:fs/promises";import{join as Ks}from"node:path";var Vc="storage/cloud/state";function mt(e=process.cwd()){return rl()?l(e,"state"):Ks(e,Vc)}function qe(e,t=process.cwd()){return Ks(mt(t),`${e}.json`)}async function je(e,t=process.cwd()){try{let r=await lc(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 cc(mt(r),{recursive:!0});let s=`${n}.${process.pid}.tmp`;await pc(s,`${JSON.stringify(t,null,2)}
|
|
280
|
+
`,"utf8"),await uc(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 wn=268435456;function Lt(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function Sc(e){let t=mc("sha256");for await(let r of fc(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=vn(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,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=xt(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=zs(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=vn(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,hr({allowSsh:s.allowSsh!==!1,sitePorts:v,allowedPorts:[...s.firewall?.allowedPorts??[],...hs(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=It(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=It(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"),hr({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=yn(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=Yt({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=It(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"),hr({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=yn(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)=>bn(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,"-")}-${Vs()}.tar.gz`}`,i=await Sc(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 ${Lt(a)} /var/ts-cloud/staging`,`test -s ${Lt(c)}`,`cp -- ${Lt(c)} ${Lt(s)}`].join(`
|
|
282
|
+
`);try{this.sshExec(u.publicIp,m);continue}catch{}let f=`${a}/.${i}-${Vs()}.tmp`;try{this.scpToHost(u.publicIp,e.localPath,f),this.sshExec(u.publicIp,lr(f,c,s))}catch(v){try{this.sshExec(u.publicIp,ur(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
|
+
`),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(!gc(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=hc(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
|
+
`))}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{js(`ssh ${this.sshBaseArgs(e,["-o","ConnectTimeout=5"]).map(Lt).join(" ")} true`,{stdio:"pipe",maxBuffer:wn});return}catch(i){s=i,await this.sleep(t)}throw Error(`Timed out waiting for SSH on ${e} after ${r}ms: ${s?.message??"unknown error"}`)}async waitForCloudInit(e){let{cloudInitIntervalMs:t,cloudInitTimeoutMs:r}=this.bootWait,n=Date.now();while(Date.now()-n<r){try{let s=this.sshExec(e,"if command -v cloud-init >/dev/null 2>&1; then cloud-init status --long 2>/dev/null || true; else echo 'status: done'; fi");if(/status:\s*error/.test(s))throw Error(`cloud-init reported an error on ${e}:
|
|
285
|
+
${s}`);if(/status:\s*(?:done|degraded)/.test(s))return}catch(s){if(s instanceof Error&&/cloud-init reported an error/.test(s.message))throw s}await this.sleep(t)}throw Error(`Timed out waiting for cloud-init to finish on ${e} after ${r}ms`)}outputsFromState(e,t){return{deployStoragePath:e.deployStoragePath||"/var/ts-cloud/staging",appInstanceId:e.serverId?String(e.serverId):void 0,appPublicIp:t?.public_net.ipv4?.ip||e.publicIp,appPublicIpv6:De(t?.public_net.ipv6?.ip)||e.publicIpv6,sshUser:e.sshUser||this.sshUser,servicesPrivateIp:e.servicesPrivateIp}}static SSH_HOST_KEY_OPTS=["-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR"];static SSH_KEEPALIVE_OPTS=["-o","ConnectTimeout=30","-o","ServerAliveInterval=15","-o","ServerAliveCountMax=4"];sshBaseArgs(e,t=[]){return["-i",this.sshPrivateKeyPath,...Pe.SSH_HOST_KEY_OPTS,...Pe.SSH_KEEPALIVE_OPTS,"-o","BatchMode=yes",...t,`${this.sshUser}@${e}`]}scpToHost(e,t,r){let n=["scp",...Dt,"-i",this.sshPrivateKeyPath,...Pe.SSH_HOST_KEY_OPTS,...Pe.SSH_KEEPALIVE_OPTS,"-o","BatchMode=yes",t,`${this.sshUser}@${e}:${r}`].map((i)=>`"${i.replace(/"/g,"\\\"")}"`).join(" "),s=3;for(let i=1;i<=3;i++)try{js(n,{stdio:"pipe",maxBuffer:wn});return}catch(a){if(i===3)throw Error(jt(a))}}sshExec(e,t){try{return dc("ssh",[...this.sshBaseArgs(e),$c],{encoding:"utf8",input:t,stdio:["pipe","pipe","pipe"],maxBuffer:wn})}catch(r){throw Error(`${jt(r)}${Jn(r,t)}`)}}}class eo{name="ssh";usesCloudFormation=!1;async getComputeOutputs(){return{appPublicIp:"127.0.0.1",sshUser:"root"}}async uploadRelease(e){return{artifactRef:e.localPath}}async findComputeTargets(e){if((e.role||"app")!=="app")return[];return[{id:"localhost",name:"localhost",publicIp:"127.0.0.1",status:"running"}]}async runRemoteDeploy(e){let t=e.commands.join(`
|
|
286
|
+
`);try{let r=Bun.spawn(["bash","-c",t],{stdout:"pipe",stderr:"pipe",env:process.env}),[n,s,i]=await Promise.all([new Response(r.stdout).text(),new Response(r.stderr).text(),r.exited]);return{success:i===0,instanceCount:1,perInstance:[{instanceId:"localhost",status:i===0?"Success":"Failed",output:n,error:s}]}}catch(r){return{success:!1,instanceCount:1,perInstance:[{instanceId:"localhost",status:"Failed",error:r?.message??String(r)}],error:r?.message??String(r)}}}}function qc(){let e=process.env.TS_CLOUD_DASHBOARD_BOX;return e!=null&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}import{createHash as nl,randomUUID as uo}from"node:crypto";import{createReadStream as sl}from"node:fs";import{isIP as ol}from"node:net";import{createHash as vc}from"node:crypto";import{appendFile as yc,mkdir as bc,readFile as Tc}from"node:fs/promises";import{dirname as wc}from"node:path";var Gs=268435456,qs=async(e,t)=>{let r=Bun.spawn(e,{stdin:t===void 0?"ignore":Buffer.from(t),stdout:"pipe",stderr:"pipe"}),[n,s,i]=await Promise.all([r.exited,new Response(r.stdout).text(),new Response(r.stderr).text()]);return{code:n,signal:r.signalCode,stdout:s.slice(-Gs),stderr:i.slice(-Gs)}},Ug=["-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR"],Qg=["-o","ConnectTimeout=30","-o","ServerAliveInterval=15","-o","ServerAliveCountMax=4"];function Ws(e){if(e.hostKey==="insecure")return[...Ug];return["-o",`StrictHostKeyChecking=${e.hostKey.policy==="pin"?"yes":"accept-new"}`,"-o",`UserKnownHostsFile=${e.hostKey.knownHostsFile}`,"-o","LogLevel=ERROR"]}function Qs(e){let t=[...Qg];if(e.connectTimeoutSec!==void 0)t[1]=`ConnectTimeout=${e.connectTimeoutSec}`;return t}function jc(e,t,r=[]){return["-i",e.identityFile,"-p",String(e.port??22),...Ws(e),...Qs(e),"-o","BatchMode=yes",...r,`${e.user}@${t}`]}function Hg(e,t,r,n){return["-i",e.identityFile,"-P",String(e.port??22),...Ws(e),...Qs(e),"-o","BatchMode=yes",r,`${e.user}@${t}:${n}`]}function ht(e){return`SHA256:${vc("sha256").update(Buffer.from(e,"base64")).digest("base64").replace(/=+$/,"")}`}async function ui(e,t=22,r=qs){let n=await r(["ssh-keyscan","-T","10","-p",String(t),"-t","ed25519",e]),s=n.stdout.split(`
|
|
287
287
|
`).find((i)=>i&&!i.startsWith("#"))?.trim().split(/\s+/);if(n.code!==0||!s?.[1]||!s[2])throw Error(`SSH host-key scan failed: ${n.stderr.trim()||"no key returned"}`);return{algorithm:s[1],key:s[2]}}function zc(e,t=22){return t===22?e:`[${e}]:${t}`}function Gg(e,t,r){return`${zc(e,t)} ${r.algorithm} ${r.key}`}function Vg(e,t,r=22){let n=zc(t,r);for(let s of e.split(`
|
|
288
|
-
`)){let i=s.trim();if(!i||i.startsWith("#")||i.startsWith("@"))continue;let[a,c,u]=i.split(/\s+/);if(!a||!c||!u)continue;if(a.split(",").includes(n))return{algorithm:c,key:u}}return null}function Kc(e=process.cwd()){return l(e,"ssh","known_hosts")}async function
|
|
289
|
-
`,{mode:384})}class Mr{options;run;scan;readKnownHosts;appendKnownHosts;constructor(e,t={}){this.options=e;this.run=t.run??
|
|
288
|
+
`)){let i=s.trim();if(!i||i.startsWith("#")||i.startsWith("@"))continue;let[a,c,u]=i.split(/\s+/);if(!a||!c||!u)continue;if(a.split(",").includes(n))return{algorithm:c,key:u}}return null}function Kc(e=process.cwd()){return l(e,"ssh","known_hosts")}async function Cc(e){try{return await Tc(e,"utf8")}catch{return""}}async function Pc(e,t){await bc(wc(e),{recursive:!0}),await yc(e,`${t}
|
|
289
|
+
`,{mode:384})}class Mr{options;run;scan;readKnownHosts;appendKnownHosts;constructor(e,t={}){this.options=e;this.run=t.run??qs,this.scan=t.scan??ui,this.readKnownHosts=t.readKnownHosts??Cc,this.appendKnownHosts=t.appendKnownHosts??Pc}runnerFor(e={}){if(e.sudo!==void 0)return ci({sudo:e.sudo});return this.options.runner??ci()}async exec(e,t,r={}){let n=await this.run(["ssh",...jc(this.options,e),this.runnerFor(r)],t);if(n.code!==0){let s={status:n.code,signal:n.signal,stdout:n.stdout,stderr:n.stderr};throw Error(`${jt(s)}${Jn(s,t)}`)}return n.stdout}async scp(e,t,r){let n=["scp",...Dt,...Hg(this.options,e,t,r)],s=3;for(let i=1;i<=3;i++){let a=await this.run(n);if(a.code===0)return;if(i===3)throw Error(jt({status:a.code,signal:a.signal,stdout:a.stdout,stderr:a.stderr}))}}async probe(e){return(await this.run(["ssh",...jc(this.options,e,["-o","ConnectTimeout=5"]),"true"])).code===0}async ensureHostKey(e){let t=this.options.port??22;if(this.options.hostKey==="insecure")try{return{fingerprint:ht((await this.scan(e,t,this.run)).key),pinnedNow:!1}}catch{return{fingerprint:"",pinnedNow:!1}}let{policy:r,knownHostsFile:n}=this.options.hostKey,s=Vg(await this.readKnownHosts(n),e,t);if(s)return{fingerprint:ht(s.key),pinnedNow:!1};let i=await this.scan(e,t,this.run);if(r==="pin")return await this.appendKnownHosts(n,Gg(e,t,i)),{fingerprint:ht(i.key),pinnedNow:!0};return{fingerprint:ht(i.key),pinnedNow:!1}}}import{isIP as Ec}from"node:net";var ke=1,Wc="/var/lib/ts-cloud";function qg(e=ke){return`${Wc}/bootstrap.v${e}`}var jg=1;function Rc(e){return e==="aarch64"||e==="arm64"}function oo(e){let t=e.lanIp?.trim()||e.facts?.lanIp?.trim();return t&&Ec(t)!==0?t:void 0}function to(e,t,r){if(!bt(e.infrastructure?.compute?.managedServices?.vitess))return;if(t==="raspberry-pi"||Rc(r))throw Error(`managedServices.vitess is enabled, but Vitess publishes only x86_64 release tarballs and this host is ${r??"a Raspberry Pi (arm64)"}. Drop managedServices.vitess or deploy it to an x86_64 host.`)}function tt(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function Dc(){return`
|
|
290
290
|
# A Pi 5 has no battery-backed RTC and boots in 1970 until NTP answers. apt
|
|
291
291
|
# rejects Release files "from the future" and ACME rejects a skewed clock, so
|
|
292
292
|
# wait (bounded) for systemd-timesyncd before anything touches the network
|
|
@@ -302,7 +302,7 @@ if command -v timedatectl >/dev/null 2>&1; then
|
|
|
302
302
|
systemctl start systemd-time-wait-sync >/dev/null 2>&1 || true
|
|
303
303
|
fi
|
|
304
304
|
fi
|
|
305
|
-
`}function
|
|
305
|
+
`}function Ic(){return`
|
|
306
306
|
# SD cards wear; a journal allowed to grow to the default 10% of the disk is
|
|
307
307
|
# the single biggest writer on an idle Pi. Bound it.
|
|
308
308
|
install -d -m 0755 /etc/systemd/journald.conf.d
|
|
@@ -313,11 +313,11 @@ MaxRetentionSec=7day
|
|
|
313
313
|
Compress=yes
|
|
314
314
|
TS_CLOUD_JOURNAL_EOF
|
|
315
315
|
systemctl restart systemd-journald
|
|
316
|
-
`}function
|
|
316
|
+
`}function Ac(e){return`
|
|
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
|
|
320
|
+
`}function el(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",...oo(e)?{ip:oo(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??[],...el(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,19 +325,19 @@ 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(
|
|
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
|
`)}
|
|
332
332
|
`}if(I+=` exit 0
|
|
333
333
|
fi
|
|
334
|
-
`,I+=
|
|
334
|
+
`,I+=Dc(),n==="raspberry-pi")I+=Ic();if(s)I+=Ac(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(
|
|
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
|
-
`;return I}var At={user:"root",port:22,privateKeyPath:"~/.ssh/id_ed25519",hostKey:"pin",profile:"generic",publicIp:"auto"},
|
|
340
|
+
`;return I}var At={user:"root",port:22,privateKeyPath:"~/.ssh/id_ed25519",hostKey:"pin",profile:"generic",publicIp:"auto"},ao=["pin","accept-new","insecure"],lo=["raspberry-pi","generic"];function _t(...e){for(let t of e){let r=process.env[t]?.trim();if(r)return r}return}function Ut(...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 Ut(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 mr(Ut(t,e?.privateKeyPath,_t("TS_CLOUD_SSH_KEY"))??At.privateKeyPath)}function Xg(e,t){let r=Ut(t,e?.ssh?.hostKey,_t("TS_CLOUD_SSH_HOST_KEY"))??At.hostKey;if(!ao.includes(r))throw Error(`Invalid ssh.hostKey '${r}'. Use one of: ${ao.join(", ")}.`);return r}function Yg(e,t=At.user,r){return r??e?.ssh?.sudo??t!=="root"}function Zg(e,t){let r=Ut(t,e?.ssh?.profile,_t("TS_CLOUD_SSH_PROFILE"))??At.profile;if(!lo.includes(r))throw Error(`Invalid ssh.profile '${r}'. Use one of: ${lo.join(", ")}.`);return r}function ep(e,t){return Ut(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
|
|
341
341
|
. /etc/os-release 2>/dev/null || true
|
|
342
342
|
# Strings are stripped of quotes, backslashes and newlines rather than escaped:
|
|
343
343
|
# nothing reported here legitimately contains them, and a probe that cannot
|
|
@@ -371,21 +371,21 @@ printf '"privilege":"%s"' "$(sudo -n true >/dev/null 2>&1 && printf sudo || prin
|
|
|
371
371
|
printf '}\\n'
|
|
372
372
|
`;function fi(e){let t=e.split(`
|
|
373
373
|
`).map((r)=>r.trim()).filter(Boolean).at(-1);if(!t||!t.startsWith("{"))throw Error(`Preflight returned no facts:
|
|
374
|
-
${e.trim().slice(-2000)}`);try{return JSON.parse(t)}catch(r){throw Error(`Preflight returned malformed facts: ${r.message}`)}}var vt=1073741824;function
|
|
374
|
+
${e.trim().slice(-2000)}`);try{return JSON.parse(t)}catch(r){throw Error(`Preflight returned malformed facts: ${r.message}`)}}var vt=1073741824;function tl(e){return e==="aarch64"||e==="arm64"}function hi(e,t){let r=[],n=e.arch??"";if(!tl(n)&&!(n==="x86_64"&&t.profile==="generic"))r.push({code:"arch.not-aarch64",severity:"error",message:t.profile==="raspberry-pi"?`The raspberry-pi profile expects a 64-bit ARM OS; this host reports ${n||"an unknown architecture"}.`:`Unsupported architecture ${n||"(unknown)"}.`,remediation:t.profile==="raspberry-pi"?"Flash the 64-bit Raspberry Pi OS or Ubuntu Server arm64 image.":"Use an x86_64 or arm64 Linux host."});let s=`${e.osId??""} ${e.osIdLike??""}`.toLowerCase();if(!/\b(?:debian|ubuntu|raspbian)\b/.test(s))r.push({code:"os.unsupported",severity:"error",message:`The bootstrap targets Debian and Ubuntu (apt); this host reports ${e.os||"an unknown OS"}.`,remediation:"Install Raspberry Pi OS, Debian or Ubuntu Server."});let i=e.memoryBytes??0;if(i<vt)r.push({code:"memory.low",severity:"error",message:`${(i/vt).toFixed(2)} GiB of memory; the runtime plus a gateway needs at least 1 GiB.`,remediation:"Use a host with 2 GiB or more."});else if(i<2*vt)r.push({code:"memory.low",severity:"warning",message:`${(i/vt).toFixed(2)} GiB of memory; on-box builds and managed services will be tight.`,remediation:"Build releases in CI rather than on the host, and keep managedServices small."});if((e.diskFreeBytes??0)<4*vt)r.push({code:"disk.low",severity:"error",message:`${((e.diskFreeBytes??0)/vt).toFixed(1)} GiB free on /; releases, the artifact cache and swap need at least 4 GiB.`,remediation:"Free space or use a larger card or disk."});if(t.user!=="root"&&!e.sudoOk)r.push({code:"sudo.missing",severity:"error",message:`${t.user} cannot run sudo without a password, and the bootstrap needs root.`,remediation:`Add '${t.user} ALL=(ALL) NOPASSWD:ALL' to /etc/sudoers.d/ts-cloud, or deploy as root.`});if(!e.timeSynced)r.push({code:"time.unsynced",severity:"warning",message:"The clock is not NTP-synchronised yet; the bootstrap waits for it before running apt.",remediation:"Nothing to do unless it never syncs: then check the network and systemd-timesyncd."});if(!e.httpsOk)r.push({code:"https.blocked",severity:"error",message:"The host cannot reach https://github.com, so it cannot download the runtime or packages.",remediation:"Check DNS, the default route and any egress firewall from the host."});if(e.cloudInitPresent&&/running/i.test(e.cloudInitStatus??""))r.push({code:"cloud-init.running",severity:"info",message:"cloud-init is still running its first boot; the adopt waits for it to finish."});if(e.piModel)r.push({code:"pi.model",severity:"info",message:e.piModel});if(e.kernelBits===32)r.push({code:"bits.32",severity:"error",message:"This is a 32-bit userland; bun ships no 32-bit build.",remediation:"Flash a 64-bit OS image."});return r}function Ai(e){return e.some((t)=>t.severity==="error")}function yi(e){if(e.length===0)return"No findings.";let t=Math.max(...e.map((r)=>r.code.length));return e.map((r)=>{let n=`${r.severity.padEnd(7)} ${r.code.padEnd(t)} ${r.message}`;return r.remediation?`${n}
|
|
375
375
|
${" ".repeat(t+10)}${r.remediation}`:n}).join(`
|
|
376
|
-
`)}var Si="/var/ts-cloud/staging",
|
|
377
|
-
`);try{await this.exec(c.publicIp,u);continue}catch{}let m=`${
|
|
376
|
+
`)}var Si="/var/ts-cloud/staging",Cn=Or,rp="TS_CLOUD_SSH_SKIP_BOOTSTRAP",il=["size","instances","appServers","servicesServer","loadBalancer","fleet","image","bakedImage","allowSsh"];function Ht(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function al(e){let t=nl("sha256");for await(let r of sl(e))t.update(r);return t.digest("hex")}function np(e,t){if(e.cloud?.attachTo)throw Error("cloud.attachTo is not supported by the ssh provider: it deploys to the hosts in ssh.hosts and nothing else.");if(t.hosts.length>1)throw Error(`ssh.hosts lists ${t.hosts.length} hosts; multi-host ssh fleets are not supported yet.`);if(bt(e.infrastructure?.compute?.managedServices?.vitess))to(e,t.profile);let r=e.infrastructure?.compute??{};return il.filter((n)=>r[n]!==void 0).map((n)=>`infrastructure.compute.${n} has no effect with the ssh provider; the host is what it is.`)}class Fr{name="ssh";usesCloudFormation=!1;settings;cwd;bootWait;transportInstance;constructor(e={}){this.settings=pi(void 0,{hosts:e.hosts,user:e.user,port:e.port,privateKeyPath:e.privateKeyPath,hostKey:e.hostKey,sudo:e.sudo,profile:e.profile,publicIp:e.publicIp,lan:e.lan}),this.cwd=e.cwd??process.cwd(),this.transportInstance=e.transport,this.bootWait={sshIntervalMs:e.bootWait?.sshIntervalMs??5000,sshTimeoutMs:e.bootWait?.sshTimeoutMs??300000,cloudInitIntervalMs:e.bootWait?.cloudInitIntervalMs??5000,cloudInitTimeoutMs:e.bootWait?.cloudInitTimeoutMs??600000}}get host(){if(this.settings.hosts.length>1)throw Error(`ssh.hosts lists ${this.settings.hosts.length} hosts; multi-host ssh fleets are not supported yet.`);return this.settings.hosts[0]}get transport(){if(!this.transportInstance){let e=this.host;this.transportInstance=new Mr({user:e.user,port:e.port,identityFile:e.privateKeyPath,hostKey:this.settings.hostKey==="insecure"?"insecure":{policy:this.settings.hostKey,knownHostsFile:Kc(this.cwd)}})}return this.transportInstance}exec(e,t){return this.transport.exec(e,t,{sudo:this.settings.sudo})}async findComputeTargets(e){if((e.role||"app")!=="app")return[];let{host:t}=this.host;return[{id:t,name:t,publicIp:t,status:"running"}]}async getComputeOutputs(){let{host:e,user:t}=this.host;return{appInstanceId:e,appPublicIp:e,sshUser:t,deployStoragePath:Si}}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 ssh compute targets found for release upload");let n=`${e.remoteKey.replace(/^releases\//,"").replace(/\.tar\.gz$/,"").replace(/\//g,"-")}-${uo()}.tar.gz`,s=`${Si}/${n}`,i=await al(e.localPath),a=`${Cn}/${i}.tar.gz`;for(let c of t){if(!c.publicIp)throw Error(`Target ${c.id} has no address for SCP upload`);let u=["set -euo pipefail",`mkdir -p ${Ht(Cn)} ${Ht(Si)}`,`test -s ${Ht(a)}`,`cp -- ${Ht(a)} ${Ht(s)}`].join(`
|
|
377
|
+
`);try{await this.exec(c.publicIp,u);continue}catch{}let m=`${Cn}/.${i}-${uo()}.tmp`;try{await this.transport.scp(c.publicIp,e.localPath,m),await this.exec(c.publicIp,lr(m,a,s))}catch(f){throw await this.exec(c.publicIp,ur(m)).catch(()=>{}),f}}return{artifactRef:s}}async runRemoteDeploy(e){if(e.targets.length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets provided"};let t=e.commands.join(`
|
|
378
378
|
`),r=[];for(let s of e.targets){if(!s.publicIp){r.push({instanceId:s.id,status:"Failed",error:"Missing address"});continue}try{let i=await this.exec(s.publicIp,t);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")}}targetHost(){return this.host.host}ensureHostKey(e=this.host.host){return this.transport.ensureHostKey(e)}async preflight(e=this.host.host){let t=await this.transport.exec(e,mi,{sudo:!1}),r=fi(t);return{facts:r,findings:hi(r,{user:this.host.user,profile:this.settings.profile})}}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e;for(let y of np(t,this.settings))console.warn(`[ts-cloud] ${y}`);let n=this.host,s=p(t,r),i=await je(s,this.cwd),a=process.env[rp]==="1"&&i?.provider==="ssh"&&i.host===n.host&&i.bootstrapVersion===ke,c=await this.ensureHostKey(n.host);if(c.pinnedNow)console.warn(`[ts-cloud] pinned ${n.host} host key ${c.fingerprint}`);await this.waitForSshReady(n.host);let{facts:u,findings:m}=await this.preflight(n.host);if(Ai(m))throw Error(`Preflight failed for ${n.host}; refusing to bootstrap it.
|
|
379
|
-
${yi(m)}`);for(let y of m)console.warn(`[ts-cloud] ${y.severity}: ${y.message}`);if(u.cloudInitPresent&&/running/i.test(u.cloudInitStatus??""))await this.waitForCloudInit(n.host);let f=u.lanIp?.trim()||(
|
|
380
|
-
${s}`);if(/status:\s*(?:done|degraded)/.test(s))return}catch(s){if(s instanceof Error&&/cloud-init reported an error/.test(s.message))throw s}await this.sleep(t)}throw Error(`Timed out waiting for cloud-init to finish on ${e} after ${r}ms`)}}function F(e){if(qc())return new eo;switch(e.provider??be(e.config)){case"aws":return new Br({region:e.config.project.region});case"hetzner":return new Pe({apiToken:e.config.hetzner?.apiToken,allowStateOnly:Boolean(e.config.cloud?.attachTo),sshPrivateKeyPath:e.config.hetzner?.sshPrivateKeyPath,sshPublicKeyPath:e.config.hetzner?.sshPublicKeyPath,sshUser:e.config.hetzner?.sshUser,location:e.config.hetzner?.location});case"ssh":return new Fr({hosts:e.config.ssh?.hosts,hostKey:e.config.ssh?.hostKey,sudo:e.config.ssh?.sudo,profile:e.config.ssh?.profile,publicIp:e.config.ssh?.publicIp,lan:e.config.ssh?.lan});case"fly":throw Error("Fly.io has no box to provision or reach over SSH: deploy it with deployToFly() from @stacksjs/ts-cloud.");default:throw Error(`Unknown cloud provider: ${e.provider??be(e.config)}`)}}class ro{drivers=new Map;getDriver(e,t){let r=t??be(e),n=`${r}:${e.project.slug}:${e.project.region||"default"}`,s=this.drivers.get(n);if(s)return s;let i=F({config:e,provider:r});return this.drivers.set(n,i),i}}var ip=new ro;var sp="/var/lib/ts-cloud/bootstrap.sh",op={"raspberry-pi-os":"bootfs",ubuntu:"system-boot"},
|
|
381
|
-
`)||!/^(?:ssh|ecdsa|sk)-/.test(t))throw Error("publicKey must be one public key line, e.g. the contents of ~/.ssh/id_ed25519.pub.");if(e.wifi){if(!e.wifi.ssid)throw Error("wifi.ssid is required.");if(!e.wifi.passphrase)throw Error("wifi.passphrase is required.");if(!
|
|
379
|
+
${yi(m)}`);for(let y of m)console.warn(`[ts-cloud] ${y.severity}: ${y.message}`);if(u.cloudInitPresent&&/running/i.test(u.cloudInitStatus??""))await this.waitForCloudInit(n.host);let f=u.lanIp?.trim()||(ol(n.host)!==0?n.host:void 0),v=i?.provider==="ssh"?i.bootstrappedAt:void 0;if(!a){let y=gi({config:t,environment:r,profile:this.settings.profile,facts:u,sudoUser:n.user!=="root"?n.user:void 0,lan:this.settings.lan,lanIp:f});Pr(await this.exec(n.host,y)),v=new Date().toISOString()}let _={provider:"ssh",stackName:s,host:n.host,sshUser:n.user,sshPort:n.port,hostKeyFingerprint:c.fingerprint||void 0,publicIp:this.settings.publicIp==="auto"?void 0:this.settings.publicIp,lanIp:u.lanIp||void 0,deployStoragePath:Si,profile:this.settings.profile,bootstrapVersion:ke,bootstrappedAt:v};await ft(s,_,this.cwd);let S=await this.getComputeOutputs();if(j(t.infrastructure?.compute)&&ad(this.settings.lan)==="local-ca")S.lanCaCertPath=co(),console.warn(`[ts-cloud] LAN certificate authority on ${n.host} at ${S.lanCaCertPath}. Fetch it with: scp ${n.user}@${n.host}:${S.lanCaCertPath} ./rpx-root-ca.crt`);return S}async destroyCompute(e){let t=p(e.config,e.environment),r=this.host;return console.warn(`[ts-cloud] forgot ${r.host} for ${t}; nothing was removed on the host (stop the systemd units and remove /var/ts-cloud and /etc/rpx by hand if you want it clean).`),await ft(t,{provider:"ssh",stackName:t,host:r.host,sshUser:r.user,sshPort:r.port},this.cwd).catch(()=>{}),{destroyed:[`local state for ${t}`]}}async sleep(e){await new Promise((t)=>setTimeout(t,e))}async waitForSshReady(e){let{sshIntervalMs:t,sshTimeoutMs:r}=this.bootWait,n=Date.now();do{if(await this.transport.probe(e))return;await this.sleep(t)}while(Date.now()-n<r);throw Error(`Timed out waiting for SSH on ${e} after ${r}ms`)}async waitForCloudInit(e){let{cloudInitIntervalMs:t,cloudInitTimeoutMs:r}=this.bootWait,n=Date.now();while(Date.now()-n<r){try{let s=await this.transport.exec(e,"if command -v cloud-init >/dev/null 2>&1; then cloud-init status --long 2>/dev/null || true; else echo 'status: done'; fi",{sudo:!1});if(/status:\s*error/.test(s))throw Error(`cloud-init reported an error on ${e}:
|
|
380
|
+
${s}`);if(/status:\s*(?:done|degraded)/.test(s))return}catch(s){if(s instanceof Error&&/cloud-init reported an error/.test(s.message))throw s}await this.sleep(t)}throw Error(`Timed out waiting for cloud-init to finish on ${e} after ${r}ms`)}}function F(e){if(qc())return new eo;switch(e.provider??be(e.config)){case"aws":return new Br({region:e.config.project.region});case"hetzner":return new Pe({apiToken:e.config.hetzner?.apiToken,allowStateOnly:Boolean(e.config.cloud?.attachTo),sshPrivateKeyPath:e.config.hetzner?.sshPrivateKeyPath,sshPublicKeyPath:e.config.hetzner?.sshPublicKeyPath,sshUser:e.config.hetzner?.sshUser,location:e.config.hetzner?.location});case"ssh":return new Fr({hosts:e.config.ssh?.hosts,hostKey:e.config.ssh?.hostKey,sudo:e.config.ssh?.sudo,profile:e.config.ssh?.profile,publicIp:e.config.ssh?.publicIp,lan:e.config.ssh?.lan});case"fly":throw Error("Fly.io has no box to provision or reach over SSH: deploy it with deployToFly() from @stacksjs/ts-cloud.");default:throw Error(`Unknown cloud provider: ${e.provider??be(e.config)}`)}}class ro{drivers=new Map;getDriver(e,t){let r=t??be(e),n=`${r}:${e.project.slug}:${e.project.region||"default"}`,s=this.drivers.get(n);if(s)return s;let i=F({config:e,provider:r});return this.drivers.set(n,i),i}}var ip=new ro;var sp="/var/lib/ts-cloud/bootstrap.sh",op={"raspberry-pi-os":"bootfs",ubuntu:"system-boot"},cl=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,ll=/^[a-z_][a-z0-9_-]{0,31}$/,ul=/^[A-Z]{2}$/;function ye(e){return JSON.stringify(e)}function pl(e){if(!cl.test(e.hostname))throw Error(`Invalid hostname '${e.hostname}': use lowercase letters, digits and hyphens.`);if(!ll.test(e.user))throw Error(`Invalid user '${e.user}': use a lowercase Unix user name.`);let t=e.publicKey.trim();if(!t||t.includes(`
|
|
381
|
+
`)||!/^(?:ssh|ecdsa|sk)-/.test(t))throw Error("publicKey must be one public key line, e.g. the contents of ~/.ssh/id_ed25519.pub.");if(e.wifi){if(!e.wifi.ssid)throw Error("wifi.ssid is required.");if(!e.wifi.passphrase)throw Error("wifi.passphrase is required.");if(!ul.test(e.wifi.country))throw Error(`wifi.country must be a two-letter regulatory domain such as DE or US, not '${e.wifi.country}'.`)}}function dl(e,t){let r=[`hostname: ${ye(e.hostname)}`,"manage_etc_hosts: true","users:",` - name: ${ye(e.user)}`," ssh_authorized_keys:",` - ${ye(e.publicKey.trim())}`,` sudo: ${ye("ALL=(ALL) NOPASSWD:ALL")}`," shell: /bin/bash"," lock_passwd: true","ssh_pwauth: false"];if(e.timezone)r.push(`timezone: ${ye(e.timezone)}`);if(e.locale)r.push(`locale: ${ye(e.locale)}`);if(r.push("package_update: true"),t==="raspberry-pi-os")r.push("rpi:"," enable_ssh: true"," interfaces:"," spi: false"," i2c: false"," onewire: false"," remote_gpio: false"," serial:"," console: false"," hardware: false");return`${r.join(`
|
|
382
382
|
`)}
|
|
383
|
-
`}function
|
|
383
|
+
`}function ml(e){let t=["version: 2","ethernets:"," eth0:"," match:",` name: ${ye("e*")}`," dhcp4: true"," dhcp6: true"," optional: true"];if(e.wifi)t.push("wifis:"," wlan0:"," dhcp4: true"," dhcp6: true"," optional: true",` regulatory-domain: ${ye(e.wifi.country)}`," access-points:",` ${ye(e.wifi.ssid)}:`,` password: ${ye(e.wifi.passphrase)}`);return`${t.join(`
|
|
384
384
|
`)}
|
|
385
|
-
`}function
|
|
385
|
+
`}function fl(e){return[`instance-id: ${ye(`ts-cloud-${e.hostname}`)}`,`local-hostname: ${ye(e.hostname)}`].join(`
|
|
386
386
|
`)+`
|
|
387
|
-
`}function
|
|
388
|
-
`)}function Jc(e,t,r){
|
|
387
|
+
`}function gl(e,t){return[`Copy user-data, network-config and meta-data onto the boot partition of the flashed card (the volume named '${op[t]}'), replacing the files already there.`,"Eject the card, put it in the board and power it on.","The first boot takes a few minutes: cloud-init creates the user, waits for the clock to sync, then runs the ts-cloud bootstrap (packages, runtime, gateway).",`Then, from this machine: cloud ssh:preflight ${e.hostname}.local --user ${e.user}`,"When the preflight is clean, cloud deploy adopts the host and ships the sites."].join(`
|
|
388
|
+
`)}function Jc(e,t,r){pl(e);let n={scriptPath:sp,permissions:"0700",before:dl(e,r.os)};return{files:{"user-data":se(t,n),"network-config":ml(e),"meta-data":fl(e)},instructions:gl(e,r.os)}}function po(e){return e.infrastructure?.compute??{}}function ap(e){let t=po(e),r=t.monitoring;return{firewallPorts:[...new Set([22,80,443,...t.firewall?.allowedPorts??[]])].filter((s)=>Number.isInteger(s)&&s>=1&&s<=65535).sort((s,i)=>s-i),monitoring:r!==!1&&(typeof r!=="object"||r.enabled!==!1),autoUpdates:t.autoUpdates!==!1,swapGb:Math.max(0,Math.floor(t.swapGb??2)),sshPasswordAuthentication:!1,sshMaxStartups:"100:30:200",journalMaxUse:"256M",journalRetention:"14day"}}function hl(e){return["install -d -m 0755 /etc/ssh/sshd_config.d /etc/systemd/journald.conf.d /etc/sysctl.d /etc/fail2ban/jail.d","cat > /etc/ssh/sshd_config.d/99-ts-cloud-hardening.conf <<'TS_CLOUD_SSH_EOF'","# Managed by ts-cloud host optimization.","PasswordAuthentication no","KbdInteractiveAuthentication no","PermitRootLogin prohibit-password","MaxAuthTries 4","LoginGraceTime 30",`MaxStartups ${e.sshMaxStartups}`,"TS_CLOUD_SSH_EOF","sshd -t","systemctl reload ssh","cat > /etc/systemd/journald.conf.d/99-ts-cloud-retention.conf <<'TS_CLOUD_JOURNAL_EOF'","[Journal]",`SystemMaxUse=${e.journalMaxUse}`,`MaxRetentionSec=${e.journalRetention}`,"Compress=yes","TS_CLOUD_JOURNAL_EOF","systemctl restart systemd-journald","journalctl --vacuum-size=256M --vacuum-time=14d >/dev/null","cat > /etc/sysctl.d/99-ts-cloud-production.conf <<'TS_CLOUD_SYSCTL_EOF'","# Managed by ts-cloud host optimization.","vm.swappiness=10","vm.dirty_background_ratio=5","vm.dirty_ratio=15","net.core.somaxconn=4096","net.ipv4.tcp_max_syn_backlog=4096","net.ipv4.tcp_fin_timeout=30","net.ipv4.tcp_keepalive_time=300","net.ipv4.tcp_keepalive_intvl=30","net.ipv4.tcp_keepalive_probes=5","fs.inotify.max_user_watches=524288","TS_CLOUD_SYSCTL_EOF","sysctl --system >/dev/null","export DEBIAN_FRONTEND=noninteractive","command -v fail2ban-client >/dev/null 2>&1 || apt-get install -y fail2ban","cat > /etc/fail2ban/jail.d/99-ts-cloud-sshd.conf <<'TS_CLOUD_FAIL2BAN_EOF'","[sshd]","enabled = true","backend = systemd","bantime = 1h","findtime = 10m","maxretry = 5","TS_CLOUD_FAIL2BAN_EOF","systemctl enable --now fail2ban","systemctl restart fail2ban"]}function Sl(e){if(e===0)return[];return["if ! swapon --show=NAME --noheadings 2>/dev/null | grep -qx '/swapfile'; then",` if [ ! -f /swapfile ]; then fallocate -l ${e}G /swapfile || dd if=/dev/zero of=/swapfile bs=1M count=${e*1024} status=none; fi`," chmod 600 /swapfile"," mkswap /swapfile >/dev/null"," swapon /swapfile","fi","grep -qE '^/swapfile\\s' /etc/fstab || echo '/swapfile none swap sw 0 0' >> /etc/fstab"]}function cp(e){let t=po(e),r=ap(e),n=t.monitoring??!0,s=t.firewall??{enabled:!0};return["set -euo pipefail",...j(t)?["systemctl disable --now nginx.service bun-gateway.service ts-cloud-nginx.service 2>/dev/null || true","systemctl reset-failed nginx.service bun-gateway.service ts-cloud-nginx.service 2>/dev/null || true"]:[],...Sl(r.swapGb),...Ue(r.autoUpdates),...xe(n),...hl(r),...Qt(s),"systemctl daemon-reload","systemctl reset-failed"]}var _l=String.raw`
|
|
389
389
|
const text = (command) => {
|
|
390
390
|
const result = Bun.spawnSync(['bash', '-lc', command], { stdout: 'pipe', stderr: 'pipe' })
|
|
391
391
|
return result.stdout.toString().trim()
|
|
@@ -416,24 +416,24 @@ console.log(JSON.stringify({
|
|
|
416
416
|
failedUnits: lines("systemctl --failed --type=service --no-legend --plain | awk '{print $1}'"),
|
|
417
417
|
publicTcpPorts: [...new Set(publicTcpPorts)].sort((a, b) => a - b),
|
|
418
418
|
}))
|
|
419
|
-
`;function
|
|
420
|
-
`),n=`printf %s ${Buffer.from(r).toString("base64")} | base64 -d | bash`;await Se(t.host,n,t)}async function Mh(e){let t=await Se(e.host,_l
|
|
421
|
-
`,"utf8"),await
|
|
422
|
-
`,"utf8"),async()=>{await
|
|
419
|
+
`;function vl(e){return`printf %s ${Buffer.from(e).toString("base64")} | base64 -d | bun -`}async function $h(e,t){let r=cp(e).join(`
|
|
420
|
+
`),n=`printf %s ${Buffer.from(r).toString("base64")} | base64 -d | bash`;await Se(t.host,n,t)}async function Mh(e){let t=await Se(e.host,vl(_l),e);return JSON.parse(t)}function Fh(e,t){let r=[],n=new Set(t.firewallPorts),s=e.firewallPorts.filter((a)=>!n.has(a)),i=t.firewallPorts.filter((a)=>!e.firewallPorts.includes(a));if(!t.firewallActive)r.push("UFW is not active");if(s.length>0)r.push(`UFW is missing ports: ${s.join(", ")}`);if(i.length>0)r.push(`UFW has unexpected ports: ${i.join(", ")}`);if(t.passwordAuthentication)r.push("SSH password authentication remains enabled");if(t.rootPasswordLogin)r.push("SSH root password login remains enabled");if(!t.fail2banActive)r.push("fail2ban is not active");if(e.autoUpdates&&!t.unattendedUpgradesActive)r.push("unattended upgrades are not active");if(e.monitoring&&!t.metricsTimerActive)r.push("metrics timer is not active");if(e.monitoring&&!t.metricsSnapshotFresh)r.push("metrics snapshot is stale");if(e.swapGb>0&&t.swapBytes<e.swapGb*1073741824*0.9)r.push("configured swap is missing");if(t.failedUnits.length>0)r.push(`failed services: ${t.failedUnits.join(", ")}`);return r}import{mkdir as vr,readFile as yl,rename as mo,rmdir as $l,stat as bl,unlink as Tl,writeFile as fo}from"node:fs/promises";import{join as yr}from"node:path";function Xc(e){return yr(mt(),`${e}-resize.json`)}function dp(e){return yr(mt(),`${e}-resize.lock`)}async function Uh(e){try{return JSON.parse(await yl(Xc(e),"utf8"))}catch{return null}}async function Qh(e){let t=Xc(e.stackName);await vr(mt(),{recursive:!0});let r=`${t}.${process.pid}.tmp`;await fo(r,`${JSON.stringify(e,null,2)}
|
|
421
|
+
`,"utf8"),await mo(r,t)}async function Hh(e,t=1800000){let r=dp(e);await vr(mt(),{recursive:!0});try{await vr(r)}catch(n){if(Date.now()-(await bl(r)).mtimeMs<=t)throw Error(`Another resize process holds ${r}.`);await mo(r,`${r}.stale-${Date.now()}`),await vr(r)}return await fo(yr(r,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
|
|
422
|
+
`,"utf8"),async()=>{await Tl(yr(r,"owner.json")).catch(()=>{}),await $l(r).catch(()=>{})}}async function Ii(e,t){let r=Ve(t.publicKey),n=(await e.listSshKeys()).find((i)=>Ve(i.public_key)===r);if(n)return{id:n.id,name:n.name,created:!1};let s=await e.createSshKey({name:t.name,publicKey:t.publicKey.trim(),labels:t.labels});return{id:s.id,name:s.name,created:!0}}async function bi(e,t){let r=(await e.listFirewalls()).find((s)=>s.name===t.name);if(r)return await e.setFirewallRules(r.id,t.rules),{id:r.id,name:r.name,created:!1};let{firewall:n}=await e.createFirewall({name:t.name,rules:t.rules,labels:t.labels});return{id:n.id,name:n.name,created:!0}}async function Ci(e,t){let{waitForRunning:r=!0,...n}=t,s=(await e.listServers()).find((a)=>a.name===t.name),i=!s;if(!s)s=(await e.createServer(n)).server;if(r)s=await e.waitForServerRunning(s.id);return{server:s,created:i}}function Ei(e){let t=e.public_net.ipv4?.ip;if(!t)throw Error(`Hetzner server "${e.name}" (#${e.id}) has no public IPv4`);return t}var Yc="/aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id";function Zc(e){let t=e.sshPublicKey.trim(),r=["#cloud-config","disable_root: false","ssh_authorized_keys:",` - ${t}`];if(e.bootstrapScript){let s=e.bootstrapScript.split(`
|
|
423
423
|
`).map((i)=>` ${i}`).join(`
|
|
424
424
|
`);r.push("write_files:"," - path: /var/lib/cloud/box-bootstrap.sh"," permissions: '0755'"," owner: root:root"," content: |",s)}if(r.push("runcmd:",` - mkdir -p /root/.ssh && grep -qF "${t}" /root/.ssh/authorized_keys 2>/dev/null || echo "${t}" >> /root/.ssh/authorized_keys`),e.bootstrapScript)r.push(" - [ bash, /var/lib/cloud/box-bootstrap.sh ]");return`${r.join(`
|
|
425
425
|
`)}
|
|
426
|
-
`}function
|
|
427
|
-
`)}var rd="dashboard";function no(){return Q("dashboard-credentials.json")}function
|
|
428
|
-
`),
|
|
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
|
|
430
|
-
`),
|
|
426
|
+
`}function wl(e=[]){let t=[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"],description:"SSH"}];for(let r of e)t.push({direction:"in",protocol:r.protocol,...r.protocol==="icmp"?{}:{port:String(r.port)},source_ips:["0.0.0.0/0","::/0"]});return t}class ed{client;provider="hetzner";constructor(e){this.client=e}async ensureBox(e){let t=await Ii(this.client,{name:`${e.name}-key`,publicKey:e.sshPublicKey}),r=await bi(this.client,{name:`${e.name}-fw`,rules:wl(e.ports)}),{server:n,created:s}=await Ci(this.client,{name:e.name,serverType:e.size,image:e.image??"ubuntu-24.04",location:e.location,sshKeys:[t.id],firewalls:[{firewall:r.id}],userData:Zc(e),labels:e.labels});return{provider:"hetzner",id:String(n.id),name:n.name,publicIp:Ei(n),created:s}}async destroyBox(e){let t=[],r=(await this.client.listServers()).find((s)=>s.name===e);if(r){let s=await this.client.deleteServer(r.id);await this.client.waitForAction(s.id).catch(()=>{}),t.push(`server ${e} (#${r.id})`)}let n=(await this.client.listFirewalls()).find((s)=>s.name===`${e}-fw`);if(n)for(let s=0;s<10;s++)try{await this.client.deleteFirewall(n.id),t.push(`firewall ${e}-fw (#${n.id})`);break}catch{if(s===9)break;await new Promise((i)=>setTimeout(i,3000))}return{destroyed:t}}}function Cl(e=[]){let t=[{IpProtocol:"tcp",FromPort:22,ToPort:22,IpRanges:[{CidrIp:"0.0.0.0/0",Description:"SSH"}]}];for(let r of e)t.push(r.protocol==="icmp"?{IpProtocol:"icmp",FromPort:-1,ToPort:-1,IpRanges:[{CidrIp:"0.0.0.0/0"}]}:{IpProtocol:r.protocol,FromPort:r.port,ToPort:r.port,IpRanges:[{CidrIp:"0.0.0.0/0"}]});return t}class td{provider="aws";ec2;ssm;constructor(e){this.ec2=e.ec2,this.ssm=e.ssm}async findInstance(e,t){return(await this.ec2.describeInstances({Filters:[{Name:"tag:Name",Values:[e]},{Name:"instance-state-name",Values:t}]})).Reservations?.flatMap((n)=>n.Instances??[])[0]}async waitForPublicIp(e,t=300000){let r=Date.now();while(Date.now()-r<t){let n=await this.ec2.getInstance(e);if(n?.State?.Name==="running"&&n.PublicIpAddress)return n;await new Promise((s)=>setTimeout(s,5000))}throw Error(`EC2 instance ${e} did not reach running with a public IP within ${t}ms`)}async ensureSecurityGroup(e){let t=`${e.name}-sg`,n=(await this.ec2.describeSecurityGroups({Filters:[{Name:"group-name",Values:[t]}]})).SecurityGroups?.[0]?.GroupId;if(n)return n;let s=await this.ec2.createSecurityGroup({GroupName:t,Description:`box ${e.name} (managed by ts-cloud box-provision)`});if(!s.GroupId)throw Error(`could not create security group ${t}`);return await this.ec2.authorizeSecurityGroupIngress({GroupId:s.GroupId,IpPermissions:Cl(e.ports)}),s.GroupId}async resolveImage(e){if(e.image?.startsWith("ami-"))return e.image;let r=(await this.ssm.getParameter({Name:Yc})).Parameter?.Value;if(!r)throw Error(`could not resolve the Ubuntu 24.04 AMI via SSM (${Yc})`);return r}async ensureBox(e){let t=await this.findInstance(e.name,["pending","running"]);if(t?.InstanceId){let u=await this.waitForPublicIp(t.InstanceId);return{provider:"aws",id:u.InstanceId,name:e.name,publicIp:u.PublicIpAddress,created:!1}}let[r,n]=await Promise.all([this.ensureSecurityGroup(e),this.resolveImage(e)]),s=[{Key:"Name",Value:e.name},...Object.entries(e.labels??{}).map(([u,m])=>({Key:u,Value:m}))],a=(await this.ec2.runInstances({ImageId:n,InstanceType:e.size,MinCount:1,MaxCount:1,SecurityGroupIds:[r],UserData:Buffer.from(Zc(e),"utf8").toString("base64"),TagSpecifications:[{ResourceType:"instance",Tags:s}]})).Instances?.[0]?.InstanceId;if(!a)throw Error(`RunInstances returned no instance for box ${e.name}`);let c=await this.waitForPublicIp(a);return{provider:"aws",id:a,name:e.name,publicIp:c.PublicIpAddress,created:!0}}async destroyBox(e){let t=[],r=await this.findInstance(e,["pending","running","stopping","stopped"]);if(r?.InstanceId){await this.ec2.terminateInstances([r.InstanceId]),t.push(`instance ${e} (${r.InstanceId})`);let i=Date.now();while(Date.now()-i<300000){let a=await this.ec2.getInstance(r.InstanceId);if(!a||a.State?.Name==="terminated")break;await new Promise((c)=>setTimeout(c,5000))}}let s=(await this.ec2.describeSecurityGroups({Filters:[{Name:"group-name",Values:[`${e}-sg`]}]})).SecurityGroups?.[0]?.GroupId;if(s)for(let i=0;i<10;i++)try{await this.ec2.deleteSecurityGroup(s),t.push(`security group ${e}-sg (${s})`);break}catch{if(i===9)break;await new Promise((a)=>setTimeout(a,3000))}return{destroyed:t}}}function Gh(e){if(e.provider==="hetzner"){if(!e.hetzner)throw Error('createBoxProvisioner: options.hetzner (a HetznerClient) is required for provider "hetzner"');return new ed(e.hetzner)}if(!e.aws)throw Error('createBoxProvisioner: options.aws ({ ec2, ssm }) is required for provider "aws"');return new td(e.aws)}import{copyFileSync as au}from"node:fs";import{tmpdir as cu}from"node:os";import{join as lu}from"node:path";var Pl=`${ae}/project`;function go(e,t){let r=t.ownerSlug.trim(),n=t.selfSlug?.trim(),s={total:e.length,owner:[],self:[],others:new Map,unmanaged:[]};for(let i of e){let a=i.labels?.[Pl]?.trim();if(!a){s.unmanaged.push(i.name);continue}if(a===r){s.owner.push(i.name);continue}if(n&&a===n){s.self.push(i.name);continue}let c=s.others.get(a);if(c)c.push(i.name);else s.others.set(a,[i.name])}return s}function Pn(e){let t=e.unmanaged.length;for(let r of e.others.values())t+=r.length;return t}function ho(e,t){let r=Pn(e),n=[];if(n.push(`Attaching to '${t.ownerSlug}' shares one provider project, so this deploy's credential can write to all ${e.total} server(s) it can see.`),r===0)return n.push("Nothing outside the two projects being joined is reachable with it."),n;n.push(`${r} of them belong to neither project:`);for(let s of[...e.others.keys()].sort())n.push(` ${s}: ${[...e.others.get(s)].sort().join(", ")}`);if(e.unmanaged.length>0)n.push(` not managed by ts-cloud: ${[...e.unmanaged].sort().join(", ")}`);return n.push("A compromised CI run or a mistargeted teardown in this project now reaches those. Keep the app in its own provider project instead if that is not acceptable, which rules out attaching."),n}import{execSync as _o}from"node:child_process";import{randomBytes as Rl}from"node:crypto";import{chmodSync as Ol,copyFileSync as Dl,existsSync as rt,mkdirSync as vo,readFileSync as yo,statSync as xl,writeFileSync as Rn}from"node:fs";import{tmpdir as Il}from"node:os";import{basename as Al,dirname as Dn,isAbsolute as $o,join as de,resolve as Ll}from"node:path";import{fileURLToPath as bo}from"node:url";function En(e){if(!e||typeof e!=="object")return e;return Object.fromEntries(Object.keys(e).map((t)=>[t,""]))}function El(e){let t=JSON.parse(JSON.stringify(e??{}));if(t.hetzner)delete t.hetzner.apiToken;delete t.aws,delete t.stateDir;for(let r of Object.values(t.sites??{})){if(r?.env)r.env=En(r.env);if(r?.environment)r.environment=En(r.environment)}for(let r of Object.values(t.environments??{}))if(r?.variables)r.variables=En(r.variables);for(let r of Object.values(t.infrastructure?.databases??{}))if(r?.password)r.password="";if(t.infrastructure?.appDatabase?.password)t.infrastructure.appDatabase.password="";if(t.infrastructure?.compute?.database?.password)t.infrastructure.compute.database.password="";if(t.infrastructure?.compute?.managedServices?.vitess?.password)t.infrastructure.compute.managedServices.vitess.password="";return t}function So(e){let t=El(e);return["// Generated by ts-cloud for the management dashboard — do not edit.","//","// This is the project's resolved cloud config, inlined so it needs no","// imports on the box. Credentials are deliberately absent.",`export default ${JSON.stringify(t,null,2)}`,""].join(`
|
|
427
|
+
`)}var rd="dashboard";function no(){return Q("dashboard-credentials.json")}function Ul(){return Rl(24).toString("base64url")}function nd(e,t,r){let n=process.env.TS_CLOUD_UI_PASSWORD?.trim();if(n)return{password:n,source:"env"};if(On(process.env.TS_CLOUD_UI_PUBLIC))return{password:void 0,source:"public"};let s=no(),i=l(e,"dashboard-credentials.json");try{if(rt(i)){let c=JSON.parse(yo(i,"utf8"));if(c?.password)return{password:c.password,source:"generated"}}}catch{}let a=Ul();try{vo(Dn(i),{recursive:!0}),Rn(i,`${JSON.stringify({username:t,password:a,generatedAt:new Date().toISOString()},null,2)}
|
|
428
|
+
`),Ol(i,384),r.info(`Management dashboard: generated a password for '${t}' and saved it to ${s} (read it there — it is not printed). Set TS_CLOUD_UI_PASSWORD to pin your own, or TS_CLOUD_UI_PUBLIC=1 to serve without auth.`)}catch(c){r.warn(`Management dashboard: could not persist the generated password (${c?.message??c}). Using it for this deploy only — pass: ${a}
|
|
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 To={info:()=>{},warn:()=>{}};function On(e){return e!=null&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function Hl(){return Q("dashboard-release")}function wo(){let e=Dn(bo(import.meta.url));for(let t of[de(e,"..","..","package.json"),de(e,"..","package.json")])try{let r=JSON.parse(yo(t,"utf8"));if(r.name==="@stacksjs/ts-cloud"&&r.version)return`^${r.version}`}catch{}return"latest"}function kl(){return process.env.TS_CLOUD_UI_VERSION?.trim()||wo()}function Nl(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{vo(n,{recursive:!0}),Rn(de(n,"cloud.config.ts"),So(e));let s=kl();if(s.startsWith("file:")){let a=s.slice(5),c=$o(a)?a:Ll(t,a);if(!rt(c)||!xl(c).isFile())s=wo(),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=Al(c),m=de(n,u);if(c!==m)Dl(c,m);s=`file:./${u}`}}let i={name:"ts-cloud-dashboard",private:!0,type:"module",dependencies:{"@stacksjs/ts-cloud":s}};return Rn(de(n,"package.json"),`${JSON.stringify(i,null,2)}
|
|
430
|
+
`),Hl()}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=Dn(bo(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??To,n=t.cwd??process.cwd();if(On(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(!On(process.env.TS_CLOUD_UI_STATIC)){let S=Nl(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 xn(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??To;try{if(typeof e.build==="string"&&e.build.trim())n.info(`Management dashboard: building UI (${e.build})`),_o(e.build,{cwd:r,stdio:"inherit"});let s=$o(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(Il(),`${t.slug}-${t.siteName??rd}-${t.sha}.tar.gz`);return _o(`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 Ml=new Set(["laravel","php","statamic","wordpress"]);function Ur(e){if(e.framework)return e.framework;if(e.type&&Ml.has(e.type))return"laravel";return"stacks"}var Co=`eval "$(cd ${T} && pantry env 2>/dev/null)"`,Po="/usr/local/bin/bun",Fl="node_modules/@stacksjs/ts-cloud/dist/bin/stacks-scheduler.js",zl="node_modules/@stacksjs/ts-cloud/dist/bin/stacks-queue-worker.js",Eo={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:()=>`${Po} ${Fl}`,queueWorkerCommand:(e,{current:t})=>{let r=[`--queue=${e.queue||"default"}`,`--sleep=${e.sleep??3}`,`--tries=${e.tries??3}`,`--timeout=${e.timeout??60}`];return`${Po} ${t}/${zl} ${r.join(" ")}`}},Bl={id:"laravel",wrapExec:(e)=>`/bin/sh -lc '${Co}; exec ${e}'`,schedulerMode:"cron",schedulerCommand:({current:e})=>`cd ${e} && ${Co} && 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(" ")}`}},Kl={stacks:Eo,laravel:Bl};function Ro(e){return Kl[e]??Eo}function Oo(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function jl(e){return`'${e.split("'").join("'\\''")}'`}function Do(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"unnamed"}function Vl(e,t,r){return`${e}-${t}-queue-${r}`}function Gl(e,t,r,n){return`${e}-${t}-daemon-${r.name?Do(r.name):Do(r.command).slice(0,32)||String(n)}`}function In(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
|
|
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
|
|
434
|
-
`);return[`cat > ${t} <<'TS_CLOUD_DNSCREDS_EOF'`,r,"TS_CLOUD_DNSCREDS_EOF",`chmod 600 ${t}`]}function
|
|
435
|
-
`)){let s=n.indexOf(
|
|
436
|
-
`)}function
|
|
432
|
+
`}function An(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_UNIT_EOF'`,t.replace(/\n$/,""),"TS_CLOUD_UNIT_EOF"]}function ql(e,t){return`/etc/cron.d/${e}-${t}-scheduler`}function Ln(e){let{slug:t,siteName:r,site:n}=e,i=`${e.appBase??`/var/www/${r}`}/current`,a=Ro(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=Vl(t,r,m.length);m.push(W),u.push(...An(W,In({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=`${Gl(t,r,x,H)}-${I}`;m.push(W),u.push(...An(W,In({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(...An(y,In({description:`${r} scheduler (managed by ts-cloud)`,workingDir:i,execStart:a.wrapExec(a.schedulerCommand(c)),environment:a.execEnv,memoryHigh:x.memoryHigh,memoryMax:x.memoryMax})),...ar(`${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 '^${Oo(t)}-${Oo(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=ql(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}${jl(x.heartbeatUrl)} >/dev/null 2>&1`}let O=`* * * * * root ${H}
|
|
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 Un(e){return!!(e.queues?.length||e.daemons?.length||e.scheduler)}function Hn(e){if(e.ssl?.provider)return e.ssl.provider;return e.domain?"letsencrypt":"none"}var xo={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 Io(e){return`/etc/letsencrypt/ts-cloud-${e}.ini`}function Wl(e){let t=e?xo[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 Yl(e){if(!e.credentials||Object.keys(e.credentials).length===0)return[];let t=Io(e.provider),r=Object.entries(e.credentials).map(([n,s])=>`${n} = ${s}`).join(`
|
|
434
|
+
`);return[`cat > ${t} <<'TS_CLOUD_DNSCREDS_EOF'`,r,"TS_CLOUD_DNSCREDS_EOF",`chmod 600 ${t}`]}function Xl(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=xo[t.provider].plugin;if(n.push(`--${s}`),t.provider!=="route53"&&t.credentials)n.push(`--${s}-credentials ${Io(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 kn(e){if(Hn(e)!=="letsencrypt"||!e.domain)return[];let t=e.ssl,r=t?.dns,n=t?.wildcard===!0;if(n&&!r)return[];return[...Wl(r),...r?Yl(r):[],...Xl({domain:e.domain,aliases:e.aliases,email:t?.email,wildcard:n,dns:r})]}function Ao(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 br="$CREATE_RELEASE",Tr="$ACTIVATE_RELEASE",Ho="$RESTART_QUEUES",Lo="composer install --no-interaction --prefer-dist --optimize-autoloader --no-dev",Jl=["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 Ql(e){switch(e){case"laravel":case"statamic":return[br,Lo,...Jl,Tr,Ho];case"php":case"wordpress":return[br,`${Lo} || true`,Tr];case"static":case"spa":return[br,Tr]}}function Zl(e,t){return e.replace(/^php\s+/,`${t} `).replace(/(\s)php\s+artisan\s+/g,`$1${t} artisan `)}function eu(e,t){let r=tr(t);return[`cat > ${e} <<'TS_CLOUD_ENV_EOF'`,r,"TS_CLOUD_ENV_EOF",`chmod 600 ${e}`]}function Uo(e,t,r){return[`cat > ${e} <<'${r}'`,t.replace(/\n$/,""),r,`chmod 600 ${e}`]}function tu(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(...Uo(`${e}/auth.json`,n,"TS_CLOUD_AUTHJSON_EOF"))}if(t.npmrc)r.push(...Uo(`${e}/.npmrc`,t.npmrc,"TS_CLOUD_NPMRC_EOF"));return r}function ko(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 No(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??rr,m=[...u,...ir(r.env,u)],f=r.keepReleases??Pt,v=r.deployScript?.length?r.deployScript:Ql(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(...or(i,{releaseId:n,commit:s,branch:r.repository.branch,keepLogs:f})),_.push(...Et(c,m)),r.env&&Object.keys(r.env).length>0)_.push(...eu(`${c.shared}/.env`,r.env));for(let S of v){let y=S.trim();if(y===br)_.push(...Ao({repository:r.repository,releaseDir:c.release,commit:s})),_.push(...sr(c,m)),_.push(`cd ${c.release}`),_.push(...tu(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===Tr)_.push(...ct(c)),_.push(...lt(c,f)),_.push(`(cd ${T} && pantry restart php-fpm) 2>/dev/null || true`);else if(y===Ho)_.push(`${a} artisan queue:restart || true`);else _.push(Zl(S,a))}return _}var wr={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"]}},kt="ts-cloud-service:";function ru(e){return e===!0||typeof e==="object"&&e!=null}function Mo(e){if(!e)return[];return Object.keys(wr).filter((t)=>ru(e[t]))}function Fo(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 "${kt}$TS_CLOUD_SVC:present"; return 0; fi`," done",` if ts_cloud_port_open "$TS_CLOUD_PORT"; then echo "${kt}$TS_CLOUD_SVC:present"; return 0; fi`,` echo "${kt}$TS_CLOUD_SVC:missing"`," return 0","}",...e.filter((t)=>wr[t]).map((t)=>`ts_cloud_probe ${t} ${wr[t].port} ${wr[t].binaries.join(" ")}`),"exit 0"]}function zo(e,t){if(!e)return[];let r=new Map;for(let n of e.split(`
|
|
435
|
+
`)){let s=n.indexOf(kt);if(s===-1)continue;let[i,a]=n.slice(s+kt.length).trim().split(":");if(i)r.set(i,a)}return t.filter((n)=>r.get(n)==="missing")}function Bo(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 Ko="/var/lib/pantry/php-fpm/pool.d",nu=9100,su=400;function Cr(e){return(e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"site").slice(0,28)}function jo(e){return`web_${Cr(e)}`}function ou(e){let t=Cr(e),r=0;for(let n=0;n<t.length;n++)r=r*31+t.charCodeAt(n)>>>0;return nu+r%su}function Nn(e){return`127.0.0.1:${ou(e)}`}function iu(e){let t=Cr(e.siteName),r=jo(e.siteName),n=e.maxChildren??10;return[`; ts-cloud-managed pool for ${e.siteName} (site isolation)`,`[${t}]`,`user = ${r}`,`group = ${r}`,`listen = ${Nn(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 Vo(e){let t=jo(e.siteName),r=Cr(e.siteName),n=`${Ko}/${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 ${Ko}`,`cat > ${n} <<'TS_CLOUD_FPMPOOL_EOF'`,iu(e).replace(/\n$/,""),"TS_CLOUD_FPMPOOL_EOF",`(cd ${T} && pantry restart php-fpm) 2>/dev/null || true`]}var Rr={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};function uu(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function so(e,t,r=Rr){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?Ms(S.servicesPrivateIp,g(n)):rs(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=fn(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=No({siteName:i,site:N,releaseId:u,appBase:q,defaultPhpVersion:R}),X=!j(x),E=Hn(a)==="custom"&&a.ssl?.certPath&&a.ssl?.keyPath?{certPath:a.ssl.certPath,keyPath:a.ssl.keyPath}:void 0,L=a.isolation?Vo({siteName:i,appBase:q}):[],ie=X?Zr({siteName:i,domain:a.domain||i,aliases:a.aliases,type:a.type,appDir:`${q}/current`,webDirectory:a.webDirectory,phpVersion:R,fastcgiPass:a.isolation?Nn(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:Jr(a.nginx,x?.nginxTemplates),clientMaxBodySize:a.nginx?.clientMaxBodySize,hsts:a.ssl?.hsts,tlsProtocols:a.ssl?.tlsProtocols,security:a.security}):[],re=X?kn(a):[],Le=Un(a)?Ln({slug:c,siteName:i,site:a,phpVersion:R,appBase:q}):[],Nt=X?ko(a):[];r.step(`Deploying PHP site '${i}' to ${y.length} target(s)...`);let Ke=await e.runRemoteDeploy({targets:y,commands:[...mn(q,c),...xr(q,c),...Y,...L,...ie,...re,...Le,...Nt,...H],comment:`ts-cloud deploy ${c}/${i}@${u}`,tags:{Project:c,Environment:s,Role:"app"}}),Fn=as(n.notifications,a.notifications);if(!Ke.success)return await Go(e,y,H,r),await tn(Fn,"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 Yo=a.domain?` → https://${a.domain}`:"";return await tn(Fn,"deploy",`✅ Deployed ${c}/${i}@${u}${Yo}`),{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?Zr({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:Jr(a.nginx,x?.nginxTemplates),clientMaxBodySize:a.nginx?.clientMaxBodySize,hsts:a.ssl?.hsts,tlsProtocols:a.ssl?.tlsProtocols,security:a.security}):[],ge=ne?kn(a):[],P=Un(a)?Ln({slug:c,siteName:i,site:a,appBase:Z}):[],D=[...or(Z,{releaseId:u,commit:u,branch:a.repository?.branch??"main"}),...mn(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 Go(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 Go(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 Er(e){return`'${e.replaceAll("'","'\\''")}'`}function pu(e,t,r=!1,n=[]){let s=`${e}-dashboard-`,i=t.map((c)=>`${e}-${c}.service`),a=r?[`export TS_CLOUD_DASHBOARD_KEEP_DOMAINS=${Er(JSON.stringify(n))}`,"rm -f /run/ts-cloud-dashboard-routes-changed",`/usr/local/bin/bun --bun -e ${Er(`
|
|
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=${Er(s)}`,`TS_CLOUD_DASHBOARD_SERVER_OWNER=${r?"1":"0"}`,`TS_CLOUD_DASHBOARD_DESIRED=${Er(` ${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 du(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:pu(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 mu(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=go(i,{ownerSlug:s,selfSlug:n.project.slug}),c=Pn(a)>0;for(let u of ho(a,{ownerSlug:s,selfSlug:n.project.slug}))if(c)r.warn(u);else r.info(u)}async function fu(e,t,r){let{config:n,environment:s}=t,i=n.cloud?.attachTo;if(!i)return!0;let a=Mo(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:Fo(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 zo(_.output,a))v.add(S);if(v.size===0)return!0;return r.error(Bo([...v],i,m[0]?.publicIp)),!1}async function gu(e,t,r){let{config:n,environment:s}=t;if(!n.cloud?.attachTo)return!0;let i=n.infrastructure?.compute,a=g(n),c=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=Rr}=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?[]:xn(t);if(f&&e.rpxConfig&&e.rpxConfig!==t&&!cr(e.rpxConfig))vi(e.rpxConfig,{cwd:m,logger:{info:()=>{},warn:()=>{}}});if(f&&!await du(n,e,xn(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=lu(cu(),`${u}-${O}-${s}.tar.gz`);au(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 mu(n,e,c),!await fu(n,e,c))return!1;if(!await gu(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 hu(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=Rr}=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 hu(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=Rr}=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 ${uu(`${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",Mn="origin",qo="origin-failover";function Wo(e,t){let r={TargetOriginId:Mn,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(Mn,e.originDomain,e.originShield?{Enabled:!0,OriginShieldRegion:e.originShieldRegion}:{Enabled:!1},a)],m={Quantity:0},f=Wo(null,"static");if(r!==void 0)u.push(c(qo,r,{Enabled:!1})),m=cn({primaryOriginId:Mn,secondaryOriginId:qo,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((_)=>Wo(_.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};
|