@stacksjs/ts-cloud 0.16.1 → 0.16.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/dist/aws/index.js +1 -1
  2. package/dist/bin/{chunk-ghbd1dcz.js → chunk-35p4sfb5.js} +1 -1
  3. package/dist/bin/{chunk-fae1s9p5.js → chunk-8595qcv0.js} +1 -1
  4. package/dist/bin/{chunk-8qmc6yvq.js → chunk-fqajjdy7.js} +23 -23
  5. package/dist/bin/cli.js +4 -4
  6. package/dist/bin/dashboard-server.js +1 -1
  7. package/dist/{chunk-azcvwr5m.js → chunk-11s59686.js} +2 -2
  8. package/dist/{chunk-etmbw4er.js → chunk-aszeyg2w.js} +2 -2
  9. package/dist/{chunk-xacvkpf8.js → chunk-bvspqd2m.js} +1 -1
  10. package/dist/{chunk-b9pm7mbd.js → chunk-c3pvfcme.js} +13 -13
  11. package/dist/{chunk-f9pzjzye.js → chunk-f0t7y458.js} +2 -2
  12. package/dist/{chunk-tg6yasej.js → chunk-f27a8et2.js} +1 -1
  13. package/dist/{chunk-dky93h4d.js → chunk-fgww8ya2.js} +1 -1
  14. package/dist/chunk-gk5ehe62.js +1 -0
  15. package/dist/{chunk-bkv2p4hp.js → chunk-hhy358y8.js} +2 -2
  16. package/dist/{chunk-jnt7ab86.js → chunk-nnfdz28e.js} +2 -2
  17. package/dist/{chunk-d51q92t7.js → chunk-qzbmm0f6.js} +42 -42
  18. package/dist/{chunk-cwjskpj4.js → chunk-r5pjnw74.js} +2 -2
  19. package/dist/{chunk-epqpf6jd.js → chunk-scy8mzqk.js} +1 -1
  20. package/dist/{chunk-dp93dqcr.js → chunk-ttgff76x.js} +38 -38
  21. package/dist/{chunk-a0d0h33y.js → chunk-yqfkq6q7.js} +1 -1
  22. package/dist/deploy/index.js +1 -1
  23. package/dist/dns/index.js +1 -1
  24. package/dist/drivers/index.js +1 -1
  25. package/dist/index.js +26 -26
  26. package/dist/operations/index.js +1 -1
  27. package/dist/protection/index.js +1 -1
  28. package/dist/spend/index.js +1 -1
  29. package/dist/ui/404.html +1 -1
  30. package/dist/ui/accept-invitation.html +1 -1
  31. package/dist/ui/access-denied.html +1 -1
  32. package/dist/ui/account/automation.html +5 -5
  33. package/dist/ui/account/security.html +2 -2
  34. package/dist/ui/applications/compose.html +6 -6
  35. package/dist/ui/applications/new.html +2 -2
  36. package/dist/ui/data/backups.html +6 -6
  37. package/dist/ui/data/services.html +5 -5
  38. package/dist/ui/data/volumes.html +5 -5
  39. package/dist/ui/index.html +6 -6
  40. package/dist/ui/infrastructure/topology.html +6 -6
  41. package/dist/ui/integrations.html +1 -1
  42. package/dist/ui/operations/alerts.html +5 -5
  43. package/dist/ui/operations/configuration.html +5 -5
  44. package/dist/ui/operations/jobs.html +5 -5
  45. package/dist/ui/operations/maintenance.html +5 -5
  46. package/dist/ui/operations/observability.html +6 -6
  47. package/dist/ui/operations/previews.html +6 -6
  48. package/dist/ui/operations/queue.html +5 -5
  49. package/dist/ui/operations/regions.html +5 -5
  50. package/dist/ui/operations/releases.html +6 -6
  51. package/dist/ui/operations/spend.html +6 -6
  52. package/dist/ui/operations/workloads.html +5 -5
  53. package/dist/ui/security.html +2 -2
  54. package/dist/ui/server/actions.html +6 -6
  55. package/dist/ui/server/activity.html +2 -2
  56. package/dist/ui/server/capacity.html +6 -6
  57. package/dist/ui/server/database.html +6 -6
  58. package/dist/ui/server/deployments.html +6 -6
  59. package/dist/ui/server/diagnostics.html +2 -2
  60. package/dist/ui/server/firewall.html +5 -5
  61. package/dist/ui/server/fleet.html +6 -6
  62. package/dist/ui/server/logs.html +6 -6
  63. package/dist/ui/server/metrics.html +6 -6
  64. package/dist/ui/server/security.html +2 -2
  65. package/dist/ui/server/services.html +1 -1
  66. package/dist/ui/server/sites.html +5 -5
  67. package/dist/ui/server/ssh-keys.html +6 -6
  68. package/dist/ui/server/team.html +6 -6
  69. package/dist/ui/server/terminal.html +2 -2
  70. package/dist/ui/serverless/alarms.html +6 -6
  71. package/dist/ui/serverless/assets.html +2 -2
  72. package/dist/ui/serverless/cost.html +2 -2
  73. package/dist/ui/serverless/data.html +6 -6
  74. package/dist/ui/serverless/deployments.html +2 -2
  75. package/dist/ui/serverless/firewall.html +2 -2
  76. package/dist/ui/serverless/functions.html +6 -6
  77. package/dist/ui/serverless/logs.html +6 -6
  78. package/dist/ui/serverless/metrics.html +2 -2
  79. package/dist/ui/serverless/queues.html +6 -6
  80. package/dist/ui/serverless/secrets.html +6 -6
  81. package/dist/ui/serverless/traces.html +6 -6
  82. package/dist/ui/serverless.html +6 -6
  83. package/package.json +3 -3
  84. package/dist/chunk-h1anhx3y.js +0 -1
@@ -12,7 +12,7 @@ EOF`,`DISK_PCT=$(df -P / | awk 'NR==2{gsub("%","",$5); print $5}')`,"UPTIME_SEC=
12
12
  `)}
13
13
  `}return`${["server {"," listen 80;"," listen [::]:80;",` server_name ${r};`,...s,"}"].join(`
14
14
  `)}
15
- `}function Xt(e){let t=`/etc/nginx/sites-available/${e.siteName}`,r=`/etc/nginx/sites-enabled/${e.siteName}`,s=Oo(e),n=[...qt()];if(e.auth){let i=Hs(e.siteName),o=(l)=>l.split("'").join("'\\''"),a=o(e.auth.password),c=o(e.auth.username);n.push(`TS_CLOUD_HTPASS=$(openssl passwd -apr1 '${a}')`,`printf '%s:%s\\n' '${c}' "$TS_CLOUD_HTPASS" > ${i}`,`chmod 640 ${i}`,`chown root:www-data ${i} 2>/dev/null || true`)}return n.push(`cat > ${t} <<'TS_CLOUD_NGINX_EOF'`,s.replace(/\n$/,""),"TS_CLOUD_NGINX_EOF",`ln -sf ${t} ${r}`,"rm -f /etc/nginx/sites-enabled/default",`${$e} -t`,"systemctl reload ts-cloud-nginx 2>/dev/null || systemctl restart ts-cloud-nginx 2>/dev/null || true"),n}var $e="/usr/local/bin/ts-cloud-nginx";function qt(e="/opt/pantry"){return[...gr(),...Xe(["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 > ${$e} <<'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 ${$e}`,"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=${$e} -t`,`ExecStart=${$e} -g 'daemon off;'`,`ExecReload=${$e} -s reload`,"Restart=always","RestartSec=3","","[Install]","WantedBy=multi-user.target","TS_CLOUD_NGINXUNIT_EOF","systemctl daemon-reload","systemctl enable ts-cloud-nginx","ls /etc/nginx/sites-enabled/* >/dev/null 2>&1 && systemctl restart ts-cloud-nginx || true"]}function rt(e,t){return!e.events||e.events.includes(t)}async function Yt(e,t,r,s={}){if(!e)return[];let n=s.fetchImpl??globalThis.fetch,i=[],o=[],a=(c,l)=>n(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)}).catch(()=>{return});if(e.slack?.webhookUrl&&rt(e,t))i.push("slack"),o.push(a(e.slack.webhookUrl,{text:r}));if(e.discord?.webhookUrl&&rt(e,t))i.push("discord"),o.push(a(e.discord.webhookUrl,{content:r}));if(e.telegram?.botToken&&e.telegram.chatId&&rt(e,t)){i.push("telegram");let c=`https://api.telegram.org/bot${e.telegram.botToken}/sendMessage`;o.push(a(c,{chat_id:e.telegram.chatId,text:r}))}if(e.webhook?.url&&rt(e,t))if(i.push("webhook"),(e.webhook.method||"POST")==="GET"){let c=e.webhook.url.includes("?")?"&":"?",l=`${e.webhook.url}${c}event=${encodeURIComponent(t)}&message=${encodeURIComponent(r)}`;o.push(n(l,{method:"GET"}).catch(()=>{return}))}else o.push(a(e.webhook.url,{event:t,message:r}));if(e.email?.to&&rt(e,t))i.push("email"),o.push(Do(e.email,t,r));return await Promise.all(o),i}async function Do(e,t,r){try{let s=await import("./chunk-xvn07b0e.js");await s.email.send({to:e.to,from:e.from,subject:`[ts-cloud] ${t}`,text:r})}catch{}}function Ls(e,t){return t??e}function ke(e){if(!e)return[];let t=[];if(e.slack?.webhookUrl)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"text\\":\\"$MSG\\"}" ${e.slack.webhookUrl} || true`);if(e.discord?.webhookUrl)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"content\\":\\"$MSG\\"}" ${e.discord.webhookUrl} || true`);if(e.telegram?.botToken&&e.telegram.chatId)t.push(`curl -fsS -X POST "https://api.telegram.org/bot${e.telegram.botToken}/sendMessage" --data-urlencode "chat_id=${e.telegram.chatId}" --data-urlencode "text=$MSG" || true`);if(e.webhook?.url)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"message\\":\\"$MSG\\"}" ${e.webhook.url} || true`);if(t.length===0)return[];return["cat > /usr/local/bin/ts-cloud-notify <<'TS_CLOUD_NOTIFY_EOF'","#!/bin/bash",'MSG="$1"',...t,"TS_CLOUD_NOTIFY_EOF","chmod +x /usr/local/bin/ts-cloud-notify"]}import{isIP as Us}from"node:net";var Vr="/etc/rpx/certs",zs="/etc/rpx/local-ca",Ao="rpx-root-ca.crt";function St(e=zs){return`${e.replace(/\/+$/,"")}/${Ao}`}function er(e){if(e.toLowerCase().endsWith(".local"))return!1;return e.split(".").length===2}function Gi(e,t={}){let r=new Set;for(let s of Object.values(e)){if(!s?.domain)continue;if(P(s)==="bucket")continue;r.add(s.domain)}if(t.autoWww!==!1)for(let s of[...r]){if(!er(s))continue;r.add(`www.${s}`)}return[...r]}var No=["1.1.1.1","8.8.8.8"],ko="/var/www/acme-challenge";function Ho(e){if(typeof e==="string")return{to:e};let t={to:e.to};if(e.status!=null)t.status=e.status;if(e.preservePath!=null)t.preservePath=e.preservePath;return t}function Lo(e){let t=e.auth;if(!t||t.enabled===!1||!t.password)return;return{username:t.username||"admin",password:t.password,...t.realm?{realm:t.realm}:{}}}function tr(e){if(!e)return;return e.tls??"local-ca"}function Ki(e,t){if(e.cloud?.provider!=="ssh")return;let r=e.ssh?.lan;if(!r)return;return{...r.hostname?{hostname:r.hostname}:{},tls:r.tls??"local-ca",...t?{ip:t}:{}}}function Fs(e){if(e.cloud?.provider!=="ssh")return;return e.ssh?.profile}function Mo(e){let t=e.trim().toLowerCase();if(!t||t.startsWith("*")||t.includes(":")||t.includes("/")||t.includes(" "))return!1;if(Us(t)!==0)return!1;return t.endsWith(".local")||!t.includes(".")}function Uo(e,t,r){let s=[],n=new Set,i=(l,p)=>{let d=l.trim().toLowerCase();if(!d||n.has(d))return;n.add(d),s.push({host:d,source:p})},o=t.hostname?.trim(),a=(o||`${r}.local`).toLowerCase();if(i(a,o?"ssh.lan.hostname":`the ssh provider's default LAN name for project "${r}"`),Object.entries(e).some(([l,p])=>!!p&&Cr(l)))i(`dashboard.${a}`,"the management dashboard site");for(let[l,p]of Object.entries(e)){if(!p?.domain)continue;if(P(p)==="bucket")continue;if(!Mo(p.domain))continue;i(p.domain,`site "${l}"`)}return s}function zo(e,t){if(!t?.length)return;return t.find((r)=>{let s=(r.startsWith(".")?r.slice(1):r).toLowerCase();return e===s||e.endsWith(`.${s}`)})}function Fo(e,t){if(!t?.enabled)return;for(let{host:r,source:s}of e){let n=zo(r,t.allowedSuffixes);if(!n)continue;throw Error(`The LAN certificate authority and public on-demand TLS both claim "${r}". LAN source: ${s}. Public source: the on-demand TLS allowed suffix "${n}", which is derived from the site domains. A host is either LAN-only, with a certificate signed by the box's own CA, or public, with one issued by Let's Encrypt, never both. Give the LAN a name no site domain covers (ssh.lan.hostname), or take that domain out of the sites this deploy routes.`)}}function Bs(e){if(!e||e==="/")return;let t=`/${e}`.replace(/\/+/g,"/").replace(/\/+$/,"");if(!t.startsWith("/"))t=`/${t}`;return t===""||t==="/"?void 0:t}function Jt(e,t){let s=(t?`${e}${t}`:e).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return s.length>0?s:"rpx"}function Bo(e,t){if(!t||t.length===0)return`localhost:${e}`;return t.map((r)=>`${r.privateIp??r.publicIp}:${e}`)}function Ks(e,t,r){let s=(t.wwwRoot??"/var/www").replace(/\/+$/,""),n=t.slug??"app",i=t.proxy.certsDir??Vr,o=t.proxy.loadBalancer,a=[],c=new Set;for(let[m,g]of Object.entries(e)){if(!g||!g.domain)continue;let h=P(g);if(h==="bucket")continue;let _=Bs(g.path),w=Jt(g.domain,_),b=Lo(g);if(h==="redirect"){a.push({to:g.domain,path:_,redirect:Ho(g.redirect),id:w,...b?{auth:b}:{}}),c.add(g.domain);continue}if(h==="proxy"){let y=gs(g);if(y.length===0)continue;let T=y.length===1?y[0]:y;a.push({to:g.domain,path:_,from:T,id:w,...b?{auth:b}:{},...Array.isArray(T)&&o?{loadBalancer:o}:{}}),c.add(g.domain);continue}if(h==="server-app"){if(typeof g.port!=="number")continue;let y=Bo(g.port,r);a.push({to:g.domain,path:_,from:y,id:w,...b?{auth:b}:{},...Array.isArray(y)&&o?{loadBalancer:o}:{}})}else a.push({to:g.domain,path:_,static:{dir:`${s}/${n}-${m}/current`,spa:g.spa??!1,pathRewriteStyle:g.pathRewriteStyle??"directory"},cleanUrls:g.pathRewriteStyle!=="flat",...b?{auth:b}:{},id:w});c.add(g.domain)}if(t.proxy.autoWww!==!1)for(let m of[...c]){if(!er(m))continue;let g=`www.${m}`;if(c.has(g))continue;a.push({to:g,redirect:{to:`https://${m}`},id:Jt(g)}),c.add(g)}a.sort((m,g)=>{if(m.to!==g.to)return m.to.localeCompare(g.to);return(g.path?.length??0)-(m.path?.length??0)});let l={proxies:a,productionCerts:{certsDir:i,certsDirServerNames:[...c]},https:!0,hostsManagement:!1,cleanup:{hosts:!1,certs:!1}};if(t.proxy.onDemandTls&&c.size>0)l.onDemandTls={enabled:!0,allowedSuffixes:[...c],email:t.proxy.onDemandTlsEmail,certsDir:i,staging:t.proxy.onDemandTlsStaging??!1};if(t.proxy.onDemandTls)l.acmeChallengeWebroot=t.proxy.acmeWebroot??ko;let p=t.proxy.cdn,d=p?.frontedHosts?.length?p.frontedHosts:[...c];if(p?.secret&&d.length>0)l.originGuard={header:p.secretHeader??"X-Origin-Verify",value:p.secret,hosts:d};if(t.lan)if(tr(t.lan)==="off")l.https=!1;else{let m=Uo(e,t.lan,n);Fo(m,l.onDemandTls);let g=t.lan.ip&&Us(t.lan.ip)!==0?[t.lan.ip]:[];l.localCa={dir:zs,hosts:m.map((h)=>h.host),...g.length>0?{ips:g}:{},installTrust:!0}}return l}function fe(e,t){return Ks(e,t)}function Me(e,t,r){return Ks(e,r,t)}function Q(e){return e?.webServer==="rpx"||e?.proxy?.engine==="rpx"}var st="/etc/rpx",J="/opt/rpx-gateway",Qt="/etc/rpx/gateway.ts",He="/etc/rpx/gateway",ye="rpx-gateway.service",ae="/etc/rpx/sites.d";function Ko(e=ae,t=Vr){return`// Generated by ts-cloud — rpx gateway assembler.
15
+ `}function Xt(e){let t=`/etc/nginx/sites-available/${e.siteName}`,r=`/etc/nginx/sites-enabled/${e.siteName}`,s=Oo(e),n=[...qt()];if(e.auth){let i=Hs(e.siteName),o=(l)=>l.split("'").join("'\\''"),a=o(e.auth.password),c=o(e.auth.username);n.push(`TS_CLOUD_HTPASS=$(openssl passwd -apr1 '${a}')`,`printf '%s:%s\\n' '${c}' "$TS_CLOUD_HTPASS" > ${i}`,`chmod 640 ${i}`,`chown root:www-data ${i} 2>/dev/null || true`)}return n.push(`cat > ${t} <<'TS_CLOUD_NGINX_EOF'`,s.replace(/\n$/,""),"TS_CLOUD_NGINX_EOF",`ln -sf ${t} ${r}`,"rm -f /etc/nginx/sites-enabled/default",`${$e} -t`,"systemctl reload ts-cloud-nginx 2>/dev/null || systemctl restart ts-cloud-nginx 2>/dev/null || true"),n}var $e="/usr/local/bin/ts-cloud-nginx";function qt(e="/opt/pantry"){return[...gr(),...Xe(["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 > ${$e} <<'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 ${$e}`,"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=${$e} -t`,`ExecStart=${$e} -g 'daemon off;'`,`ExecReload=${$e} -s reload`,"Restart=always","RestartSec=3","","[Install]","WantedBy=multi-user.target","TS_CLOUD_NGINXUNIT_EOF","systemctl daemon-reload","systemctl enable ts-cloud-nginx","ls /etc/nginx/sites-enabled/* >/dev/null 2>&1 && systemctl restart ts-cloud-nginx || true"]}function rt(e,t){return!e.events||e.events.includes(t)}async function Yt(e,t,r,s={}){if(!e)return[];let n=s.fetchImpl??globalThis.fetch,i=[],o=[],a=(c,l)=>n(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)}).catch(()=>{return});if(e.slack?.webhookUrl&&rt(e,t))i.push("slack"),o.push(a(e.slack.webhookUrl,{text:r}));if(e.discord?.webhookUrl&&rt(e,t))i.push("discord"),o.push(a(e.discord.webhookUrl,{content:r}));if(e.telegram?.botToken&&e.telegram.chatId&&rt(e,t)){i.push("telegram");let c=`https://api.telegram.org/bot${e.telegram.botToken}/sendMessage`;o.push(a(c,{chat_id:e.telegram.chatId,text:r}))}if(e.webhook?.url&&rt(e,t))if(i.push("webhook"),(e.webhook.method||"POST")==="GET"){let c=e.webhook.url.includes("?")?"&":"?",l=`${e.webhook.url}${c}event=${encodeURIComponent(t)}&message=${encodeURIComponent(r)}`;o.push(n(l,{method:"GET"}).catch(()=>{return}))}else o.push(a(e.webhook.url,{event:t,message:r}));if(e.email?.to&&rt(e,t))i.push("email"),o.push(Do(e.email,t,r));return await Promise.all(o),i}async function Do(e,t,r){try{let s=await import("./chunk-xvn07b0e.js");await s.email.send({to:e.to,from:e.from,subject:`[ts-cloud] ${t}`,text:r})}catch{}}function Ls(e,t){return t??e}function ke(e){if(!e)return[];let t=[];if(e.slack?.webhookUrl)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"text\\":\\"$MSG\\"}" ${e.slack.webhookUrl} || true`);if(e.discord?.webhookUrl)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"content\\":\\"$MSG\\"}" ${e.discord.webhookUrl} || true`);if(e.telegram?.botToken&&e.telegram.chatId)t.push(`curl -fsS -X POST "https://api.telegram.org/bot${e.telegram.botToken}/sendMessage" --data-urlencode "chat_id=${e.telegram.chatId}" --data-urlencode "text=$MSG" || true`);if(e.webhook?.url)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"message\\":\\"$MSG\\"}" ${e.webhook.url} || true`);if(t.length===0)return[];return["cat > /usr/local/bin/ts-cloud-notify <<'TS_CLOUD_NOTIFY_EOF'","#!/bin/bash",'MSG="$1"',...t,"TS_CLOUD_NOTIFY_EOF","chmod +x /usr/local/bin/ts-cloud-notify"]}import{isIP as Us}from"node:net";var Vr="/etc/rpx/certs",zs="/etc/rpx/local-ca",Ao="rpx-root-ca.crt";function St(e=zs){return`${e.replace(/\/+$/,"")}/${Ao}`}function er(e){if(e.toLowerCase().endsWith(".local"))return!1;return e.split(".").length===2}function Gi(e,t={}){let r=new Set;for(let s of Object.values(e)){if(!s?.domain)continue;if(P(s)==="bucket")continue;r.add(s.domain)}if(t.autoWww!==!1)for(let s of[...r]){if(!er(s))continue;r.add(`www.${s}`)}return[...r]}var No=["1.1.1.1","8.8.8.8"],ko="/var/www/acme-challenge";function Ho(e){if(typeof e==="string")return{to:e};let t={to:e.to};if(e.status!=null)t.status=e.status;if(e.preservePath!=null)t.preservePath=e.preservePath;return t}function Lo(e){let t=e.auth;if(!t||t.enabled===!1||!t.password)return;return{username:t.username||"admin",password:t.password,...t.realm?{realm:t.realm}:{}}}function tr(e){if(!e)return;return e.tls??"local-ca"}function Ki(e,t){if(e.cloud?.provider!=="ssh")return;let r=e.ssh?.lan;if(!r)return;return{...r.hostname?{hostname:r.hostname}:{},tls:r.tls??"local-ca",...t?{ip:t}:{}}}function Fs(e){if(e.cloud?.provider!=="ssh")return;return e.ssh?.profile}function Mo(e){let t=e.trim().toLowerCase();if(!t||t.startsWith("*")||t.includes(":")||t.includes("/")||t.includes(" "))return!1;if(Us(t)!==0)return!1;return t.endsWith(".local")||!t.includes(".")}function Uo(e,t,r){let s=[],n=new Set,i=(l,p)=>{let d=l.trim().toLowerCase();if(!d||n.has(d))return;n.add(d),s.push({host:d,source:p})},o=t.hostname?.trim(),a=(o||`${r}.local`).toLowerCase();if(i(a,o?"ssh.lan.hostname":`the ssh provider's default LAN name for project "${r}"`),Object.entries(e).some(([l,p])=>!!p&&Cr(l)))i(`dashboard.${a}`,"the management dashboard site");for(let[l,p]of Object.entries(e)){if(!p?.domain)continue;if(P(p)==="bucket")continue;if(!Mo(p.domain))continue;i(p.domain,`site "${l}"`)}return s}function zo(e,t){if(!t?.length)return;return t.find((r)=>{let s=(r.startsWith(".")?r.slice(1):r).toLowerCase();return e===s||e.endsWith(`.${s}`)})}function Fo(e,t){if(!t?.enabled)return;for(let{host:r,source:s}of e){let n=zo(r,t.allowedSuffixes);if(!n)continue;throw Error(`The LAN certificate authority and public on-demand TLS both claim "${r}". LAN source: ${s}. Public source: the on-demand TLS allowed suffix "${n}", which is derived from the site domains. A host is either LAN-only, with a certificate signed by the box's own CA, or public, with one issued by Let's Encrypt, never both. Give the LAN a name no site domain covers (ssh.lan.hostname), or take that domain out of the sites this deploy routes.`)}}function Bs(e){if(!e||e==="/")return;let t=`/${e}`.replace(/\/+/g,"/").replace(/\/+$/,"");if(!t.startsWith("/"))t=`/${t}`;return t===""||t==="/"?void 0:t}function Jt(e,t){let s=(t?`${e}${t}`:e).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return s.length>0?s:"rpx"}function Bo(e,t){if(!t||t.length===0)return`localhost:${e}`;return t.map((r)=>`${r.privateIp??r.publicIp}:${e}`)}function Ks(e,t,r){let s=(t.wwwRoot??"/var/www").replace(/\/+$/,""),n=t.slug??"app",i=t.proxy.certsDir??Vr,o=t.proxy.loadBalancer,a=[],c=new Set;for(let[m,g]of Object.entries(e)){if(!g||!g.domain)continue;let h=P(g);if(h==="bucket")continue;let _=Bs(g.path),w=Jt(g.domain,_),b=Lo(g);if(h==="redirect"){a.push({to:g.domain,path:_,redirect:Ho(g.redirect),id:w,...b?{auth:b}:{}}),c.add(g.domain);continue}if(h==="proxy"){let y=gs(g);if(y.length===0)continue;let T=y.length===1?y[0]:y;a.push({to:g.domain,path:_,from:T,id:w,...b?{auth:b}:{},...Array.isArray(T)&&o?{loadBalancer:o}:{}}),c.add(g.domain);continue}if(h==="server-app"){if(typeof g.port!=="number")continue;let y=Bo(g.port,r);a.push({to:g.domain,path:_,from:y,id:w,...b?{auth:b}:{},...Array.isArray(y)&&o?{loadBalancer:o}:{}})}else a.push({to:g.domain,path:_,static:{dir:`${s}/${n}-${m}/current`,spa:g.spa??!1,pathRewriteStyle:g.pathRewriteStyle??"directory"},cleanUrls:g.pathRewriteStyle!=="flat",...b?{auth:b}:{},id:w});c.add(g.domain)}if(t.proxy.autoWww!==!1)for(let m of[...c]){if(!er(m))continue;let g=`www.${m}`;if(c.has(g))continue;a.push({to:g,redirect:{to:`https://${m}`},id:Jt(g)}),c.add(g)}a.sort((m,g)=>{if(m.to!==g.to)return m.to.localeCompare(g.to);return(g.path?.length??0)-(m.path?.length??0)});let l={proxies:a,productionCerts:{certsDir:i,certsDirServerNames:[...c]},https:!0,hostsManagement:!1,cleanup:{hosts:!1,certs:!1}};if(t.proxy.onDemandTls&&c.size>0)l.onDemandTls={enabled:!0,allowedSuffixes:[...c],email:t.proxy.onDemandTlsEmail,certsDir:i,staging:t.proxy.onDemandTlsStaging??!1};if(t.proxy.onDemandTls)l.acmeChallengeWebroot=t.proxy.acmeWebroot??ko;let p=t.proxy.cdn,d=p?.frontedHosts?.length?p.frontedHosts:[...c];if(p?.secret&&d.length>0)l.originGuard={header:p.secretHeader??"X-Origin-Verify",value:p.secret,hosts:d};if(t.lan)if(tr(t.lan)==="off")l.https=!1;else{let m=Uo(e,t.lan,n);Fo(m,l.onDemandTls);let g=t.lan.ip&&Us(t.lan.ip)!==0?[t.lan.ip]:[];l.localCa={dir:zs,hosts:m.map((h)=>h.host),...g.length>0?{ips:g}:{},installTrust:!0}}return l}function fe(e,t){return Ks(e,t)}function Me(e,t,r){return Ks(e,r,t)}function Q(e){return e?.webServer==="rpx"||e?.proxy?.engine==="rpx"}var st="/etc/rpx",J="/opt/rpx-gateway",Qt="/etc/rpx/gateway.ts",He="/etc/rpx/gateway",me="rpx-gateway.service",te="/etc/rpx/sites.d";function Ko(e=te,t=Vr){return`// Generated by ts-cloud — rpx gateway assembler.
16
16
  // Merges every app's fragment in ${e} so independent deploys compose
17
17
  // without clobbering each other. Each deploy writes only its own <slug>.json.
18
18
  import { startProxies } from '@stacksjs/rpx'
@@ -135,13 +135,13 @@ const retained = Array.isArray(current.proxies) ? current.proxies.filter(isDashb
135
135
  const next = Array.isArray(candidate.proxies) ? candidate.proxies.filter(route => !isDashboard(route)) : []
136
136
  candidate.proxies = [...next, ...retained]
137
137
  writeFileSync(candidatePath, JSON.stringify(candidate, null, 2) + '\\n', { mode: 0o600 })
138
- `.trim();return[`__tsc_fragment_candidate="$(mktemp "${e}.candidate.XXXXXX")"`,`cat > "$__tsc_fragment_candidate" <<'${r}'`,t,r,'chmod 0600 "$__tsc_fragment_candidate"',`if [ -f ${e} ]; then TS_CLOUD_RPX_CURRENT_FRAGMENT=${e} TS_CLOUD_RPX_CANDIDATE_FRAGMENT="$__tsc_fragment_candidate" ${s.bunBin} -e ${jo(n)}; fi`,`mv -f "$__tsc_fragment_candidate" ${e}`,`chmod 0600 ${e}`]}var Go={high:"256M",max:"384M"},Wo={high:"512M",max:"768M"};function rr(e){return`rpx-cert-renew-${(e||"app").replace(/[^a-z0-9._-]+/gi,"-")}.service`}function nr(e){let t=new Set;for(let r of e.proxies){let s=r.to;if(!s||s.startsWith("*")||s.includes(":")||!s.includes("."))continue;t.add(s)}return[...t]}function Ms(e){let{config:t,proxy:r}=e,s=t.acmeChallengeWebroot,n=nr(t);if(!r.onDemandTls||!s||n.length===0)return[];let i=e.bunBin??"/usr/local/bin/bun",o=r.tlsxVersion??"latest",a=t.productionCerts.certsDir,c=r.onDemandTlsEmail??`webmaster@${n[0]}`,l=`${i} ${J}/node_modules/@stacksjs/tlsx/dist/bin/cli.js`,p=n.join(","),d=n.join(" "),m=(e.slug||"app").replace(/[^a-z0-9._-]+/gi,"-"),g=`${st}/renew-certs-${m}.sh`,h=rr(m),_=`rpx-cert-renew-${m}.timer`,w=["#!/bin/sh","# Generated by ts-cloud — issue/renew rpx gateway TLS certs via tlsx http-01.","# The running gateway serves the challenge from $WEBROOT on :80, so this needs","# no downtime and no DNS credentials. Reloads the gateway only if a cert changed.","set -u",`CERTS='${a}'`,`WEBROOT='${s}'`,`EMAIL='${c}'`,`TLSX="${l}"`,`BUN='${i}'`,`DOMAINS='${p}'`,"DNS_ATTEMPTS='24'","DNS_DELAY_SECONDS='5'",`DNS_RESOLVERS='${No.join(" ")}'`,"dns_resolves() {",' d="$1"'," for ns in $DNS_RESOLVERS; do",` if $BUN --eval "const{Resolver}=require('node:dns');const r=new Resolver();r.setServers([process.argv[1]]);r.resolve4(process.argv[2],e=>process.exit(e?1:0))" "$ns" "$d" >/dev/null 2>&1; then`," return 0"," fi"," done",' getent ahosts "$d" >/dev/null 2>&1',"}","wait_for_dns() {",' d="$1"'," attempt=1",' while ! dns_resolves "$d"; do',' if [ "$attempt" -ge "$DNS_ATTEMPTS" ]; then',' echo "DNS for $d did not become resolvable after $DNS_ATTEMPTS attempts" >&2'," return 1"," fi",' echo "Waiting for public DNS before ACME: $d (attempt $attempt/$DNS_ATTEMPTS)"',' sleep "$DNS_DELAY_SECONDS"'," attempt=$((attempt + 1))"," done","}",'before=$(cat "$CERTS"/*.crt 2>/dev/null | sha256sum)',`for d in ${d}; do`,' if [ ! -s "$CERTS/$d.crt" ]; then',' if wait_for_dns "$d"; then',' $TLSX acme:issue -d "$d" --method http-01 --webroot "$WEBROOT" --dir "$CERTS" --prod --email "$EMAIL" || echo "issue $d failed (non-fatal)"'," else",' echo "issue $d skipped until DNS resolves (non-fatal)"'," fi"," # rpx reloads its SNI set when a PEM appears. Complete that reload"," # before the next hostname starts http-01, or :80 can disappear in"," # the middle of the following challenge on a multi-domain deploy.",` [ -s "$CERTS/$d.crt" ] && systemctl restart ${ye}`," fi","done",'$TLSX acme:renew --domains "$DOMAINS" --method http-01 --webroot "$WEBROOT" --dir "$CERTS" --days 30 --prod --email "$EMAIL" || echo "renew: some domains failed (non-fatal)"','rm -f "$CERTS"/*.chain.crt','after=$(cat "$CERTS"/*.crt 2>/dev/null | sha256sum)',`[ "$before" = "$after" ] || systemctl restart ${ye}`].join(`
139
- `),b=["[Unit]",`Description=Issue/renew rpx gateway TLS certs for ${m} (tlsx http-01)`,`After=network-online.target ${ye}`,"Wants=network-online.target","","[Service]","Type=oneshot",`ExecStart=${g}`].join(`
138
+ `.trim();return[`__tsc_fragment_candidate="$(mktemp "${e}.candidate.XXXXXX")"`,`cat > "$__tsc_fragment_candidate" <<'${r}'`,t,r,'chmod 0600 "$__tsc_fragment_candidate"',`if [ -f ${e} ]; then TS_CLOUD_RPX_CURRENT_FRAGMENT=${e} TS_CLOUD_RPX_CANDIDATE_FRAGMENT="$__tsc_fragment_candidate" ${s.bunBin} -e ${jo(n)}; fi`,`mv -f "$__tsc_fragment_candidate" ${e}`,`chmod 0600 ${e}`]}var Go={high:"256M",max:"384M"},Wo={high:"512M",max:"768M"};function rr(e){return`rpx-cert-renew-${(e||"app").replace(/[^a-z0-9._-]+/gi,"-")}.service`}function nr(e){let t=new Set;for(let r of e.proxies){let s=r.to;if(!s||s.startsWith("*")||s.includes(":")||!s.includes("."))continue;t.add(s)}return[...t]}function Ms(e){let{config:t,proxy:r}=e,s=t.acmeChallengeWebroot,n=nr(t);if(!r.onDemandTls||!s||n.length===0)return[];let i=e.bunBin??"/usr/local/bin/bun",o=r.tlsxVersion??"latest",a=t.productionCerts.certsDir,c=r.onDemandTlsEmail??`webmaster@${n[0]}`,l=`${i} ${J}/node_modules/@stacksjs/tlsx/dist/bin/cli.js`,p=n.join(","),d=n.join(" "),m=(e.slug||"app").replace(/[^a-z0-9._-]+/gi,"-"),g=`${st}/renew-certs-${m}.sh`,h=rr(m),_=`rpx-cert-renew-${m}.timer`,w=["#!/bin/sh","# Generated by ts-cloud — issue/renew rpx gateway TLS certs via tlsx http-01.","# The running gateway serves the challenge from $WEBROOT on :80, so this needs","# no downtime and no DNS credentials. Reloads the gateway only if a cert changed.","set -u",`CERTS='${a}'`,`WEBROOT='${s}'`,`EMAIL='${c}'`,`TLSX="${l}"`,`BUN='${i}'`,`DOMAINS='${p}'`,"DNS_ATTEMPTS='24'","DNS_DELAY_SECONDS='5'",`DNS_RESOLVERS='${No.join(" ")}'`,"dns_resolves() {",' d="$1"'," for ns in $DNS_RESOLVERS; do",` if $BUN --eval "const{Resolver}=require('node:dns');const r=new Resolver();r.setServers([process.argv[1]]);r.resolve4(process.argv[2],e=>process.exit(e?1:0))" "$ns" "$d" >/dev/null 2>&1; then`," return 0"," fi"," done",' getent ahosts "$d" >/dev/null 2>&1',"}","wait_for_dns() {",' d="$1"'," attempt=1",' while ! dns_resolves "$d"; do',' if [ "$attempt" -ge "$DNS_ATTEMPTS" ]; then',' echo "DNS for $d did not become resolvable after $DNS_ATTEMPTS attempts" >&2'," return 1"," fi",' echo "Waiting for public DNS before ACME: $d (attempt $attempt/$DNS_ATTEMPTS)"',' sleep "$DNS_DELAY_SECONDS"'," attempt=$((attempt + 1))"," done","}",'before=$(cat "$CERTS"/*.crt 2>/dev/null | sha256sum)',`for d in ${d}; do`,' if [ ! -s "$CERTS/$d.crt" ]; then',' if wait_for_dns "$d"; then',' $TLSX acme:issue -d "$d" --method http-01 --webroot "$WEBROOT" --dir "$CERTS" --prod --email "$EMAIL" || echo "issue $d failed (non-fatal)"'," else",' echo "issue $d skipped until DNS resolves (non-fatal)"'," fi"," # rpx reloads its SNI set when a PEM appears. Complete that reload"," # before the next hostname starts http-01, or :80 can disappear in"," # the middle of the following challenge on a multi-domain deploy.",` [ -s "$CERTS/$d.crt" ] && systemctl restart ${me}`," fi","done",'$TLSX acme:renew --domains "$DOMAINS" --method http-01 --webroot "$WEBROOT" --dir "$CERTS" --days 30 --prod --email "$EMAIL" || echo "renew: some domains failed (non-fatal)"','rm -f "$CERTS"/*.chain.crt','after=$(cat "$CERTS"/*.crt 2>/dev/null | sha256sum)',`[ "$before" = "$after" ] || systemctl restart ${me}`].join(`
139
+ `),b=["[Unit]",`Description=Issue/renew rpx gateway TLS certs for ${m} (tlsx http-01)`,`After=network-online.target ${me}`,"Wants=network-online.target","","[Service]","Type=oneshot",`ExecStart=${g}`].join(`
140
140
  `),y=["[Unit]",`Description=Daily rpx gateway TLS cert issuance/renewal for ${m}`,"","[Timer]","OnCalendar=*-*-* 03:30:00","RandomizedDelaySec=1h","Persistent=true","","[Install]","WantedBy=timers.target"].join(`
141
- `);return[`mkdir -p ${s}`,...e.tenant?[]:[`(cd ${J} && ${i} add @stacksjs/tlsx@${o}) || true`],...Le(g,w,"TS_CLOUD_RENEW_EOF"),`chmod +x ${g}`,...Le(`/etc/systemd/system/${h}`,b,"TS_CLOUD_RENEW_SVC_EOF"),...Le(`/etc/systemd/system/${_}`,y,"TS_CLOUD_RENEW_TIMER_EOF"),"systemctl daemon-reload",`systemctl enable --now ${_} || true`,`${g} || true`]}function me(e){let{config:t,proxy:r}=e,s=e.bunBin??"/usr/local/bin/bun",n=r.version??"latest",i=t.productionCerts.certsDir,o=(e.slug||"app").replace(/[^a-z0-9._-]+/gi,"-"),a=JSON.stringify({slug:o,...t},null,2),c=Ko(ae,i);if(e.tenant)return["set -euo pipefail",`if [ ! -x ${He} ] || [ ! -d ${J}/node_modules/@stacksjs/rpx ]; then`,` echo "ts-cloud: no rpx gateway on this box. This project attaches to another project's compute, so it does not provision one - deploy the owning project first." >&2`," exit 1","fi",`mkdir -p ${ae} ${i}`,...Zt(`${ae}/${o}.json`,a,"TS_CLOUD_RPX_FRAGMENT_EOF",{bunBin:s,preserveManagementDashboardRoutes:e.preserveManagementDashboardRoutes}),`systemctl restart ${ye}`,...Ms(e)];let p=[`Environment=RPX_UPSTREAM_TIMEOUT=${r.upstreamTimeout??60}`];if(typeof r.maxUpstreamConns==="number")p.push(`Environment=RPX_MAX_UPSTREAM_CONNS=${r.maxUpstreamConns}`);let d=e.profile==="raspberry-pi"?Go:Wo,m=r.memoryHigh??d.high,g=r.memoryMax??d.max;return["set -euo pipefail",`mkdir -p ${st} ${ae} ${i} ${J}`,`rm -rf ${J}.next ${J}.prev`,`mkdir -p ${J}.next`,`(cd ${J}.next && ${s} add @stacksjs/rpx@${n})`,`mv ${J} ${J}.prev`,`mv ${J}.next ${J}`,`rm -rf ${J}.prev`,`ln -sfn ${J}/node_modules ${st}/node_modules`,...Zt(`${ae}/${o}.json`,a,"TS_CLOUD_RPX_FRAGMENT_EOF",{bunBin:s,preserveManagementDashboardRoutes:e.preserveManagementDashboardRoutes}),...Le(Qt,c,"TS_CLOUD_RPX_EOF"),`${s} build --production --compile --outfile ${He}.next ${Qt}`,`chmod 0755 ${He}.next`,`mv -f ${He}.next ${He}`,...Le(`/etc/systemd/system/${ye}`,["[Unit]","Description=rpx reverse-proxy gateway (managed by ts-cloud)","After=network.target network-online.target","Wants=network-online.target","","[Service]","Type=simple",`ExecStart=${He}`,`WorkingDirectory=${J}`,"Environment=BUN_INSTALL=/root/.bun","Environment=APP_ENV=production","Environment=NODE_ENV=production",...p,"MemoryAccounting=true",`MemoryHigh=${m}`,`MemoryMax=${g}`,"CPUWeight=500","IOWeight=500","OOMPolicy=stop","Restart=always","RestartSec=5","StartLimitIntervalSec=120","StartLimitBurst=5",`ExecStartPre=/bin/sh -c 'for p in 80 443; do fuser -k -n tcp "$p" 2>/dev/null || true; done; sleep 1'`,"LimitNOFILE=1048576","AmbientCapabilities=CAP_NET_BIND_SERVICE","","[Install]","WantedBy=multi-user.target"].join(`
142
- `),"TS_CLOUD_RPX_UNIT_EOF"),"systemctl daemon-reload","systemctl disable --now bun-gateway.service 2>/dev/null || true","systemctl disable --now bun-gateway-renew.timer bun-gateway-renew.service 2>/dev/null || true","rm -f /etc/systemd/system/bun-gateway-renew.timer /etc/systemd/system/bun-gateway-renew.service","systemctl disable --now ts-cloud-nginx.service 2>/dev/null || true",`for timer in /etc/systemd/system/rpx-cert-renew-*.timer; do [ -e "$timer" ] || continue; unit="$(basename "$timer")"; tenant="\${unit#rpx-cert-renew-}"; tenant="\${tenant%.timer}"; [ -f "${ae}/$tenant.json" ] && continue; systemctl disable --now "$unit" 2>/dev/null || true; rm -f "$timer" "/etc/systemd/system/rpx-cert-renew-$tenant.service" "${st}/renew-certs-$tenant.sh"; done`,`systemctl enable ${ye}`,`systemctl restart ${ye}`,...Ms(e)]}function Ge(e){let t=(e.slug||"app").replace(/[^a-z0-9._-]+/gi,"-"),r=JSON.stringify({slug:t,...e.config},null,2);return["set -euo pipefail",`mkdir -p ${ae}`,...Zt(`${ae}/${t}.json`,r,"TS_CLOUD_RPX_FRAGMENT_EOF",{bunBin:"/usr/local/bin/bun",preserveManagementDashboardRoutes:e.preserveManagementDashboardRoutes}),`systemctl restart ${ye}`]}function Ue(e=[],t={}){let r=t.path??"/root/.ssh/authorized_keys",n=[`mkdir -p ${r.replace(/\/[^/]*$/,"")}`,`touch ${r}`,`sed -i '/^${js("# >>> ts-cloud managed keys >>>")}$/,/^${js("# <<< ts-cloud managed keys <<<")}$/d' ${r}`];if(e.length>0){let i=["# >>> ts-cloud managed keys >>>",...e.map((o)=>`${o.publicKey.trim()} ${o.name}`),"# <<< ts-cloud managed keys <<<"].join(`
141
+ `);return[`mkdir -p ${s}`,...e.tenant?[]:[`(cd ${J} && ${i} add @stacksjs/tlsx@${o}) || true`],...Le(g,w,"TS_CLOUD_RENEW_EOF"),`chmod +x ${g}`,...Le(`/etc/systemd/system/${h}`,b,"TS_CLOUD_RENEW_SVC_EOF"),...Le(`/etc/systemd/system/${_}`,y,"TS_CLOUD_RENEW_TIMER_EOF"),"systemctl daemon-reload",`systemctl enable --now ${_} || true`,`${g} || true`]}function ge(e){let{config:t,proxy:r}=e,s=e.bunBin??"/usr/local/bin/bun",n=r.version??"latest",i=t.productionCerts.certsDir,o=(e.slug||"app").replace(/[^a-z0-9._-]+/gi,"-"),a=JSON.stringify({slug:o,...t},null,2),c=Ko(te,i);if(e.tenant)return["set -euo pipefail",`if [ ! -x ${He} ] || [ ! -d ${J}/node_modules/@stacksjs/rpx ]; then`,` echo "ts-cloud: no rpx gateway on this box. This project attaches to another project's compute, so it does not provision one - deploy the owning project first." >&2`," exit 1","fi",`mkdir -p ${te} ${i}`,`__tsc_rpx_before="$(sha256sum ${te}/${o}.json 2>/dev/null | cut -d' ' -f1 || true)"`,...Zt(`${te}/${o}.json`,a,"TS_CLOUD_RPX_FRAGMENT_EOF",{bunBin:s,preserveManagementDashboardRoutes:e.preserveManagementDashboardRoutes}),`__tsc_rpx_after="$(sha256sum ${te}/${o}.json 2>/dev/null | cut -d' ' -f1 || true)"`,`if [ "$__tsc_rpx_before" != "$__tsc_rpx_after" ] || ! systemctl is-active --quiet ${me}; then`,` systemctl restart ${me}`,"else",` echo "[ts-cloud] rpx routes for ${o} unchanged - leaving the shared gateway alone"`,"fi",...Ms(e)];let p=[`Environment=RPX_UPSTREAM_TIMEOUT=${r.upstreamTimeout??60}`];if(typeof r.maxUpstreamConns==="number")p.push(`Environment=RPX_MAX_UPSTREAM_CONNS=${r.maxUpstreamConns}`);let d=e.profile==="raspberry-pi"?Go:Wo,m=r.memoryHigh??d.high,g=r.memoryMax??d.max;return["set -euo pipefail",`mkdir -p ${st} ${te} ${i} ${J}`,`rm -rf ${J}.next ${J}.prev`,`mkdir -p ${J}.next`,`(cd ${J}.next && ${s} add @stacksjs/rpx@${n})`,`mv ${J} ${J}.prev`,`mv ${J}.next ${J}`,`rm -rf ${J}.prev`,`ln -sfn ${J}/node_modules ${st}/node_modules`,...Zt(`${te}/${o}.json`,a,"TS_CLOUD_RPX_FRAGMENT_EOF",{bunBin:s,preserveManagementDashboardRoutes:e.preserveManagementDashboardRoutes}),...Le(Qt,c,"TS_CLOUD_RPX_EOF"),`${s} build --production --compile --outfile ${He}.next ${Qt}`,`chmod 0755 ${He}.next`,`mv -f ${He}.next ${He}`,...Le(`/etc/systemd/system/${me}`,["[Unit]","Description=rpx reverse-proxy gateway (managed by ts-cloud)","After=network.target network-online.target","Wants=network-online.target","","[Service]","Type=simple",`ExecStart=${He}`,`WorkingDirectory=${J}`,"Environment=BUN_INSTALL=/root/.bun","Environment=APP_ENV=production","Environment=NODE_ENV=production",...p,"MemoryAccounting=true",`MemoryHigh=${m}`,`MemoryMax=${g}`,"CPUWeight=500","IOWeight=500","OOMPolicy=stop","Restart=always","RestartSec=5","StartLimitIntervalSec=120","StartLimitBurst=5",`ExecStartPre=/bin/sh -c 'for p in 80 443; do fuser -k -n tcp "$p" 2>/dev/null || true; done; sleep 1'`,"LimitNOFILE=1048576","AmbientCapabilities=CAP_NET_BIND_SERVICE","","[Install]","WantedBy=multi-user.target"].join(`
142
+ `),"TS_CLOUD_RPX_UNIT_EOF"),"systemctl daemon-reload","systemctl disable --now bun-gateway.service 2>/dev/null || true","systemctl disable --now bun-gateway-renew.timer bun-gateway-renew.service 2>/dev/null || true","rm -f /etc/systemd/system/bun-gateway-renew.timer /etc/systemd/system/bun-gateway-renew.service","systemctl disable --now ts-cloud-nginx.service 2>/dev/null || true",`for timer in /etc/systemd/system/rpx-cert-renew-*.timer; do [ -e "$timer" ] || continue; unit="$(basename "$timer")"; tenant="\${unit#rpx-cert-renew-}"; tenant="\${tenant%.timer}"; [ -f "${te}/$tenant.json" ] && continue; systemctl disable --now "$unit" 2>/dev/null || true; rm -f "$timer" "/etc/systemd/system/rpx-cert-renew-$tenant.service" "${st}/renew-certs-$tenant.sh"; done`,`systemctl enable ${me}`,`systemctl restart ${me}`,...Ms(e)]}function Ge(e){let t=(e.slug||"app").replace(/[^a-z0-9._-]+/gi,"-"),r=JSON.stringify({slug:t,...e.config},null,2);return["set -euo pipefail",`mkdir -p ${te}`,...Zt(`${te}/${t}.json`,r,"TS_CLOUD_RPX_FRAGMENT_EOF",{bunBin:"/usr/local/bin/bun",preserveManagementDashboardRoutes:e.preserveManagementDashboardRoutes}),`systemctl restart ${me}`]}function Ue(e=[],t={}){let r=t.path??"/root/.ssh/authorized_keys",n=[`mkdir -p ${r.replace(/\/[^/]*$/,"")}`,`touch ${r}`,`sed -i '/^${js("# >>> ts-cloud managed keys >>>")}$/,/^${js("# <<< ts-cloud managed keys <<<")}$/d' ${r}`];if(e.length>0){let i=["# >>> ts-cloud managed keys >>>",...e.map((o)=>`${o.publicKey.trim()} ${o.name}`),"# <<< ts-cloud managed keys <<<"].join(`
143
143
  `);n.push(`cat >> ${r} <<'TS_CLOUD_KEYS_EOF'`,i,"TS_CLOUD_KEYS_EOF",`chmod 600 ${r}`)}return n}function js(e){return e.replace(/[.*[\]\\/^$]/g,"\\$&")}function Ws(e,t){let r=`/tmp/ts-cloud-${e}.sh`,s=`TS_CLOUD_${e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}_EOF`;return[`cat > ${r} <<'${s}'`,t.replace(/\n$/,""),s,`chmod +x ${r}`,`bash ${r} || echo "ts-cloud: ${e} setup did not complete; continuing" >&2`,`rm -f ${r}`]}function Vs(e,t){if(e===!1)return;if(e===!0||e===void 0)return t;return e}var Gs={enabled:!0,ports:[80,443]},Vo={mode:"detection",paranoiaLevel:1};function Xo(e=!0,t=[]){let r=Vs(e,Gs);if(!r||r.enabled===!1)return[];let s=[...new Set([...r.ports??Gs.ports??[],...t])].sort((n,i)=>n-i);return Ws("ddos",mr({...r,ports:s}))}function qo(e=!0){let t=Vs(e,Vo);if(!t||t.mode==="off")return[];return Ws("waf",ps(t))}function Xs(e={},t=[]){return[...Xo(e.ddos,t),...qo(e.waf)]}function Yo(e){return`${e}-sftp`}function qs(e){return e.port??2222}function Jo(e){let t=e.sftp.storage;if(t?.type==="efs"&&t.path)return t.path;return`/var/sftp/${e.slug}`}function ze(e){return`'${e.split("'").join("'\\''")}'`}function Ys(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[n,i]of Object.entries(e.users))if(!i.sshPublicKeys?.length)throw Error(`sftp: user ${n} needs at least one SSH public key`)}function Js(e){let{slug:t,sftp:r}=e,s=Yo(t),n=Jo(e),i=qs(r),o="/etc/ts-sftp/host_key",a="/etc/ts-sftp/users",c=r.serviceUser??"ts-sftp",l=[`# --- ts-sftp (${s}) ---`,`id -u ${c} >/dev/null 2>&1 || useradd --system --home-dir ${ze(n)} --shell /usr/sbin/nologin ${c}`,'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 ${ze(n)} /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 ${ze(`${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'],p=[];for(let[d,m]of Object.entries(r.users)){let g=(m.homeDirectory??d).replace(/^\/+|\/+$/g,"");if(!g||g.split("/").includes(".."))throw Error(`sftp: invalid homeDirectory for user ${d}`);let h=`/etc/ts-sftp/users/${d}.pub`;l.push(`mkdir -p ${ze(`${n}/${g}`)}`,`printf '%s\\n' ${ze(m.sshPublicKeys.join(`
144
- `))} > ${h}`,`chmod 644 ${h}`),p.push(`--user ${d}:${h}`)}return l.push(`chown -R ${c}:${c} ${ze(n)} /etc/ts-sftp`,`cat > /etc/systemd/system/${s}.service <<TSCLOUD_SFTP_UNIT`,"[Unit]","Description=ts-sftp file transfer server","After=network.target","","[Service]",`User=${c}`,`ExecStart=$BUN_BIN /opt/ts-sftp/node_modules/ts-sftp/dist/bin/cli.js serve --root ${n} --host-key /etc/ts-sftp/host_key --port ${i}${r.readOnly?" --read-only":""} ${p.join(" ")}`,"Restart=always","RestartSec=2","NoNewPrivileges=true","PrivateTmp=true","ProtectSystem=strict",`ReadWritePaths=${n}`,"","[Install]","WantedBy=multi-user.target","TSCLOUD_SFTP_UNIT","systemctl daemon-reload",`systemctl enable ${s}.service`,`systemctl restart ${s}.service`),l}function Qs(e){return e?[qs(e)]:[]}var Qo=[80,443];function vt(e={}){if(e.enabled===!1)return[];let t=[...new Set([...Qo,...e.allowedPorts||[]])].filter((s)=>Number.isInteger(s)&&s>=1&&s<=65535).sort((s,n)=>s-n),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 s of t)r.push(`ufw allow ${s}/tcp`);return r.push("ufw --force enable"),r}function Oe(e,t){let r=e.infrastructure?.compute??{},s=r.runtime==="php"||!!r.php,n=pi(e,{environment:t?.environment}),i=s||!!r.managedServices,o=i?gr():[],a=!Q(r),c=s?[...o,...yt({versions:r.php?.versions,default:r.php?.default,extensions:r.php?.extensions,installNginx:a,optimizeForProduction:r.php?.optimizeForProduction,ini:r.php?.ini}),...a?qt():[]]:void 0,l=[],p=C(e);if(!s&&i)l.push(...o);if(l.push(...ke(e.notifications)),r.managedServices)l.push(...lo(r.managedServices,{mail:n.enabled?n:void 0}),...ht(p,r.managedServices));let d=e.infrastructure?.sftp;if(d)Ys(d,U(e)),l.push(...Js({slug:e.project.slug,sftp:d}));let m=r.firewall??(s?{enabled:!0}:{enabled:!1}),g=$s(n);if(l.push(...vt(g.length>0?{...m,allowedPorts:[...m.allowedPorts??[],...g]}:m)),l.push(...Xs({ddos:r.ddos,waf:r.waf},[...r.firewall?.allowedPorts??[],...g])),l.push(...be(r.autoUpdates??s)),l.push(...Wi(r.appUpdates)),l.push(...we(r.monitoring??s)),l.push(...Ue(r.sshKeys,{path:t?.authorizedKeysPath})),r.backups?.enabled)l.push(...uo({database:p,backups:r.backups}));return{runtime:r.runtime||"bun",runtimeVersion:r.runtimeVersion||"latest",phpBox:s,phpProvision:c,servicesProvision:l.length>0?l:void 0}}function te(e={}){let{runtime:t="bun",runtimeVersion:r="latest",systemPackages:s=[],database:n,phpProvision:i,servicesProvision:o,caddyfile:a,rpxProvision:c,baked:l=!1,swapGb:p=2}=e,d=new Set(s);if(n==="sqlite")d.add("sqlite3");else if(n==="mysql")d.add("mysql-client");else if(n==="postgres")d.add("postgresql-client");let m=`#!/bin/bash
144
+ `))} > ${h}`,`chmod 644 ${h}`),p.push(`--user ${d}:${h}`)}return l.push(`chown -R ${c}:${c} ${ze(n)} /etc/ts-sftp`,`cat > /etc/systemd/system/${s}.service <<TSCLOUD_SFTP_UNIT`,"[Unit]","Description=ts-sftp file transfer server","After=network.target","","[Service]",`User=${c}`,`ExecStart=$BUN_BIN /opt/ts-sftp/node_modules/ts-sftp/dist/bin/cli.js serve --root ${n} --host-key /etc/ts-sftp/host_key --port ${i}${r.readOnly?" --read-only":""} ${p.join(" ")}`,"Restart=always","RestartSec=2","NoNewPrivileges=true","PrivateTmp=true","ProtectSystem=strict",`ReadWritePaths=${n}`,"","[Install]","WantedBy=multi-user.target","TSCLOUD_SFTP_UNIT","systemctl daemon-reload",`systemctl enable ${s}.service`,`systemctl restart ${s}.service`),l}function Qs(e){return e?[qs(e)]:[]}var Qo=[80,443];function vt(e={}){if(e.enabled===!1)return[];let t=[...new Set([...Qo,...e.allowedPorts||[]])].filter((s)=>Number.isInteger(s)&&s>=1&&s<=65535).sort((s,n)=>s-n),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 s of t)r.push(`ufw allow ${s}/tcp`);return r.push("ufw --force enable"),r}function Oe(e,t){let r=e.infrastructure?.compute??{},s=r.runtime==="php"||!!r.php,n=pi(e,{environment:t?.environment}),i=s||!!r.managedServices,o=i?gr():[],a=!Q(r),c=s?[...o,...yt({versions:r.php?.versions,default:r.php?.default,extensions:r.php?.extensions,installNginx:a,optimizeForProduction:r.php?.optimizeForProduction,ini:r.php?.ini}),...a?qt():[]]:void 0,l=[],p=C(e);if(!s&&i)l.push(...o);if(l.push(...ke(e.notifications)),r.managedServices)l.push(...lo(r.managedServices,{mail:n.enabled?n:void 0}),...ht(p,r.managedServices));let d=e.infrastructure?.sftp;if(d)Ys(d,U(e)),l.push(...Js({slug:e.project.slug,sftp:d}));let m=r.firewall??(s?{enabled:!0}:{enabled:!1}),g=$s(n);if(l.push(...vt(g.length>0?{...m,allowedPorts:[...m.allowedPorts??[],...g]}:m)),l.push(...Xs({ddos:r.ddos,waf:r.waf},[...r.firewall?.allowedPorts??[],...g])),l.push(...be(r.autoUpdates??s)),l.push(...Wi(r.appUpdates)),l.push(...we(r.monitoring??s)),l.push(...Ue(r.sshKeys,{path:t?.authorizedKeysPath})),r.backups?.enabled)l.push(...uo({database:p,backups:r.backups}));return{runtime:r.runtime||"bun",runtimeVersion:r.runtimeVersion||"latest",phpBox:s,phpProvision:c,servicesProvision:l.length>0?l:void 0}}function re(e={}){let{runtime:t="bun",runtimeVersion:r="latest",systemPackages:s=[],database:n,phpProvision:i,servicesProvision:o,caddyfile:a,rpxProvision:c,baked:l=!1,swapGb:p=2}=e,d=new Set(s);if(n==="sqlite")d.add("sqlite3");else if(n==="mysql")d.add("mysql-client");else if(n==="postgres")d.add("postgresql-client");let m=`#!/bin/bash
145
145
  set -euo pipefail
146
146
  `,g=Math.floor(p);if(g>0)m+=`
147
147
  # Swap: a swapless box under memory pressure lets the kernel OOM killer choose
@@ -251,11 +251,11 @@ ${h.join(`
251
251
  `)}
252
252
  `}return m+=`
253
253
  echo "ts-cloud bootstrap complete — instance is ready for site deploys"
254
- `,m}var Zs="/aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id";function en(e){let t=[{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"}],r=new Set;for(let s of Object.values(e.sites||{}))if(s&&typeof s.port==="number"&&![22,80,443].includes(s.port))r.add(s.port);for(let s of r)t.push({port:s,protocol:"tcp",cidr:"0.0.0.0/0"});return t}function tn(e){let t=e.infrastructure?.compute??{},r=Oe(e),s=t.proxy?.engine==="rpx"?me({proxy:t.proxy,config:fe(e.sites??{},{proxy:t.proxy,slug:e.project.slug}),slug:e.project.slug,bunBin:t.runtime==="node"||t.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0;return te({runtime:r.runtime,runtimeVersion:r.runtimeVersion,systemPackages:t.systemPackages,database:e.infrastructure?.database,phpProvision:r.phpProvision,servicesProvision:r.servicesProvision,rpxProvision:s,baked:t.bakedImage===!0,swapGb:t.swapGb})}function rn(e){return Buffer.from(e,"utf8").toString("base64")}function sn(e){return e.infrastructure?.compute?.image??null}function bt(e,t){return`${e}-${t}-app-sg`}function ir(e,t,r="app"){return[{Key:"Project",Value:e},{Key:"Environment",Value:t},{Key:"Role",Value:r},{Key:"ManagedBy",Value:"ts-cloud"}]}function Zo(e,t,r){if(!e?.length)return!1;let s=(n)=>e.find((i)=>i.Key===n)?.Value;return s("Project")===t&&s("Environment")===r}function nn(e,t){let r=bt(t.slug,t.environment);return e.find((s)=>{if(s.GroupName!==r)return!1;if(t.vpcId&&s.VpcId&&s.VpcId!==t.vpcId)return!1;if(!!s.Tags?.some((i)=>i.Key==="Project"))return Zo(s.Tags,t.slug,t.environment);return!!t.vpcId&&s.VpcId===t.vpcId})}function ta(e){try{let t=on(ea(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 wt{name="aws";usesCloudFormation=!0;region;ec2Client;cfnClient;constructor(e={}){this.region=e.region||"us-east-1",this.ec2Client=e.ec2Client??((t)=>new K(t)),this.cfnClient=e.cfnClient??((t)=>new v(t))}resolveRegion(e){return e.project.region||this.region}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e,s=this.resolveRegion(t),n=t.project.slug,i=t.infrastructure?.compute;if(!i)throw Error("infrastructure.compute is required to provision AWS compute");let o=this.ec2Client(s),a=await this.findComputeTargets({slug:n,environment:r,role:"app",region:s});if(a.length>0){let R=a[0];return{appInstanceId:R.id,appPublicIp:R.publicIp,appPublicIpv6:R.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}let c=sn(t);if(!c){if(c=(await new We(s).getParameter({Name:Zs})).Parameter?.Value??null,!c)throw Error("Could not resolve the Ubuntu 24.04 AMI from SSM")}let l=await o.describeVpcs(),p=(l.Vpcs||[]).find((R)=>R.IsDefault)||(l.Vpcs||[])[0];if(!p?.VpcId)throw Error("No VPC found to launch the instance into");let d=(await o.describeSubnets({Filters:[{Name:"vpc-id",Values:[p.VpcId]}]})).Subnets||[],m=d.find((R)=>R.MapPublicIpOnLaunch)||d[0],g=m?.SubnetId;if(!m?.MapPublicIpOnLaunch)console.warn("ts-cloud: no public subnet found; the instance may not get a public IP (deploys/SSL need one).");let h=bt(n,r),w=(await o.describeSecurityGroups({Filters:[{Name:"group-name",Values:[h]},{Name:"vpc-id",Values:[p.VpcId]}]})).SecurityGroups?.[0]?.GroupId;if(!w)w=(await o.createSecurityGroup({GroupName:h,Description:`ts-cloud ${n}/${r} app`,VpcId:p.VpcId,TagSpecifications:[{ResourceType:"security-group",Tags:ir(n,r)}]})).GroupId;let b=en(t);await o.authorizeSecurityGroupIngress({GroupId:w,IpPermissions:b.map((R)=>({IpProtocol:R.protocol,FromPort:R.port,ToPort:R.port,IpRanges:[{CidrIp:R.cidr}]}))}).catch((R)=>{if(!/InvalidPermission\.Duplicate/.test(R instanceof Error?R.message:""))throw R});let y=rn(tn(t)),T=i.server?.instanceType||"t3.small",D=(await o.runInstances({ImageId:c,InstanceType:T,MinCount:1,MaxCount:1,SecurityGroupIds:w?[w]:void 0,SubnetId:g,UserData:y,IamInstanceProfile:i.server?.iamInstanceProfile?{Name:i.server.iamInstanceProfile}:void 0,TagSpecifications:[{ResourceType:"instance",Tags:[{Key:"Name",Value:`${n}-${r}-app`},...ir(n,r)]}]})).Instances?.[0]?.InstanceId;if(!D)throw Error("RunInstances did not return an instance id");let O=await o.waitForInstanceState(D,"running");if(!O)throw Error(`Instance ${D} did not reach 'running' before timeout`);return{appInstanceId:D,appPublicIp:O.PublicIpAddress,appPublicIpv6:de(O.Ipv6Address),sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}async destroyCompute(e){let{config:t,environment:r}=e,s=t.project.slug,n=this.resolveRegion(t),i=this.ec2Client(n),o=[],c=(await this.findComputeTargets({slug:s,environment:r,role:"app",region:n})).map((h)=>h.id),l;if(c.length>0)l=(await i.describeInstances({InstanceIds:c}).catch(()=>({Reservations:[]}))).Reservations?.flatMap((_)=>_.Instances??[]).find((_)=>_.VpcId)?.VpcId;if(c.length>0)await i.terminateInstances(c),o.push(...c.map((h)=>`instance ${h}`)),await Promise.all(c.map((h)=>i.waitForInstanceState(h,"terminated").catch(()=>{return})));let p=bt(s,r),d=[{Name:"group-name",Values:[p]}];if(l)d.push({Name:"vpc-id",Values:[l]});let m=await i.describeSecurityGroups({Filters:d}).catch(()=>({SecurityGroups:[]})),g=nn(m.SecurityGroups??[],{slug:s,environment:r,vpcId:l});if(g?.GroupId)for(let h=0;h<10;h++)try{await i.deleteSecurityGroup(g.GroupId),o.push(`security group ${p}`);break}catch{await new Promise((_)=>setTimeout(_,3000))}return{destroyed:o}}async getComputeOutputs(e){let t=this.resolveRegion(e.config),r=E(e.config,e.environment),s=this.cfnClient(t);try{let n=await s.getStackOutputs(r);return{deployBucketName:n.deployBucketName,appInstanceId:n.appInstanceId,appPublicIp:n.appPublicIp,sshUser:"ec2-user"}}catch(n){if(!/does not exist|ValidationError/i.test(n instanceof Error?n.message:""))throw n;let o=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",region:t}))[0];return{appInstanceId:o?.id,appPublicIp:o?.publicIp,appPublicIpv6:o?.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}}async uploadRelease(e){let t=this.resolveRegion(e.config),s=(await this.getComputeOutputs({config:e.config,environment:e.environment})).deployBucketName;if(!s)throw Error("No deployBucketName in stack outputs. Re-deploy infrastructure to add the staging bucket.");return await new f(t).putObject({bucket:s,key:e.remoteKey,body:on(e.localPath),contentType:"application/gzip"}),{artifactRef:`s3://${s}/${e.remoteKey}`}}async findComputeTargets(e){let t=e.region??this.region,r=this.ec2Client(t),s=[{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"]}],n=await r.describeInstances({Filters:s}),i=this.reservationsToTargets(n.Reservations);if(i.length>0||(e.role||"app")!=="app")return i;let o=e.stackName??`${e.slug}-${e.environment}`,a=ta(o);if(!a)try{a=(await this.cfnClient(t).getStackOutputs(o)).appInstanceId??null}catch{a=null}if(!a)return[];try{let c=await r.describeInstances({InstanceIds:[a],Filters:[{Name:"instance-state-name",Values:["running","pending"]}]});return this.reservationsToTargets(c.Reservations)}catch{return[]}}reservationsToTargets(e){let t=[];for(let r of e||[])for(let s of r.Instances||[]){if(!s.InstanceId)continue;let n=s.Tags?.find((i)=>i.Key==="Name")?.Value;t.push({id:s.InstanceId,name:n,publicIp:s.PublicIpAddress,publicIpv6:de(s.Ipv6Address),privateIp:s.PrivateIpAddress,status:s.State?.Name})}return t}bashWrap(e){return["bash <<'TS_CLOUD_BASH_EOF'",e.join(`
254
+ `,m}var Zs="/aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id";function en(e){let t=[{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"}],r=new Set;for(let s of Object.values(e.sites||{}))if(s&&typeof s.port==="number"&&![22,80,443].includes(s.port))r.add(s.port);for(let s of r)t.push({port:s,protocol:"tcp",cidr:"0.0.0.0/0"});return t}function tn(e){let t=e.infrastructure?.compute??{},r=Oe(e),s=t.proxy?.engine==="rpx"?ge({proxy:t.proxy,config:fe(e.sites??{},{proxy:t.proxy,slug:e.project.slug}),slug:e.project.slug,bunBin:t.runtime==="node"||t.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0;return re({runtime:r.runtime,runtimeVersion:r.runtimeVersion,systemPackages:t.systemPackages,database:e.infrastructure?.database,phpProvision:r.phpProvision,servicesProvision:r.servicesProvision,rpxProvision:s,baked:t.bakedImage===!0,swapGb:t.swapGb})}function rn(e){return Buffer.from(e,"utf8").toString("base64")}function sn(e){return e.infrastructure?.compute?.image??null}function bt(e,t){return`${e}-${t}-app-sg`}function ir(e,t,r="app"){return[{Key:"Project",Value:e},{Key:"Environment",Value:t},{Key:"Role",Value:r},{Key:"ManagedBy",Value:"ts-cloud"}]}function Zo(e,t,r){if(!e?.length)return!1;let s=(n)=>e.find((i)=>i.Key===n)?.Value;return s("Project")===t&&s("Environment")===r}function nn(e,t){let r=bt(t.slug,t.environment);return e.find((s)=>{if(s.GroupName!==r)return!1;if(t.vpcId&&s.VpcId&&s.VpcId!==t.vpcId)return!1;if(!!s.Tags?.some((i)=>i.Key==="Project"))return Zo(s.Tags,t.slug,t.environment);return!!t.vpcId&&s.VpcId===t.vpcId})}function ta(e){try{let t=on(ea(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 wt{name="aws";usesCloudFormation=!0;region;ec2Client;cfnClient;constructor(e={}){this.region=e.region||"us-east-1",this.ec2Client=e.ec2Client??((t)=>new K(t)),this.cfnClient=e.cfnClient??((t)=>new v(t))}resolveRegion(e){return e.project.region||this.region}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e,s=this.resolveRegion(t),n=t.project.slug,i=t.infrastructure?.compute;if(!i)throw Error("infrastructure.compute is required to provision AWS compute");let o=this.ec2Client(s),a=await this.findComputeTargets({slug:n,environment:r,role:"app",region:s});if(a.length>0){let R=a[0];return{appInstanceId:R.id,appPublicIp:R.publicIp,appPublicIpv6:R.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}let c=sn(t);if(!c){if(c=(await new We(s).getParameter({Name:Zs})).Parameter?.Value??null,!c)throw Error("Could not resolve the Ubuntu 24.04 AMI from SSM")}let l=await o.describeVpcs(),p=(l.Vpcs||[]).find((R)=>R.IsDefault)||(l.Vpcs||[])[0];if(!p?.VpcId)throw Error("No VPC found to launch the instance into");let d=(await o.describeSubnets({Filters:[{Name:"vpc-id",Values:[p.VpcId]}]})).Subnets||[],m=d.find((R)=>R.MapPublicIpOnLaunch)||d[0],g=m?.SubnetId;if(!m?.MapPublicIpOnLaunch)console.warn("ts-cloud: no public subnet found; the instance may not get a public IP (deploys/SSL need one).");let h=bt(n,r),w=(await o.describeSecurityGroups({Filters:[{Name:"group-name",Values:[h]},{Name:"vpc-id",Values:[p.VpcId]}]})).SecurityGroups?.[0]?.GroupId;if(!w)w=(await o.createSecurityGroup({GroupName:h,Description:`ts-cloud ${n}/${r} app`,VpcId:p.VpcId,TagSpecifications:[{ResourceType:"security-group",Tags:ir(n,r)}]})).GroupId;let b=en(t);await o.authorizeSecurityGroupIngress({GroupId:w,IpPermissions:b.map((R)=>({IpProtocol:R.protocol,FromPort:R.port,ToPort:R.port,IpRanges:[{CidrIp:R.cidr}]}))}).catch((R)=>{if(!/InvalidPermission\.Duplicate/.test(R instanceof Error?R.message:""))throw R});let y=rn(tn(t)),T=i.server?.instanceType||"t3.small",D=(await o.runInstances({ImageId:c,InstanceType:T,MinCount:1,MaxCount:1,SecurityGroupIds:w?[w]:void 0,SubnetId:g,UserData:y,IamInstanceProfile:i.server?.iamInstanceProfile?{Name:i.server.iamInstanceProfile}:void 0,TagSpecifications:[{ResourceType:"instance",Tags:[{Key:"Name",Value:`${n}-${r}-app`},...ir(n,r)]}]})).Instances?.[0]?.InstanceId;if(!D)throw Error("RunInstances did not return an instance id");let O=await o.waitForInstanceState(D,"running");if(!O)throw Error(`Instance ${D} did not reach 'running' before timeout`);return{appInstanceId:D,appPublicIp:O.PublicIpAddress,appPublicIpv6:de(O.Ipv6Address),sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}async destroyCompute(e){let{config:t,environment:r}=e,s=t.project.slug,n=this.resolveRegion(t),i=this.ec2Client(n),o=[],c=(await this.findComputeTargets({slug:s,environment:r,role:"app",region:n})).map((h)=>h.id),l;if(c.length>0)l=(await i.describeInstances({InstanceIds:c}).catch(()=>({Reservations:[]}))).Reservations?.flatMap((_)=>_.Instances??[]).find((_)=>_.VpcId)?.VpcId;if(c.length>0)await i.terminateInstances(c),o.push(...c.map((h)=>`instance ${h}`)),await Promise.all(c.map((h)=>i.waitForInstanceState(h,"terminated").catch(()=>{return})));let p=bt(s,r),d=[{Name:"group-name",Values:[p]}];if(l)d.push({Name:"vpc-id",Values:[l]});let m=await i.describeSecurityGroups({Filters:d}).catch(()=>({SecurityGroups:[]})),g=nn(m.SecurityGroups??[],{slug:s,environment:r,vpcId:l});if(g?.GroupId)for(let h=0;h<10;h++)try{await i.deleteSecurityGroup(g.GroupId),o.push(`security group ${p}`);break}catch{await new Promise((_)=>setTimeout(_,3000))}return{destroyed:o}}async getComputeOutputs(e){let t=this.resolveRegion(e.config),r=E(e.config,e.environment),s=this.cfnClient(t);try{let n=await s.getStackOutputs(r);return{deployBucketName:n.deployBucketName,appInstanceId:n.appInstanceId,appPublicIp:n.appPublicIp,sshUser:"ec2-user"}}catch(n){if(!/does not exist|ValidationError/i.test(n instanceof Error?n.message:""))throw n;let o=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",region:t}))[0];return{appInstanceId:o?.id,appPublicIp:o?.publicIp,appPublicIpv6:o?.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}}async uploadRelease(e){let t=this.resolveRegion(e.config),s=(await this.getComputeOutputs({config:e.config,environment:e.environment})).deployBucketName;if(!s)throw Error("No deployBucketName in stack outputs. Re-deploy infrastructure to add the staging bucket.");return await new f(t).putObject({bucket:s,key:e.remoteKey,body:on(e.localPath),contentType:"application/gzip"}),{artifactRef:`s3://${s}/${e.remoteKey}`}}async findComputeTargets(e){let t=e.region??this.region,r=this.ec2Client(t),s=[{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"]}],n=await r.describeInstances({Filters:s}),i=this.reservationsToTargets(n.Reservations);if(i.length>0||(e.role||"app")!=="app")return i;let o=e.stackName??`${e.slug}-${e.environment}`,a=ta(o);if(!a)try{a=(await this.cfnClient(t).getStackOutputs(o)).appInstanceId??null}catch{a=null}if(!a)return[];try{let c=await r.describeInstances({InstanceIds:[a],Filters:[{Name:"instance-state-name",Values:["running","pending"]}]});return this.reservationsToTargets(c.Reservations)}catch{return[]}}reservationsToTargets(e){let t=[];for(let r of e||[])for(let s of r.Instances||[]){if(!s.InstanceId)continue;let n=s.Tags?.find((i)=>i.Key==="Name")?.Value;t.push({id:s.InstanceId,name:n,publicIp:s.PublicIpAddress,publicIpv6:de(s.Ipv6Address),privateIp:s.PrivateIpAddress,status:s.State?.Name})}return t}bashWrap(e){return["bash <<'TS_CLOUD_BASH_EOF'",e.join(`
255
255
  `),"TS_CLOUD_BASH_EOF"]}async runRemoteDeploy(e){let t=this.region,r=new We(t);if(e.targets.length>0){let n=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(!n.CommandId)return{success:!1,instanceCount:0,perInstance:[],error:"Failed to send SSM command"};return this.pollSsmCommand(r,n.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 s=await r.sendCommandByTags({tags:e.tags,commands:this.bashWrap(e.commands),timeoutSeconds:e.timeoutSeconds||600,comment:e.comment});return{success:s.success,instanceCount:s.instanceCount,perInstance:s.perInstance.map((n)=>({instanceId:n.instanceId,status:n.status,output:n.output,error:n.error})),error:s.error}}async pollSsmCommand(e,t,r,s=600000){let i=Date.now(),o=new Set(["Success","Failed","Cancelled","TimedOut"]),a=[];while(Date.now()-i<s){await new Promise((p)=>setTimeout(p,3000));try{if(a=await e.listCommandInvocations({CommandId:t,Details:!0}),a.length>=r&&a.every((d)=>o.has(d.Status||"")))break}catch{}}let c=a.map((p)=>({instanceId:p.InstanceId,status:p.Status||"Unknown",output:p.StandardOutputContent,error:p.StandardErrorContent})),l=c.length>0&&c.every((p)=>p.status==="Success");return{success:l,instanceCount:c.length,perInstance:c,error:l?void 0:Ie(c,"One or more SSM command invocations failed")}}}function an(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 or(e,t,r={}){let s=Bun.spawn(["ssh",...an(r),`${r.user??"root"}@${e}`,t],{stdout:"pipe",stderr:"pipe"}),[n,i]=await Promise.all([new Response(s.stdout).text(),new Response(s.stderr).text()]);return{code:await s.exited,stdout:n,stderr:i}}async function Re(e,t,r={}){let s=await or(e,t,r);if(s.code!==0)throw Error(`ssh \`${t}\` on ${e} failed (${s.code}): ${s.stderr.trim()||s.stdout.trim()}`);return s.stdout}async function fr(e,t={}){let r=t.timeoutMs??180000,s=t.pollIntervalMs??5000,n=Date.now();while(Date.now()-n<r){let i=await or(e,"echo ready",t);if(i.code===0&&i.stdout.includes("ready"))return;await new Promise((o)=>setTimeout(o,s))}throw Error(`SSH not ready on ${e} after ${r}ms`)}function nt(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(`
256
256
  `)}var hr=nt();import{execFileSync as pa,execSync as mn}from"node:child_process";import{createHash as da,randomUUID as fn}from"node:crypto";import{createReadStream as ma,existsSync as fa,readFileSync as ga}from"node:fs";function cn(e={}){let t=Math.max(1,e.appServers??e.instances??1),r=!!e.servicesServer||t>1,s=t>1||!!e.server?.loadBalancer;return{appServers:t,loadBalancer:s,dedicatedServices:r,servicesOnApp:!r}}function ln(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 yr(e){let t=e.infrastructure?.compute??{},r=C(e);return[...lo(t.managedServices??{mysql:!0,redis:!0},{bindPrivate:!0}),...ht(r,t.managedServices??{mysql:!0}),...be(!0),...we(!0),...Ue(t.sshKeys),...ke(e.notifications),...t.backups?.enabled?[...uo({database:r,backups:t.backups})]:[]]}import{homedir as ra}from"node:os";import{join as sa}from"node:path";var $t={location:"fsn1",image:"ubuntu-24.04",sshUser:"root",sshPrivateKeyPath:"~/.ssh/id_ed25519"};function zr(e){return e.startsWith("~/")?sa(ra(),e.slice(2)):e}function Fe(...e){for(let t of e){let r=process.env[t]?.trim();if(r)return r}return}function Be(...e){for(let t of e){let r=t?.trim();if(r)return r}return}function it(e,t){return Be(e,t?.hetzner?.apiToken,Fe("HCLOUD_TOKEN","HETZNER_API_TOKEN"))}function Sr(e,t){return Be(t,e?.hetzner?.location,Fe("HCLOUD_LOCATION","HETZNER_LOCATION"))??$t.location}function ot(e,t){let r=e?.infrastructure?.compute;return Be(t,r?.image,e?.hetzner?.image,Fe("HCLOUD_IMAGE","HETZNER_IMAGE"))??$t.image}function na(e,t){return Be(t,e?.hetzner?.sshUser,Fe("HCLOUD_SSH_USER","HETZNER_SSH_USER"))??$t.sshUser}function un(e,t){return zr(Be(t,e?.hetzner?.sshPrivateKeyPath,Fe("HCLOUD_SSH_KEY","HETZNER_SSH_KEY"))??$t.sshPrivateKeyPath)}function ia(e,t,r){let s=Be(t,e?.hetzner?.sshPublicKeyPath,Fe("HCLOUD_SSH_PUBLIC_KEY","HETZNER_SSH_PUBLIC_KEY"));if(s)return zr(s);return`${r??un(e)}.pub`}function sr(e,t={}){let r=un(e,t.sshPrivateKeyPath);return{apiToken:it(t.apiToken,e),location:Sr(e,t.location),image:ot(e,t.image),sshUser:na(e,t.sshUser),sshPrivateKeyPath:r,sshPublicKeyPath:ia(e,t.sshPublicKeyPath,r)}}var oa="https://api.hetzner.cloud/v1";class _t extends Error{status;code;details;constructor(e,t,r,s){super(e);this.status=t;this.code=r;this.details=s;this.name="HetznerApiError"}}class Tt extends Error{action;constructor(e,t){super(e);this.action=t;this.name="HetznerActionError"}}class Ke{name="hetzner";apiToken;baseUrl;fetchImpl;constructor(e){this.apiToken=e.apiToken,this.baseUrl=e.baseUrl??oa,this.fetchImpl=e.fetchImpl??fetch}async request(e,t,r){let s=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)}),n=await s.text(),i;try{i=n?JSON.parse(n):{}}catch{if(!s.ok){let o=n.trim().slice(0,200)||s.statusText||"Hetzner API error";throw Error(`Hetzner API ${e} ${t} (${s.status}): ${o}`)}throw Error(`Hetzner API ${e} ${t}: unexpected non-JSON response`)}if(!s.ok){let o=i.error?.message||s.statusText||"Hetzner API error",a=i.error?.code?` [${i.error.code}]`:"";throw new _t(`Hetzner API ${e} ${t} (${s.status})${a}: ${o}`,s.status,i.error?.code,i.error?.details)}return i}async requestAll(e,t){let r=[],s=1;for(;;){let n=e.includes("?")?"&":"?",i=await this.request("GET",`${e}${n}per_page=50&page=${s}`);r.push(...i[t]??[]);let o=i.meta?.pagination?.next_page;if(!o)return r;s=o}}async listServers(){return this.requestAll("/servers","servers")}async getServer(e){return(await this.request("GET",`/servers/${e}`)).server}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 s=t?.gracefulWaitMs??120000,n=t?.pollIntervalMs??3000,i=Date.now();while(Date.now()-i<s){if((await this.getServer(e)).status==="off")return;await new Promise((a)=>setTimeout(a,n))}let o=await this.powerOffServer(e);await this.waitForAction(o.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,s=t?.maxWaitMs??300000,n=Date.now();while(Date.now()-n<s){let i=await this.getAction(e);if(i.status==="success")return i;if(i.status==="error")throw new Tt(i.error?.message||"Hetzner action failed",i);await new Promise((o)=>setTimeout(o,r))}throw Error(`Timed out waiting for Hetzner action ${e}`)}async waitForServerRunning(e,t){let r=t?.pollIntervalMs??3000,s=t?.maxWaitMs??600000,n=Date.now();while(Date.now()-n<s){let i=await this.getServer(e);if(i.status==="running")return i;await new Promise((o)=>setTimeout(o,r))}throw Error(`Timed out waiting for server ${e} to reach running state`)}async waitForServerStatus(e,t,r){let s=r?.pollIntervalMs??3000,n=r?.maxWaitMs??600000,i=Date.now();while(Date.now()-i<n){let o=await this.getServer(e);if(o.status===t)return o;await new Promise((a)=>setTimeout(a,s))}throw Error(`Timed out waiting for server ${e} to reach ${t} state`)}}function ar(e,t){let r=it(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 at(e){let[t,r]=e.trim().split(/\s+/);return r?`${t} ${r}`:t}function pn(e){if(!e)return"";return e.endsWith(`
257
257
  `)?e:`${e}
258
- `}function ge(e,t={}){let r=t.scriptPath??"/var/lib/cloud/ts-cloud-bootstrap.sh",s=t.permissions??"0755",n=e.split(`
258
+ `}function he(e,t={}){let r=t.scriptPath??"/var/lib/cloud/ts-cloud-bootstrap.sh",s=t.permissions??"0755",n=e.split(`
259
259
  `).map((i)=>` ${i}`).join(`
260
260
  `);return`#cloud-config
261
261
  ${pn(t.before)}write_files:
@@ -266,12 +266,12 @@ ${pn(t.before)}write_files:
266
266
  ${n}
267
267
  runcmd:
268
268
  - [ bash, ${r} ]
269
- ${pn(t.after)}`}function qr(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 vr={micro:"cpx11",small:"cx23",medium:"cx33",large:"cx43",xlarge:"cx53","2xlarge":"ccx33"};function pt(e){if(!e)return vr.micro;if(e in vr)return vr[e];return e}var B="ts-cloud";function j(e,t,r="app"){return{[`${B}/project`]:e,[`${B}/environment`]:t,[`${B}/role`]:r,[`${B}/managed-by`]:"ts-cloud"}}function re(e,t,r,s="app"){return br(e,t,r)&&e[`${B}/role`]===s}function br(e,t,r){if(!e)return!1;return e[`${B}/project`]===t&&e[`${B}/environment`]===r}import{mkdir as aa,readFile as ca,rename as la,writeFile as ua}from"node:fs/promises";import{join as dn}from"node:path";var wr="storage/cloud/state";function _e(e=process.cwd()){return xs()?A(e,"state"):dn(e,wr)}function je(e,t=process.cwd()){return dn(_e(t),`${e}.json`)}async function De(e,t=process.cwd()){try{let r=await ca(je(e,t),"utf8");return JSON.parse(r)}catch{return null}}async function Ve(e,t,r=process.cwd()){let s=je(e,r);await aa(_e(r),{recursive:!0});let n=`${s}.${process.pid}.tmp`;await ua(n,`${JSON.stringify(t,null,2)}
270
- `,"utf8"),await la(n,s)}async function ue(e){return De(e)}async function mt(e,t){await Ve(e,t)}var $r=268435456;function ce(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function ha(e){let t=da("sha256");for await(let r of ma(e))t.update(r);return t.digest("hex")}class Te{name="hetzner";usesCloudFormation=!1;client;sshPrivateKeyPath;sshPublicKeyPath;sshUser;location;stateOnly;waitForBoot;bootWait;constructor(e={}){let t=it(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 Ke({apiToken:t??""});let r=sr(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,s=t.project.slug,n=t.infrastructure?.compute;if(!n)throw Error("infrastructure.compute is required to provision Hetzner compute");if(t.cloud?.attachTo)return this.attachToComputeInfrastructure(t.cloud.attachTo,t,r);let i=E(t,r),o=`${s}-${r}-app`,a=n.runtime==="php"||!!n.php,c=cn(n);if(c.dedicatedServices||c.appServers>1)return a?this.provisionFleet(e,c):this.provisionBunFleet(e,c);let l=j(s,r,"app"),p=t.sites||{},d=Q(n)?[]:this.collectUpstreamPorts(p),m=`${s}-${r}-app-fw`,{firewall:g}=await this.ensureFirewall(m,l,qr({allowSsh:n.allowSsh!==!1,sitePorts:d,allowedPorts:[...n.firewall?.allowedPorts??[],...Qs(t.infrastructure?.sftp)]})),h=await this.ensureSshKey(s,r,l),_=await ue(i);if(_?.serverId){let F=await this.tryGetServer(_.serverId);if(F&&F.status!=="off")return this.outputsFromState(_,F)}let w=await this.findExistingServer(s,r,o);if(w&&w.status!=="off"){let F={provider:"hetzner",stackName:i,serverId:w.id,serverName:w.name,publicIp:w.public_net.ipv4?.ip,publicIpv6:de(w.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await mt(i,F),this.outputsFromState(F,w)}let b=n.proxy?.engine==="rpx"?me({proxy:n.proxy,config:fe(p,{proxy:n.proxy,slug:t.project.slug}),slug:t.project.slug,bunBin:n.runtime==="node"||n.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,y=Oe(t,{environment:r}),T=n.bakedImage===!0,S=te({runtime:y.runtime,runtimeVersion:y.runtimeVersion,systemPackages:n.systemPackages,database:t.infrastructure?.database,phpProvision:y.phpProvision,servicesProvision:y.servicesProvision,rpxProvision:b,baked:T,swapGb:n.swapGb}),D=ge(S),O=pt(n.size),R=ot(t),{server:k,action:se}=await this.client.createServer({name:o,serverType:O,image:R,location:t.hetzner?.location||this.location,userData:D,labels:l,sshKeys:h?[h]:void 0,firewalls:[{firewall:g.id}]});await this.client.waitForAction(se.id);let z=await this.client.waitForServerRunning(k.id),X={provider:"hetzner",stackName:i,serverId:z.id,serverName:z.name,firewallId:g.id,publicIp:z.public_net.ipv4?.ip,publicIpv6:de(z.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};await mt(i,X);let q=z.public_net.ipv4?.ip;if(q&&this.waitForBoot)await this.waitForSshReady(q),await this.waitForCloudInit(q);return this.outputsFromState(X,z)}async provisionFleet(e,t){let{config:r,environment:s}=e,n=r.project.slug,i=r.infrastructure.compute,o=E(r,s),a=pt(i.size),c=ot(r),l=r.hetzner?.location||this.location,p=i.bakedImage===!0,d=await ue(o);if(d?.loadBalancerId){let G=(await this.client.listLoadBalancers().catch(()=>[])).find((I)=>I.id===d.loadBalancerId);if(G)return{appPublicIp:G.public_net?.ipv4?.ip,loadBalancerIp:G.public_net?.ipv4?.ip,servicesPrivateIp:d.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}let m=await this.ensureSshKey(n,s,j(n,s,"app")),g=`${n}-${s}-net`,_=(await this.client.listNetworks().catch(()=>[])).find((N)=>N.name===g)??await this.client.createNetwork({name:g,labels:j(n,s,"app")}),{firewall:w}=await this.ensureFirewall(`${n}-${s}-app-fw`,j(n,s,"app"),qr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),{firewall:b}=await this.ensureFirewall(`${n}-${s}-services-fw`,j(n,s,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[_.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[_.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[_.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[_.ip_range]}]),y=yr(r),T=ge(te({runtime:"php",servicesProvision:y,baked:p,swapGb:i.swapGb})),S=await this.client.listServers().catch(()=>[]),D=[],O=S.find((N)=>re(N.labels,n,s,"services"));if(!O){let{server:N,action:G}=await this.client.createServer({name:`${n}-${s}-services`,serverType:pt(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:c,location:l,userData:T,labels:j(n,s,"services"),sshKeys:m?[m]:void 0,firewalls:[{firewall:b.id}],networks:[_.id]});await this.client.waitForAction(G.id),O=await this.client.waitForServerRunning(N.id),D.push(N.id)}let R=O.id,k=O.private_net?.[0]?.ip??(await this.client.getServer(R)).private_net?.[0]?.ip,se=[...be(!0),...we(!0),...Ue(i.sshKeys),...ke(r.notifications)],z=yt({versions:i.php?.versions,default:i.php?.default,extensions:i.php?.extensions,installNginx:!Q(i),optimizeForProduction:i.php?.optimizeForProduction,ini:i.php?.ini}),X=ge(te({runtime:"php",phpProvision:z,servicesProvision:se,baked:p,swapGb:i.swapGb})),q=S.filter((N)=>re(N.labels,n,s,"app")),F=q.map((N)=>N.id);if(q.length>t.appServers)for(let N of q.slice(t.appServers))await this.client.deleteServer(N.id).catch(()=>{}),F.splice(F.indexOf(N.id),1);for(let N=q.length;N<t.appServers;N++){let{server:G,action:I}=await this.client.createServer({name:`${n}-${s}-app-${N+1}`,serverType:a,image:c,location:l,userData:X,labels:j(n,s,"app"),sshKeys:m?[m]:void 0,firewalls:[{firewall:w.id}],networks:[_.id]});await this.client.waitForAction(I.id),F.push(G.id),D.push(G.id)}if(this.waitForBoot&&D.length>0)await Promise.all(D.map(async(N)=>{let I=(await this.client.waitForServerRunning(N)).public_net.ipv4?.ip;if(I)await this.waitForSshReady(I),await this.waitForCloudInit(I)}));let ee=`${n}-${s}-lb`,H,he;if(t.loadBalancer){let G=(await this.client.listLoadBalancers().catch(()=>[])).find((I)=>I.name===ee)??await this.client.createLoadBalancer({name:ee,location:l,network:_.id,labels:j(n,s,"lb"),labelSelector:`ts-cloud/project=${n},ts-cloud/environment=${s},ts-cloud/role=app`,services:[{listenPort:80,destinationPort:80},{listenPort:443,destinationPort:443}]});he=G.id,H=G.public_net?.ipv4?.ip}let Y=H??(await this.client.getServer(F[0]).catch(()=>{return}))?.public_net.ipv4?.ip,pe={provider:"hetzner",stackName:o,networkId:_.id,loadBalancerId:he,servicesServerId:R,servicesPrivateIp:k,publicIp:Y,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await mt(o,pe),{appPublicIp:Y,loadBalancerIp:H,servicesPrivateIp:k,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async provisionBunFleet(e,t){let{config:r,environment:s}=e,n=r.project.slug,i=r.infrastructure.compute,o=E(r,s),a=pt(i.size),c=ot(r),l=r.hetzner?.location||this.location,p=i.bakedImage===!0,d=r.sites||{},m=await ue(o);if(m?.lbServerId){let I=await this.tryGetServer(m.lbServerId);if(I&&I.status!=="off"){let L=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"},V=await this.findComputeTargets({slug:n,environment:s,role:"app",stackName:o});return this.refreshLbRoutes(I,d,V.map((oe)=>({privateIp:oe.privateIp,publicIp:oe.publicIp})),L,n),{appPublicIp:I.public_net.ipv4?.ip??m.publicIp,loadBalancerIp:I.public_net.ipv4?.ip??m.publicIp,servicesPrivateIp:m.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}}let g=await this.ensureSshKey(n,s,j(n,s,"app")),h=`${n}-${s}-net`,w=(await this.client.listNetworks().catch(()=>[])).find((I)=>I.name===h)??await this.client.createNetwork({name:h,labels:j(n,s,"app")}),b=this.collectUpstreamPorts(d),{firewall:y}=await this.ensureFirewall(`${n}-${s}-app-fw`,j(n,s,"app"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},...b.map((I)=>({direction:"in",protocol:"tcp",port:String(I),source_ips:[w.ip_range],description:`ts-cloud port ${I} (private, LB-only)`}))]),{firewall:T}=await this.ensureFirewall(`${n}-${s}-lb-fw`,j(n,s,"lb"),qr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),S=await this.client.listServers().catch(()=>[]),D=[],O,R,k=!!i.servicesServer||!!i.managedServices,se=t.dedicatedServices&&k;if(se){let{firewall:I}=await this.ensureFirewall(`${n}-${s}-services-fw`,j(n,s,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[w.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[w.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[w.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[w.ip_range]}]),L=yr(r),V=ge(te({runtime:"bun",servicesProvision:L,baked:p,swapGb:i.swapGb})),oe=S.find((ve)=>re(ve.labels,n,s,"services"));if(!oe){let{server:ve,action:Ze}=await this.client.createServer({name:`${n}-${s}-services`,serverType:pt(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:c,location:l,userData:V,labels:j(n,s,"services"),sshKeys:g?[g]:void 0,firewalls:[{firewall:I.id}],networks:[w.id]});await this.client.waitForAction(Ze.id),oe=await this.client.waitForServerRunning(ve.id),D.push(ve.id)}O=oe.id,R=oe.private_net?.[0]?.ip??(await this.client.getServer(O)).private_net?.[0]?.ip}let z=se?{...i,managedServices:void 0,backups:void 0}:i,X=Oe({...r,infrastructure:{...r.infrastructure,compute:z}},{environment:s}),q=ge(te({runtime:X.runtime,runtimeVersion:X.runtimeVersion,systemPackages:i.systemPackages,database:r.infrastructure?.database,servicesProvision:X.servicesProvision,baked:p,swapGb:i.swapGb})),F=S.filter((I)=>re(I.labels,n,s,"app")),ee=F.map((I)=>I.id);if(F.length>t.appServers)for(let I of F.slice(t.appServers))await this.client.deleteServer(I.id).catch(()=>{}),ee.splice(ee.indexOf(I.id),1);for(let I=F.length;I<t.appServers;I++){let{server:L,action:V}=await this.client.createServer({name:`${n}-${s}-app-${I+1}`,serverType:a,image:c,location:l,userData:q,labels:j(n,s,"app"),sshKeys:g?[g]:void 0,firewalls:[{firewall:y.id}],networks:[w.id]});await this.client.waitForAction(V.id),ee.push(L.id),D.push(L.id)}if(this.waitForBoot&&D.length>0)await Promise.all(D.map(async(I)=>{let V=(await this.client.waitForServerRunning(I)).public_net.ipv4?.ip;if(V)await this.waitForSshReady(V),await this.waitForCloudInit(V)}));let H=[];for(let I of ee){let L=S.find((V)=>V.id===I);if(!L||!L.private_net?.[0]?.ip)L=await this.client.getServer(I).catch(()=>L);H.push({privateIp:L?.private_net?.[0]?.ip,publicIp:L?.public_net.ipv4?.ip})}let he=`${n}-${s}-lb`,Y,pe;if(t.loadBalancer){let I=S.find((V)=>re(V.labels,n,s,"lb")),L=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"};if(!I){let V=me({proxy:L,config:Me(d,H,{proxy:L,slug:n}),slug:n,bunBin:X.runtime==="node"||X.runtime==="deno"?void 0:"/usr/local/bin/bun"}),oe=ge(te({runtime:"bun",rpxProvision:V,baked:!1})),ve=typeof i.loadBalancer==="object"?i.loadBalancer.size:void 0,{server:Ze,action:Kt}=await this.client.createServer({name:he,serverType:pt(ve??"micro"),image:c,location:l,userData:oe,labels:j(n,s,"lb"),sshKeys:g?[g]:void 0,firewalls:[{firewall:T.id}],networks:[w.id]});if(await this.client.waitForAction(Kt.id),I=await this.client.waitForServerRunning(Ze.id),this.waitForBoot){let et=I.public_net.ipv4?.ip;if(et)await this.waitForSshReady(et),await this.waitForCloudInit(et)}}else this.refreshLbRoutes(I,d,H,L,n);Y=I.id,pe=I.public_net.ipv4?.ip}let N=pe??(await this.client.getServer(ee[0]).catch(()=>{return}))?.public_net.ipv4?.ip,G={provider:"hetzner",stackName:o,networkId:w.id,lbServerId:Y,appServerIds:ee,servicesServerId:O,servicesPrivateIp:R,publicIp:N,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await mt(o,G),{appPublicIp:N,loadBalancerIp:pe,servicesPrivateIp:R,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async destroyCompute(e){let{config:t,environment:r}=e,s=t.project.slug,n=E(t,r),i=await ue(n),o=[],a=`${s}-${r}-lb`,l=(await this.client.listLoadBalancers().catch(()=>[])).find((y)=>y.name===a);if(l)try{await this.client.deleteLoadBalancer(l.id),o.push(`load balancer ${a}`)}catch{}let p=await this.client.listServers().catch(()=>[]),d=new Set;for(let y of p)if(re(y.labels,s,r,"app")||re(y.labels,s,r,"services")||re(y.labels,s,r,"lb"))d.add(y.id);if(i?.serverId)d.add(i.serverId);if(i?.servicesServerId)d.add(i.servicesServerId);if(i?.lbServerId)d.add(i.lbServerId);for(let y of i?.appServerIds??[])d.add(y);for(let y of d)try{await this.client.deleteServer(y),o.push(`server ${y}`)}catch{}let m=await this.client.listFirewalls().catch(()=>[]);for(let y of[`${s}-${r}-app-fw`,`${s}-${r}-services-fw`,`${s}-${r}-lb-fw`]){let T=m.find((S)=>S.name===y);if(!T)continue;for(let S=0;S<12;S++)try{await this.client.deleteFirewall(T.id),o.push(`firewall ${y}`);break}catch{await this.sleep(3000)}}let g=`${s}-${r}-net`,_=(await this.client.listNetworks().catch(()=>[])).find((y)=>y.name===g);if(_)for(let y=0;y<12;y++)try{await this.client.deleteNetwork(_.id),o.push(`network ${g}`);break}catch{await this.sleep(3000)}let b=(await this.client.listSshKeys().catch(()=>[])).filter((y)=>br(y.labels,s,r));for(let y of b)try{await this.client.deleteSshKey(y.id),o.push(`ssh key ${y.name}`)}catch{}return await mt(n,{provider:"hetzner",stackName:n}).catch(()=>{}),{destroyed:o}}async getComputeOutputs(e){let t=E(e.config,e.environment),r=await ue(t);if(r?.serverId){let i=await this.tryGetServer(r.serverId);if(i)return this.outputsFromState(r,i)}if(r?.lbServerId){let o=(await this.tryGetServer(r.lbServerId))?.public_net.ipv4?.ip??r.publicIp;return{...this.outputsFromState(r),appPublicIp:o,loadBalancerIp:o}}if(r?.loadBalancerId||r?.servicesPrivateIp)return this.outputsFromState(r);let n=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:E(e.config,e.environment)}))[0];return{deployStoragePath:"/var/ts-cloud/staging",appInstanceId:n?.id,appPublicIp:n?.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:E(e.config,e.environment)});if(t.length===0)throw Error("No Hetzner compute targets found for release upload");let n=`/var/ts-cloud/staging/${`${e.remoteKey.replace(/^releases\//,"").replace(/\.tar\.gz$/,"").replace(/\//g,"-")}-${fn()}.tar.gz`}`,i=await ha(e.localPath),o="/var/ts-cloud/artifacts",a=`${o}/${i}.tar.gz`;for(let c of t){if(!c.publicIp)throw Error(`Target ${c.id} has no public IP for SCP upload`);let l=["set -euo pipefail",`mkdir -p ${ce(o)} /var/ts-cloud/staging`,`test -s ${ce(a)}`,`cp -- ${ce(a)} ${ce(n)}`].join(`
269
+ ${pn(t.after)}`}function qr(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 vr={micro:"cpx11",small:"cx23",medium:"cx33",large:"cx43",xlarge:"cx53","2xlarge":"ccx33"};function pt(e){if(!e)return vr.micro;if(e in vr)return vr[e];return e}var B="ts-cloud";function j(e,t,r="app"){return{[`${B}/project`]:e,[`${B}/environment`]:t,[`${B}/role`]:r,[`${B}/managed-by`]:"ts-cloud"}}function se(e,t,r,s="app"){return br(e,t,r)&&e[`${B}/role`]===s}function br(e,t,r){if(!e)return!1;return e[`${B}/project`]===t&&e[`${B}/environment`]===r}import{mkdir as aa,readFile as ca,rename as la,writeFile as ua}from"node:fs/promises";import{join as dn}from"node:path";var wr="storage/cloud/state";function _e(e=process.cwd()){return xs()?A(e,"state"):dn(e,wr)}function je(e,t=process.cwd()){return dn(_e(t),`${e}.json`)}async function De(e,t=process.cwd()){try{let r=await ca(je(e,t),"utf8");return JSON.parse(r)}catch{return null}}async function Ve(e,t,r=process.cwd()){let s=je(e,r);await aa(_e(r),{recursive:!0});let n=`${s}.${process.pid}.tmp`;await ua(n,`${JSON.stringify(t,null,2)}
270
+ `,"utf8"),await la(n,s)}async function ue(e){return De(e)}async function mt(e,t){await Ve(e,t)}var $r=268435456;function ce(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function ha(e){let t=da("sha256");for await(let r of ma(e))t.update(r);return t.digest("hex")}class Te{name="hetzner";usesCloudFormation=!1;client;sshPrivateKeyPath;sshPublicKeyPath;sshUser;location;stateOnly;waitForBoot;bootWait;constructor(e={}){let t=it(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 Ke({apiToken:t??""});let r=sr(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,s=t.project.slug,n=t.infrastructure?.compute;if(!n)throw Error("infrastructure.compute is required to provision Hetzner compute");if(t.cloud?.attachTo)return this.attachToComputeInfrastructure(t.cloud.attachTo,t,r);let i=E(t,r),o=`${s}-${r}-app`,a=n.runtime==="php"||!!n.php,c=cn(n);if(c.dedicatedServices||c.appServers>1)return a?this.provisionFleet(e,c):this.provisionBunFleet(e,c);let l=j(s,r,"app"),p=t.sites||{},d=Q(n)?[]:this.collectUpstreamPorts(p),m=`${s}-${r}-app-fw`,{firewall:g}=await this.ensureFirewall(m,l,qr({allowSsh:n.allowSsh!==!1,sitePorts:d,allowedPorts:[...n.firewall?.allowedPorts??[],...Qs(t.infrastructure?.sftp)]})),h=await this.ensureSshKey(s,r,l),_=await ue(i);if(_?.serverId){let F=await this.tryGetServer(_.serverId);if(F&&F.status!=="off")return this.outputsFromState(_,F)}let w=await this.findExistingServer(s,r,o);if(w&&w.status!=="off"){let F={provider:"hetzner",stackName:i,serverId:w.id,serverName:w.name,publicIp:w.public_net.ipv4?.ip,publicIpv6:de(w.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await mt(i,F),this.outputsFromState(F,w)}let b=n.proxy?.engine==="rpx"?ge({proxy:n.proxy,config:fe(p,{proxy:n.proxy,slug:t.project.slug}),slug:t.project.slug,bunBin:n.runtime==="node"||n.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,y=Oe(t,{environment:r}),T=n.bakedImage===!0,S=re({runtime:y.runtime,runtimeVersion:y.runtimeVersion,systemPackages:n.systemPackages,database:t.infrastructure?.database,phpProvision:y.phpProvision,servicesProvision:y.servicesProvision,rpxProvision:b,baked:T,swapGb:n.swapGb}),D=he(S),O=pt(n.size),R=ot(t),{server:k,action:ne}=await this.client.createServer({name:o,serverType:O,image:R,location:t.hetzner?.location||this.location,userData:D,labels:l,sshKeys:h?[h]:void 0,firewalls:[{firewall:g.id}]});await this.client.waitForAction(ne.id);let z=await this.client.waitForServerRunning(k.id),X={provider:"hetzner",stackName:i,serverId:z.id,serverName:z.name,firewallId:g.id,publicIp:z.public_net.ipv4?.ip,publicIpv6:de(z.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};await mt(i,X);let q=z.public_net.ipv4?.ip;if(q&&this.waitForBoot)await this.waitForSshReady(q),await this.waitForCloudInit(q);return this.outputsFromState(X,z)}async provisionFleet(e,t){let{config:r,environment:s}=e,n=r.project.slug,i=r.infrastructure.compute,o=E(r,s),a=pt(i.size),c=ot(r),l=r.hetzner?.location||this.location,p=i.bakedImage===!0,d=await ue(o);if(d?.loadBalancerId){let G=(await this.client.listLoadBalancers().catch(()=>[])).find((I)=>I.id===d.loadBalancerId);if(G)return{appPublicIp:G.public_net?.ipv4?.ip,loadBalancerIp:G.public_net?.ipv4?.ip,servicesPrivateIp:d.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}let m=await this.ensureSshKey(n,s,j(n,s,"app")),g=`${n}-${s}-net`,_=(await this.client.listNetworks().catch(()=>[])).find((N)=>N.name===g)??await this.client.createNetwork({name:g,labels:j(n,s,"app")}),{firewall:w}=await this.ensureFirewall(`${n}-${s}-app-fw`,j(n,s,"app"),qr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),{firewall:b}=await this.ensureFirewall(`${n}-${s}-services-fw`,j(n,s,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[_.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[_.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[_.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[_.ip_range]}]),y=yr(r),T=he(re({runtime:"php",servicesProvision:y,baked:p,swapGb:i.swapGb})),S=await this.client.listServers().catch(()=>[]),D=[],O=S.find((N)=>se(N.labels,n,s,"services"));if(!O){let{server:N,action:G}=await this.client.createServer({name:`${n}-${s}-services`,serverType:pt(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:c,location:l,userData:T,labels:j(n,s,"services"),sshKeys:m?[m]:void 0,firewalls:[{firewall:b.id}],networks:[_.id]});await this.client.waitForAction(G.id),O=await this.client.waitForServerRunning(N.id),D.push(N.id)}let R=O.id,k=O.private_net?.[0]?.ip??(await this.client.getServer(R)).private_net?.[0]?.ip,ne=[...be(!0),...we(!0),...Ue(i.sshKeys),...ke(r.notifications)],z=yt({versions:i.php?.versions,default:i.php?.default,extensions:i.php?.extensions,installNginx:!Q(i),optimizeForProduction:i.php?.optimizeForProduction,ini:i.php?.ini}),X=he(re({runtime:"php",phpProvision:z,servicesProvision:ne,baked:p,swapGb:i.swapGb})),q=S.filter((N)=>se(N.labels,n,s,"app")),F=q.map((N)=>N.id);if(q.length>t.appServers)for(let N of q.slice(t.appServers))await this.client.deleteServer(N.id).catch(()=>{}),F.splice(F.indexOf(N.id),1);for(let N=q.length;N<t.appServers;N++){let{server:G,action:I}=await this.client.createServer({name:`${n}-${s}-app-${N+1}`,serverType:a,image:c,location:l,userData:X,labels:j(n,s,"app"),sshKeys:m?[m]:void 0,firewalls:[{firewall:w.id}],networks:[_.id]});await this.client.waitForAction(I.id),F.push(G.id),D.push(G.id)}if(this.waitForBoot&&D.length>0)await Promise.all(D.map(async(N)=>{let I=(await this.client.waitForServerRunning(N)).public_net.ipv4?.ip;if(I)await this.waitForSshReady(I),await this.waitForCloudInit(I)}));let ee=`${n}-${s}-lb`,H,ye;if(t.loadBalancer){let G=(await this.client.listLoadBalancers().catch(()=>[])).find((I)=>I.name===ee)??await this.client.createLoadBalancer({name:ee,location:l,network:_.id,labels:j(n,s,"lb"),labelSelector:`ts-cloud/project=${n},ts-cloud/environment=${s},ts-cloud/role=app`,services:[{listenPort:80,destinationPort:80},{listenPort:443,destinationPort:443}]});ye=G.id,H=G.public_net?.ipv4?.ip}let Y=H??(await this.client.getServer(F[0]).catch(()=>{return}))?.public_net.ipv4?.ip,pe={provider:"hetzner",stackName:o,networkId:_.id,loadBalancerId:ye,servicesServerId:R,servicesPrivateIp:k,publicIp:Y,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await mt(o,pe),{appPublicIp:Y,loadBalancerIp:H,servicesPrivateIp:k,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async provisionBunFleet(e,t){let{config:r,environment:s}=e,n=r.project.slug,i=r.infrastructure.compute,o=E(r,s),a=pt(i.size),c=ot(r),l=r.hetzner?.location||this.location,p=i.bakedImage===!0,d=r.sites||{},m=await ue(o);if(m?.lbServerId){let I=await this.tryGetServer(m.lbServerId);if(I&&I.status!=="off"){let L=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"},V=await this.findComputeTargets({slug:n,environment:s,role:"app",stackName:o});return this.refreshLbRoutes(I,d,V.map((ae)=>({privateIp:ae.privateIp,publicIp:ae.publicIp})),L,n),{appPublicIp:I.public_net.ipv4?.ip??m.publicIp,loadBalancerIp:I.public_net.ipv4?.ip??m.publicIp,servicesPrivateIp:m.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}}let g=await this.ensureSshKey(n,s,j(n,s,"app")),h=`${n}-${s}-net`,w=(await this.client.listNetworks().catch(()=>[])).find((I)=>I.name===h)??await this.client.createNetwork({name:h,labels:j(n,s,"app")}),b=this.collectUpstreamPorts(d),{firewall:y}=await this.ensureFirewall(`${n}-${s}-app-fw`,j(n,s,"app"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},...b.map((I)=>({direction:"in",protocol:"tcp",port:String(I),source_ips:[w.ip_range],description:`ts-cloud port ${I} (private, LB-only)`}))]),{firewall:T}=await this.ensureFirewall(`${n}-${s}-lb-fw`,j(n,s,"lb"),qr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),S=await this.client.listServers().catch(()=>[]),D=[],O,R,k=!!i.servicesServer||!!i.managedServices,ne=t.dedicatedServices&&k;if(ne){let{firewall:I}=await this.ensureFirewall(`${n}-${s}-services-fw`,j(n,s,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[w.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[w.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[w.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[w.ip_range]}]),L=yr(r),V=he(re({runtime:"bun",servicesProvision:L,baked:p,swapGb:i.swapGb})),ae=S.find((ve)=>se(ve.labels,n,s,"services"));if(!ae){let{server:ve,action:Ze}=await this.client.createServer({name:`${n}-${s}-services`,serverType:pt(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:c,location:l,userData:V,labels:j(n,s,"services"),sshKeys:g?[g]:void 0,firewalls:[{firewall:I.id}],networks:[w.id]});await this.client.waitForAction(Ze.id),ae=await this.client.waitForServerRunning(ve.id),D.push(ve.id)}O=ae.id,R=ae.private_net?.[0]?.ip??(await this.client.getServer(O)).private_net?.[0]?.ip}let z=ne?{...i,managedServices:void 0,backups:void 0}:i,X=Oe({...r,infrastructure:{...r.infrastructure,compute:z}},{environment:s}),q=he(re({runtime:X.runtime,runtimeVersion:X.runtimeVersion,systemPackages:i.systemPackages,database:r.infrastructure?.database,servicesProvision:X.servicesProvision,baked:p,swapGb:i.swapGb})),F=S.filter((I)=>se(I.labels,n,s,"app")),ee=F.map((I)=>I.id);if(F.length>t.appServers)for(let I of F.slice(t.appServers))await this.client.deleteServer(I.id).catch(()=>{}),ee.splice(ee.indexOf(I.id),1);for(let I=F.length;I<t.appServers;I++){let{server:L,action:V}=await this.client.createServer({name:`${n}-${s}-app-${I+1}`,serverType:a,image:c,location:l,userData:q,labels:j(n,s,"app"),sshKeys:g?[g]:void 0,firewalls:[{firewall:y.id}],networks:[w.id]});await this.client.waitForAction(V.id),ee.push(L.id),D.push(L.id)}if(this.waitForBoot&&D.length>0)await Promise.all(D.map(async(I)=>{let V=(await this.client.waitForServerRunning(I)).public_net.ipv4?.ip;if(V)await this.waitForSshReady(V),await this.waitForCloudInit(V)}));let H=[];for(let I of ee){let L=S.find((V)=>V.id===I);if(!L||!L.private_net?.[0]?.ip)L=await this.client.getServer(I).catch(()=>L);H.push({privateIp:L?.private_net?.[0]?.ip,publicIp:L?.public_net.ipv4?.ip})}let ye=`${n}-${s}-lb`,Y,pe;if(t.loadBalancer){let I=S.find((V)=>se(V.labels,n,s,"lb")),L=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"};if(!I){let V=ge({proxy:L,config:Me(d,H,{proxy:L,slug:n}),slug:n,bunBin:X.runtime==="node"||X.runtime==="deno"?void 0:"/usr/local/bin/bun"}),ae=he(re({runtime:"bun",rpxProvision:V,baked:!1})),ve=typeof i.loadBalancer==="object"?i.loadBalancer.size:void 0,{server:Ze,action:Kt}=await this.client.createServer({name:ye,serverType:pt(ve??"micro"),image:c,location:l,userData:ae,labels:j(n,s,"lb"),sshKeys:g?[g]:void 0,firewalls:[{firewall:T.id}],networks:[w.id]});if(await this.client.waitForAction(Kt.id),I=await this.client.waitForServerRunning(Ze.id),this.waitForBoot){let et=I.public_net.ipv4?.ip;if(et)await this.waitForSshReady(et),await this.waitForCloudInit(et)}}else this.refreshLbRoutes(I,d,H,L,n);Y=I.id,pe=I.public_net.ipv4?.ip}let N=pe??(await this.client.getServer(ee[0]).catch(()=>{return}))?.public_net.ipv4?.ip,G={provider:"hetzner",stackName:o,networkId:w.id,lbServerId:Y,appServerIds:ee,servicesServerId:O,servicesPrivateIp:R,publicIp:N,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await mt(o,G),{appPublicIp:N,loadBalancerIp:pe,servicesPrivateIp:R,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async destroyCompute(e){let{config:t,environment:r}=e,s=t.project.slug,n=E(t,r),i=await ue(n),o=[],a=`${s}-${r}-lb`,l=(await this.client.listLoadBalancers().catch(()=>[])).find((y)=>y.name===a);if(l)try{await this.client.deleteLoadBalancer(l.id),o.push(`load balancer ${a}`)}catch{}let p=await this.client.listServers().catch(()=>[]),d=new Set;for(let y of p)if(se(y.labels,s,r,"app")||se(y.labels,s,r,"services")||se(y.labels,s,r,"lb"))d.add(y.id);if(i?.serverId)d.add(i.serverId);if(i?.servicesServerId)d.add(i.servicesServerId);if(i?.lbServerId)d.add(i.lbServerId);for(let y of i?.appServerIds??[])d.add(y);for(let y of d)try{await this.client.deleteServer(y),o.push(`server ${y}`)}catch{}let m=await this.client.listFirewalls().catch(()=>[]);for(let y of[`${s}-${r}-app-fw`,`${s}-${r}-services-fw`,`${s}-${r}-lb-fw`]){let T=m.find((S)=>S.name===y);if(!T)continue;for(let S=0;S<12;S++)try{await this.client.deleteFirewall(T.id),o.push(`firewall ${y}`);break}catch{await this.sleep(3000)}}let g=`${s}-${r}-net`,_=(await this.client.listNetworks().catch(()=>[])).find((y)=>y.name===g);if(_)for(let y=0;y<12;y++)try{await this.client.deleteNetwork(_.id),o.push(`network ${g}`);break}catch{await this.sleep(3000)}let b=(await this.client.listSshKeys().catch(()=>[])).filter((y)=>br(y.labels,s,r));for(let y of b)try{await this.client.deleteSshKey(y.id),o.push(`ssh key ${y.name}`)}catch{}return await mt(n,{provider:"hetzner",stackName:n}).catch(()=>{}),{destroyed:o}}async getComputeOutputs(e){let t=E(e.config,e.environment),r=await ue(t);if(r?.serverId){let i=await this.tryGetServer(r.serverId);if(i)return this.outputsFromState(r,i)}if(r?.lbServerId){let o=(await this.tryGetServer(r.lbServerId))?.public_net.ipv4?.ip??r.publicIp;return{...this.outputsFromState(r),appPublicIp:o,loadBalancerIp:o}}if(r?.loadBalancerId||r?.servicesPrivateIp)return this.outputsFromState(r);let n=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:E(e.config,e.environment)}))[0];return{deployStoragePath:"/var/ts-cloud/staging",appInstanceId:n?.id,appPublicIp:n?.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:E(e.config,e.environment)});if(t.length===0)throw Error("No Hetzner compute targets found for release upload");let n=`/var/ts-cloud/staging/${`${e.remoteKey.replace(/^releases\//,"").replace(/\.tar\.gz$/,"").replace(/\//g,"-")}-${fn()}.tar.gz`}`,i=await ha(e.localPath),o="/var/ts-cloud/artifacts",a=`${o}/${i}.tar.gz`;for(let c of t){if(!c.publicIp)throw Error(`Target ${c.id} has no public IP for SCP upload`);let l=["set -euo pipefail",`mkdir -p ${ce(o)} /var/ts-cloud/staging`,`test -s ${ce(a)}`,`cp -- ${ce(a)} ${ce(n)}`].join(`
271
271
  `);try{this.sshExec(c.publicIp,l);continue}catch{}let p=`${o}/.${i}-${fn()}.tmp`;this.scpToHost(c.publicIp,e.localPath,p),this.sshExec(c.publicIp,["set -euo pipefail",`chmod 600 ${ce(p)}`,`mv -f -- ${ce(p)} ${ce(a)}`,`cp -- ${ce(a)} ${ce(n)}`,`find ${ce(o)} -type f -name '*.tar.gz' -mtime +7 -delete 2>/dev/null || true`].join(`
272
- `))}return{artifactRef:n}}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 ue(e.stackName??`${e.slug}-${e.environment}`),o=[...new Set(t==="app"?[i?.serverId,...i?.appServerIds??[]]:t==="lb"?[i?.lbServerId]:[i?.servicesServerId])].filter((l)=>typeof l==="number");if(this.stateOnly){if(o.length>0&&i?.publicIp)return o.map((l)=>({id:String(l),name:l===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 a=await this.client.listServers();if(o.length>0){let l=[];for(let p of o){let d=a.find((m)=>m.id===p)??await this.tryGetServer(p);if(p===i?.serverId&&i.serverName&&d?.name!==i.serverName)continue;if(d&&d.status!=="off")l.push(d)}if(l.length>0)return l.map(r)}let c=a.filter((l)=>re(l.labels,e.slug,e.environment,t));if(c.length>0)return c.map(r);if(t==="app"){let l=a.filter((p)=>p.status!=="off"&&p.labels?.[`${B}/managed-by`]==="ts-cloud"&&p.labels?.[`${B}/environment`]===e.environment&&p.labels?.[`${B}/role`]==="app");if(l.length===1)return l.map(r)}return[]}if(this.stateOnly)throw Error(`Hetzner API token required to discover '${t}' compute targets.`);let n=(await this.client.listServers()).filter((i)=>re(i.labels,e.slug,e.environment,t));if(n.length>0)return n.map(r);return[]}async attachToComputeInfrastructure(e,t,r){let s=await this.client.listServers(),n=(m)=>s.filter((g)=>g.status!=="off"&&re(g.labels,e,r,m)),i=n("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 o=n("lb")[0],a=n("services")[0],c=i[0],l=o??c,p=E(t,r),d={provider:"hetzner",stackName:p,serverId:c.id,serverName:c.name,appServerIds:i.map((m)=>m.id),lbServerId:o?.id,servicesServerId:a?.id,servicesPrivateIp:a?.private_net?.[0]?.ip,publicIp:l.public_net.ipv4?.ip,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await mt(p,d),this.outputsFromState(d)}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(`
272
+ `))}return{artifactRef:n}}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 ue(e.stackName??`${e.slug}-${e.environment}`),o=[...new Set(t==="app"?[i?.serverId,...i?.appServerIds??[]]:t==="lb"?[i?.lbServerId]:[i?.servicesServerId])].filter((l)=>typeof l==="number");if(this.stateOnly){if(o.length>0&&i?.publicIp)return o.map((l)=>({id:String(l),name:l===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 a=await this.client.listServers();if(o.length>0){let l=[];for(let p of o){let d=a.find((m)=>m.id===p)??await this.tryGetServer(p);if(p===i?.serverId&&i.serverName&&d?.name!==i.serverName)continue;if(d&&d.status!=="off")l.push(d)}if(l.length>0)return l.map(r)}let c=a.filter((l)=>se(l.labels,e.slug,e.environment,t));if(c.length>0)return c.map(r);if(t==="app"){let l=a.filter((p)=>p.status!=="off"&&p.labels?.[`${B}/managed-by`]==="ts-cloud"&&p.labels?.[`${B}/environment`]===e.environment&&p.labels?.[`${B}/role`]==="app");if(l.length===1)return l.map(r)}return[]}if(this.stateOnly)throw Error(`Hetzner API token required to discover '${t}' compute targets.`);let n=(await this.client.listServers()).filter((i)=>se(i.labels,e.slug,e.environment,t));if(n.length>0)return n.map(r);return[]}async attachToComputeInfrastructure(e,t,r){let s=await this.client.listServers(),n=(m)=>s.filter((g)=>g.status!=="off"&&se(g.labels,e,r,m)),i=n("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 o=n("lb")[0],a=n("services")[0],c=i[0],l=o??c,p=E(t,r),d={provider:"hetzner",stackName:p,serverId:c.id,serverName:c.name,appServerIds:i.map((m)=>m.id),lbServerId:o?.id,servicesServerId:a?.id,servicesPrivateIp:a?.private_net?.[0]?.ip,publicIp:l.public_net.ipv4?.ip,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await mt(p,d),this.outputsFromState(d)}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(`
273
273
  `),r=[];for(let n of e.targets){if(!n.publicIp){r.push({instanceId:n.id,status:"Failed",error:"Missing public IP"});continue}try{let i=this.sshExec(n.publicIp,t);Ne(i),r.push({instanceId:n.id,status:"Success",output:i})}catch(i){r.push({instanceId:n.id,status:"Failed",error:i.message})}}let s=r.every((n)=>n.status==="Success");return{success:s,instanceCount:e.targets.length,perInstance:r,error:s?void 0:Ie(r,"One or more SSH deploy commands failed")}}async ensureSshKey(e,t,r){if(!fa(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 s=ga(this.sshPublicKeyPath,"utf8").trim(),n=at(s),o=(await this.client.listSshKeys()).find((c)=>at(c.public_key)===n);if(o)return o.id;return(await this.client.createSshKey({name:`${e}-${t}-deploy`,publicKey:s,labels:r})).id}async tryGetServer(e){try{return await this.client.getServer(e)}catch{return null}}refreshLbRoutes(e,t,r,s,n){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 o=r.filter((c)=>c.privateIp||c.publicIp);if(o.length===0){console.warn(`[ts-cloud] No routable app boxes found for LB '${e.name}' — leaving its current rpx routes untouched.`);return}let a=Me(t,o,{proxy:s,slug:n});this.sshExec(i,Ge({config:a,slug:n}).join(`
274
- `))}async findExistingServer(e,t,r){let s=await this.client.listServers(),n=s.find((o)=>re(o.labels,e,t,"app")||o.name===r);if(n)return n;let i=s.filter((o)=>o.status!=="off"&&o.labels?.[`${B}/managed-by`]==="ts-cloud"&&o.labels?.[`${B}/environment`]===t&&o.labels?.[`${B}/role`]==="app");if(i.length===1){let o=i[0],a=o.labels?.[`${B}/project`]??"unknown";return console.warn(`[ts-cloud] No server named '${r}' found; adopting existing ts-cloud app server '${o.name}' (project label '${a}') for project '${e}' — `+"updating it in place instead of provisioning a new server."),o}return}async ensureFirewall(e,t,r){let n=(await this.client.listFirewalls()).find((o)=>o.name===e);if(n)return await this.client.setFirewallRules(n.id,r),{firewall:n};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,s=Date.now(),n;while(Date.now()-s<r)try{mn(`ssh ${this.sshBaseArgs(e,["-o","ConnectTimeout=5"]).map(ce).join(" ")} true`,{stdio:"pipe",maxBuffer:$r});return}catch(i){n=i,await this.sleep(t)}throw Error(`Timed out waiting for SSH on ${e} after ${r}ms: ${n?.message??"unknown error"}`)}async waitForCloudInit(e){let{cloudInitIntervalMs:t,cloudInitTimeoutMs:r}=this.bootWait,s=Date.now();while(Date.now()-s<r){try{let n=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(n))throw Error(`cloud-init reported an error on ${e}:
274
+ `))}async findExistingServer(e,t,r){let s=await this.client.listServers(),n=s.find((o)=>se(o.labels,e,t,"app")||o.name===r);if(n)return n;let i=s.filter((o)=>o.status!=="off"&&o.labels?.[`${B}/managed-by`]==="ts-cloud"&&o.labels?.[`${B}/environment`]===t&&o.labels?.[`${B}/role`]==="app");if(i.length===1){let o=i[0],a=o.labels?.[`${B}/project`]??"unknown";return console.warn(`[ts-cloud] No server named '${r}' found; adopting existing ts-cloud app server '${o.name}' (project label '${a}') for project '${e}' — `+"updating it in place instead of provisioning a new server."),o}return}async ensureFirewall(e,t,r){let n=(await this.client.listFirewalls()).find((o)=>o.name===e);if(n)return await this.client.setFirewallRules(n.id,r),{firewall:n};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,s=Date.now(),n;while(Date.now()-s<r)try{mn(`ssh ${this.sshBaseArgs(e,["-o","ConnectTimeout=5"]).map(ce).join(" ")} true`,{stdio:"pipe",maxBuffer:$r});return}catch(i){n=i,await this.sleep(t)}throw Error(`Timed out waiting for SSH on ${e} after ${r}ms: ${n?.message??"unknown error"}`)}async waitForCloudInit(e){let{cloudInitIntervalMs:t,cloudInitTimeoutMs:r}=this.bootWait,s=Date.now();while(Date.now()-s<r){try{let n=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(n))throw Error(`cloud-init reported an error on ${e}:
275
275
  ${n}`);if(/status:\s*(?:done|degraded)/.test(n))return}catch(n){if(n instanceof Error&&/cloud-init reported an error/.test(n.message))throw n}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,...Te.SSH_HOST_KEY_OPTS,...Te.SSH_KEEPALIVE_OPTS,"-o","BatchMode=yes",...t,`${this.sshUser}@${e}`]}scpToHost(e,t,r){let s=["scp","-i",this.sshPrivateKeyPath,...Te.SSH_HOST_KEY_OPTS,...Te.SSH_KEEPALIVE_OPTS,"-o","BatchMode=yes",t,`${this.sshUser}@${e}:${r}`].map((i)=>`"${i.replace(/"/g,"\\\"")}"`).join(" "),n=3;for(let i=1;i<=3;i++)try{mn(s,{stdio:"pipe",maxBuffer:$r});return}catch(o){if(i===3)throw Error(Ee(o))}}sshExec(e,t){try{return pa("ssh",[...this.sshBaseArgs(e),hr],{encoding:"utf8",input:t,stdio:["pipe","pipe","pipe"],maxBuffer:$r})}catch(r){throw Error(`${Ee(r)}${tt(r,t)}`)}}}class Pt{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(`
276
276
  `);try{let r=Bun.spawn(["bash","-c",t],{stdout:"pipe",stderr:"pipe",env:process.env}),[s,n,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:s,error:n}]}}catch(r){return{success:!1,instanceCount:1,perInstance:[{instanceId:"localhost",status:"Failed",error:r?.message??String(r)}],error:r?.message??String(r)}}}}function _r(){let e=process.env.TS_CLOUD_DASHBOARD_BOX;return e!=null&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}import{createHash as Na,randomUUID as Mn}from"node:crypto";import{createReadStream as ka}from"node:fs";import{isIP as Ha}from"node:net";import{createHash as ya}from"node:crypto";import{appendFile as Sa,mkdir as va,readFile as ba}from"node:fs/promises";import{dirname as wa}from"node:path";var gn=268435456,hn=async(e,t)=>{let r=Bun.spawn(e,{stdin:t===void 0?"ignore":Buffer.from(t),stdout:"pipe",stderr:"pipe"}),[s,n,i]=await Promise.all([r.exited,new Response(r.stdout).text(),new Response(r.stderr).text()]);return{code:s,signal:r.signalCode,stdout:n.slice(-gn),stderr:i.slice(-gn)}},yn=["-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR"],Sn=["-o","ConnectTimeout=30","-o","ServerAliveInterval=15","-o","ServerAliveCountMax=4"];function vn(e){if(e.hostKey==="insecure")return[...yn];return["-o",`StrictHostKeyChecking=${e.hostKey.policy==="pin"?"yes":"accept-new"}`,"-o",`UserKnownHostsFile=${e.hostKey.knownHostsFile}`,"-o","LogLevel=ERROR"]}function bn(e){let t=[...Sn];if(e.connectTimeoutSec!==void 0)t[1]=`ConnectTimeout=${e.connectTimeoutSec}`;return t}function Tr(e,t,r=[]){return["-i",e.identityFile,"-p",String(e.port??22),...vn(e),...bn(e),"-o","BatchMode=yes",...r,`${e.user}@${t}`]}function wn(e,t,r,s){return["-i",e.identityFile,"-P",String(e.port??22),...vn(e),...bn(e),"-o","BatchMode=yes",r,`${e.user}@${t}:${s}`]}function cr(e){return`SHA256:${ya("sha256").update(Buffer.from(e,"base64")).digest("base64").replace(/=+$/,"")}`}async function Ji(e,t=22,r=hn){let s=await r(["ssh-keyscan","-T","10","-p",String(t),"-t","ed25519",e]),n=s.stdout.split(`
277
277
  `).find((i)=>i&&!i.startsWith("#"))?.trim().split(/\s+/);if(s.code!==0||!n?.[1]||!n[2])throw Error(`SSH host-key scan failed: ${s.stderr.trim()||"no key returned"}`);return{algorithm:n[1],key:n[2]}}function Pr(e,t=22){return t===22?e:`[${e}]:${t}`}function $n(e,t,r){return`${Pr(e,t)} ${r.algorithm} ${r.key}`}function _n(e,t,r=22){let s=Pr(t,r);for(let n of e.split(`
@@ -307,7 +307,7 @@ systemctl restart systemd-journald
307
307
  # The deploy user uploads releases as itself (scp), while the scripts run as
308
308
  # root through sudo. setgid group-writable directories let both write.
309
309
  install -d -m 2775 -g "$(id -gn ${Ae(e)})" /var/ts-cloud/artifacts /var/ts-cloud/staging
310
- `}function Da(e){let t=Ae(e),r=`/home/${e}`;return[`chown -R ${t}:"$(id -gn ${t})" ${Ae(`${r}/.ssh`)}`,`chmod 700 ${Ae(`${r}/.ssh`)}`]}function lr(e){let{config:t,environment:r,profile:s,sudoUser:n}=e;Ct(t,s,e.facts?.arch);let i=t.infrastructure?.compute??{},o=t.sites??{},a=t.project.slug,c=e.lan?{...e.lan.hostname?{hostname:e.lan.hostname}:{},tls:e.lan.tls??"local-ca",...Tn(e)?{ip:Tn(e)}:{}}:void 0,l=i.proxy?.engine==="rpx"?fe(o,{proxy:i.proxy,slug:a,lan:c}):void 0,p=i.proxy?.engine==="rpx"&&l?me({proxy:i.proxy,config:l,slug:a,profile:s,bunBin:i.runtime==="node"||i.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,d=i.proxy?.engine==="rpx"&&l?Ge({config:l,slug:a}):void 0,m=n?`/home/${n}/.ssh/authorized_keys`:void 0,g=Oe(t,{environment:r,authorizedKeysPath:m}),h=n?[...g.servicesProvision??[],...Da(n)]:g.servicesProvision,_=[...new Set([...i.systemPackages??[],"psmisc","ca-certificates"])],w=i.swapGb??(s==="raspberry-pi"?xn:void 0),b=te({runtime:g.runtime,runtimeVersion:g.runtimeVersion,systemPackages:_,database:t.infrastructure?.database,phpProvision:g.phpProvision,servicesProvision:h,rpxProvision:p,swapGb:w}).replace(/^#!\/bin\/bash\nset -euo pipefail\n/,""),y=Pn(),T=l?.localCa?` lan=${l.localCa.hosts.join(",")} tls=local-ca`:c?` lan=${c.hostname??`${a}.local`} tls=${c.tls??"local-ca"}`:"",S=`#!/bin/bash
310
+ `}function Da(e){let t=Ae(e),r=`/home/${e}`;return[`chown -R ${t}:"$(id -gn ${t})" ${Ae(`${r}/.ssh`)}`,`chmod 700 ${Ae(`${r}/.ssh`)}`]}function lr(e){let{config:t,environment:r,profile:s,sudoUser:n}=e;Ct(t,s,e.facts?.arch);let i=t.infrastructure?.compute??{},o=t.sites??{},a=t.project.slug,c=e.lan?{...e.lan.hostname?{hostname:e.lan.hostname}:{},tls:e.lan.tls??"local-ca",...Tn(e)?{ip:Tn(e)}:{}}:void 0,l=i.proxy?.engine==="rpx"?fe(o,{proxy:i.proxy,slug:a,lan:c}):void 0,p=i.proxy?.engine==="rpx"&&l?ge({proxy:i.proxy,config:l,slug:a,profile:s,bunBin:i.runtime==="node"||i.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,d=i.proxy?.engine==="rpx"&&l?Ge({config:l,slug:a}):void 0,m=n?`/home/${n}/.ssh/authorized_keys`:void 0,g=Oe(t,{environment:r,authorizedKeysPath:m}),h=n?[...g.servicesProvision??[],...Da(n)]:g.servicesProvision,_=[...new Set([...i.systemPackages??[],"psmisc","ca-certificates"])],w=i.swapGb??(s==="raspberry-pi"?xn:void 0),b=re({runtime:g.runtime,runtimeVersion:g.runtimeVersion,systemPackages:_,database:t.infrastructure?.database,phpProvision:g.phpProvision,servicesProvision:h,rpxProvision:p,swapGb:w}).replace(/^#!\/bin\/bash\nset -euo pipefail\n/,""),y=Pn(),T=l?.localCa?` lan=${l.localCa.hosts.join(",")} tls=local-ca`:c?` lan=${c.hostname??`${a}.local`} tls=${c.tls??"local-ca"}`:"",S=`#!/bin/bash
311
311
  set -euo pipefail
312
312
  # ts-cloud ssh bootstrap v${Pe} profile=${s}${T}
313
313
 
@@ -325,7 +325,7 @@ fi
325
325
  ${b}`,S+=`
326
326
  install -d -m 0755 ${Ae(Rr)}
327
327
  date -u +%Y-%m-%dT%H:%M:%SZ > ${Ae(y)}
328
- echo "[ts-cloud] bootstrap v${Pe} applied (${s}); gateway fragment at ${ae}/${a}.json"
328
+ echo "[ts-cloud] bootstrap v${Pe} applied (${s}); gateway fragment at ${te}/${a}.json"
329
329
  `,l?.localCa)S+=`echo "[ts-cloud] LAN certificate authority for ${l.localCa.hosts.join(", ")} at ${St(l.localCa.dir)} (copy it to a client to trust this box)"
330
330
  `;return S}var xe={user:"root",port:22,privateKeyPath:"~/.ssh/id_ed25519",hostKey:"pin",profile:"generic",publicIp:"auto"},Cn=["pin","accept-new","insecure"],Rn=["raspberry-pi","generic"];function qe(...e){for(let t of e){let r=process.env[t]?.trim();if(r)return r}return}function ct(...e){for(let t of e){let r=t?.trim();if(r)return r}return}function En(e,t){if(t?.length)return t;if(e?.ssh?.hosts?.length)return e.ssh.hosts;let r=qe("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 In(e,t){return ct(t,e?.user,qe("TS_CLOUD_SSH_USER"))??xe.user}function On(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:qe("TS_CLOUD_SSH_PORT")}];for(let{source:s,value:n}of r){if(n===void 0||n==="")continue;let i=typeof n==="number"?n:Number(n);if(!Number.isInteger(i)||i<1||i>65535)throw Error(`Invalid SSH port from ${s}: ${String(n)}`);return i}return xe.port}function Dn(e,t){return zr(ct(t,e?.privateKeyPath,qe("TS_CLOUD_SSH_KEY"))??xe.privateKeyPath)}function An(e,t){let r=ct(t,e?.ssh?.hostKey,qe("TS_CLOUD_SSH_HOST_KEY"))??xe.hostKey;if(!Cn.includes(r))throw Error(`Invalid ssh.hostKey '${r}'. Use one of: ${Cn.join(", ")}.`);return r}function Nn(e,t=xe.user,r){return r??e?.ssh?.sudo??t!=="root"}function kn(e,t){let r=ct(t,e?.ssh?.profile,qe("TS_CLOUD_SSH_PROFILE"))??xe.profile;if(!Rn.includes(r))throw Error(`Invalid ssh.profile '${r}'. Use one of: ${Rn.join(", ")}.`);return r}function Hn(e,t){return ct(t,e?.ssh?.publicIp)??xe.publicIp}function Ln(e,t){return t??e?.ssh?.lan}function dr(e,t={}){let r=En(e,t.hosts).map((s)=>({host:s.host,user:In(s,t.user),port:On(s,t.port),privateKeyPath:Dn(s,t.privateKeyPath),role:s.role??"app"}));return{hosts:r,hostKey:An(e,t.hostKey),sudo:Nn(e,r[0]?.user,t.sudo),profile:kn(e,t.profile),publicIp:Hn(e,t.publicIp),lan:Ln(e,t.lan)}}var Er=`set -u
331
331
  . /etc/os-release 2>/dev/null || true
@@ -368,15 +368,15 @@ ${" ".repeat(t+10)}${r.remediation}`:s}).join(`
368
368
  `))}return{artifactRef:n}}async runRemoteDeploy(e){if(e.targets.length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets provided"};let t=e.commands.join(`
369
369
  `),r=[];for(let n of e.targets){if(!n.publicIp){r.push({instanceId:n.id,status:"Failed",error:"Missing address"});continue}try{let i=await this.exec(n.publicIp,t);Ne(i),r.push({instanceId:n.id,status:"Success",output:i})}catch(i){r.push({instanceId:n.id,status:"Failed",error:i.message})}}let s=r.every((n)=>n.status==="Success");return{success:s,instanceCount:e.targets.length,perInstance:r,error:s?void 0:Ie(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,Er,{sudo:!1}),r=Ir(t);return{facts:r,findings:Or(r,{user:this.host.user,profile:this.settings.profile})}}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e;for(let h of zn(t,this.settings))console.warn(`[ts-cloud] ${h}`);let s=this.host,n=E(t,r),i=await De(n,this.cwd),o=process.env[Un]==="1"&&i?.provider==="ssh"&&i.host===s.host&&i.bootstrapVersion===Pe,a=await this.ensureHostKey(s.host);if(a.pinnedNow)console.warn(`[ts-cloud] pinned ${s.host} host key ${a.fingerprint}`);await this.waitForSshReady(s.host);let{facts:c,findings:l}=await this.preflight(s.host);if(ur(l))throw Error(`Preflight failed for ${s.host}; refusing to bootstrap it.
370
370
  ${Hr(l)}`);for(let h of l)console.warn(`[ts-cloud] ${h.severity}: ${h.message}`);if(c.cloudInitPresent&&/running/i.test(c.cloudInitStatus??""))await this.waitForCloudInit(s.host);let p=c.lanIp?.trim()||(Ha(s.host)!==0?s.host:void 0),d=i?.provider==="ssh"?i.bootstrappedAt:void 0;if(!o){let h=lr({config:t,environment:r,profile:this.settings.profile,facts:c,sudoUser:s.user!=="root"?s.user:void 0,lan:this.settings.lan,lanIp:p});Ne(await this.exec(s.host,h)),d=new Date().toISOString()}let m={provider:"ssh",stackName:n,host:s.host,sshUser:s.user,sshPort:s.port,hostKeyFingerprint:a.fingerprint||void 0,publicIp:this.settings.publicIp==="auto"?void 0:this.settings.publicIp,lanIp:c.lanIp||void 0,deployStoragePath:lt,profile:this.settings.profile,bootstrapVersion:Pe,bootstrappedAt:d};await Ve(n,m,this.cwd);let g=await this.getComputeOutputs();if(Q(t.infrastructure?.compute)&&tr(this.settings.lan)==="local-ca")g.lanCaCertPath=St(),console.warn(`[ts-cloud] LAN certificate authority on ${s.host} at ${g.lanCaCertPath}. Fetch it with: scp ${s.user}@${s.host}:${g.lanCaCertPath} ./rpx-root-ca.crt`);return g}async destroyCompute(e){let t=E(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 Ve(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,s=Date.now();do{if(await this.transport.probe(e))return;await this.sleep(t)}while(Date.now()-s<r);throw Error(`Timed out waiting for SSH on ${e} after ${r}ms`)}async waitForCloudInit(e){let{cloudInitIntervalMs:t,cloudInitTimeoutMs:r}=this.bootWait,s=Date.now();while(Date.now()-s<r){try{let n=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(n))throw Error(`cloud-init reported an error on ${e}:
371
- ${n}`);if(/status:\s*(?:done|degraded)/.test(n))return}catch(n){if(n instanceof Error&&/cloud-init reported an error/.test(n.message))throw n}await this.sleep(t)}throw Error(`Timed out waiting for cloud-init to finish on ${e} after ${r}ms`)}}function x(e){if(_r())return new Pt;switch(e.provider??U(e.config)){case"aws":return new wt({region:e.config.project.region});case"hetzner":return new Te({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 pr({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});default:throw Error(`Unknown cloud provider: ${e.provider??U(e.config)}`)}}class Fn{drivers=new Map;getDriver(e,t){let r=t??U(e),s=`${r}:${e.project.slug}:${e.project.region||"default"}`,n=this.drivers.get(s);if(n)return n;let i=x({config:e,provider:r});return this.drivers.set(s,i),i}}var md=new Fn;var Bn="/var/lib/ts-cloud/bootstrap.sh",Xi={"raspberry-pi-os":"bootfs",ubuntu:"system-boot"},Ua=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,za=/^[a-z_][a-z0-9_-]{0,31}$/,Ka=/^[A-Z]{2}$/;function ne(e){return JSON.stringify(e)}function ja(e){if(!Ua.test(e.hostname))throw Error(`Invalid hostname '${e.hostname}': use lowercase letters, digits and hyphens.`);if(!za.test(e.user))throw Error(`Invalid user '${e.user}': use a lowercase Unix user name.`);let t=e.publicKey.trim();if(!t||t.includes(`
372
- `)||!/^(?: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(!Ka.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 Ga(e,t){let r=[`hostname: ${ne(e.hostname)}`,"manage_etc_hosts: true","users:",` - name: ${ne(e.user)}`," ssh_authorized_keys:",` - ${ne(e.publicKey.trim())}`,` sudo: ${ne("ALL=(ALL) NOPASSWD:ALL")}`," shell: /bin/bash"," lock_passwd: true","ssh_pwauth: false"];if(e.timezone)r.push(`timezone: ${ne(e.timezone)}`);if(e.locale)r.push(`locale: ${ne(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(`
371
+ ${n}`);if(/status:\s*(?:done|degraded)/.test(n))return}catch(n){if(n instanceof Error&&/cloud-init reported an error/.test(n.message))throw n}await this.sleep(t)}throw Error(`Timed out waiting for cloud-init to finish on ${e} after ${r}ms`)}}function x(e){if(_r())return new Pt;switch(e.provider??U(e.config)){case"aws":return new wt({region:e.config.project.region});case"hetzner":return new Te({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 pr({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});default:throw Error(`Unknown cloud provider: ${e.provider??U(e.config)}`)}}class Fn{drivers=new Map;getDriver(e,t){let r=t??U(e),s=`${r}:${e.project.slug}:${e.project.region||"default"}`,n=this.drivers.get(s);if(n)return n;let i=x({config:e,provider:r});return this.drivers.set(s,i),i}}var md=new Fn;var Bn="/var/lib/ts-cloud/bootstrap.sh",Xi={"raspberry-pi-os":"bootfs",ubuntu:"system-boot"},Ua=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,za=/^[a-z_][a-z0-9_-]{0,31}$/,Ka=/^[A-Z]{2}$/;function ie(e){return JSON.stringify(e)}function ja(e){if(!Ua.test(e.hostname))throw Error(`Invalid hostname '${e.hostname}': use lowercase letters, digits and hyphens.`);if(!za.test(e.user))throw Error(`Invalid user '${e.user}': use a lowercase Unix user name.`);let t=e.publicKey.trim();if(!t||t.includes(`
372
+ `)||!/^(?: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(!Ka.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 Ga(e,t){let r=[`hostname: ${ie(e.hostname)}`,"manage_etc_hosts: true","users:",` - name: ${ie(e.user)}`," ssh_authorized_keys:",` - ${ie(e.publicKey.trim())}`,` sudo: ${ie("ALL=(ALL) NOPASSWD:ALL")}`," shell: /bin/bash"," lock_passwd: true","ssh_pwauth: false"];if(e.timezone)r.push(`timezone: ${ie(e.timezone)}`);if(e.locale)r.push(`locale: ${ie(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(`
373
373
  `)}
374
- `}function Wa(e){let t=["version: 2","ethernets:"," eth0:"," match:",` name: ${ne("e*")}`," dhcp4: true"," dhcp6: true"," optional: true"];if(e.wifi)t.push("wifis:"," wlan0:"," dhcp4: true"," dhcp6: true"," optional: true",` regulatory-domain: ${ne(e.wifi.country)}`," access-points:",` ${ne(e.wifi.ssid)}:`,` password: ${ne(e.wifi.passphrase)}`);return`${t.join(`
374
+ `}function Wa(e){let t=["version: 2","ethernets:"," eth0:"," match:",` name: ${ie("e*")}`," dhcp4: true"," dhcp6: true"," optional: true"];if(e.wifi)t.push("wifis:"," wlan0:"," dhcp4: true"," dhcp6: true"," optional: true",` regulatory-domain: ${ie(e.wifi.country)}`," access-points:",` ${ie(e.wifi.ssid)}:`,` password: ${ie(e.wifi.passphrase)}`);return`${t.join(`
375
375
  `)}
376
- `}function Va(e){return[`instance-id: ${ne(`ts-cloud-${e.hostname}`)}`,`local-hostname: ${ne(e.hostname)}`].join(`
376
+ `}function Va(e){return[`instance-id: ${ie(`ts-cloud-${e.hostname}`)}`,`local-hostname: ${ie(e.hostname)}`].join(`
377
377
  `)+`
378
378
  `}function Xa(e,t){return[`Copy user-data, network-config and meta-data onto the boot partition of the flashed card (the volume named '${Xi[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(`
379
- `)}function Qi(e,t,r){ja(e);let s={scriptPath:Bn,permissions:"0700",before:Ga(e,r.os)};return{files:{"user-data":ge(t,s),"network-config":Wa(e),"meta-data":Va(e)},instructions:Xa(e,r.os)}}function qa(e){return e.location?.name??e.datacenter?.location.name??"unknown"}function Je(e){return typeof e==="number"&&Number.isFinite(e)?e:0}function Ya(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(Je(t.cores)<Je(e.cores))r.push("CPU");if(Je(t.memory)<Je(e.memory))r.push("memory");if(Je(t.disk)<Je(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 Zn(e,t,r,s=!0){let[n,i]=await Promise.all([e.getServer(t),e.getServerType(r)]);if(!i)throw Error(`Hetzner server type ${r} was not found.`);let o=n.server_type,a=o.name===i.name;if(!a)Ya(o,i);let c=qa(n),l=i.locations?.find((p)=>p.name===c);return{serverId:t,serverName:n.name,location:c,currentType:o,targetType:i,capacityAvailable:l?.available!==!1,alreadyComplete:a,upgradeDisk:s}}function Kn(e){if(e instanceof _t&&e.code==="resource_unavailable")return!0;if(e instanceof Tt){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 Se(e,t,r){await e?.onPhase?.(t,r)}async function Dr(e,t,r){await e.waitForAction(t.id,{pollIntervalMs:r.actionPollIntervalMs,maxWaitMs:r.actionTimeoutMs})}var Et=async({client:e,hooks:t,actionPollIntervalMs:r,actionTimeoutMs:s,serverPollIntervalMs:n,serverTimeoutMs:i},o,a,c)=>{let l=await e.getServer(o.serverId);if(l.status!=="running"){await Se(t,c?"recovering":"powering-on",{serverId:o.serverId});let d=await e.powerOnServer(o.serverId);await Dr(e,d,{actionPollIntervalMs:r,actionTimeoutMs:s}),l=await e.waitForServerRunning(o.serverId,{pollIntervalMs:n,maxWaitMs:i})}await Se(t,"verifying",{serverId:o.serverId,recovered:c});let p=await t?.afterBoot?.(l,o.targetType,a,{recovered:c});return{server:l,verification:p}};async function ns(e){let{client:t,hooks:r}=e,s=e.upgradeDisk??!0;await Se(r,"planning",{serverId:e.serverId,targetType:e.targetType});let n=await Zn(t,e.serverId,e.targetType,s),i=await t.getServer(n.serverId);if(n.alreadyComplete){let c=await Et(e,n,e.manifest,!1);return await Se(r,"complete",{alreadyComplete:!0}),{status:"already-complete",plan:n,verification:c.verification}}if(!n.capacityAvailable&&!e.attemptUnavailable)return await Se(r,"waiting-capacity",{location:n.location,targetType:n.targetType.name}),{status:"waiting-capacity",plan:n};let o=e.manifest;if(i.status==="off"&&!e.resumeFromOff){let c=await Et(e,n,void 0,!0);return{status:"recovered",plan:n,server:c.server,verification:c.verification,retryable:!0,error:"Server was already off without a resumable resize checkpoint; powered it back on."}}if(i.status==="running"){await Se(r,"preflight",{serverId:n.serverId}),o=await r?.preflight?.(i,n.targetType),await Se(r,"shutting-down",{serverId:n.serverId});let c=await t.shutdownServer(n.serverId);await Dr(t,c,e),i=await t.waitForServerStatus(n.serverId,"off",{pollIntervalMs:e.serverPollIntervalMs,maxWaitMs:e.serverTimeoutMs})}try{await Se(r,"resizing",{serverId:n.serverId,from:n.currentType.name,to:n.targetType.name,upgradeDisk:s});let c=await t.changeServerType(n.serverId,n.targetType.name,s);await Dr(t,c,e)}catch(c){let l=await Et(e,n,o,!0);return{status:"recovered",plan:n,server:l.server,manifest:o,verification:l.verification,retryable:Kn(c),error:c instanceof Error?c.message:String(c)}}let a=await Et(e,n,o,!1);if(a.verification&&!a.verification.ok)throw Error(`Resize completed but verification failed: ${(a.verification.failures??[]).join("; ")}`);return await Se(r,"complete",{serverId:n.serverId,targetType:n.targetType.name}),{status:"completed",plan:n,server:a.server,manifest:o,verification:a.verification}}var Ja=String.raw`
379
+ `)}function Qi(e,t,r){ja(e);let s={scriptPath:Bn,permissions:"0700",before:Ga(e,r.os)};return{files:{"user-data":he(t,s),"network-config":Wa(e),"meta-data":Va(e)},instructions:Xa(e,r.os)}}function qa(e){return e.location?.name??e.datacenter?.location.name??"unknown"}function Je(e){return typeof e==="number"&&Number.isFinite(e)?e:0}function Ya(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(Je(t.cores)<Je(e.cores))r.push("CPU");if(Je(t.memory)<Je(e.memory))r.push("memory");if(Je(t.disk)<Je(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 Zn(e,t,r,s=!0){let[n,i]=await Promise.all([e.getServer(t),e.getServerType(r)]);if(!i)throw Error(`Hetzner server type ${r} was not found.`);let o=n.server_type,a=o.name===i.name;if(!a)Ya(o,i);let c=qa(n),l=i.locations?.find((p)=>p.name===c);return{serverId:t,serverName:n.name,location:c,currentType:o,targetType:i,capacityAvailable:l?.available!==!1,alreadyComplete:a,upgradeDisk:s}}function Kn(e){if(e instanceof _t&&e.code==="resource_unavailable")return!0;if(e instanceof Tt){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 Se(e,t,r){await e?.onPhase?.(t,r)}async function Dr(e,t,r){await e.waitForAction(t.id,{pollIntervalMs:r.actionPollIntervalMs,maxWaitMs:r.actionTimeoutMs})}var Et=async({client:e,hooks:t,actionPollIntervalMs:r,actionTimeoutMs:s,serverPollIntervalMs:n,serverTimeoutMs:i},o,a,c)=>{let l=await e.getServer(o.serverId);if(l.status!=="running"){await Se(t,c?"recovering":"powering-on",{serverId:o.serverId});let d=await e.powerOnServer(o.serverId);await Dr(e,d,{actionPollIntervalMs:r,actionTimeoutMs:s}),l=await e.waitForServerRunning(o.serverId,{pollIntervalMs:n,maxWaitMs:i})}await Se(t,"verifying",{serverId:o.serverId,recovered:c});let p=await t?.afterBoot?.(l,o.targetType,a,{recovered:c});return{server:l,verification:p}};async function ns(e){let{client:t,hooks:r}=e,s=e.upgradeDisk??!0;await Se(r,"planning",{serverId:e.serverId,targetType:e.targetType});let n=await Zn(t,e.serverId,e.targetType,s),i=await t.getServer(n.serverId);if(n.alreadyComplete){let c=await Et(e,n,e.manifest,!1);return await Se(r,"complete",{alreadyComplete:!0}),{status:"already-complete",plan:n,verification:c.verification}}if(!n.capacityAvailable&&!e.attemptUnavailable)return await Se(r,"waiting-capacity",{location:n.location,targetType:n.targetType.name}),{status:"waiting-capacity",plan:n};let o=e.manifest;if(i.status==="off"&&!e.resumeFromOff){let c=await Et(e,n,void 0,!0);return{status:"recovered",plan:n,server:c.server,verification:c.verification,retryable:!0,error:"Server was already off without a resumable resize checkpoint; powered it back on."}}if(i.status==="running"){await Se(r,"preflight",{serverId:n.serverId}),o=await r?.preflight?.(i,n.targetType),await Se(r,"shutting-down",{serverId:n.serverId});let c=await t.shutdownServer(n.serverId);await Dr(t,c,e),i=await t.waitForServerStatus(n.serverId,"off",{pollIntervalMs:e.serverPollIntervalMs,maxWaitMs:e.serverTimeoutMs})}try{await Se(r,"resizing",{serverId:n.serverId,from:n.currentType.name,to:n.targetType.name,upgradeDisk:s});let c=await t.changeServerType(n.serverId,n.targetType.name,s);await Dr(t,c,e)}catch(c){let l=await Et(e,n,o,!0);return{status:"recovered",plan:n,server:l.server,manifest:o,verification:l.verification,retryable:Kn(c),error:c instanceof Error?c.message:String(c)}}let a=await Et(e,n,o,!1);if(a.verification&&!a.verification.ok)throw Error(`Resize completed but verification failed: ${(a.verification.failures??[]).join("; ")}`);return await Se(r,"complete",{serverId:n.serverId,targetType:n.targetType.name}),{status:"completed",plan:n,server:a.server,manifest:o,verification:a.verification}}var Ja=String.raw`
380
380
  const { readdir, readFile, readlink, stat } = await import('node:fs/promises')
381
381
 
382
382
  const text = (command) => {
@@ -521,13 +521,13 @@ console.log(JSON.stringify({
521
521
  [Service]
522
522
  MemoryAccounting=true
523
523
  MemoryHigh=%sM
524
- ' "$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)"',...kr()]}function kr(){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 _c(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']}function Qn(e){let{unitBase:t,unitPattern:r,port:s}=e,n=e.path&&e.path.startsWith("/")?e.path:"/",i=Math.max(10,e.intervalSeconds??60),o=Math.max(1,e.failuresBeforeRestart??3),a=`/usr/local/sbin/${t}-liveness`,l=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 > ${a} <<'TS_CLOUD_LIVENESS_EOF'`,"#!/bin/sh","set -eu",`exec 9>/run/${t}-liveness.lock`,"flock -n 9 || exit 0",l,'[ -n "$TS_CLOUD_UNIT" ] || exit 0','systemctl is-active --quiet "$TS_CLOUD_UNIT" || exit 0',`if curl -s -o /dev/null --max-time 5 "http://127.0.0.1:${s}${n}"; then`,` rm -f /run/${t}-liveness.fail`," exit 0","fi",`TS_CLOUD_FAILS=$(cat /run/${t}-liveness.fail 2>/dev/null || echo 0)`,"TS_CLOUD_FAILS=$((TS_CLOUD_FAILS + 1))",`echo "$TS_CLOUD_FAILS" > /run/${t}-liveness.fail`,`[ "$TS_CLOUD_FAILS" -ge ${o} ] || exit 0`,`logger -t ${t}-liveness "no HTTP response on 127.0.0.1:${s}${n} after $TS_CLOUD_FAILS checks; restarting $TS_CLOUD_UNIT"`,'systemctl restart "$TS_CLOUD_UNIT"',`rm -f /run/${t}-liveness.fail`,"TS_CLOUD_LIVENESS_EOF",`chmod +x ${a}`,`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=${a}`,"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`]}function Mr(e){let{siteName:t,slug:r,artifactFetch:s,releaseId:n,execStart:i,envEntries:o,port:a,keepReleases:c=ai,preStartCommands:l=[],healthCheckPath:p,healthGateSeconds:d=5,liveness:m,memoryHigh:g="auto",memoryMax:h,cpuWeight:_,ioWeight:w,tasksMax:b,stopTimeout:y}=e,T=[..._!=null?[`CPUWeight=${_}`]:[],...w!=null?[`IOWeight=${w}`]:[],...b!=null?[`TasksMax=${b}`]:[],...y?[`TimeoutStopSec=${y}`]:[]],S=e.zeroDowntime??a!=null,D=e.appDir??`/var/www/${t}`,O=Lt(D,n),R=`${r}-${t}`,k=`${R}.service`,se=ut(r,t,n),z=e.sharedPaths??[],X=Fa([".env",...z,...kt(o,z)]),q=Nt(o),F=l.length>0?[`cd ${O.release}`,...l]:[],ee=["set -euo pipefail",...bs(O),Ts(O),...s,...ci(O,X),...vs(O),`tar xzf ${se} -C "$TS_CLOUD_STAGED"`,`rm -f ${se}`,`cat > ${O.shared}/.env <<'TS_CLOUD_ENV_EOF'`,q,"TS_CLOUD_ENV_EOF",`chmod 600 ${O.shared}/.env`,...Es(O),`find ${O.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' ${O.shared}/.env 2>/dev/null || true`,...mo(O,X),...F];if(S&&a!=null){let H=`${R}@${n}.service`,he=p?p.startsWith("/")?p:`/${p}`:null,Y=`{ echo "[ts-cloud] release ${n} failed its health gate — previous release keeps serving" >&2; journalctl -u ${H} -n 50 --no-pager >&2 || true; systemctl stop ${H} 2>/dev/null || true; exit 1; }`;return[...ee,`cat > /etc/systemd/system/${R}@.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} release %i (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${O.releases}/%i`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...g&&g!=="auto"?[`MemoryHigh=${g}`]:[],...h?[`MemoryMax=${h}`]:[],...T,`EnvironmentFile=${O.releases}/%i/.env`,`Environment=PORT=${a}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...g==="auto"?Jn(`${R}@.service`):kr(),..._c(H),`TS_CLOUD_OLD_UNITS=$(systemctl list-units --plain --no-legend --type=service "${R}@*.service" 2>/dev/null | awk '{print $1}' | grep -v "^${H}$" || true)`,`if [ -f /etc/systemd/system/${k} ] && systemctl is-active --quiet ${k}; then echo "[ts-cloud] retiring pre-zero-downtime unit ${k} (one-time restart cutover)"; systemctl stop ${k}; fi`,`systemctl restart ${H}`,`TS_CLOUD_GATE_OK=1; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do sleep 1; systemctl is-active --quiet ${H} || { TS_CLOUD_GATE_OK=0; break; }; done`,`if [ "$TS_CLOUD_GATE_OK" -ne 1 ]; then echo "[ts-cloud] release ${n} could not overlap the previous release (no SO_REUSEPORT?) — retiring old instances 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 ${H}; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do sleep 1; systemctl is-active --quiet ${H} || ${Y}; done; fi`,...he?[`curl -sf -o /dev/null --max-time 10 "http://127.0.0.1:${a}${he}" || ${Y}`]:[],...Jr(O),`systemctl enable ${H} 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 ${Math.max(1,d)}); do if ss -ltnH "sport = :${a}" 2>/dev/null | grep -q .; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done`,`if [ "$TS_CLOUD_LISTENING" -ne 1 ]; then echo "[ts-cloud] nothing is listening on ${a} after retiring the previous release — restarting ${H} on the now-free port" >&2; systemctl restart ${H}; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do if ss -ltnH "sport = :${a}" 2>/dev/null | grep -q .; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done; fi`,`if [ "$TS_CLOUD_LISTENING" -ne 1 ]; then echo "[ts-cloud] ${H} is active but never bound ${a}" >&2; journalctl -u ${H} -n 50 --no-pager >&2 || true; exit 1; fi`,`systemctl list-unit-files --plain --no-legend "${R}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v -e "^${H}$" -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/${k} ]; then systemctl disable ${k} 2>/dev/null || true; rm -f /etc/systemd/system/${k}; systemctl daemon-reload; fi`,...Xr(O,c),...m===!1?[]:Qn({unitBase:R,unitPattern:`${R}@*.service`,port:a,path:m?.path??p,intervalSeconds:m?.intervalSeconds,failuresBeforeRestart:m?.failuresBeforeRestart})]}return[...ee,`cat > /etc/systemd/system/${k} <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${O.current}`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...g&&g!=="auto"?[`MemoryHigh=${g}`]:[],...h?[`MemoryMax=${h}`]:[],...T,`EnvironmentFile=${O.current}/.env`,...a?[`Environment=PORT=${a}`]:[],"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...g==="auto"?Jn(k):kr(),`systemctl enable ${k}`,...Jr(O),`systemctl restart ${k}`,`systemctl is-active ${k}`,...Xr(O,c),...m===!1||!a?[]:Qn({unitBase:R,unitPattern:k,port:a,path:m?.path??p,intervalSeconds:m?.intervalSeconds,failuresBeforeRestart:m?.failuresBeforeRestart})]}function Ur(e){let{siteName:t,artifactFetch:r,releaseId:s,keepReleases:n=ai,preStartCommands:i=[]}=e,o=e.appDir??`/var/www/${t}`,a=Lt(o,s),c=ut(e.slug,t,s),l=i.length>0?[`cd ${a.release}`,...i]:[];return["set -euo pipefail",...bs(a),Ts(a),...r,...ci(a,[]),...vs(a),`tar xzf ${c} -C "$TS_CLOUD_STAGED"`,...Es(a),`rm -f ${c}`,...l,...Jr(a),...Xr(a,n)]}function ut(e,t,r){return`/tmp/${[e,t,r].filter(Boolean).join("-")}-release.tar.gz`}function Fr(e,t,r,s){return[`aws s3 cp "s3://${e}/${t}" ${s} --region ${r}`]}function Br(e,t){return[`mv "${e}" ${t}`]}function Kr(){return['echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',"find /var/ts-cloud/staging -xdev -maxdepth 1 -type f -mmin +60 -delete 2>/dev/null || true",'find /tmp -xdev -maxdepth 1 -type f -name "*-release.tar.gz" -mmin +60 -delete 2>/dev/null || true',"find /root/.bun/install/cache -xdev -type f -mtime +7 -delete 2>/dev/null || true","find /root/.bun/install/cache -xdev -depth -type d -empty -delete 2>/dev/null || true","journalctl --vacuum-time=14d --vacuum-size=512M >/dev/null 2>&1 || true",'if command -v docker >/dev/null 2>&1; then docker image prune --all --force --filter "until=168h" >/dev/null 2>&1 || true; fi','if command -v podman >/dev/null 2>&1; then podman image prune --all --force --filter "until=168h" >/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",'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"']}import{copyFileSync as Vc}from"node:fs";import{tmpdir as Xc}from"node:os";import{join as qc}from"node:path";var Tc=`${B}/project`;function ri(e,t){let r=t.ownerSlug.trim(),s=t.selfSlug?.trim(),n={total:e.length,owner:[],self:[],others:new Map,unmanaged:[]};for(let i of e){let o=i.labels?.[Tc]?.trim();if(!o){n.unmanaged.push(i.name);continue}if(o===r){n.owner.push(i.name);continue}if(s&&o===s){n.self.push(i.name);continue}let a=n.others.get(o);if(a)a.push(i.name);else n.others.set(o,[i.name])}return n}function jr(e){let t=e.unmanaged.length;for(let r of e.others.values())t+=r.length;return t}function si(e,t){let r=jr(e),s=[];if(s.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 s.push("Nothing outside the two projects being joined is reachable with it."),s;s.push(`${r} of them belong to neither project:`);for(let n of[...e.others.keys()].sort())s.push(` ${n}: ${[...e.others.get(n)].sort().join(", ")}`);if(e.unmanaged.length>0)s.push(` not managed by ts-cloud: ${[...e.unmanaged].sort().join(", ")}`);return s.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."),s}var Pc=new Set(["laravel","php","statamic","wordpress"]);function Gr(e){if(e.framework)return e.framework;if(e.type&&Pc.has(e.type))return"laravel";return"stacks"}var oi=`eval "$(cd ${M} && pantry env 2>/dev/null)"`,li="/usr/local/bin/bun",xc="storage/framework/core/buddy/src/cli.ts",Cc="node_modules/@stacksjs/ts-cloud/dist/bin/stacks-scheduler.js",ui={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:()=>`${li} ${Cc}`,queueWorkerCommand:(e,{current:t})=>{let r=[`--queue=${e.queue||"default"}`,`--sleep=${e.sleep??3}`,`--tries=${e.tries??3}`,`--timeout=${e.timeout??60}`];return`${li} ${t}/${xc} queue:work ${r.join(" ")}`}},Rc={id:"laravel",wrapExec:(e)=>`/bin/sh -lc '${oi}; exec ${e}'`,schedulerMode:"cron",schedulerCommand:({current:e})=>`cd ${e} && ${oi} && php artisan schedule:run`,queueWorkerCommand:(e,{current:t})=>{let r=`${t}/artisan`;if(e.horizon)return`php ${r} horizon`;let s=[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)s.push(`--max-jobs=${e.maxJobs}`);if(e.maxTime)s.push(`--max-time=${e.maxTime}`);return`php ${r} queue:work ${s.join(" ")}`}},Ec={stacks:ui,laravel:Rc};function di(e){return Ec[e]??ui}function mi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ic(e){return`'${e.split("'").join("'\\''")}'`}function fi(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"unnamed"}function Oc(e,t,r){return`${e}-${t}-queue-${r}`}function Dc(e,t,r,s){return`${e}-${t}-daemon-${r.name?fi(r.name):fi(r.command).slice(0,32)||String(s)}`}function Yr(e){let t=["[Unit]",`Description=${e.description}`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${e.workingDir}`,...Object.entries(e.environment??{}).map(([r,s])=>`Environment="${r}=${s}"`),`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(`
524
+ ' "$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)"',...kr()]}function kr(){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 _c(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']}function Qn(e){let{unitBase:t,unitPattern:r,port:s}=e,n=e.path&&e.path.startsWith("/")?e.path:"/",i=Math.max(10,e.intervalSeconds??60),o=Math.max(1,e.failuresBeforeRestart??3),a=`/usr/local/sbin/${t}-liveness`,l=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 > ${a} <<'TS_CLOUD_LIVENESS_EOF'`,"#!/bin/sh","set -eu",`exec 9>/run/${t}-liveness.lock`,"flock -n 9 || exit 0",l,'[ -n "$TS_CLOUD_UNIT" ] || exit 0','systemctl is-active --quiet "$TS_CLOUD_UNIT" || exit 0',`if curl -s -o /dev/null --max-time 5 "http://127.0.0.1:${s}${n}"; then`,` rm -f /run/${t}-liveness.fail`," exit 0","fi",`TS_CLOUD_FAILS=$(cat /run/${t}-liveness.fail 2>/dev/null || echo 0)`,"TS_CLOUD_FAILS=$((TS_CLOUD_FAILS + 1))",`echo "$TS_CLOUD_FAILS" > /run/${t}-liveness.fail`,`[ "$TS_CLOUD_FAILS" -ge ${o} ] || exit 0`,`logger -t ${t}-liveness "no HTTP response on 127.0.0.1:${s}${n} after $TS_CLOUD_FAILS checks; restarting $TS_CLOUD_UNIT"`,'systemctl restart "$TS_CLOUD_UNIT"',`rm -f /run/${t}-liveness.fail`,"TS_CLOUD_LIVENESS_EOF",`chmod +x ${a}`,`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=${a}`,"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`]}function Mr(e){let{siteName:t,slug:r,artifactFetch:s,releaseId:n,execStart:i,envEntries:o,port:a,keepReleases:c=ai,preStartCommands:l=[],healthCheckPath:p,healthGateSeconds:d=5,liveness:m,memoryHigh:g="auto",memoryMax:h,cpuWeight:_,ioWeight:w,tasksMax:b,stopTimeout:y}=e,T=[..._!=null?[`CPUWeight=${_}`]:[],...w!=null?[`IOWeight=${w}`]:[],...b!=null?[`TasksMax=${b}`]:[],...y?[`TimeoutStopSec=${y}`]:[]],S=e.zeroDowntime??a!=null,D=e.appDir??`/var/www/${t}`,O=Lt(D,n),R=`${r}-${t}`,k=`${R}.service`,ne=ut(r,t,n),z=e.sharedPaths??[],X=Fa([".env",...z,...kt(o,z)]),q=Nt(o),F=l.length>0?[`cd ${O.release}`,...l]:[],ee=["set -euo pipefail",...bs(O),Ts(O),...s,...ci(O,X),...vs(O),`tar xzf ${ne} -C "$TS_CLOUD_STAGED"`,`rm -f ${ne}`,`cat > ${O.shared}/.env <<'TS_CLOUD_ENV_EOF'`,q,"TS_CLOUD_ENV_EOF",`chmod 600 ${O.shared}/.env`,...Es(O),`find ${O.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' ${O.shared}/.env 2>/dev/null || true`,...mo(O,X),...F];if(S&&a!=null){let H=`${R}@${n}.service`,ye=p?p.startsWith("/")?p:`/${p}`:null,Y=`{ echo "[ts-cloud] release ${n} failed its health gate — previous release keeps serving" >&2; journalctl -u ${H} -n 50 --no-pager >&2 || true; systemctl stop ${H} 2>/dev/null || true; exit 1; }`;return[...ee,`cat > /etc/systemd/system/${R}@.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} release %i (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${O.releases}/%i`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...g&&g!=="auto"?[`MemoryHigh=${g}`]:[],...h?[`MemoryMax=${h}`]:[],...T,`EnvironmentFile=${O.releases}/%i/.env`,`Environment=PORT=${a}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...g==="auto"?Jn(`${R}@.service`):kr(),..._c(H),`TS_CLOUD_OLD_UNITS=$(systemctl list-units --plain --no-legend --type=service "${R}@*.service" 2>/dev/null | awk '{print $1}' | grep -v "^${H}$" || true)`,`if [ -f /etc/systemd/system/${k} ] && systemctl is-active --quiet ${k}; then echo "[ts-cloud] retiring pre-zero-downtime unit ${k} (one-time restart cutover)"; systemctl stop ${k}; fi`,`systemctl restart ${H}`,`TS_CLOUD_GATE_OK=1; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do sleep 1; systemctl is-active --quiet ${H} || { TS_CLOUD_GATE_OK=0; break; }; done`,`if [ "$TS_CLOUD_GATE_OK" -ne 1 ]; then echo "[ts-cloud] release ${n} could not overlap the previous release (no SO_REUSEPORT?) — retiring old instances 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 ${H}; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do sleep 1; systemctl is-active --quiet ${H} || ${Y}; done; fi`,...ye?[`curl -sf -o /dev/null --max-time 10 "http://127.0.0.1:${a}${ye}" || ${Y}`]:[],...Jr(O),`systemctl enable ${H} 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 ${Math.max(1,d)}); do if ss -ltnH "sport = :${a}" 2>/dev/null | grep -q .; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done`,`if [ "$TS_CLOUD_LISTENING" -ne 1 ]; then echo "[ts-cloud] nothing is listening on ${a} after retiring the previous release — restarting ${H} on the now-free port" >&2; systemctl restart ${H}; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do if ss -ltnH "sport = :${a}" 2>/dev/null | grep -q .; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done; fi`,`if [ "$TS_CLOUD_LISTENING" -ne 1 ]; then echo "[ts-cloud] ${H} is active but never bound ${a}" >&2; journalctl -u ${H} -n 50 --no-pager >&2 || true; exit 1; fi`,`systemctl list-unit-files --plain --no-legend "${R}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v -e "^${H}$" -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/${k} ]; then systemctl disable ${k} 2>/dev/null || true; rm -f /etc/systemd/system/${k}; systemctl daemon-reload; fi`,...Xr(O,c),...m===!1?[]:Qn({unitBase:R,unitPattern:`${R}@*.service`,port:a,path:m?.path??p,intervalSeconds:m?.intervalSeconds,failuresBeforeRestart:m?.failuresBeforeRestart})]}return[...ee,`cat > /etc/systemd/system/${k} <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${O.current}`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...g&&g!=="auto"?[`MemoryHigh=${g}`]:[],...h?[`MemoryMax=${h}`]:[],...T,`EnvironmentFile=${O.current}/.env`,...a?[`Environment=PORT=${a}`]:[],"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...g==="auto"?Jn(k):kr(),`systemctl enable ${k}`,...Jr(O),`systemctl restart ${k}`,`systemctl is-active ${k}`,...Xr(O,c),...m===!1||!a?[]:Qn({unitBase:R,unitPattern:k,port:a,path:m?.path??p,intervalSeconds:m?.intervalSeconds,failuresBeforeRestart:m?.failuresBeforeRestart})]}function Ur(e){let{siteName:t,artifactFetch:r,releaseId:s,keepReleases:n=ai,preStartCommands:i=[]}=e,o=e.appDir??`/var/www/${t}`,a=Lt(o,s),c=ut(e.slug,t,s),l=i.length>0?[`cd ${a.release}`,...i]:[];return["set -euo pipefail",...bs(a),Ts(a),...r,...ci(a,[]),...vs(a),`tar xzf ${c} -C "$TS_CLOUD_STAGED"`,...Es(a),`rm -f ${c}`,...l,...Jr(a),...Xr(a,n)]}function ut(e,t,r){return`/tmp/${[e,t,r].filter(Boolean).join("-")}-release.tar.gz`}function Fr(e,t,r,s){return[`aws s3 cp "s3://${e}/${t}" ${s} --region ${r}`]}function Br(e,t){return[`mv "${e}" ${t}`]}function Kr(){return['echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',"find /var/ts-cloud/staging -xdev -maxdepth 1 -type f -mmin +60 -delete 2>/dev/null || true",'find /tmp -xdev -maxdepth 1 -type f -name "*-release.tar.gz" -mmin +60 -delete 2>/dev/null || true',"find /root/.bun/install/cache -xdev -type f -mtime +7 -delete 2>/dev/null || true","find /root/.bun/install/cache -xdev -depth -type d -empty -delete 2>/dev/null || true","journalctl --vacuum-time=14d --vacuum-size=512M >/dev/null 2>&1 || true",'if command -v docker >/dev/null 2>&1; then docker image prune --all --force --filter "until=168h" >/dev/null 2>&1 || true; fi','if command -v podman >/dev/null 2>&1; then podman image prune --all --force --filter "until=168h" >/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",'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"']}import{copyFileSync as Vc}from"node:fs";import{tmpdir as Xc}from"node:os";import{join as qc}from"node:path";var Tc=`${B}/project`;function ri(e,t){let r=t.ownerSlug.trim(),s=t.selfSlug?.trim(),n={total:e.length,owner:[],self:[],others:new Map,unmanaged:[]};for(let i of e){let o=i.labels?.[Tc]?.trim();if(!o){n.unmanaged.push(i.name);continue}if(o===r){n.owner.push(i.name);continue}if(s&&o===s){n.self.push(i.name);continue}let a=n.others.get(o);if(a)a.push(i.name);else n.others.set(o,[i.name])}return n}function jr(e){let t=e.unmanaged.length;for(let r of e.others.values())t+=r.length;return t}function si(e,t){let r=jr(e),s=[];if(s.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 s.push("Nothing outside the two projects being joined is reachable with it."),s;s.push(`${r} of them belong to neither project:`);for(let n of[...e.others.keys()].sort())s.push(` ${n}: ${[...e.others.get(n)].sort().join(", ")}`);if(e.unmanaged.length>0)s.push(` not managed by ts-cloud: ${[...e.unmanaged].sort().join(", ")}`);return s.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."),s}var Pc=new Set(["laravel","php","statamic","wordpress"]);function Gr(e){if(e.framework)return e.framework;if(e.type&&Pc.has(e.type))return"laravel";return"stacks"}var oi=`eval "$(cd ${M} && pantry env 2>/dev/null)"`,li="/usr/local/bin/bun",xc="storage/framework/core/buddy/src/cli.ts",Cc="node_modules/@stacksjs/ts-cloud/dist/bin/stacks-scheduler.js",ui={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:()=>`${li} ${Cc}`,queueWorkerCommand:(e,{current:t})=>{let r=[`--queue=${e.queue||"default"}`,`--sleep=${e.sleep??3}`,`--tries=${e.tries??3}`,`--timeout=${e.timeout??60}`];return`${li} ${t}/${xc} queue:work ${r.join(" ")}`}},Rc={id:"laravel",wrapExec:(e)=>`/bin/sh -lc '${oi}; exec ${e}'`,schedulerMode:"cron",schedulerCommand:({current:e})=>`cd ${e} && ${oi} && php artisan schedule:run`,queueWorkerCommand:(e,{current:t})=>{let r=`${t}/artisan`;if(e.horizon)return`php ${r} horizon`;let s=[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)s.push(`--max-jobs=${e.maxJobs}`);if(e.maxTime)s.push(`--max-time=${e.maxTime}`);return`php ${r} queue:work ${s.join(" ")}`}},Ec={stacks:ui,laravel:Rc};function di(e){return Ec[e]??ui}function mi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ic(e){return`'${e.split("'").join("'\\''")}'`}function fi(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"unnamed"}function Oc(e,t,r){return`${e}-${t}-queue-${r}`}function Dc(e,t,r,s){return`${e}-${t}-daemon-${r.name?fi(r.name):fi(r.command).slice(0,32)||String(s)}`}function Yr(e){let t=["[Unit]",`Description=${e.description}`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${e.workingDir}`,...Object.entries(e.environment??{}).map(([r,s])=>`Environment="${r}=${s}"`),`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(`
525
525
  `)}
526
526
  `}function Zr(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_UNIT_EOF'`,t.replace(/\n$/,""),"TS_CLOUD_UNIT_EOF"]}function Ac(e,t){return`/etc/cron.d/${e}-${t}-scheduler`}function es(e){let{slug:t,siteName:r,site:s}=e,i=`${e.appBase??`/var/www/${r}`}/current`,o=di(Gr(s)),a={current:i},c=[],l=[];(s.queues||[]).forEach((b,y)=>{let T=Math.max(1,b.processes??1);for(let S=0;S<T;S++){let D=Oc(t,r,l.length);l.push(D),c.push(...Zr(D,Yr({description:`${r} queue worker ${y}.${S} (managed by ts-cloud)`,workingDir:i,execStart:o.wrapExec(o.queueWorkerCommand(b,a)),environment:o.execEnv,stopWaitSecs:b.stopWaitSecs??90})))}}),(s.daemons||[]).forEach((b,y)=>{let T=Math.max(1,b.processes??1);for(let S=0;S<T;S++){let D=`${Dc(t,r,b,y)}-${S}`;l.push(D),c.push(...Zr(D,Yr({description:`${r} daemon ${b.name||b.command} (managed by ts-cloud)`,workingDir:b.directory||i,execStart:o.wrapExec(b.command),environment:o.execEnv,restart:b.restart,user:b.user})))}});let m=s.scheduler,g=m===!0||typeof m==="object"&&m!==null,h=`${t}-${r}-scheduler`;if(g&&o.schedulerMode==="daemon")l.push(h),c.push(...Zr(h,Yr({description:`${r} scheduler (managed by ts-cloud)`,workingDir:i,execStart:o.wrapExec(o.schedulerCommand(a)),environment:o.execEnv})));let _=l.map((b)=>`${b}.service`).join(" ");c.push("systemctl daemon-reload",`TS_CLOUD_DESIRED="${_}"`,`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E '^${mi(t)}-${mi(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 b of l)c.push(`systemctl enable ${b}.service`,`systemctl restart ${b}.service`);let w=Ac(t,r);if(g&&o.schedulerMode==="cron"){let b=typeof m==="object"&&m!==null?m:void 0,y=`${o.schedulerCommand(a)} >> /dev/null 2>&1`;if(b?.heartbeatUrl){let S=b.heartbeatMethod||"GET",D=S==="GET"?"":`-X ${S} `;y+=` && curl -fsS -m 10 ${D}${Ic(b.heartbeatUrl)} >/dev/null 2>&1`}let T=`* * * * * root ${y}
527
527
  `.replace(/%/g,"\\%");c.push(`cat > ${w} <<'TS_CLOUD_CRON_EOF'`,T.replace(/\n$/,""),"TS_CLOUD_CRON_EOF",`chmod 644 ${w}`)}else c.push(`rm -f ${w}`);return c}function ts(e){return!!(e.queues?.length||e.daemons?.length||e.scheduler)}function us(e){if(e.ssl?.provider)return e.ssl.provider;return e.domain?"letsencrypt":"none"}var gi={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 hi(e){return`/etc/letsencrypt/ts-cloud-${e}.ini`}function Nc(e){let t=e?gi[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 kc(e){if(!e.credentials||Object.keys(e.credentials).length===0)return[];let t=hi(e.provider),r=Object.entries(e.credentials).map(([s,n])=>`${s} = ${n}`).join(`
528
- `);return[`cat > ${t} <<'TS_CLOUD_DNSCREDS_EOF'`,r,"TS_CLOUD_DNSCREDS_EOF",`chmod 600 ${t}`]}function Hc(e){let t=e.dns,r=e.wildcard?[`*.${e.domain}`,e.domain]:[e.domain,...e.aliases||[]].filter(Boolean),s=["certbot","--non-interactive","--agree-tos","--keep-until-expiring"];if(t){let n=gi[t.provider].plugin;if(s.push(`--${n}`),t.provider!=="route53"&&t.credentials)s.push(`--${n}-credentials ${hi(t.provider)}`);if(typeof t.propagationSeconds==="number"&&t.provider!=="route53")s.push(`--${n}-propagation-seconds ${t.propagationSeconds}`);s.push("certonly")}else s.push("--nginx",`--nginx-ctl ${$e}`,e.redirect===!1?"--no-redirect":"--redirect");if(e.email)s.push(`-m ${e.email}`);else s.push("--register-unsafely-without-email");for(let n of r)s.push(`-d ${n}`);return[s.join(" ")]}function fs(e){if(us(e)!=="letsencrypt"||!e.domain)return[];let t=e.ssl,r=t?.dns,s=t?.wildcard===!0;if(s&&!r)return[];return[...Nc(r),...r?kc(r):[],...Hc({domain:e.domain,aliases:e.aliases,email:t?.email,wildcard:s,dns:r})]}function yi(e){let{repository:t,releaseDir:r,commit:s}=e,n=t.branch||"main",i=t.url,o=[`rm -rf ${r}`,`mkdir -p ${r}`];if(t.strategy==="tag")if(t.tag)o.push(`git clone -q --depth 1 --branch ${ie(t.tag)} ${ie(i)} ${r}`),o.push(`printf '%s' ${ie(t.tag)} > ${r}/.ts-cloud-tag`);else{let a=t.tagPattern||"v*";o.push(`TS_CLOUD_TAG="$(git ls-remote --tags --refs --sort=-v:refname ${ie(i)} ${ie(`refs/tags/${a}`)} | head -n1 | sed 's#.*refs/tags/##')"`,`test -n "$TS_CLOUD_TAG" || { echo "no tags matching" ${ie(a)} "found in" ${ie(i)} >&2; exit 1; }`,`git clone -q --depth 1 --branch "$TS_CLOUD_TAG" ${ie(i)} ${r}`,`printf '%s' "$TS_CLOUD_TAG" > ${r}/.ts-cloud-tag`)}else if(s)o.push(`git -C ${r} init -q`,`git -C ${r} remote add origin ${ie(i)}`,`git -C ${r} fetch -q --depth 1 origin ${ie(s)}`,`git -C ${r} checkout -q FETCH_HEAD`);else o.push(`git clone -q --depth 1 --branch ${ie(n)} ${ie(i)} ${r}`);return o.push(`git -C ${r} rev-parse HEAD > ${r}/.ts-cloud-sha`),o}function ie(e){return`'${e.split("'").join("'\\''")}'`}var Ht="$CREATE_RELEASE",Mt="$ACTIVATE_RELEASE",bi="$RESTART_QUEUES",Si="composer install --no-interaction --prefer-dist --optimize-autoloader --no-dev",Lc=["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 Mc(e){switch(e){case"laravel":case"statamic":return[Ht,Si,...Lc,Mt,bi];case"php":case"wordpress":return[Ht,`${Si} || true`,Mt];case"static":case"spa":return[Ht,Mt]}}function Uc(e,t){return e.replace(/^php\s+/,`${t} `).replace(/(\s)php\s+artisan\s+/g,`$1${t} artisan `)}function zc(e,t){let r=Nt(t);return[`cat > ${e} <<'TS_CLOUD_ENV_EOF'`,r,"TS_CLOUD_ENV_EOF",`chmod 600 ${e}`]}function vi(e,t,r){return[`cat > ${e} <<'${r}'`,t.replace(/\n$/,""),r,`chmod 600 ${e}`]}function Fc(e,t){if(!t)return[];let r=[];if(t.composerAuth){let s=typeof t.composerAuth==="string"?t.composerAuth:JSON.stringify(t.composerAuth,null,2);r.push(...vi(`${e}/auth.json`,s,"TS_CLOUD_AUTHJSON_EOF"))}if(t.npmrc)r.push(...vi(`${e}/.npmrc`,t.npmrc,"TS_CLOUD_NPMRC_EOF"));return r}function wi(e){let t=e.healthCheck?.path;if(!t||!e.domain)return[];let s=`http://127.0.0.1${t.startsWith("/")?t:`/${t}`}`;return[`echo "[ts-cloud] health check ${s} (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 "${s}" 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 $i(e){let{siteName:t,site:r,releaseId:s,commit:n}=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}`,o="php",a=Lt(i,s),c=r.sharedPaths??po,l=[...c,...kt(r.env,c)],p=r.keepReleases??ai,d=r.deployScript?.length?r.deployScript:Mc(r.type??"laravel"),m=["set -euo pipefail",'export HOME="${HOME:-/root}"','export COMPOSER_HOME="${COMPOSER_HOME:-/root/.composer}"',"export COMPOSER_ALLOW_SUPERUSER=1",ft()];if(m.push(...go(i,{releaseId:s,commit:n,branch:r.repository.branch,keepLogs:p})),m.push(...ci(a,l)),r.env&&Object.keys(r.env).length>0)m.push(...zc(`${a.shared}/.env`,r.env));for(let g of d){let h=g.trim();if(h===Ht)m.push(...yi({repository:r.repository,releaseDir:a.release,commit:n})),m.push(...mo(a,l)),m.push(`cd ${a.release}`),m.push(...Fc(a.release,r.credentials)),m.push(`chown -R www-data:www-data ${a.shared}/storage 2>/dev/null || true`,`[ -d ${a.release}/bootstrap/cache ] && chown -R www-data:www-data ${a.release}/bootstrap/cache 2>/dev/null || true`,`chmod -R ug+rwX ${a.shared}/storage 2>/dev/null || true`);else if(h===Mt)m.push(...Jr(a)),m.push(...Xr(a,p)),m.push(`(cd ${M} && pantry restart php-fpm) 2>/dev/null || true`);else if(h===bi)m.push(`${o} artisan queue:restart || true`);else m.push(Uc(g,o))}return m}var Ut={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"]}},dt="ts-cloud-service:";function Bc(e){return e===!0||typeof e==="object"&&e!=null}function _i(e){if(!e)return[];return Object.keys(Ut).filter((t)=>Bc(e[t]))}function Ti(e){if(e.length===0)return[];return[ft(),"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 "${dt}$TS_CLOUD_SVC:present"; return 0; fi`," done",` if ts_cloud_port_open "$TS_CLOUD_PORT"; then echo "${dt}$TS_CLOUD_SVC:present"; return 0; fi`,` echo "${dt}$TS_CLOUD_SVC:missing"`," return 0","}",...e.filter((t)=>Ut[t]).map((t)=>`ts_cloud_probe ${t} ${Ut[t].port} ${Ut[t].binaries.join(" ")}`),"exit 0"]}function Pi(e,t){if(!e)return[];let r=new Map;for(let s of e.split(`
528
+ `);return[`cat > ${t} <<'TS_CLOUD_DNSCREDS_EOF'`,r,"TS_CLOUD_DNSCREDS_EOF",`chmod 600 ${t}`]}function Hc(e){let t=e.dns,r=e.wildcard?[`*.${e.domain}`,e.domain]:[e.domain,...e.aliases||[]].filter(Boolean),s=["certbot","--non-interactive","--agree-tos","--keep-until-expiring"];if(t){let n=gi[t.provider].plugin;if(s.push(`--${n}`),t.provider!=="route53"&&t.credentials)s.push(`--${n}-credentials ${hi(t.provider)}`);if(typeof t.propagationSeconds==="number"&&t.provider!=="route53")s.push(`--${n}-propagation-seconds ${t.propagationSeconds}`);s.push("certonly")}else s.push("--nginx",`--nginx-ctl ${$e}`,e.redirect===!1?"--no-redirect":"--redirect");if(e.email)s.push(`-m ${e.email}`);else s.push("--register-unsafely-without-email");for(let n of r)s.push(`-d ${n}`);return[s.join(" ")]}function fs(e){if(us(e)!=="letsencrypt"||!e.domain)return[];let t=e.ssl,r=t?.dns,s=t?.wildcard===!0;if(s&&!r)return[];return[...Nc(r),...r?kc(r):[],...Hc({domain:e.domain,aliases:e.aliases,email:t?.email,wildcard:s,dns:r})]}function yi(e){let{repository:t,releaseDir:r,commit:s}=e,n=t.branch||"main",i=t.url,o=[`rm -rf ${r}`,`mkdir -p ${r}`];if(t.strategy==="tag")if(t.tag)o.push(`git clone -q --depth 1 --branch ${oe(t.tag)} ${oe(i)} ${r}`),o.push(`printf '%s' ${oe(t.tag)} > ${r}/.ts-cloud-tag`);else{let a=t.tagPattern||"v*";o.push(`TS_CLOUD_TAG="$(git ls-remote --tags --refs --sort=-v:refname ${oe(i)} ${oe(`refs/tags/${a}`)} | head -n1 | sed 's#.*refs/tags/##')"`,`test -n "$TS_CLOUD_TAG" || { echo "no tags matching" ${oe(a)} "found in" ${oe(i)} >&2; exit 1; }`,`git clone -q --depth 1 --branch "$TS_CLOUD_TAG" ${oe(i)} ${r}`,`printf '%s' "$TS_CLOUD_TAG" > ${r}/.ts-cloud-tag`)}else if(s)o.push(`git -C ${r} init -q`,`git -C ${r} remote add origin ${oe(i)}`,`git -C ${r} fetch -q --depth 1 origin ${oe(s)}`,`git -C ${r} checkout -q FETCH_HEAD`);else o.push(`git clone -q --depth 1 --branch ${oe(n)} ${oe(i)} ${r}`);return o.push(`git -C ${r} rev-parse HEAD > ${r}/.ts-cloud-sha`),o}function oe(e){return`'${e.split("'").join("'\\''")}'`}var Ht="$CREATE_RELEASE",Mt="$ACTIVATE_RELEASE",bi="$RESTART_QUEUES",Si="composer install --no-interaction --prefer-dist --optimize-autoloader --no-dev",Lc=["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 Mc(e){switch(e){case"laravel":case"statamic":return[Ht,Si,...Lc,Mt,bi];case"php":case"wordpress":return[Ht,`${Si} || true`,Mt];case"static":case"spa":return[Ht,Mt]}}function Uc(e,t){return e.replace(/^php\s+/,`${t} `).replace(/(\s)php\s+artisan\s+/g,`$1${t} artisan `)}function zc(e,t){let r=Nt(t);return[`cat > ${e} <<'TS_CLOUD_ENV_EOF'`,r,"TS_CLOUD_ENV_EOF",`chmod 600 ${e}`]}function vi(e,t,r){return[`cat > ${e} <<'${r}'`,t.replace(/\n$/,""),r,`chmod 600 ${e}`]}function Fc(e,t){if(!t)return[];let r=[];if(t.composerAuth){let s=typeof t.composerAuth==="string"?t.composerAuth:JSON.stringify(t.composerAuth,null,2);r.push(...vi(`${e}/auth.json`,s,"TS_CLOUD_AUTHJSON_EOF"))}if(t.npmrc)r.push(...vi(`${e}/.npmrc`,t.npmrc,"TS_CLOUD_NPMRC_EOF"));return r}function wi(e){let t=e.healthCheck?.path;if(!t||!e.domain)return[];let s=`http://127.0.0.1${t.startsWith("/")?t:`/${t}`}`;return[`echo "[ts-cloud] health check ${s} (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 "${s}" 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 $i(e){let{siteName:t,site:r,releaseId:s,commit:n}=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}`,o="php",a=Lt(i,s),c=r.sharedPaths??po,l=[...c,...kt(r.env,c)],p=r.keepReleases??ai,d=r.deployScript?.length?r.deployScript:Mc(r.type??"laravel"),m=["set -euo pipefail",'export HOME="${HOME:-/root}"','export COMPOSER_HOME="${COMPOSER_HOME:-/root/.composer}"',"export COMPOSER_ALLOW_SUPERUSER=1",ft()];if(m.push(...go(i,{releaseId:s,commit:n,branch:r.repository.branch,keepLogs:p})),m.push(...ci(a,l)),r.env&&Object.keys(r.env).length>0)m.push(...zc(`${a.shared}/.env`,r.env));for(let g of d){let h=g.trim();if(h===Ht)m.push(...yi({repository:r.repository,releaseDir:a.release,commit:n})),m.push(...mo(a,l)),m.push(`cd ${a.release}`),m.push(...Fc(a.release,r.credentials)),m.push(`chown -R www-data:www-data ${a.shared}/storage 2>/dev/null || true`,`[ -d ${a.release}/bootstrap/cache ] && chown -R www-data:www-data ${a.release}/bootstrap/cache 2>/dev/null || true`,`chmod -R ug+rwX ${a.shared}/storage 2>/dev/null || true`);else if(h===Mt)m.push(...Jr(a)),m.push(...Xr(a,p)),m.push(`(cd ${M} && pantry restart php-fpm) 2>/dev/null || true`);else if(h===bi)m.push(`${o} artisan queue:restart || true`);else m.push(Uc(g,o))}return m}var Ut={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"]}},dt="ts-cloud-service:";function Bc(e){return e===!0||typeof e==="object"&&e!=null}function _i(e){if(!e)return[];return Object.keys(Ut).filter((t)=>Bc(e[t]))}function Ti(e){if(e.length===0)return[];return[ft(),"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 "${dt}$TS_CLOUD_SVC:present"; return 0; fi`," done",` if ts_cloud_port_open "$TS_CLOUD_PORT"; then echo "${dt}$TS_CLOUD_SVC:present"; return 0; fi`,` echo "${dt}$TS_CLOUD_SVC:missing"`," return 0","}",...e.filter((t)=>Ut[t]).map((t)=>`ts_cloud_probe ${t} ${Ut[t].port} ${Ut[t].binaries.join(" ")}`),"exit 0"]}function Pi(e,t){if(!e)return[];let r=new Map;for(let s of e.split(`
529
529
  `)){let n=s.indexOf(dt);if(n===-1)continue;let[i,o]=s.slice(n+dt.length).trim().split(":");if(i)r.set(i,o)}return t.filter((s)=>r.get(s)==="missing")}function xi(e,t,r){let s=r?` on ${r}`:"",n=e.map((o)=>`managedServices.${o}`).join(", "),i=e.length===1?`no ${e[0]}`:`none of ${e.join(", ")}`;return`This project declares ${n}, but '${t}' has ${i}${s}. 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 Ci="/var/lib/pantry/php-fpm/pool.d",Kc=9100,jc=400;function zt(e){return(e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"site").slice(0,28)}function Ri(e){return`web_${zt(e)}`}function Gc(e){let t=zt(e),r=0;for(let s=0;s<t.length;s++)r=r*31+t.charCodeAt(s)>>>0;return Kc+r%jc}function hs(e){return`127.0.0.1:${Gc(e)}`}function Wc(e){let t=zt(e.siteName),r=Ri(e.siteName),s=e.maxChildren??10;return[`; ts-cloud-managed pool for ${e.siteName} (site isolation)`,`[${t}]`,`user = ${r}`,`group = ${r}`,`listen = ${hs(e.siteName)}`,"pm = dynamic",`pm.max_children = ${s}`,"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(`
530
- `)}function Ei(e){let t=Ri(e.siteName),r=zt(e.siteName),s=`${Ci}/${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 ${Ci}`,`cat > ${s} <<'TS_CLOUD_FPMPOOL_EOF'`,Wc(e).replace(/\n$/,""),"TS_CLOUD_FPMPOOL_EOF",`(cd ${M} && pantry restart php-fpm) 2>/dev/null || true`]}var Bt={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};function Yc(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function Ii(e,t,r=Bt){let{config:s,environment:n,siteName:i,site:o,slug:a,sha:c,runtime:l,localTarballPath:p}=t,d=`releases/${i}/${c}.tar.gz`,m=E(s,n),g=await e.getComputeOutputs({config:s,environment:n}),h=await e.findComputeTargets({slug:a,environment:n,role:"app",stackName:m});if(h.length===0)return{success:!1,error:e.name==="aws"?`Stack '${m}' has no EC2 instances tagged Project=${a} Environment=${n} Role=app, and storage/cloud/state/${m}.json pins no live instance. For a shared box, record its instanceId there.`:`No Hetzner servers labeled ts-cloud/project=${a} ts-cloud/environment=${n} ts-cloud/role=app, and storage/cloud/state/${m}.json pins no live server. For a shared box, record its serverId there.`};let _=g.servicesPrivateIp?ln(g.servicesPrivateIp,C(s)):Ba(C(s)),w=Os(pi(s,{environment:n})),b=s.infrastructure?.compute,y=Q(b)?{HOST:"127.0.0.1"}:{},T=n==="production"?{APP_ENV:"production",NODE_ENV:"production"}:{},S={..._,...w,...y,...o.env||{},...T},D=Nr(S,o.sharedPaths??[]);if(D.warning)r.warn(`Site '${i}': ${D.warning}`);else if(D.path)r.info(`Site '${i}': sharing '${D.path}' so the SQLite database survives deploys.`);if(ni(o)){let pe=o.phpVersion??b?.php?.default??b?.php?.versions?.[0],N=W(a,i),G=Object.keys(_).length>0?{...o,env:S}:o,I=$i({siteName:i,site:G,releaseId:c,appBase:N,defaultPhpVersion:pe}),L=!Q(b),oe=us(o)==="custom"&&o.ssl?.certPath&&o.ssl?.keyPath?{certPath:o.ssl.certPath,keyPath:o.ssl.keyPath}:void 0,ve=o.isolation?Ei({siteName:i,appBase:N}):[],Ze=L?Xt({siteName:i,domain:o.domain||i,aliases:o.aliases,type:o.type,appDir:`${N}/current`,webDirectory:o.webDirectory,phpVersion:pe,fastcgiPass:o.isolation?hs(i):void 0,redirects:o.redirects,ssl:oe,auth:o.auth&&o.auth.enabled!==!1&&o.auth.password?{username:o.auth.username||"admin",password:o.auth.password,realm:o.auth.realm}:void 0,serverSnippet:Vt(o.nginx,b?.nginxTemplates),clientMaxBodySize:o.nginx?.clientMaxBodySize,hsts:o.ssl?.hsts,tlsProtocols:o.ssl?.tlsProtocols,security:o.security}):[],Kt=L?fs(o):[],et=ts(o)?es({slug:a,siteName:i,site:o,phpVersion:pe,appBase:N}):[],Vi=L?wi(o):[];r.step(`Deploying PHP site '${i}' to ${h.length} target(s)...`);let Ce=await e.runRemoteDeploy({targets:h,commands:[...ws(N,a),...I,...ve,...Ze,...Kt,...et,...Vi],comment:`ts-cloud deploy ${a}/${i}@${c}`,tags:{Project:a,Environment:n,Role:"app"}}),Ds=Ls(s.notifications,o.notifications);if(!Ce.success)return await Yt(Ds,"deploy-failed",`❌ Deploy of ${a}/${i}@${c} failed: ${Ce.error||"unknown error"}`),{success:!1,error:Ce.error||"Remote PHP deploy failed",instanceCount:Ce.instanceCount,perInstance:Ce.perInstance};let to=o.domain?` → https://${o.domain}`:"";return await Yt(Ds,"deploy",`✅ Deployed ${a}/${i}@${c}${to}`),{success:!0,instanceCount:Ce.instanceCount,perInstance:Ce.perInstance}}if(!p)return{success:!1,error:`Site '${i}' requires a release tarball but none was provided`};let O=await e.uploadRelease({config:s,environment:n,localPath:p,remoteKey:d,targets:h}),R=ut(a,i,c),k=e.name==="aws"?Fr(g.deployBucketName,d,s.project.region||"us-east-1",R):Br(O.artifactRef,R),se=P(o),z=W(a,i),X=se==="server-static"?Ur({siteName:i,slug:a,appDir:z,artifactFetch:k,releaseId:c,preStartCommands:o.preStart}):Mr({siteName:i,slug:a,appDir:z,artifactFetch:k,releaseId:c,execStart:Lr(o.start,l,`${z.replace(/\/+$/,"")}/releases/%i`),envEntries:S,port:o.port,preStartCommands:o.preStart,sharedPaths:o.sharedPaths,zeroDowntime:o.zeroDowntime!==!1,healthCheckPath:o.healthCheck?.path,memoryHigh:o.memoryHigh,memoryMax:o.memoryMax,cpuWeight:o.cpuWeight,ioWeight:o.ioWeight,tasksMax:o.tasksMax,stopTimeout:o.stopTimeout}),q=se==="server-static"&&!Q(b)&&!!o.domain,F=q?Xt({siteName:i,domain:o.domain,aliases:o.aliases,type:o.type==="spa"?"spa":"static",appDir:`${z}/current`,webDirectory:"",redirects:o.redirects,auth:o.auth&&o.auth.enabled!==!1&&o.auth.password?{username:o.auth.username||"admin",password:o.auth.password,realm:o.auth.realm}:void 0,serverSnippet:Vt(o.nginx,b?.nginxTemplates),clientMaxBodySize:o.nginx?.clientMaxBodySize,hsts:o.ssl?.hsts,tlsProtocols:o.ssl?.tlsProtocols,security:o.security}):[],ee=q?fs(o):[],H=ts(o)?es({slug:a,siteName:i,site:o,appBase:z}):[],he=[...go(z,{releaseId:c,commit:c,branch:o.repository?.branch??"main"}),...ws(z,a),...X,...F,...ee,...H,...Kr()];r.step(`Deploying to ${h.length} target(s)...`);let Y=await e.runRemoteDeploy({targets:h,commands:he,comment:`ts-cloud deploy ${a}/${i}@${c}`,tags:{Project:a,Environment:n,Role:"app"}});if(!Y.success)return{success:!1,error:Y.error||"Remote deploy failed",instanceCount:Y.instanceCount,perInstance:Y.perInstance};return{success:!0,instanceCount:Y.instanceCount,perInstance:Y.perInstance}}function Ft(e){return`'${e.replaceAll("'","'\\''")}'`}function Jc(e,t,r=!1,s=[]){let n=`${e}-dashboard-`,i=t.map((a)=>`${e}-${a}.service`),o=r?[`export TS_CLOUD_DASHBOARD_KEEP_DOMAINS=${Ft(JSON.stringify(s))}`,"rm -f /run/ts-cloud-dashboard-routes-changed",`/usr/local/bin/bun --bun -e ${Ft(`
530
+ `)}function Ei(e){let t=Ri(e.siteName),r=zt(e.siteName),s=`${Ci}/${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 ${Ci}`,`cat > ${s} <<'TS_CLOUD_FPMPOOL_EOF'`,Wc(e).replace(/\n$/,""),"TS_CLOUD_FPMPOOL_EOF",`(cd ${M} && pantry restart php-fpm) 2>/dev/null || true`]}var Bt={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};function Yc(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function Ii(e,t,r=Bt){let{config:s,environment:n,siteName:i,site:o,slug:a,sha:c,runtime:l,localTarballPath:p}=t,d=`releases/${i}/${c}.tar.gz`,m=E(s,n),g=await e.getComputeOutputs({config:s,environment:n}),h=await e.findComputeTargets({slug:a,environment:n,role:"app",stackName:m});if(h.length===0)return{success:!1,error:e.name==="aws"?`Stack '${m}' has no EC2 instances tagged Project=${a} Environment=${n} Role=app, and storage/cloud/state/${m}.json pins no live instance. For a shared box, record its instanceId there.`:`No Hetzner servers labeled ts-cloud/project=${a} ts-cloud/environment=${n} ts-cloud/role=app, and storage/cloud/state/${m}.json pins no live server. For a shared box, record its serverId there.`};let _=g.servicesPrivateIp?ln(g.servicesPrivateIp,C(s)):Ba(C(s)),w=Os(pi(s,{environment:n})),b=s.infrastructure?.compute,y=Q(b)?{HOST:"127.0.0.1"}:{},T=n==="production"?{APP_ENV:"production",NODE_ENV:"production"}:{},S={..._,...w,...y,...o.env||{},...T},D=Nr(S,o.sharedPaths??[]);if(D.warning)r.warn(`Site '${i}': ${D.warning}`);else if(D.path)r.info(`Site '${i}': sharing '${D.path}' so the SQLite database survives deploys.`);if(ni(o)){let pe=o.phpVersion??b?.php?.default??b?.php?.versions?.[0],N=W(a,i),G=Object.keys(_).length>0?{...o,env:S}:o,I=$i({siteName:i,site:G,releaseId:c,appBase:N,defaultPhpVersion:pe}),L=!Q(b),ae=us(o)==="custom"&&o.ssl?.certPath&&o.ssl?.keyPath?{certPath:o.ssl.certPath,keyPath:o.ssl.keyPath}:void 0,ve=o.isolation?Ei({siteName:i,appBase:N}):[],Ze=L?Xt({siteName:i,domain:o.domain||i,aliases:o.aliases,type:o.type,appDir:`${N}/current`,webDirectory:o.webDirectory,phpVersion:pe,fastcgiPass:o.isolation?hs(i):void 0,redirects:o.redirects,ssl:ae,auth:o.auth&&o.auth.enabled!==!1&&o.auth.password?{username:o.auth.username||"admin",password:o.auth.password,realm:o.auth.realm}:void 0,serverSnippet:Vt(o.nginx,b?.nginxTemplates),clientMaxBodySize:o.nginx?.clientMaxBodySize,hsts:o.ssl?.hsts,tlsProtocols:o.ssl?.tlsProtocols,security:o.security}):[],Kt=L?fs(o):[],et=ts(o)?es({slug:a,siteName:i,site:o,phpVersion:pe,appBase:N}):[],Vi=L?wi(o):[];r.step(`Deploying PHP site '${i}' to ${h.length} target(s)...`);let Ce=await e.runRemoteDeploy({targets:h,commands:[...ws(N,a),...I,...ve,...Ze,...Kt,...et,...Vi],comment:`ts-cloud deploy ${a}/${i}@${c}`,tags:{Project:a,Environment:n,Role:"app"}}),Ds=Ls(s.notifications,o.notifications);if(!Ce.success)return await Yt(Ds,"deploy-failed",`❌ Deploy of ${a}/${i}@${c} failed: ${Ce.error||"unknown error"}`),{success:!1,error:Ce.error||"Remote PHP deploy failed",instanceCount:Ce.instanceCount,perInstance:Ce.perInstance};let to=o.domain?` → https://${o.domain}`:"";return await Yt(Ds,"deploy",`✅ Deployed ${a}/${i}@${c}${to}`),{success:!0,instanceCount:Ce.instanceCount,perInstance:Ce.perInstance}}if(!p)return{success:!1,error:`Site '${i}' requires a release tarball but none was provided`};let O=await e.uploadRelease({config:s,environment:n,localPath:p,remoteKey:d,targets:h}),R=ut(a,i,c),k=e.name==="aws"?Fr(g.deployBucketName,d,s.project.region||"us-east-1",R):Br(O.artifactRef,R),ne=P(o),z=W(a,i),X=ne==="server-static"?Ur({siteName:i,slug:a,appDir:z,artifactFetch:k,releaseId:c,preStartCommands:o.preStart}):Mr({siteName:i,slug:a,appDir:z,artifactFetch:k,releaseId:c,execStart:Lr(o.start,l,`${z.replace(/\/+$/,"")}/releases/%i`),envEntries:S,port:o.port,preStartCommands:o.preStart,sharedPaths:o.sharedPaths,zeroDowntime:o.zeroDowntime!==!1,healthCheckPath:o.healthCheck?.path,memoryHigh:o.memoryHigh,memoryMax:o.memoryMax,cpuWeight:o.cpuWeight,ioWeight:o.ioWeight,tasksMax:o.tasksMax,stopTimeout:o.stopTimeout}),q=ne==="server-static"&&!Q(b)&&!!o.domain,F=q?Xt({siteName:i,domain:o.domain,aliases:o.aliases,type:o.type==="spa"?"spa":"static",appDir:`${z}/current`,webDirectory:"",redirects:o.redirects,auth:o.auth&&o.auth.enabled!==!1&&o.auth.password?{username:o.auth.username||"admin",password:o.auth.password,realm:o.auth.realm}:void 0,serverSnippet:Vt(o.nginx,b?.nginxTemplates),clientMaxBodySize:o.nginx?.clientMaxBodySize,hsts:o.ssl?.hsts,tlsProtocols:o.ssl?.tlsProtocols,security:o.security}):[],ee=q?fs(o):[],H=ts(o)?es({slug:a,siteName:i,site:o,appBase:z}):[],ye=[...go(z,{releaseId:c,commit:c,branch:o.repository?.branch??"main"}),...ws(z,a),...X,...F,...ee,...H,...Kr()];r.step(`Deploying to ${h.length} target(s)...`);let Y=await e.runRemoteDeploy({targets:h,commands:ye,comment:`ts-cloud deploy ${a}/${i}@${c}`,tags:{Project:a,Environment:n,Role:"app"}});if(!Y.success)return{success:!1,error:Y.error||"Remote deploy failed",instanceCount:Y.instanceCount,perInstance:Y.perInstance};return{success:!0,instanceCount:Y.instanceCount,perInstance:Y.perInstance}}function Ft(e){return`'${e.replaceAll("'","'\\''")}'`}function Jc(e,t,r=!1,s=[]){let n=`${e}-dashboard-`,i=t.map((a)=>`${e}-${a}.service`),o=r?[`export TS_CLOUD_DASHBOARD_KEEP_DOMAINS=${Ft(JSON.stringify(s))}`,"rm -f /run/ts-cloud-dashboard-routes-changed",`/usr/local/bin/bun --bun -e ${Ft(`
531
531
  const { chmodSync, existsSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } = require('node:fs')
532
532
  const { basename, join } = require('node:path')
533
533
  const root = '/etc/rpx/sites.d'
@@ -555,7 +555,7 @@ MemoryHigh=%sM
555
555
  changed = true
556
556
  }
557
557
  if (changed) writeFileSync('/run/ts-cloud-dashboard-routes-changed', '')
558
- `)}`,"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=${Ft(n)}`,`TS_CLOUD_DASHBOARD_SERVER_OWNER=${r?"1":"0"}`,`TS_CLOUD_DASHBOARD_DESIRED=${Ft(` ${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",...o]}async function Qc(e,t,r,s){let{config:n,environment:i}=t,o=n.project.slug,a=E(n,i),c=await e.findComputeTargets({slug:o,environment:i,role:"app",stackName:a});if(c.length===0)return!0;let l=await e.runRemoteDeploy({targets:c,commands:Jc(o,r,!n.cloud?.attachTo,r.map((p)=>n.sites?.[p]?.domain).filter((p)=>typeof p==="string")),comment:`ts-cloud reconcile management dashboard ${o}`,tags:{Project:o,Environment:i,Role:"app"}});if(!l.success)return s.error(`Management dashboard reconciliation failed: ${l.error||"unknown error"}`),!1;return!0}async function Zc(e,t,r){let{config:s}=t,n=s.cloud?.attachTo;if(!n||!e.listReachableResources)return;let i;try{i=await e.listReachableResources()}catch(c){r.warn(`Could not determine this credential's reach: ${c instanceof Error?c.message:String(c)}`);return}let o=ri(i,{ownerSlug:n,selfSlug:s.project.slug}),a=jr(o)>0;for(let c of si(o,{ownerSlug:n,selfSlug:s.project.slug}))if(a)r.warn(c);else r.info(c)}async function el(e,t,r){let{config:s,environment:n}=t,i=s.cloud?.attachTo;if(!i)return!0;let o=_i(s.infrastructure?.compute?.managedServices);if(o.length===0)return!0;let a=s.project.slug,c=E(s,n),l=await e.findComputeTargets({slug:a,environment:n,role:"app",stackName:c});if(l.length===0)return!0;let p=await e.runRemoteDeploy({targets:l,commands:Ti(o),comment:`ts-cloud preflight managed services ${a}`,tags:{Project:a,Environment:n,Role:"app"}});if(!p.success)return r.warn(`Could not check '${i}' for the declared services: ${p.error||"unknown error"}`),!0;let d=new Set;for(let m of p.perInstance)for(let g of Pi(m.output,o))d.add(g);if(d.size===0)return!0;return r.error(xi([...d],i,l[0]?.publicIp)),!1}async function tl(e,t,r){let{config:s,environment:n}=t;if(!s.cloud?.attachTo)return!0;let i=s.infrastructure?.compute,o=C(s),a=ht(o,i?.managedServices??{});if(a.length===0)return!0;let c=s.project.slug,l=E(s,n),p=await e.findComputeTargets({slug:c,environment:n,role:"app",stackName:l});if(p.length===0)return!0;r.step(`Ensuring database '${o?.name}' + role exist on the shared box...`);let d=await e.runRemoteDeploy({targets:p,commands:a,comment:`ts-cloud ensure database ${c}/${o?.name}`,tags:{Project:c,Environment:n,Role:"app"}});if(!d.success)return r.error(`Ensuring database '${o?.name}' failed: ${d.error||"unknown error"}`),!1;return r.success(`Database '${o?.name}' is ready on ${d.instanceCount} target(s)`),!0}async function Zi(e){let{config:t,environment:r,driver:s,sha:n,runtime:i,tarballForSite:o,logger:a=Bt}=e,c=t.project.slug,l=e.cwd??process.cwd(),p=e.managementDashboard!==!1,d=jt(t);if(p)io(t,{cwd:l,logger:{info:a.info,warn:a.warn}});let m=!p||d?[]:oo(t);if(p&&e.rpxConfig&&e.rpxConfig!==t&&!jt(e.rpxConfig))io(e.rpxConfig,{cwd:l,logger:{info:()=>{},warn:()=>{}}});if(p&&!await Qc(s,e,oo(t),a))return!1;let g=null,h=new Map;if(m.length>0)if(g=ms(t.sites?.[m[0]],{cwd:l,slug:c,sha:n,siteName:m[0],logger:{info:a.info,warn:a.warn}}),!g){a.warn("Management dashboard: no artifact available — skipping dashboard site(s) for this deploy.");for(let T of m)if(t.sites)delete t.sites[T]}else for(let T of m){if(T===m[0]){h.set(T,g);continue}try{let S=qc(Xc(),`${c}-${T}-${n}.tar.gz`);Vc(g,S),h.set(T,S)}catch{h.set(T,g)}}let _=t.sites||{},w=Object.entries(_).filter(([T,S])=>{if(!S)return!1;let D=P(S);if(D==="bucket")return a.warn(`Site '${T}' targets a bucket — skipping (handled by the static-site path, not compute).`),!1;if(D==="redirect")return!1;if(D==="proxy")return!1;return!0});if(w.length===0)return ys(e);if(await Zc(s,e,a),!await el(s,e,a))return!1;if(!await tl(s,e,a))return!1;let b=(T)=>h.get(T)??o(T);for(let[T,S]of w){a.step(`Deploying site: ${T}`);let D=ni(S)?void 0:b(T),O=await Ii(s,{config:t,environment:r,siteName:T,site:S,slug:c,sha:n,runtime:i,localTarballPath:D},a);if(!O.success){if(a.error(`Deploy of '${T}' failed: ${O.error||"unknown error"}`),O.perInstance)for(let R of O.perInstance)a.error(` ${R.instanceId}: ${R.status}${R.error?` — ${R.error}`:""}`);return!1}if(a.success(`Deployed ${c}/${T}@${n} to ${O.instanceCount} target(s)`),O.perInstance)for(let R of O.perInstance)a.info(` ✓ ${R.instanceId}: ${R.status}`)}if(!await ys(e))return!1;return!0}async function rl(e,t,r){let s=Ki(e);if(!s||s.tls==="off")return s;let n=await De(t,r),i=n?.provider==="ssh"?n.lanIp:void 0;return i?{...s,ip:i}:s}async function ys(e){let{config:t,environment:r,driver:s,logger:n=Bt}=e,i=e.rpxConfig??t,o=i.infrastructure?.compute?.proxy??t.infrastructure?.compute?.proxy;if(o?.engine!=="rpx")return!0;let a=i.sites||{},c=t.project.slug,l=E(t,r),p=await s.findComputeTargets({slug:c,environment:r,role:"lb",stackName:l});if(p.length>0){let y=(await s.findComputeTargets({slug:c,environment:r,role:"app",stackName:l})).map((D)=>({privateIp:D.privateIp,publicIp:D.publicIp})),T=Me(a,y,{proxy:o,slug:c});if(T.proxies.length===0)return n.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;n.step(`Reloading the load balancer's rpx gateway with ${T.proxies.length} route(s)...`);let S=await s.runRemoteDeploy({targets:p,commands:Ge({config:T,slug:c,preserveManagementDashboardRoutes:e.managementDashboard===!1}),comment:`ts-cloud rpx gateway reload ${c}`,tags:{Project:c,Environment:r,Role:"lb"}});if(!S.success)return n.error(`rpx gateway reload failed: ${S.error||"unknown error"}`),!1;return n.success(`rpx gateway reloaded on ${S.instanceCount} load balancer(s)`),!0}let d=await rl(t,l,e.cwd),m=fe(a,{proxy:o,slug:c,lan:d});if(m.proxies.length===0)return n.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;let g=await s.findComputeTargets({slug:c,environment:r,role:"app",stackName:l});if(g.length===0)return n.warn("rpx gateway: no compute targets found — skipping gateway reload."),!0;let h=Boolean(t.cloud?.attachTo);if(h&&(o.version||o.tlsxVersion))n.warn(`rpx gateway: ignoring proxy.version/tlsxVersion — this project attaches to '${t.cloud?.attachTo}' and the gateway belongs to that box's owner.`);n.step(`Reloading rpx gateway with ${m.proxies.length} route(s)...`);let _=me({proxy:o,config:m,slug:c,tenant:h,profile:Fs(t),preserveManagementDashboardRoutes:e.managementDashboard===!1}),w=await s.runRemoteDeploy({targets:g,commands:_,comment:`ts-cloud rpx gateway reload ${c}`,tags:{Project:c,Environment:r,Role:"app"}});if(!w.success)return n.error(`rpx gateway reload failed: ${w.error||"unknown error"}`),!1;return n.success(`rpx gateway reloaded on ${w.instanceCount} target(s)`),!0}async function eo(e){let{config:t,environment:r,driver:s,logger:n=Bt}=e,i=e.rpxConfig??t,o=i.infrastructure?.compute?.proxy??t.infrastructure?.compute?.proxy;if(o?.engine!=="rpx"||!o.onDemandTls)return!0;let a=fe(i.sites||{},{proxy:o,slug:t.project.slug});if(a.proxies.length===0)return!0;let c=nr(a);if(c.length===0)return!0;let l=t.project.slug,p=E(t,r),d="lb",m=await s.findComputeTargets({slug:l,environment:r,role:d,stackName:p});if(m.length===0)d="app",m=await s.findComputeTargets({slug:l,environment:r,role:d,stackName:p});if(m.length===0)return n.warn("rpx TLS: no gateway targets found - skipping certificate issuance."),!0;n.step("Issuing rpx TLS certificates after DNS reconciliation...");let g=c.map((_)=>`test -s ${Yc(`${a.productionCerts.certsDir}/${_}.crt`)}`).join(" && "),h=await s.runRemoteDeploy({targets:m,commands:[`systemctl start ${rr(l)}`,g],comment:`ts-cloud rpx TLS issuance ${l}`,tags:{Project:l,Environment:r,Role:d}});if(!h.success)return n.error(`rpx TLS issuance failed: ${h.error||"unknown error"}`),!1;return n.success(`rpx TLS certificates reconciled on ${h.instanceCount} gateway target(s)`),!0}import{createHash as sl}from"node:crypto";function _a(e){let t=_s(e.name),r=Ps(e.publicKey),s=il([...e.existingKeys??[],{name:t,publicKey:r}]);return Di(e.configText,s)}function $a(e){let t=_s(e.name),r=(e.existingKeys??[]).filter((s)=>s.name!==t);if((e.existingKeys??[]).length===r.length)throw Error(`SSH key '${t}' does not exist in compute.sshKeys`);return Di(e.configText,r)}function Ot(e=[]){return e.map((t)=>({name:t.name,publicKey:t.publicKey,type:ol(t.publicKey),fingerprint:al(t.publicKey),added:"configured"}))}function Di(e,t){let r=cl(e,"compute"),s=nl(t),n=ll(e,r.start,r.end,"sshKeys");if(n){let c=n.propertyStart;while(c>0&&e[c-1]!==`
558
+ `)}`,"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=${Ft(n)}`,`TS_CLOUD_DASHBOARD_SERVER_OWNER=${r?"1":"0"}`,`TS_CLOUD_DASHBOARD_DESIRED=${Ft(` ${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",...o]}async function Qc(e,t,r,s){let{config:n,environment:i}=t,o=n.project.slug,a=E(n,i),c=await e.findComputeTargets({slug:o,environment:i,role:"app",stackName:a});if(c.length===0)return!0;let l=await e.runRemoteDeploy({targets:c,commands:Jc(o,r,!n.cloud?.attachTo,r.map((p)=>n.sites?.[p]?.domain).filter((p)=>typeof p==="string")),comment:`ts-cloud reconcile management dashboard ${o}`,tags:{Project:o,Environment:i,Role:"app"}});if(!l.success)return s.error(`Management dashboard reconciliation failed: ${l.error||"unknown error"}`),!1;return!0}async function Zc(e,t,r){let{config:s}=t,n=s.cloud?.attachTo;if(!n||!e.listReachableResources)return;let i;try{i=await e.listReachableResources()}catch(c){r.warn(`Could not determine this credential's reach: ${c instanceof Error?c.message:String(c)}`);return}let o=ri(i,{ownerSlug:n,selfSlug:s.project.slug}),a=jr(o)>0;for(let c of si(o,{ownerSlug:n,selfSlug:s.project.slug}))if(a)r.warn(c);else r.info(c)}async function el(e,t,r){let{config:s,environment:n}=t,i=s.cloud?.attachTo;if(!i)return!0;let o=_i(s.infrastructure?.compute?.managedServices);if(o.length===0)return!0;let a=s.project.slug,c=E(s,n),l=await e.findComputeTargets({slug:a,environment:n,role:"app",stackName:c});if(l.length===0)return!0;let p=await e.runRemoteDeploy({targets:l,commands:Ti(o),comment:`ts-cloud preflight managed services ${a}`,tags:{Project:a,Environment:n,Role:"app"}});if(!p.success)return r.warn(`Could not check '${i}' for the declared services: ${p.error||"unknown error"}`),!0;let d=new Set;for(let m of p.perInstance)for(let g of Pi(m.output,o))d.add(g);if(d.size===0)return!0;return r.error(xi([...d],i,l[0]?.publicIp)),!1}async function tl(e,t,r){let{config:s,environment:n}=t;if(!s.cloud?.attachTo)return!0;let i=s.infrastructure?.compute,o=C(s),a=ht(o,i?.managedServices??{});if(a.length===0)return!0;let c=s.project.slug,l=E(s,n),p=await e.findComputeTargets({slug:c,environment:n,role:"app",stackName:l});if(p.length===0)return!0;r.step(`Ensuring database '${o?.name}' + role exist on the shared box...`);let d=await e.runRemoteDeploy({targets:p,commands:a,comment:`ts-cloud ensure database ${c}/${o?.name}`,tags:{Project:c,Environment:n,Role:"app"}});if(!d.success)return r.error(`Ensuring database '${o?.name}' failed: ${d.error||"unknown error"}`),!1;return r.success(`Database '${o?.name}' is ready on ${d.instanceCount} target(s)`),!0}async function Zi(e){let{config:t,environment:r,driver:s,sha:n,runtime:i,tarballForSite:o,logger:a=Bt}=e,c=t.project.slug,l=e.cwd??process.cwd(),p=e.managementDashboard!==!1,d=jt(t);if(p)io(t,{cwd:l,logger:{info:a.info,warn:a.warn}});let m=!p||d?[]:oo(t);if(p&&e.rpxConfig&&e.rpxConfig!==t&&!jt(e.rpxConfig))io(e.rpxConfig,{cwd:l,logger:{info:()=>{},warn:()=>{}}});if(p&&!await Qc(s,e,oo(t),a))return!1;let g=null,h=new Map;if(m.length>0)if(g=ms(t.sites?.[m[0]],{cwd:l,slug:c,sha:n,siteName:m[0],logger:{info:a.info,warn:a.warn}}),!g){a.warn("Management dashboard: no artifact available — skipping dashboard site(s) for this deploy.");for(let T of m)if(t.sites)delete t.sites[T]}else for(let T of m){if(T===m[0]){h.set(T,g);continue}try{let S=qc(Xc(),`${c}-${T}-${n}.tar.gz`);Vc(g,S),h.set(T,S)}catch{h.set(T,g)}}let _=t.sites||{},w=Object.entries(_).filter(([T,S])=>{if(!S)return!1;let D=P(S);if(D==="bucket")return a.warn(`Site '${T}' targets a bucket — skipping (handled by the static-site path, not compute).`),!1;if(D==="redirect")return!1;if(D==="proxy")return!1;return!0});if(w.length===0)return ys(e);if(await Zc(s,e,a),!await el(s,e,a))return!1;if(!await tl(s,e,a))return!1;let b=(T)=>h.get(T)??o(T);for(let[T,S]of w){a.step(`Deploying site: ${T}`);let D=ni(S)?void 0:b(T),O=await Ii(s,{config:t,environment:r,siteName:T,site:S,slug:c,sha:n,runtime:i,localTarballPath:D},a);if(!O.success){if(a.error(`Deploy of '${T}' failed: ${O.error||"unknown error"}`),O.perInstance)for(let R of O.perInstance)a.error(` ${R.instanceId}: ${R.status}${R.error?` — ${R.error}`:""}`);return!1}if(a.success(`Deployed ${c}/${T}@${n} to ${O.instanceCount} target(s)`),O.perInstance)for(let R of O.perInstance)a.info(` ✓ ${R.instanceId}: ${R.status}`)}if(!await ys(e))return!1;return!0}async function rl(e,t,r){let s=Ki(e);if(!s||s.tls==="off")return s;let n=await De(t,r),i=n?.provider==="ssh"?n.lanIp:void 0;return i?{...s,ip:i}:s}async function ys(e){let{config:t,environment:r,driver:s,logger:n=Bt}=e,i=e.rpxConfig??t,o=i.infrastructure?.compute?.proxy??t.infrastructure?.compute?.proxy;if(o?.engine!=="rpx")return!0;let a=i.sites||{},c=t.project.slug,l=E(t,r),p=await s.findComputeTargets({slug:c,environment:r,role:"lb",stackName:l});if(p.length>0){let y=(await s.findComputeTargets({slug:c,environment:r,role:"app",stackName:l})).map((D)=>({privateIp:D.privateIp,publicIp:D.publicIp})),T=Me(a,y,{proxy:o,slug:c});if(T.proxies.length===0)return n.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;n.step(`Reloading the load balancer's rpx gateway with ${T.proxies.length} route(s)...`);let S=await s.runRemoteDeploy({targets:p,commands:Ge({config:T,slug:c,preserveManagementDashboardRoutes:e.managementDashboard===!1}),comment:`ts-cloud rpx gateway reload ${c}`,tags:{Project:c,Environment:r,Role:"lb"}});if(!S.success)return n.error(`rpx gateway reload failed: ${S.error||"unknown error"}`),!1;return n.success(`rpx gateway reloaded on ${S.instanceCount} load balancer(s)`),!0}let d=await rl(t,l,e.cwd),m=fe(a,{proxy:o,slug:c,lan:d});if(m.proxies.length===0)return n.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;let g=await s.findComputeTargets({slug:c,environment:r,role:"app",stackName:l});if(g.length===0)return n.warn("rpx gateway: no compute targets found — skipping gateway reload."),!0;let h=Boolean(t.cloud?.attachTo);if(h&&(o.version||o.tlsxVersion))n.warn(`rpx gateway: ignoring proxy.version/tlsxVersion — this project attaches to '${t.cloud?.attachTo}' and the gateway belongs to that box's owner.`);n.step(`Reloading rpx gateway with ${m.proxies.length} route(s)...`);let _=ge({proxy:o,config:m,slug:c,tenant:h,profile:Fs(t),preserveManagementDashboardRoutes:e.managementDashboard===!1}),w=await s.runRemoteDeploy({targets:g,commands:_,comment:`ts-cloud rpx gateway reload ${c}`,tags:{Project:c,Environment:r,Role:"app"}});if(!w.success)return n.error(`rpx gateway reload failed: ${w.error||"unknown error"}`),!1;return n.success(`rpx gateway reloaded on ${w.instanceCount} target(s)`),!0}async function eo(e){let{config:t,environment:r,driver:s,logger:n=Bt}=e,i=e.rpxConfig??t,o=i.infrastructure?.compute?.proxy??t.infrastructure?.compute?.proxy;if(o?.engine!=="rpx"||!o.onDemandTls)return!0;let a=fe(i.sites||{},{proxy:o,slug:t.project.slug});if(a.proxies.length===0)return!0;let c=nr(a);if(c.length===0)return!0;let l=t.project.slug,p=E(t,r),d="lb",m=await s.findComputeTargets({slug:l,environment:r,role:d,stackName:p});if(m.length===0)d="app",m=await s.findComputeTargets({slug:l,environment:r,role:d,stackName:p});if(m.length===0)return n.warn("rpx TLS: no gateway targets found - skipping certificate issuance."),!0;n.step("Issuing rpx TLS certificates after DNS reconciliation...");let g=c.map((_)=>`test -s ${Yc(`${a.productionCerts.certsDir}/${_}.crt`)}`).join(" && "),h=await s.runRemoteDeploy({targets:m,commands:[`systemctl start ${rr(l)}`,g],comment:`ts-cloud rpx TLS issuance ${l}`,tags:{Project:l,Environment:r,Role:d}});if(!h.success)return n.error(`rpx TLS issuance failed: ${h.error||"unknown error"}`),!1;return n.success(`rpx TLS certificates reconciled on ${h.instanceCount} gateway target(s)`),!0}import{createHash as sl}from"node:crypto";function _a(e){let t=_s(e.name),r=Ps(e.publicKey),s=il([...e.existingKeys??[],{name:t,publicKey:r}]);return Di(e.configText,s)}function $a(e){let t=_s(e.name),r=(e.existingKeys??[]).filter((s)=>s.name!==t);if((e.existingKeys??[]).length===r.length)throw Error(`SSH key '${t}' does not exist in compute.sshKeys`);return Di(e.configText,r)}function Ot(e=[]){return e.map((t)=>({name:t.name,publicKey:t.publicKey,type:ol(t.publicKey),fingerprint:al(t.publicKey),added:"configured"}))}function Di(e,t){let r=cl(e,"compute"),s=nl(t),n=ll(e,r.start,r.end,"sshKeys");if(n){let c=n.propertyStart;while(c>0&&e[c-1]!==`
559
559
  `&&/\s/.test(e[c-1]))c--;return`${e.slice(0,c)}${s}${e.slice(n.end+1)}`}let i=e.slice(0,r.end).trimEnd(),o=e.slice(r.end),a=i.endsWith(",")||i.endsWith("{")?"":",";return`${i}${a}
560
560
  ${s},
561
561
  ${o}`}function nl(e){if(e.length===0)return" sshKeys: []";return` sshKeys: [