@stacksjs/ts-cloud 0.9.3 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/aws/index.js +1 -269
- package/dist/bin/chunk-08c0pzkb.js +1 -0
- package/dist/bin/chunk-12210qvj.js +1 -0
- package/dist/bin/chunk-1v6bt68w.js +6 -0
- package/dist/bin/chunk-35ttwn26.js +70 -0
- package/dist/bin/chunk-3r3be05z.js +1 -0
- package/dist/bin/chunk-41yqpdv7.js +2 -0
- package/dist/bin/chunk-5rv31chh.js +1 -0
- package/dist/bin/chunk-6eat8ezk.js +2 -0
- package/dist/bin/chunk-6gktf2m2.js +1 -0
- package/dist/bin/chunk-6zjy949y.js +141 -0
- package/dist/bin/chunk-7wzdaqh6.js +2 -0
- package/dist/bin/chunk-80ar3aty.js +1 -0
- package/dist/bin/chunk-8rwhsp5b.js +2 -0
- package/dist/bin/chunk-936vp7dx.js +44 -0
- package/dist/bin/chunk-9px3rg4a.js +4 -0
- package/dist/bin/chunk-anm3ae6z.js +7364 -0
- package/dist/bin/{chunk-ynjvbphf.js → chunk-axvr7dwa.js} +6 -6
- package/dist/bin/chunk-b0hj9m5e.js +2 -0
- package/dist/bin/{chunk-mh0kdzqp.js → chunk-b2ymh8k0.js} +1 -1
- package/dist/bin/chunk-b35989e3.js +50 -0
- package/dist/bin/chunk-c2b6nk0q.js +37 -0
- package/dist/bin/chunk-ckxpgwxw.js +3 -0
- package/dist/bin/chunk-d6zzgvtn.js +92 -0
- package/dist/bin/chunk-da8zpf82.js +1 -0
- package/dist/bin/chunk-ddmjjstg.js +1 -0
- package/dist/bin/chunk-dhhz4zyj.js +1 -0
- package/dist/bin/chunk-dj9a67c3.js +9 -0
- package/dist/bin/chunk-ds1z880f.js +1 -0
- package/dist/bin/chunk-dvkj4k6h.js +111 -0
- package/dist/bin/chunk-eh40fpvj.js +1 -0
- package/dist/bin/chunk-ey9fagrr.js +6 -0
- package/dist/bin/chunk-ezftw2q4.js +1 -0
- package/dist/bin/chunk-g6a4n3rh.js +1 -0
- package/dist/bin/chunk-g90nqfgv.js +585 -0
- package/dist/bin/chunk-gs40j75w.js +1 -0
- package/dist/bin/chunk-jjjts1vt.js +1 -0
- package/dist/bin/{chunk-ry030a6b.js → chunk-jnsbzqzz.js} +30 -30
- package/dist/bin/chunk-jnx4jgw8.js +1 -0
- package/dist/bin/chunk-jt1tndm2.js +3 -0
- package/dist/bin/chunk-kybdb0ws.js +2 -0
- package/dist/bin/chunk-m3nqw76h.js +3 -0
- package/dist/bin/chunk-mn6j22zn.js +6 -0
- package/dist/bin/chunk-nb0yjkv5.js +2 -0
- package/dist/bin/chunk-pjpa4x52.js +2 -0
- package/dist/bin/chunk-pkgkfe6s.js +2 -0
- package/dist/bin/chunk-pnz5hk8n.js +60 -0
- package/dist/bin/chunk-q46zr2tv.js +1 -0
- package/dist/bin/chunk-qtdngvs8.js +1 -0
- package/dist/bin/chunk-sbejksrh.js +2 -0
- package/dist/bin/chunk-svyd4v6c.js +34 -0
- package/dist/bin/chunk-tna7ay8d.js +1 -0
- package/dist/bin/chunk-tp4c2mv1.js +1 -0
- package/dist/bin/chunk-w5d6tr2x.js +1 -0
- package/dist/bin/chunk-wewcjam5.js +1 -0
- package/dist/bin/chunk-xv4bscrm.js +1 -0
- package/dist/bin/chunk-y9eyc5pw.js +1 -0
- package/dist/bin/chunk-y9f8649w.js +512 -0
- package/dist/bin/cli.js +428 -418
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/chunk-06jk7ba9.js +7355 -0
- package/dist/chunk-0e16qt6k.js +5 -0
- package/dist/chunk-13hxhzaz.js +34 -0
- package/dist/chunk-2p89vt3b.js +2 -0
- package/dist/chunk-77t2ctwn.js +2 -0
- package/dist/chunk-88z37ey4.js +114 -0
- package/dist/chunk-8c4715hz.js +2 -0
- package/dist/chunk-9a22225r.js +60 -0
- package/dist/chunk-as6by62d.js +1 -0
- package/dist/chunk-cd0zpxhf.js +44 -0
- package/dist/chunk-cp54a0qn.js +6 -0
- package/dist/chunk-d67xbk4v.js +141 -0
- package/dist/chunk-dckz9xve.js +2 -0
- package/dist/chunk-e1666vjv.js +2 -0
- package/dist/chunk-hhdx5k96.js +442 -0
- package/dist/chunk-kv2ztkp4.js +1617 -0
- package/dist/chunk-nrz6zypg.js +1 -0
- package/dist/chunk-q816js1y.js +1 -0
- package/dist/chunk-qh9ep11z.js +704 -0
- package/dist/chunk-rg720cqg.js +1 -0
- package/dist/chunk-snak8s7m.js +92 -0
- package/dist/chunk-vq737g82.js +1 -0
- package/dist/chunk-xd6w0c11.js +50 -0
- package/dist/chunk-xtwjt370.js +37 -0
- package/dist/chunk-y26yh5zp.js +1 -0
- package/dist/chunk-zmxffmmq.js +4 -0
- package/dist/deploy/attach-credentials.d.ts +4 -8
- package/dist/deploy/index.js +1 -168
- package/dist/dns/cloudflare.d.ts +27 -0
- package/dist/dns/godaddy.d.ts +18 -1
- package/dist/dns/index.d.ts +2 -0
- package/dist/dns/index.js +1 -41
- package/dist/dns/zone-migration.d.ts +92 -0
- package/dist/dns/zone-migration.test.d.ts +1 -0
- package/dist/drivers/hetzner/driver.d.ts +8 -1
- package/dist/drivers/index.js +1 -154
- package/dist/drivers/shared/compute-provision.d.ts +14 -2
- package/dist/drivers/shared/db-provision.d.ts +3 -2
- package/dist/drivers/shared/mail-provision.d.ts +116 -0
- package/dist/drivers/shared/mail-provision.test.d.ts +1 -0
- package/dist/drivers/shared/managed-services-probe.d.ts +47 -0
- package/dist/drivers/shared/managed-services-probe.test.d.ts +1 -0
- package/dist/drivers/shared/package-manager.d.ts +1 -0
- package/dist/drivers/shared/remote-failure.d.ts +21 -0
- package/dist/drivers/shared/remote-failure.test.d.ts +1 -0
- package/dist/drivers/shared/sqlite-shared-path.d.ts +50 -0
- package/dist/drivers/shared/sqlite-shared-path.test.d.ts +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +100 -6129
- package/dist/operations/plan.d.ts +136 -0
- package/dist/operations/plan.test.d.ts +1 -0
- package/dist/operations/server-rename.d.ts +84 -0
- package/dist/operations/server-rename.test.d.ts +1 -0
- package/dist/operations/site-move.d.ts +263 -0
- package/dist/operations/site-move.test.d.ts +1 -0
- package/dist/protection/index.js +1 -89
- package/dist/push/index.js +1 -509
- package/dist/spend/index.js +1 -173
- package/dist/ui/404.html +1 -1
- package/dist/ui/accept-invitation.html +1 -1
- package/dist/ui/access-denied.html +1 -1
- package/dist/ui/account/automation.html +5 -5
- package/dist/ui/account/security.html +2 -2
- package/dist/ui/applications/compose.html +6 -6
- package/dist/ui/applications/new.html +2 -2
- package/dist/ui/data/backups.html +80 -80
- package/dist/ui/data/services.html +78 -78
- package/dist/ui/data/volumes.html +50 -50
- package/dist/ui/index.html +50 -50
- package/dist/ui/infrastructure/topology.html +118 -118
- package/dist/ui/integrations.html +1 -1
- package/dist/ui/operations/alerts.html +47 -47
- package/dist/ui/operations/configuration.html +5 -5
- package/dist/ui/operations/jobs.html +76 -76
- package/dist/ui/operations/maintenance.html +6 -6
- package/dist/ui/operations/observability.html +82 -82
- package/dist/ui/operations/previews.html +5 -5
- package/dist/ui/operations/queue.html +6 -6
- package/dist/ui/operations/regions.html +6 -6
- package/dist/ui/operations/releases.html +6 -6
- package/dist/ui/operations/spend.html +54 -54
- package/dist/ui/operations/workloads.html +104 -104
- package/dist/ui/security.html +2 -2
- package/dist/ui/server/actions.html +56 -56
- package/dist/ui/server/activity.html +1 -1
- package/dist/ui/server/capacity.html +6 -6
- package/dist/ui/server/database.html +106 -106
- package/dist/ui/server/deployments.html +50 -50
- package/dist/ui/server/diagnostics.html +2 -2
- package/dist/ui/server/firewall.html +76 -76
- package/dist/ui/server/fleet.html +34 -34
- package/dist/ui/server/logs.html +24 -24
- package/dist/ui/server/metrics.html +112 -112
- package/dist/ui/server/security.html +1 -1
- package/dist/ui/server/services.html +27 -27
- package/dist/ui/server/sites.html +120 -120
- package/dist/ui/server/ssh-keys.html +51 -51
- package/dist/ui/server/team.html +144 -144
- package/dist/ui/server/terminal.html +15 -15
- package/dist/ui/serverless/alarms.html +52 -52
- package/dist/ui/serverless/assets.html +27 -27
- package/dist/ui/serverless/cost.html +2 -2
- package/dist/ui/serverless/data.html +36 -36
- package/dist/ui/serverless/deployments.html +27 -27
- package/dist/ui/serverless/firewall.html +1 -1
- package/dist/ui/serverless/functions.html +40 -40
- package/dist/ui/serverless/logs.html +24 -24
- package/dist/ui/serverless/metrics.html +2 -2
- package/dist/ui/serverless/queues.html +47 -47
- package/dist/ui/serverless/secrets.html +52 -52
- package/dist/ui/serverless/traces.html +6 -6
- package/dist/ui/serverless.html +54 -54
- package/dist/ui-src/src/charts.ts +17499 -12662
- package/dist/ui-src/src/topology.ts +2 -2
- package/package.json +3 -3
- package/dist/bin/chunk-09nwf2gy.js +0 -34
- package/dist/bin/chunk-14cwr6eh.js +0 -70
- package/dist/bin/chunk-271gk1n2.js +0 -6
- package/dist/bin/chunk-38pq971s.js +0 -2
- package/dist/bin/chunk-3gykfyq4.js +0 -37
- package/dist/bin/chunk-3r4fb59r.js +0 -3
- package/dist/bin/chunk-41x17hw1.js +0 -1
- package/dist/bin/chunk-4vrqm9h0.js +0 -2
- package/dist/bin/chunk-57y1zxbf.js +0 -3
- package/dist/bin/chunk-598yf4bs.js +0 -1
- package/dist/bin/chunk-8v7ddyvf.js +0 -1
- package/dist/bin/chunk-92mea34a.js +0 -1
- package/dist/bin/chunk-9pvsff8g.js +0 -1
- package/dist/bin/chunk-9v39615t.js +0 -1
- package/dist/bin/chunk-avm7tnwe.js +0 -1
- package/dist/bin/chunk-ax9mr6wm.js +0 -44
- package/dist/bin/chunk-axhnkn5g.js +0 -2
- package/dist/bin/chunk-b5gd39s8.js +0 -512
- package/dist/bin/chunk-b9qbp8j1.js +0 -1
- package/dist/bin/chunk-bz828v8q.js +0 -3
- package/dist/bin/chunk-c1vcdgvr.js +0 -1
- package/dist/bin/chunk-ctd2vg9w.js +0 -2
- package/dist/bin/chunk-dbgffky8.js +0 -1
- package/dist/bin/chunk-dwr30vbv.js +0 -1
- package/dist/bin/chunk-e3xrwh9z.js +0 -1
- package/dist/bin/chunk-fhc6ntvd.js +0 -2
- package/dist/bin/chunk-fpm59y25.js +0 -6
- package/dist/bin/chunk-fvbxvq6b.js +0 -1
- package/dist/bin/chunk-fy8j3y8p.js +0 -92
- package/dist/bin/chunk-fz21b57w.js +0 -1
- package/dist/bin/chunk-gavvf0pg.js +0 -141
- package/dist/bin/chunk-ggn7ax8p.js +0 -4
- package/dist/bin/chunk-gpe2prkm.js +0 -1
- package/dist/bin/chunk-gqf6jsmy.js +0 -1
- package/dist/bin/chunk-h5pa5men.js +0 -2
- package/dist/bin/chunk-hm08xdxf.js +0 -2
- package/dist/bin/chunk-hzgz13nf.js +0 -1
- package/dist/bin/chunk-hzqw8xm5.js +0 -111
- package/dist/bin/chunk-j703btc5.js +0 -50
- package/dist/bin/chunk-jpjamjey.js +0 -6935
- package/dist/bin/chunk-m2zwtapr.js +0 -1
- package/dist/bin/chunk-m669wtgr.js +0 -1
- package/dist/bin/chunk-mr0atd2s.js +0 -2
- package/dist/bin/chunk-ngcyftm2.js +0 -1
- package/dist/bin/chunk-p66ptpmr.js +0 -2
- package/dist/bin/chunk-p8q9bq9g.js +0 -1
- package/dist/bin/chunk-r3kv0vm9.js +0 -6
- package/dist/bin/chunk-r9hjwcj9.js +0 -6
- package/dist/bin/chunk-rtczra13.js +0 -1
- package/dist/bin/chunk-rytk89az.js +0 -60
- package/dist/bin/chunk-sgyffpgm.js +0 -581
- package/dist/bin/chunk-vek8a0w6.js +0 -1
- package/dist/bin/chunk-waayf9ay.js +0 -2
- package/dist/bin/chunk-yv9sth30.js +0 -1
- package/dist/chunk-01d86gt1.js +0 -1324
- package/dist/chunk-050r7ycy.js +0 -46516
- package/dist/chunk-1c8dbv57.js +0 -7278
- package/dist/chunk-29rse4p1.js +0 -12203
- package/dist/chunk-32e7ya18.js +0 -642
- package/dist/chunk-4cjrg98a.js +0 -597
- package/dist/chunk-50jpda9q.js +0 -371
- package/dist/chunk-6a1t7fnq.js +0 -12121
- package/dist/chunk-728jvrr0.js +0 -1701
- package/dist/chunk-7m60qnc8.js +0 -1762
- package/dist/chunk-aa2dkn7b.js +0 -205
- package/dist/chunk-d48vtdj4.js +0 -433
- package/dist/chunk-f55nkpvb.js +0 -8
- package/dist/chunk-fgk8cqew.js +0 -152
- package/dist/chunk-he9a874b.js +0 -769
- package/dist/chunk-k2yyatfw.js +0 -10
- package/dist/chunk-k4px0bnv.js +0 -23
- package/dist/chunk-nsgqsmrh.js +0 -1779
- package/dist/chunk-q0st3se8.js +0 -42033
- package/dist/chunk-qr803fye.js +0 -2122
- package/dist/chunk-rds0sy87.js +0 -1771
- package/dist/chunk-ttz2ra5j.js +0 -12
- package/dist/chunk-v0bahtg2.js +0 -4
- package/dist/chunk-va2yd85b.js +0 -200
- package/dist/chunk-x9s0cqfx.js +0 -13
- package/dist/chunk-zqtpg06c.js +0 -1752
|
@@ -1,581 +0,0 @@
|
|
|
1
|
-
import{Ne as S1}from"./chunk-3gykfyq4.js";import{Ue as y1}from"./chunk-ax9mr6wm.js";import{Xe as t1}from"./chunk-ggn7ax8p.js";import{df as V1,ef as q1,ff as u2}from"./chunk-r3kv0vm9.js";import{Af as e0,Cf as y2,Df as d0,Ff as c0,Gf as L2,Hf as l0,If as l$,Jf as p$,Kf as a$,Lf as r$,Mf as H$,Nf as P0,Pf as I0,Qf as Q1,Rf as K$,gf as U0,hf as H1,if as x1,jf as u,pf as Y0,qf as t0,rf as r0,sf as n0,tf as D1,wf as o0,xf as E0,yf as g2}from"./chunk-r9hjwcj9.js";import{Sf as F1}from"./chunk-axhnkn5g.js";import{Uf as i1}from"./chunk-h5pa5men.js";import{$f as n1}from"./chunk-fy8j3y8p.js";import{Og as A1}from"./chunk-fpm59y25.js";import{Ah as I,Ui as O1,ph as V0,qh as _0}from"./chunk-jpjamjey.js";import{Vo as Rz}from"./chunk-mh0kdzqp.js";import{existsSync as L6,readFileSync as A6}from"node:fs";import{join as R6}from"node:path";import{readFileSync as s1}from"node:fs";import{join as gz}from"node:path";function r6($={}){let z=new Set;for(let J of Object.values($)){if(!J.domain)continue;if(J.redirect||J.deploy==="server"||J.start)z.add(J.domain)}return z}function L$($){return $.replace(/\.$/,"").toLowerCase()}function Zz($,z,J){let Z=L$($.name),Y=L$(z),G=L$(J),j=G===Y?"@":G.endsWith(`.${Y}`)?G.slice(0,-(Y.length+1)):G;return Z===G||Z===j||j==="@"&&(Z===""||Z===Y)}async function Yz($,z,J,Z,Y="A"){let G=await $.listRecords(z);if(!G.success)return[`could not list ${Y} records: ${G.message||"unknown provider error"}`];let j=G.records.filter((q)=>q.type===Y&&Zz(q,z,J)),O=j.findIndex((q)=>q.content===Z);if(j.length<=1||O===-1)return[];let Q=[];for(let[q,V]of j.entries()){if(q===O)continue;let W=await $.deleteRecord(z,V);if(!W.success)Q.push(`could not remove stale ${V.name} ${Y} ${V.content}: ${W.message||"unknown provider error"}`)}return Q}function z0($){if(!$)return;let z=$.trim();if(!z)return;if(!z.includes("/"))return z;let[J]=z.split("/");if(!J.endsWith("::"))return J||void 0;return`${J}1`}var Gz=new Set(["mail","smtp","imap","mx"]);function jz($){return!Gz.has($.split(".")[0]??"")}async function n6($){let{provider:z,zone:J,fqdn:Z,ipv4:Y,ipv6:G,ttl:j=600}=$,O={published:[],warnings:[]},Q=[{type:"A",content:Y}];if(G&&jz(Z))Q.push({type:"AAAA",content:G});for(let{type:q,content:V}of Q){let W=await z.upsertRecord(J,{name:Z,type:q,content:V,ttl:j});if(W?.success===!1){O.warnings.push(`${Z} → ${V} failed: ${W.error||W.message||"unknown error"}`);continue}if(O.warnings.push(...(await Yz(z,J,Z,V,q)).map((H)=>`${Z} cleanup: ${H}`)),await Oz(z,J,Z,V,q))O.published.push({fqdn:Z,type:q,content:V});else O.warnings.push(`${Z} → ${V} reported success at ${z.name} but no matching ${q} record exists — create it manually: ${q} ${Z} → ${V}`)}return O}async function Oz($,z,J,Z,Y){try{if(typeof $?.listRecords!=="function")return!0;let G=await $.listRecords(z);if(!G?.success||!Array.isArray(G.records))return!0;return G.records.some((j)=>{let O=typeof j?.name==="string"?j.name.replace(/\.$/,""):"";return j?.type===Y&&O===J&&j?.content===Z})}catch{return!0}}class a0{client;region;constructor($="us-east-1",z){this.region=$,this.client=new A1}async putParameter($){let z={Name:$.Name,Value:$.Value};if($.Type)z.Type=$.Type;if($.Description)z.Description=$.Description;if($.KeyId)z.KeyId=$.KeyId;if($.Overwrite!==void 0)z.Overwrite=$.Overwrite;if($.AllowedPattern)z.AllowedPattern=$.AllowedPattern;if($.Tags&&$.Tags.length>0)z.Tags=$.Tags;if($.Tier)z.Tier=$.Tier;if($.DataType)z.DataType=$.DataType;let J=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.PutParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(z)});return{Version:J.Version,Tier:J.Tier}}async getParameter($){let z={Name:$.Name};if($.WithDecryption!==void 0)z.WithDecryption=$.WithDecryption;let J=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(z)});return{Parameter:J.Parameter?this.parseParameter(J.Parameter):void 0}}async getParameters($){let z={Names:$.Names};if($.WithDecryption!==void 0)z.WithDecryption=$.WithDecryption;let J=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(z)});return{Parameters:J.Parameters?.map((Z)=>this.parseParameter(Z)),InvalidParameters:J.InvalidParameters}}async getParametersByPath($){let z={Path:$.Path};if($.Recursive!==void 0)z.Recursive=$.Recursive;if($.WithDecryption!==void 0)z.WithDecryption=$.WithDecryption;if($.MaxResults)z.MaxResults=$.MaxResults;if($.NextToken)z.NextToken=$.NextToken;if($.ParameterFilters&&$.ParameterFilters.length>0)z.ParameterFilters=$.ParameterFilters;let J=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParametersByPath","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(z)});return{Parameters:J.Parameters?.map((Z)=>this.parseParameter(Z)),NextToken:J.NextToken}}async deleteParameter($){let z={Name:$.Name};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DeleteParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(z)})}async deleteParameters($){let z={Names:$},J=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DeleteParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(z)});return{DeletedParameters:J.DeletedParameters,InvalidParameters:J.InvalidParameters}}async describeParameters($){let z={};if($?.Filters&&$.Filters.length>0)z.Filters=$.Filters;if($?.ParameterFilters&&$.ParameterFilters.length>0)z.ParameterFilters=$.ParameterFilters;if($?.MaxResults)z.MaxResults=$.MaxResults;if($?.NextToken)z.NextToken=$.NextToken;let J=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DescribeParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(z)});return{Parameters:J.Parameters?.map((Z)=>this.parseParameter(Z)),NextToken:J.NextToken}}async getParameterHistory($){let z={Name:$.Name};if($.WithDecryption!==void 0)z.WithDecryption=$.WithDecryption;if($.MaxResults)z.MaxResults=$.MaxResults;if($.NextToken)z.NextToken=$.NextToken;let J=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameterHistory","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(z)});return{Parameters:J.Parameters?.map((Z)=>({Name:Z.Name,Type:Z.Type,KeyId:Z.KeyId,LastModifiedDate:Z.LastModifiedDate,LastModifiedUser:Z.LastModifiedUser,Description:Z.Description,Value:Z.Value,Version:Z.Version,Labels:Z.Labels,Tier:Z.Tier})),NextToken:J.NextToken}}async labelParameterVersion($){let z={Name:$.Name,Labels:$.Labels};if($.ParameterVersion!==void 0)z.ParameterVersion=$.ParameterVersion;let J=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.LabelParameterVersion","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(z)});return{InvalidLabels:J.InvalidLabels,ParameterVersion:J.ParameterVersion}}async addTagsToResource($){let z={ResourceType:$.ResourceType,ResourceId:$.ResourceId,Tags:$.Tags};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.AddTagsToResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(z)})}async removeTagsFromResource($){let z={ResourceType:$.ResourceType,ResourceId:$.ResourceId,TagKeys:$.TagKeys};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.RemoveTagsFromResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(z)})}async listTagsForResource($){let z={ResourceType:$.ResourceType,ResourceId:$.ResourceId};return{TagList:(await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.ListTagsForResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(z)})).TagList}}async setString($,z,J){return this.putParameter({Name:$,Value:z,Type:"String",Description:J?.description,Overwrite:J?.overwrite??!0,Tags:J?.tags})}async setSecureString($,z,J){return this.putParameter({Name:$,Value:z,Type:"SecureString",Description:J?.description,Overwrite:J?.overwrite??!0,KeyId:J?.kmsKeyId,Tags:J?.tags})}async getValue($){return(await this.getParameter({Name:$,WithDecryption:!0})).Parameter?.Value}async getAllByPath($,z=!0){let J=[],Z;do{let Y=await this.getParametersByPath({Path:$,Recursive:z,WithDecryption:!0,NextToken:Z});if(Y.Parameters)J.push(...Y.Parameters);Z=Y.NextToken}while(Z);return J}parseParameter($){return{Name:$.Name,Type:$.Type,Value:$.Value,Version:$.Version,LastModifiedDate:$.LastModifiedDate,ARN:$.ARN,DataType:$.DataType,Description:$.Description,AllowedPattern:$.AllowedPattern,KeyId:$.KeyId,Tier:$.Tier}}async sendCommand($){if(!$.InstanceIds&&!$.Targets)throw Error("SendCommand requires either InstanceIds or Targets");let z={DocumentName:$.DocumentName};if($.InstanceIds)z.InstanceIds=$.InstanceIds;if($.Targets)z.Targets=$.Targets;if($.Parameters)z.Parameters=$.Parameters;if($.TimeoutSeconds)z.TimeoutSeconds=$.TimeoutSeconds;if($.Comment)z.Comment=$.Comment;if($.OutputS3BucketName)z.OutputS3BucketName=$.OutputS3BucketName;if($.OutputS3KeyPrefix)z.OutputS3KeyPrefix=$.OutputS3KeyPrefix;let J=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.SendCommand","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(z)});return{CommandId:J.Command?.CommandId,Status:J.Command?.Status,StatusDetails:J.Command?.StatusDetails}}async getCommandInvocation($){let z={CommandId:$.CommandId,InstanceId:$.InstanceId},J=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetCommandInvocation","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(z)});return{Status:J.Status,StatusDetails:J.StatusDetails,StandardOutputContent:J.StandardOutputContent,StandardErrorContent:J.StandardErrorContent,ResponseCode:J.ResponseCode}}async runShellCommand($,z,J){let Z=await this.sendCommand({InstanceIds:[$],DocumentName:"AWS-RunShellScript",Parameters:{commands:z},TimeoutSeconds:J?.timeoutSeconds||600});if(!Z.CommandId)return{success:!1,error:"Failed to send command"};if(J?.waitForCompletion===!1)return{success:!0,status:"Pending"};let Y=J?.pollIntervalMs||2000,G=J?.maxWaitMs||300000,j=Date.now();while(Date.now()-j<G){await new Promise((O)=>setTimeout(O,Y));try{let O=await this.getCommandInvocation({CommandId:Z.CommandId,InstanceId:$});if(O.Status==="Success")return{success:!0,output:O.StandardOutputContent,error:O.StandardErrorContent,status:O.Status};if(O.Status==="Failed"||O.Status==="Cancelled"||O.Status==="TimedOut")return{success:!1,output:O.StandardOutputContent,error:O.StandardErrorContent||O.StatusDetails,status:O.Status}}catch(O){if(!O.message?.includes("InvocationDoesNotExist"))return{success:!1,error:O.message}}}return{success:!1,error:"Command timed out waiting for completion"}}async listCommandInvocations($){let z={CommandId:$.CommandId};if($.Details)z.Details=!0;return((await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.ListCommandInvocations","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(z)})).CommandInvocations||[]).map((Y)=>({InstanceId:Y.InstanceId,Status:Y.Status,StatusDetails:Y.StatusDetails,StandardOutputContent:Y.CommandPlugins?.[0]?.Output,StandardErrorContent:Y.CommandPlugins?.[0]?.StandardErrorUrl}))}async sendCommandByTags($){let z=Object.entries($.tags).map(([Q,q])=>({Key:`tag:${Q}`,Values:[q]})),J=await this.sendCommand({Targets:z,DocumentName:"AWS-RunShellScript",Parameters:{commands:$.commands},TimeoutSeconds:$.timeoutSeconds||600,Comment:$.comment});if(!J.CommandId)return{success:!1,instanceCount:0,perInstance:[],error:"Failed to send command"};let Z=$.pollIntervalMs||3000,Y=$.maxWaitMs||600000,G=Date.now(),j=new Set(["Success","Failed","Cancelled","TimedOut"]),O=[];while(Date.now()-G<Y){await new Promise((Q)=>setTimeout(Q,Z));try{if(O=await this.listCommandInvocations({CommandId:J.CommandId,Details:!0}),O.length===0)continue;if(O.every((q)=>j.has(q.Status||""))){let q=O.map((W)=>({instanceId:W.InstanceId,status:W.Status||"Unknown",output:W.StandardOutputContent,error:W.StandardErrorContent||W.StatusDetails})),V=O.every((W)=>W.Status==="Success");return{success:V,instanceCount:O.length,perInstance:q,error:V?void 0:"One or more instances reported a non-success status"}}}catch(Q){if(!Q.message?.includes("InvocationDoesNotExist"))return{success:!1,instanceCount:0,perInstance:[],error:Q.message}}}return{success:!1,instanceCount:O.length,perInstance:O.map((Q)=>({instanceId:Q.InstanceId,status:Q.Status||"Unknown"})),error:"Command timed out waiting for all instances to complete"}}}function J0($=!0){if(!$)return[];return["export DEBIAN_FRONTEND=noninteractive","dpkg-query -W -f='${Status}' unattended-upgrades 2>/dev/null | grep -q 'ok installed' || apt-get install -y unattended-upgrades","cat > /etc/apt/apt.conf.d/20auto-upgrades <<'TS_CLOUD_AUTOUPD_EOF'",'APT::Periodic::Update-Package-Lists "1";','APT::Periodic::Unattended-Upgrade "1";','APT::Periodic::Download-Upgradeable-Packages "1";','APT::Periodic::AutocleanInterval "7";',"TS_CLOUD_AUTOUPD_EOF","systemctl enable --now unattended-upgrades 2>/dev/null || true"]}var R1=[["nginx",80],["https",443],["phpFpm",9074],["mysql",3306],["postgres",5432],["redis",6379],["meilisearch",7700],["typesense",8108],["smtp",25]];function Qz($=!0){let z=typeof $==="object"?$:{},J=typeof $==="boolean"?$:$.enabled!==!1,Z=Number(z.alerts?.bandwidthTb??0);return{enabled:J,cpuLoadPerCore:z.alerts?.cpuLoadPerCore??2,memPercent:z.alerts?.memPercent??90,diskPercent:z.alerts?.diskPercent??90,bandwidthTb:Number.isFinite(Z)&&Z>0?Z:0,bandwidthPercent:z.alerts?.bandwidthPercent??80}}function Z0($=!0){let{enabled:z,cpuLoadPerCore:J,memPercent:Z,diskPercent:Y,bandwidthTb:G,bandwidthPercent:j}=Qz($);if(!z)return[];let O=Math.round(G*1000000000000),Q=R1.map(([V,W])=>`SVC_${V.toUpperCase()}=$(probe ${W})`),q=R1.map(([V])=>`"${V}":"$SVC_${V.toUpperCase()}"`).join(",");return["if ! command -v sadf >/dev/null 2>&1; then export DEBIAN_FRONTEND=noninteractive; apt-get update -qq; apt-get install -y -qq sysstat; fi","systemctl enable --now sysstat.service 2>/dev/null || true","mkdir -p /var/lib/ts-cloud","cat > /usr/local/bin/ts-cloud-metrics.sh <<'TS_CLOUD_METRICS_EOF'","#!/bin/bash","set -uo pipefail","LOAD=$(cut -d' ' -f1 /proc/loadavg)","CPUS=$(nproc)",`read MEM_TOTAL MEM_USED SWAP_TOTAL SWAP_USED <<EOF
|
|
2
|
-
$(free -m | awk '/^Mem:/{total=$2; used=$3} /^Swap:/{print total, used, $2, $3}')
|
|
3
|
-
EOF`,`DISK_PCT=$(df -P / | awk 'NR==2{gsub("%","",$5); print $5}')`,"UPTIME_SEC=$(cut -d' ' -f1 /proc/uptime | cut -d. -f1)",`RX_BYTES=$(awk -F'[: ]+' 'NR>2 && $2!="lo"{rx+=$3} END{print rx+0}' /proc/net/dev)`,`TX_BYTES=$(awk -F'[: ]+' 'NR>2 && $2!="lo"{tx+=$11} END{print tx+0}' /proc/net/dev)`,"NOW_EPOCH=$(date -u +%s); TODAY=$(date -u +%Y-%m-%d); MONTH=$(date -u +%Y-%m)","if [ -r /var/lib/ts-cloud/bandwidth-state ]; then . /var/lib/ts-cloud/bandwidth-state; fi","PREV_EPOCH=${PREV_EPOCH:-0}; PREV_RX=${PREV_RX:-0}; PREV_TX=${PREV_TX:-0}","DAY_KEY=${DAY_KEY:-$TODAY}; MONTH_KEY=${MONTH_KEY:-$MONTH}","DAY_RX=${DAY_RX:-0}; DAY_TX=${DAY_TX:-0}; MONTH_RX=${MONTH_RX:-0}; MONTH_TX=${MONTH_TX:-0}","ELAPSED=$(( NOW_EPOCH - PREV_EPOCH ))",'if [ "$PREV_EPOCH" -le 0 ] || [ "$ELAPSED" -le 0 ] || [ "$RX_BYTES" -lt "$PREV_RX" ] || [ "$TX_BYTES" -lt "$PREV_TX" ]; then'," DELTA_RX=0; DELTA_TX=0; ELAPSED=0","else"," DELTA_RX=$(( RX_BYTES - PREV_RX )); DELTA_TX=$(( TX_BYTES - PREV_TX ))","fi",'if [ "$DAY_KEY" != "$TODAY" ]; then DAY_KEY=$TODAY; DAY_RX=0; DAY_TX=0; fi','if [ "$MONTH_KEY" != "$MONTH" ]; then MONTH_KEY=$MONTH; MONTH_RX=0; MONTH_TX=0; fi',"DAY_RX=$(( DAY_RX + DELTA_RX )); DAY_TX=$(( DAY_TX + DELTA_TX ))","MONTH_RX=$(( MONTH_RX + DELTA_RX )); MONTH_TX=$(( MONTH_TX + DELTA_TX ))",'if [ "$ELAPSED" -gt 0 ]; then RX_RATE=$(( DELTA_RX / ELAPSED )); TX_RATE=$(( DELTA_TX / ELAPSED )); else RX_RATE=0; TX_RATE=0; fi',"cat > /var/lib/ts-cloud/bandwidth-state.tmp <<BWSTATE","PREV_EPOCH=$NOW_EPOCH","PREV_RX=$RX_BYTES","PREV_TX=$TX_BYTES","RX_RATE=$RX_RATE","TX_RATE=$TX_RATE","DAY_KEY=$DAY_KEY","DAY_RX=$DAY_RX","DAY_TX=$DAY_TX","MONTH_KEY=$MONTH_KEY","MONTH_RX=$MONTH_RX","MONTH_TX=$MONTH_TX","BWSTATE","mv -f /var/lib/ts-cloud/bandwidth-state.tmp /var/lib/ts-cloud/bandwidth-state","probe(){ (exec 3<>/dev/tcp/127.0.0.1/$1) 2>/dev/null && echo up || echo down; }",...Q,"LOAD=${LOAD:-0}; CPUS=${CPUS:-1}; MEM_TOTAL=${MEM_TOTAL:-0}; MEM_USED=${MEM_USED:-0}","SWAP_TOTAL=${SWAP_TOTAL:-0}; SWAP_USED=${SWAP_USED:-0}; DISK_PCT=${DISK_PCT:-0}","UPTIME_SEC=${UPTIME_SEC:-0}; RX_BYTES=${RX_BYTES:-0}; TX_BYTES=${TX_BYTES:-0}","MEM_PCT=$(( MEM_TOTAL > 0 ? MEM_USED * 100 / MEM_TOTAL : 0 ))","cat > /var/lib/ts-cloud/metrics.json.tmp <<JSON",`{"load":$LOAD,"cpus":$CPUS,"memTotalMb":$MEM_TOTAL,"memUsedMb":$MEM_USED,"memUsedPct":$MEM_PCT,"swapTotalMb":$SWAP_TOTAL,"swapUsedMb":$SWAP_USED,"diskUsedPct":$DISK_PCT,"uptimeSec":$UPTIME_SEC,"network":{"rxBytes":$RX_BYTES,"txBytes":$TX_BYTES,"rxBytesPerSec":$RX_RATE,"txBytesPerSec":$TX_RATE,"dayKey":"$DAY_KEY","rxBytesToday":$DAY_RX,"txBytesToday":$DAY_TX,"monthKey":"$MONTH_KEY","rxBytesMonth":$MONTH_RX,"txBytesMonth":$MONTH_TX,"budgetBytes":${O}},"services":{`+q+"}}","JSON","mv -f /var/lib/ts-cloud/metrics.json.tmp /var/lib/ts-cloud/metrics.json",'ALERTS=""',`if awk -v l="$LOAD" -v c="$CPUS" -v t=${J} 'BEGIN{exit !(c>0 && l/c > t)}'; then ALERTS="$ALERTS load=$LOAD/${J}xCPU"; fi`,`if [ "\${MEM_PCT:-0}" -ge ${Z} ]; then ALERTS="$ALERTS mem=\${MEM_PCT}%"; fi`,`if [ "\${DISK_PCT:-0}" -ge ${Y} ]; then ALERTS="$ALERTS disk=\${DISK_PCT}%"; fi`,"PREV=$(cat /var/lib/ts-cloud/alert-state 2>/dev/null || echo ok)",'if [ -n "$ALERTS" ]; then',' if [ "$PREV" != alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "⚠️ $(hostname): resource alert —$ALERTS" || true; fi'," echo alert > /var/lib/ts-cloud/alert-state","else",' if [ "$PREV" = alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "✅ $(hostname): resource usage back to normal" || true; fi'," echo ok > /var/lib/ts-cloud/alert-state","fi",...O>0?["BW_TOTAL=$(( MONTH_RX + MONTH_TX ))",`BW_PCT=$(( BW_TOTAL * 100 / ${O} ))`,"BW_PREV=$(cat /var/lib/ts-cloud/bandwidth-alert-state 2>/dev/null || echo ok)",`if [ "$BW_PCT" -ge ${j} ]; then`,` if [ "$BW_PREV" != alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "⚠️ $(hostname): bandwidth at \${BW_PCT}% of the ${G} TB monthly allowance ($MONTH_KEY)" || true; fi`," echo alert > /var/lib/ts-cloud/bandwidth-alert-state","else",' if [ "$BW_PREV" = alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "✅ $(hostname): bandwidth back under the monthly allowance (${BW_PCT}%)" || true; fi'," echo ok > /var/lib/ts-cloud/bandwidth-alert-state","fi"]:[],"TS_CLOUD_METRICS_EOF","chmod +x /usr/local/bin/ts-cloud-metrics.sh","cat > /etc/systemd/system/ts-cloud-metrics.service <<'TS_CLOUD_METRICS_SVC_EOF'","[Unit]","Description=ts-cloud metrics collector","","[Service]","Type=oneshot","ExecStart=/usr/local/bin/ts-cloud-metrics.sh","TS_CLOUD_METRICS_SVC_EOF","cat > /etc/systemd/system/ts-cloud-metrics.timer <<'TS_CLOUD_METRICS_TMR_EOF'","[Unit]","Description=Run ts-cloud metrics collector every minute","","[Timer]","OnCalendar=*-*-* *:*:00","AccuracySec=1s","RandomizedDelaySec=5s","Persistent=true","","[Install]","WantedBy=timers.target","TS_CLOUD_METRICS_TMR_EOF","systemctl daemon-reload","systemctl enable --now ts-cloud-metrics.timer","systemctl start ts-cloud-metrics.service"]}var Vz={"opcache.enable":"1","opcache.enable_cli":"1","opcache.memory_consumption":"256","opcache.interned_strings_buffer":"16","opcache.max_accelerated_files":"20000","opcache.validate_timestamps":"0","opcache.revalidate_freq":"0","opcache.save_comments":"1","opcache.fast_shutdown":"1",realpath_cache_size:"4096K",realpath_cache_ttl:"600"},qz="127.0.0.1:9074";function _1($){return qz}function Wz($={}){let z=$.versions?.length?$.versions:["8.3"];return $.default&&z.includes($.default)?$.default:z[0]}function Hz($={}){return{...$.optimizeForProduction===!1?{}:{...Vz},...$.ini||{}}}function Mz($={}){let z=Hz($),J=Object.keys(z);if(J.length===0)return[];let Z=J.map((G)=>`${G}=${z[G]}`),Y="ts-cloud-managed";return[r0(),"TS_CLOUD_SCAN_DIR=$(php -i 2>/dev/null | awk -F' => ' '/^Scan this dir for additional .ini files/{print $2}' | head -1)",`TS_CLOUD_LOADED_INI=$(php -r 'echo php_ini_loaded_file() ?: "";' 2>/dev/null)`,'if [ -n "$TS_CLOUD_SCAN_DIR" ] && [ "$TS_CLOUD_SCAN_DIR" != "(none)" ]; then',' mkdir -p "$TS_CLOUD_SCAN_DIR"',' TS_CLOUD_PHP_INI="$TS_CLOUD_SCAN_DIR/zz-ts-cloud.ini"',` cat > "$TS_CLOUD_PHP_INI" <<'TS_CLOUD_PHPINI_EOF'`,`; ${Y} — production PHP tuning`,...Z,"TS_CLOUD_PHPINI_EOF","else",' if [ -z "$TS_CLOUD_LOADED_INI" ]; then'," TS_CLOUD_INI_DIR=$(php -i 2>/dev/null | awk -F' => ' '/^Configuration File \\(php.ini\\) Path/{print $2}' | head -1)",' TS_CLOUD_LOADED_INI="$TS_CLOUD_INI_DIR/php.ini"',' mkdir -p "$TS_CLOUD_INI_DIR"',' touch "$TS_CLOUD_LOADED_INI"'," fi",` sed -i '/; ${Y} BEGIN/,/; ${Y} END/d' "$TS_CLOUD_LOADED_INI"`,` cat >> "$TS_CLOUD_LOADED_INI" <<'TS_CLOUD_PHPINI_EOF'`,`; ${Y} BEGIN`,...Z,`; ${Y} END`,"TS_CLOUD_PHPINI_EOF","fi",`(cd ${Y0} && pantry restart php-fpm) 2>/dev/null || true`]}function i0($={}){let z=Wz($),J=$.installNginx!==!1,Z=$.installComposer!==!1,Y=[`php.net@${z}`];if(Z)Y.push("getcomposer.org");if(J)Y.push("nginx.org");return[...n0(Y),...D1(["php-fpm"]),...Mz($)]}function A$($,z){if(!$)return[];let J=[];if($.template&&z?.[$.template])J.push(...z[$.template]);if($.serverSnippet)J.push(...$.serverSnippet);return J}function Xz($){if(!$)return"";let z=typeof $==="object"?$:{},Z=[`max-age=${z.maxAge??31536000}`];if(z.includeSubDomains??!0)Z.push("includeSubDomains");if(z.preload)Z.push("preload");return` add_header Strict-Transport-Security "${Z.join("; ")}" always;`}function Kz($){if(!$||!$.allow?.length&&!$.deny?.length)return[];let z=[];for(let J of $.deny||[])z.push(` deny ${J};`);if($.allow?.length){for(let J of $.allow)z.push(` allow ${J};`);z.push(" deny all;")}return z}function E1($){return`/etc/nginx/.htpasswd-${$}`}var Fz=new Set(["laravel","php","statamic","wordpress"]);function Bz($){return Fz.has($)}function Uz($){return $==="laravel"||$==="statamic"?"public":""}function Cz($,z){let J=$.replace(/\/+$/,""),Z=z.replace(/^\/+|\/+$/g,"");return Z?`${J}/${Z}`:J}function Lz($){let z=$.type??"laravel",J=$.webDirectory??Uz(z),Z=Cz($.appDir,J),Y=Bz(z),G=$.phpVersion??"8.3",j=[` root ${Z};`,"",' add_header X-Frame-Options "SAMEORIGIN";',' add_header X-Content-Type-Options "nosniff";'],O=Xz($.hsts);if(O)j.push(O);for(let Q of Kz($.security))j.push(Q);if(j.push("",` index ${Y?"index.php index.html":"index.html index.htm"};`,""," charset utf-8;",""),$.clientMaxBodySize)j.push(` client_max_body_size ${$.clientMaxBodySize};`,"");if($.auth)j.push(` auth_basic "${$.auth.realm||"Restricted"}";`,` auth_basic_user_file ${E1($.siteName)};`,"");for(let[Q,q]of Object.entries($.redirects||{}))j.push(` location = ${Q} { return 301 ${q}; }`);if(Object.keys($.redirects||{}).length>0)j.push("");if(Y){if(j.push(" location / {"," try_files $uri $uri/ /index.php?$query_string;"," }",""," location = /favicon.ico { access_log off; log_not_found off; }"," location = /robots.txt { access_log off; log_not_found off; }",""," error_page 404 /index.php;",""," location ~ \\.php$ {",` fastcgi_pass ${$.fastcgiPass??_1(G)};`," fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;"," include fastcgi_params;"," }",""," location ~ /\\.(?!well-known).* {"," deny all;"," }"),z==="wordpress")j.push(""," location = /xmlrpc.php { deny all; }"," location ~* /(?:wp-config\\.php|readme\\.html|license\\.txt)$ { deny all; }"," location ~* /wp-content/uploads/.*\\.php$ { deny all; }")}else if(z==="spa")j.push(" location / {"," try_files $uri $uri/ /index.html;"," }");else j.push(" location / {"," try_files $uri $uri/ =404;"," }");if($.serverSnippet&&$.serverSnippet.length>0){j.push("");for(let Q of $.serverSnippet)j.push(Q?` ${Q}`:"")}return j}function Az($){let z=[$.domain,...$.aliases||[]].filter(Boolean);for(let G of z)if(!/^(?=.{1,253}$)(?:\*\.)?[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i.test(G.trim()))throw Error(`Refusing to build a vhost: '${G}' is not a valid hostname.`);if(!z.length)throw Error("Refusing to build a vhost: no server_name (domain) was given.");let J=z.join(" "),Z=Lz($);if($.ssl){let G=["server {"," listen 80;"," listen [::]:80;",` server_name ${J};`," return 301 https://$host$request_uri;","}"],j=["server {"," listen 443 ssl;"," listen [::]:443 ssl;",` server_name ${J};`,` ssl_certificate ${$.ssl.certPath};`,` ssl_certificate_key ${$.ssl.keyPath};`,...$.tlsProtocols?.length?[` ssl_protocols ${$.tlsProtocols.join(" ")};`]:[],"",...Z,"}"];return`${[...G,"",...j].join(`
|
|
4
|
-
`)}
|
|
5
|
-
`}return`${["server {"," listen 80;"," listen [::]:80;",` server_name ${J};`,...Z,"}"].join(`
|
|
6
|
-
`)}
|
|
7
|
-
`}function R$($){let z=`/etc/nginx/sites-available/${$.siteName}`,J=`/etc/nginx/sites-enabled/${$.siteName}`,Z=Az($),Y=[...D$()];if($.auth){let G=E1($.siteName),j=(q)=>q.split("'").join("'\\''"),O=j($.auth.password),Q=j($.auth.username);Y.push(`TS_CLOUD_HTPASS=$(openssl passwd -apr1 '${O}')`,`printf '%s:%s\\n' '${Q}' "$TS_CLOUD_HTPASS" > ${G}`,`chmod 640 ${G}`,`chown root:www-data ${G} 2>/dev/null || true`)}return Y.push(`cat > ${z} <<'TS_CLOUD_NGINX_EOF'`,Z.replace(/\n$/,""),"TS_CLOUD_NGINX_EOF",`ln -sf ${z} ${J}`,"rm -f /etc/nginx/sites-enabled/default",`${G0} -t`,"systemctl reload ts-cloud-nginx 2>/dev/null || systemctl restart ts-cloud-nginx 2>/dev/null || true"),Y}var G0="/usr/local/bin/ts-cloud-nginx";function D$($="/opt/pantry"){return[...t0(),...n0(["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 > ${G0} <<'TS_CLOUD_NGINXBIN_EOF'`,"#!/bin/sh",`eval "$(cd ${$} && 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 ${G0}`,"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=${G0} -t`,`ExecStart=${G0} -g 'daemon off;'`,`ExecReload=${G0} -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 S0($,z){return!$.events||$.events.includes(z)}async function _$($,z,J,Z={}){if(!$)return[];let Y=Z.fetchImpl??globalThis.fetch,G=[],j=[],O=(Q,q)=>Y(Q,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(q)}).catch(()=>{return});if($.slack?.webhookUrl&&S0($,z))G.push("slack"),j.push(O($.slack.webhookUrl,{text:J}));if($.discord?.webhookUrl&&S0($,z))G.push("discord"),j.push(O($.discord.webhookUrl,{content:J}));if($.telegram?.botToken&&$.telegram.chatId&&S0($,z)){G.push("telegram");let Q=`https://api.telegram.org/bot${$.telegram.botToken}/sendMessage`;j.push(O(Q,{chat_id:$.telegram.chatId,text:J}))}if($.webhook?.url&&S0($,z))if(G.push("webhook"),($.webhook.method||"POST")==="GET"){let Q=$.webhook.url.includes("?")?"&":"?",q=`${$.webhook.url}${Q}event=${encodeURIComponent(z)}&message=${encodeURIComponent(J)}`;j.push(Y(q,{method:"GET"}).catch(()=>{return}))}else j.push(O($.webhook.url,{event:z,message:J}));if($.email?.to&&S0($,z))G.push("email"),j.push(Dz($.email,z,J));return await Promise.all(j),G}async function Dz($,z,J){try{await(await import("./chunk-c1vcdgvr.js")).email.send({to:$.to,from:$.from,subject:`[ts-cloud] ${z}`,text:J})}catch{}}function w1($,z){return z??$}function C0($){if(!$)return[];let z=[];if($.slack?.webhookUrl)z.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"text\\":\\"$MSG\\"}" ${$.slack.webhookUrl} || true`);if($.discord?.webhookUrl)z.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"content\\":\\"$MSG\\"}" ${$.discord.webhookUrl} || true`);if($.telegram?.botToken&&$.telegram.chatId)z.push(`curl -fsS -X POST "https://api.telegram.org/bot${$.telegram.botToken}/sendMessage" --data-urlencode "chat_id=${$.telegram.chatId}" --data-urlencode "text=$MSG" || true`);if($.webhook?.url)z.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"message\\":\\"$MSG\\"}" ${$.webhook.url} || true`);if(z.length===0)return[];return["cat > /usr/local/bin/ts-cloud-notify <<'TS_CLOUD_NOTIFY_EOF'","#!/bin/bash",'MSG="$1"',...z,"TS_CLOUD_NOTIFY_EOF","chmod +x /usr/local/bin/ts-cloud-notify"]}var x$="/etc/rpx/certs";function T$($){return $.split(".").length===2}function _z($,z={}){let J=new Set;for(let Z of Object.values($)){if(!Z?.domain)continue;if(u(Z)==="bucket")continue;J.add(Z.domain)}if(z.autoWww!==!1)for(let Z of[...J]){if(!T$(Z))continue;J.add(`www.${Z}`)}return[...J]}var Ez=["1.1.1.1","8.8.8.8"],wz="/var/www/acme-challenge";function xz($){if(typeof $==="string")return{to:$};let z={to:$.to};if($.status!=null)z.status=$.status;if($.preservePath!=null)z.preservePath=$.preservePath;return z}function Tz($){let z=$.auth;if(!z||z.enabled===!1||!z.password)return;return{username:z.username||"admin",password:z.password,...z.realm?{realm:z.realm}:{}}}function T1($){if(!$||$==="/")return;let z=`/${$}`.replace(/\/+/g,"/").replace(/\/+$/,"");if(!z.startsWith("/"))z=`/${z}`;return z===""||z==="/"?void 0:z}function E$($,z){let Z=(z?`${$}${z}`:$).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return Z.length>0?Z:"rpx"}function Nz($,z){if(!z||z.length===0)return`localhost:${$}`;return z.map((J)=>`${J.privateIp??J.publicIp}:${$}`)}function N1($,z,J){let Z=(z.wwwRoot??"/var/www").replace(/\/+$/,""),Y=z.slug??"app",G=z.proxy.certsDir??x$,j=z.proxy.loadBalancer,O=[],Q=new Set;for(let[H,M]of Object.entries($)){if(!M||!M.domain)continue;let X=u(M);if(X==="bucket")continue;let A=T1(M.path),F=E$(M.domain,A),B=Tz(M);if(X==="redirect"){O.push({to:M.domain,path:A,redirect:xz(M.redirect),id:F,...B?{auth:B}:{}}),Q.add(M.domain);continue}if(X==="proxy"){let K=x1(M);if(K.length===0)continue;let R=K.length===1?K[0]:K;O.push({to:M.domain,path:A,from:R,id:F,...B?{auth:B}:{},...Array.isArray(R)&&j?{loadBalancer:j}:{}}),Q.add(M.domain);continue}if(X==="server-app"){if(typeof M.port!=="number")continue;let K=Nz(M.port,J);O.push({to:M.domain,path:A,from:K,id:F,...B?{auth:B}:{},...Array.isArray(K)&&j?{loadBalancer:j}:{}})}else O.push({to:M.domain,path:A,static:{dir:`${Z}/${Y}-${H}/current`,spa:M.spa??!1,pathRewriteStyle:M.pathRewriteStyle??"directory"},cleanUrls:M.pathRewriteStyle!=="flat",...B?{auth:B}:{},id:F});Q.add(M.domain)}if(z.proxy.autoWww!==!1)for(let H of[...Q]){if(!T$(H))continue;let M=`www.${H}`;if(Q.has(M))continue;O.push({to:M,redirect:{to:`https://${H}`},id:E$(M)}),Q.add(M)}O.sort((H,M)=>{if(H.to!==M.to)return H.to.localeCompare(M.to);return(M.path?.length??0)-(H.path?.length??0)});let q={proxies:O,productionCerts:{certsDir:G,certsDirServerNames:[...Q]},https:!0,hostsManagement:!1,cleanup:{hosts:!1,certs:!1}};if(z.proxy.onDemandTls&&Q.size>0)q.onDemandTls={enabled:!0,allowedSuffixes:[...Q],email:z.proxy.onDemandTlsEmail,certsDir:G,staging:z.proxy.onDemandTlsStaging??!1};if(z.proxy.onDemandTls)q.acmeChallengeWebroot=z.proxy.acmeWebroot??wz;let V=z.proxy.cdn,W=V?.frontedHosts?.length?V.frontedHosts:[...Q];if(V?.secret&&W.length>0)q.originGuard={header:V.secretHeader??"X-Origin-Verify",value:V.secret,hosts:W};return q}function O0($,z){return N1($,z)}function A0($,z,J){return N1($,J,z)}function n($){return $?.webServer==="rpx"||$?.proxy?.engine==="rpx"}var f0="/etc/rpx",g="/opt/rpx-gateway",w$="/etc/rpx/gateway.ts",b0="/etc/rpx/gateway",j0="rpx-gateway.service",M0="/etc/rpx/sites.d";function kz($=M0,z=x$){return`// Generated by ts-cloud — rpx gateway assembler.
|
|
8
|
-
// Merges every app's fragment in ${$} so independent deploys compose
|
|
9
|
-
// without clobbering each other. Each deploy writes only its own <slug>.json.
|
|
10
|
-
import { startProxies } from '@stacksjs/rpx'
|
|
11
|
-
import { readdirSync, readFileSync } from 'node:fs'
|
|
12
|
-
|
|
13
|
-
const dir = ${JSON.stringify($)}
|
|
14
|
-
const proxies = []
|
|
15
|
-
const seen = new Set()
|
|
16
|
-
const owners = new Map()
|
|
17
|
-
const suffixes = new Set()
|
|
18
|
-
const guardHosts = new Set()
|
|
19
|
-
let email
|
|
20
|
-
let certsDir = ${JSON.stringify(z)}
|
|
21
|
-
let acmeChallengeWebroot
|
|
22
|
-
let guard
|
|
23
|
-
let anyProduction = false
|
|
24
|
-
let files = []
|
|
25
|
-
try { files = readdirSync(dir).filter(n => n.endsWith('.json')).sort() } catch {}
|
|
26
|
-
for (const f of files) {
|
|
27
|
-
let frag
|
|
28
|
-
// Fragments are written atomically (temp + rename by ts-cloud), so a parse
|
|
29
|
-
// failure here means a genuinely corrupt fragment, not a mid-write read. Log
|
|
30
|
-
// it LOUD — a silent skip drops that app's whole host from the routing table,
|
|
31
|
-
// which then answers 404 until someone notices. We still continue so one bad
|
|
32
|
-
// fragment can't take every other app down, but the drop is now visible.
|
|
33
|
-
try { frag = JSON.parse(readFileSync(dir + '/' + f, 'utf8')) }
|
|
34
|
-
catch (err) { console.error('[rpx-assembler] SKIPPING malformed fragment ' + f + ' — its host(s) will 404 until fixed: ' + err); continue }
|
|
35
|
-
for (const p of frag.proxies ?? []) {
|
|
36
|
-
const key = p.id || (p.to + (p.path ?? ''))
|
|
37
|
-
if (seen.has(key)) {
|
|
38
|
-
console.warn('[rpx-assembler] duplicate route ' + key + ' in ' + f + ' ignored; first declared by ' + owners.get(key))
|
|
39
|
-
continue
|
|
40
|
-
}
|
|
41
|
-
seen.add(key)
|
|
42
|
-
owners.set(key, f)
|
|
43
|
-
proxies.push(p)
|
|
44
|
-
}
|
|
45
|
-
for (const s of frag.onDemandTls?.allowedSuffixes ?? []) suffixes.add(s)
|
|
46
|
-
email ??= frag.onDemandTls?.email
|
|
47
|
-
// One gateway, one ACME directory: production wins any disagreement between
|
|
48
|
-
// co-tenants, and a fragment predating the flag counts as production. A
|
|
49
|
-
// staging cert chains to an untrusted root, so defaulting the other way
|
|
50
|
-
// breaks every client of every tenant that wanted a real cert.
|
|
51
|
-
if (frag.onDemandTls && frag.onDemandTls.staging !== true) anyProduction = true
|
|
52
|
-
if (frag.productionCerts?.certsDir) certsDir = frag.productionCerts.certsDir
|
|
53
|
-
acmeChallengeWebroot ??= frag.acmeChallengeWebroot
|
|
54
|
-
if (frag.originGuard) {
|
|
55
|
-
// One gateway means one origin-guard secret (rpx takes a single
|
|
56
|
-
// header/value). A tenant whose secret disagrees with the adopted one must
|
|
57
|
-
// NOT have its hosts guarded: its CDN would send a different value, the
|
|
58
|
-
// gateway would reject every request, and a working host would go dark.
|
|
59
|
-
// Unguarded is weaker but serving, and the mismatch is logged.
|
|
60
|
-
guard ??= { header: frag.originGuard.header, value: frag.originGuard.value }
|
|
61
|
-
if (frag.originGuard.header === guard.header && frag.originGuard.value === guard.value) {
|
|
62
|
-
for (const h of frag.originGuard.hosts ?? []) guardHosts.add(h)
|
|
63
|
-
}
|
|
64
|
-
else {
|
|
65
|
-
console.warn('[rpx-assembler] origin-guard secret in ' + f + ' differs from the one already in force; its hosts stay unguarded rather than rejecting all traffic')
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
const config = {
|
|
70
|
-
proxies,
|
|
71
|
-
productionCerts: {
|
|
72
|
-
certsDir,
|
|
73
|
-
// A shared host's cert directory also contains mail and retired-site PEMs.
|
|
74
|
-
// Keep those files on disk for their owners, but do not turn them into live
|
|
75
|
-
// OpenSSL SNI contexts when no current route can select them.
|
|
76
|
-
certsDirServerNames: [...new Set(proxies.map(p => p.to).filter(Boolean))],
|
|
77
|
-
},
|
|
78
|
-
https: true,
|
|
79
|
-
hostsManagement: false,
|
|
80
|
-
cleanup: { hosts: false, certs: false },
|
|
81
|
-
// Verbose is the hard default for ts-cloud-installed gateways: without it,
|
|
82
|
-
// rpx's TLS/routing diagnostics (tlsx on-demand 'refused issuance',
|
|
83
|
-
// 'issuance failed', 'adopted existing on-disk cert') never reach the systemd
|
|
84
|
-
// journal and a production TLS failure looks like "nothing happens". Silence
|
|
85
|
-
// it by setting RPX_VERBOSE=false on the systemd unit.
|
|
86
|
-
verbose: process.env.RPX_VERBOSE !== 'false',
|
|
87
|
-
...(suffixes.size > 0 ? { onDemandTls: { enabled: true, allowedSuffixes: [...suffixes], email, certsDir, staging: !anyProduction } } : {}),
|
|
88
|
-
...(acmeChallengeWebroot ? { acmeChallengeWebroot } : {}),
|
|
89
|
-
...(guard ? { originGuard: { header: guard.header, value: guard.value, hosts: [...guardHosts] } } : {}),
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
await startProxies(config)
|
|
93
|
-
`}function L0($,z,J,Z="0644"){return[`__tsc_tmp="$(mktemp "${$}.XXXXXX")"`,`cat > "$__tsc_tmp" <<'${J}'`,z,J,`mv -f "$__tsc_tmp" ${$}`,`chmod ${Z} ${$}`]}function Pz($){return`'${$.replaceAll("'","'\\''")}'`}function k1($,z,J,Z){if(!Z.preserveManagementDashboardRoutes)return L0($,z,J,"0600");let Y=`
|
|
94
|
-
const { readFileSync, writeFileSync } = require('node:fs')
|
|
95
|
-
const currentPath = process.env.TS_CLOUD_RPX_CURRENT_FRAGMENT
|
|
96
|
-
const candidatePath = process.env.TS_CLOUD_RPX_CANDIDATE_FRAGMENT
|
|
97
|
-
const isDashboard = route => /^(?:dashboard|cloud)\\./i.test(String(route?.to || ''))
|
|
98
|
-
const current = JSON.parse(readFileSync(currentPath, 'utf8'))
|
|
99
|
-
const candidate = JSON.parse(readFileSync(candidatePath, 'utf8'))
|
|
100
|
-
const retained = Array.isArray(current.proxies) ? current.proxies.filter(isDashboard) : []
|
|
101
|
-
const next = Array.isArray(candidate.proxies) ? candidate.proxies.filter(route => !isDashboard(route)) : []
|
|
102
|
-
candidate.proxies = [...next, ...retained]
|
|
103
|
-
writeFileSync(candidatePath, JSON.stringify(candidate, null, 2) + '\\n', { mode: 0o600 })
|
|
104
|
-
`.trim();return[`__tsc_fragment_candidate="$(mktemp "${$}.candidate.XXXXXX")"`,`cat > "$__tsc_fragment_candidate" <<'${J}'`,z,J,'chmod 0600 "$__tsc_fragment_candidate"',`if [ -f ${$} ]; then TS_CLOUD_RPX_CURRENT_FRAGMENT=${$} TS_CLOUD_RPX_CANDIDATE_FRAGMENT="$__tsc_fragment_candidate" ${Z.bunBin} -e ${Pz(Y)}; fi`,`mv -f "$__tsc_fragment_candidate" ${$}`,`chmod 0600 ${$}`]}function N$($){return`rpx-cert-renew-${($||"app").replace(/[^a-z0-9._-]+/gi,"-")}.service`}function k$($){let z=new Set;for(let J of $.proxies){let Z=J.to;if(!Z||Z.startsWith("*")||Z.includes(":")||!Z.includes("."))continue;z.add(Z)}return[...z]}function Iz($){let{config:z,proxy:J}=$,Z=z.acmeChallengeWebroot,Y=k$(z);if(!J.onDemandTls||!Z||Y.length===0)return[];let G=$.bunBin??"/usr/local/bin/bun",j=J.version??"latest",O=z.productionCerts.certsDir,Q=J.onDemandTlsEmail??`webmaster@${Y[0]}`,q=`${G} ${g}/node_modules/@stacksjs/tlsx/dist/bin/cli.js`,V=Y.join(","),W=Y.join(" "),H=($.slug||"app").replace(/[^a-z0-9._-]+/gi,"-"),M=`${f0}/renew-certs-${H}.sh`,X=N$(H),A=`rpx-cert-renew-${H}.timer`,F=["#!/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='${O}'`,`WEBROOT='${Z}'`,`EMAIL='${Q}'`,`TLSX="${q}"`,`BUN='${G}'`,`DOMAINS='${V}'`,"DNS_ATTEMPTS='24'","DNS_DELAY_SECONDS='5'",`DNS_RESOLVERS='${Ez.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 ${W}; 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 ${j0}`," 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 ${j0}`].join(`
|
|
105
|
-
`),B=["[Unit]",`Description=Issue/renew rpx gateway TLS certs for ${H} (tlsx http-01)`,`After=network-online.target ${j0}`,"Wants=network-online.target","","[Service]","Type=oneshot",`ExecStart=${M}`].join(`
|
|
106
|
-
`),K=["[Unit]",`Description=Daily rpx gateway TLS cert issuance/renewal for ${H}`,"","[Timer]","OnCalendar=*-*-* 03:30:00","RandomizedDelaySec=1h","Persistent=true","","[Install]","WantedBy=timers.target"].join(`
|
|
107
|
-
`);return[`mkdir -p ${Z}`,`(cd ${g} && ${G} add @stacksjs/tlsx@${j}) || true`,...L0(M,F,"TS_CLOUD_RENEW_EOF"),`chmod +x ${M}`,...L0(`/etc/systemd/system/${X}`,B,"TS_CLOUD_RENEW_SVC_EOF"),...L0(`/etc/systemd/system/${A}`,K,"TS_CLOUD_RENEW_TIMER_EOF"),"systemctl daemon-reload",`systemctl enable --now ${A} || true`,`${M} || true`]}function Q0($){let{config:z,proxy:J}=$,Z=$.bunBin??"/usr/local/bin/bun",Y=J.version??"latest",G=z.productionCerts.certsDir,j=($.slug||"app").replace(/[^a-z0-9._-]+/gi,"-"),O=JSON.stringify({slug:j,...z},null,2),Q=kz(M0,G),V=[`Environment=RPX_UPSTREAM_TIMEOUT=${J.upstreamTimeout??60}`];if(typeof J.maxUpstreamConns==="number")V.push(`Environment=RPX_MAX_UPSTREAM_CONNS=${J.maxUpstreamConns}`);let W=J.memoryHigh??"512M",H=J.memoryMax??"768M";return["set -euo pipefail",`mkdir -p ${f0} ${M0} ${G} ${g}`,`rm -rf ${g}.next ${g}.prev`,`mkdir -p ${g}.next`,`(cd ${g}.next && ${Z} add @stacksjs/rpx@${Y})`,`mv ${g} ${g}.prev`,`mv ${g}.next ${g}`,`rm -rf ${g}.prev`,`ln -sfn ${g}/node_modules ${f0}/node_modules`,...k1(`${M0}/${j}.json`,O,"TS_CLOUD_RPX_FRAGMENT_EOF",{bunBin:Z,preserveManagementDashboardRoutes:$.preserveManagementDashboardRoutes}),...L0(w$,Q,"TS_CLOUD_RPX_EOF"),`${Z} build --production --compile --outfile ${b0}.next ${w$}`,`chmod 0755 ${b0}.next`,`mv -f ${b0}.next ${b0}`,...L0(`/etc/systemd/system/${j0}`,["[Unit]","Description=rpx reverse-proxy gateway (managed by ts-cloud)","After=network.target network-online.target","Wants=network-online.target","","[Service]","Type=simple",`ExecStart=${b0}`,`WorkingDirectory=${g}`,"Environment=BUN_INSTALL=/root/.bun","Environment=APP_ENV=production","Environment=NODE_ENV=production",...V,"MemoryAccounting=true",`MemoryHigh=${W}`,`MemoryMax=${H}`,"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(`
|
|
108
|
-
`),"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 "${M0}/$tenant.json" ] && continue; systemctl disable --now "$unit" 2>/dev/null || true; rm -f "$timer" "/etc/systemd/system/rpx-cert-renew-$tenant.service" "${f0}/renew-certs-$tenant.sh"; done`,`systemctl enable ${j0}`,`systemctl restart ${j0}`,...Iz($)]}function h0($){let z=($.slug||"app").replace(/[^a-z0-9._-]+/gi,"-"),J=JSON.stringify({slug:z,...$.config},null,2);return["set -euo pipefail",`mkdir -p ${M0}`,...k1(`${M0}/${z}.json`,J,"TS_CLOUD_RPX_FRAGMENT_EOF",{bunBin:"/usr/local/bin/bun",preserveManagementDashboardRoutes:$.preserveManagementDashboardRoutes}),`systemctl restart ${j0}`]}function R0($=[],z={}){let J=z.path??"/root/.ssh/authorized_keys",Y=[`mkdir -p ${J.replace(/\/[^/]*$/,"")}`,`touch ${J}`,`sed -i '/^${P1("# >>> ts-cloud managed keys >>>")}$/,/^${P1("# <<< ts-cloud managed keys <<<")}$/d' ${J}`];if($.length>0){let G=["# >>> ts-cloud managed keys >>>",...$.map((j)=>`${j.publicKey.trim()} ${j.name}`),"# <<< ts-cloud managed keys <<<"].join(`
|
|
109
|
-
`);Y.push(`cat >> ${J} <<'TS_CLOUD_KEYS_EOF'`,G,"TS_CLOUD_KEYS_EOF",`chmod 600 ${J}`)}return Y}function P1($){return $.replace(/[.*[\]\\/^$]/g,"\\$&")}function b1($,z){let J=`/tmp/ts-cloud-${$}.sh`,Z=`TS_CLOUD_${$.toUpperCase().replace(/[^A-Z0-9]/g,"_")}_EOF`;return[`cat > ${J} <<'${Z}'`,z.replace(/\n$/,""),Z,`chmod +x ${J}`,`bash ${J} || echo "ts-cloud: ${$} setup did not complete; continuing" >&2`,`rm -f ${J}`]}function f1($,z){if($===!1)return;if($===!0||$===void 0)return z;return $}var I1={enabled:!0,ports:[80,443]},yz={mode:"detection",paranoiaLevel:1};function Sz($=!0,z=[]){let J=f1($,I1);if(!J||J.enabled===!1)return[];let Z=[...new Set([...J.ports??I1.ports??[],...z])].sort((Y,G)=>Y-G);return b1("ddos",y1({...J,ports:Z}))}function bz($=!0){let z=f1($,yz);if(!z||z.mode==="off")return[];return b1("waf",S1(z))}function h1($={},z=[]){return[...Sz($.ddos,z),...bz($.waf)]}function fz($){return`${$}-sftp`}function v1($){return $.port??2222}function hz($){let z=$.sftp.storage;if(z?.type==="efs"&&z.path)return z.path;return`/var/sftp/${$.slug}`}function D0($){return`'${$.split("'").join("'\\''")}'`}function m1($,z){if(z==="aws")return;let J=$.storage;if(J?.type==="s3"||!J&&!!$.bucket)throw Error(`sftp: bucket-backed storage is only available on the aws provider (Transfer Family). On ${z}, use storage: { type: 'efs' } to serve a directory on the server.`);for(let[Y,G]of Object.entries($.users))if(!G.sshPublicKeys?.length)throw Error(`sftp: user ${Y} needs at least one SSH public key`)}function g1($){let{slug:z,sftp:J}=$,Z=fz(z),Y=hz($),G=v1(J),j="/etc/ts-sftp/host_key",O="/etc/ts-sftp/users",Q=J.serviceUser??"ts-sftp",q=[`# --- ts-sftp (${Z}) ---`,`id -u ${Q} >/dev/null 2>&1 || useradd --system --home-dir ${D0(Y)} --shell /usr/sbin/nologin ${Q}`,'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 ${D0(Y)} /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@${J.version??"latest"} --no-save --production || bun add ts-sftp@${J.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 ${D0(`${z}-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'],V=[];for(let[W,H]of Object.entries(J.users)){let M=(H.homeDirectory??W).replace(/^\/+|\/+$/g,"");if(!M||M.split("/").includes(".."))throw Error(`sftp: invalid homeDirectory for user ${W}`);let X=`/etc/ts-sftp/users/${W}.pub`;q.push(`mkdir -p ${D0(`${Y}/${M}`)}`,`printf '%s\\n' ${D0(H.sshPublicKeys.join(`
|
|
110
|
-
`))} > ${X}`,`chmod 644 ${X}`),V.push(`--user ${W}:${X}`)}return q.push(`chown -R ${Q}:${Q} ${D0(Y)} /etc/ts-sftp`,`cat > /etc/systemd/system/${Z}.service <<TSCLOUD_SFTP_UNIT`,"[Unit]","Description=ts-sftp file transfer server","After=network.target","","[Service]",`User=${Q}`,`ExecStart=$BUN_BIN /opt/ts-sftp/node_modules/ts-sftp/dist/bin/cli.js serve --root ${Y} --host-key /etc/ts-sftp/host_key --port ${G}${J.readOnly?" --read-only":""} ${V.join(" ")}`,"Restart=always","RestartSec=2","NoNewPrivileges=true","PrivateTmp=true","ProtectSystem=strict",`ReadWritePaths=${Y}`,"","[Install]","WantedBy=multi-user.target","TSCLOUD_SFTP_UNIT","systemctl daemon-reload",`systemctl enable ${Z}.service`,`systemctl restart ${Z}.service`),q}function u1($){return $?[v1($)]:[]}var vz=[80,443];function s0($={}){if($.enabled===!1)return[];let z=[...new Set([...vz,...$.allowedPorts||[]])].filter((Z)=>Number.isInteger(Z)&&Z>=1&&Z<=65535).sort((Z,Y)=>Z-Y),J=["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 Z of z)J.push(`ufw allow ${Z}/tcp`);return J.push("ufw --force enable"),J}function v0($){let z=$.infrastructure?.compute??{},J=z.runtime==="php"||!!z.php,Z=J||!!z.managedServices,Y=Z?t0():[],G=!n(z),j=J?[...Y,...i0({versions:z.php?.versions,default:z.php?.default,extensions:z.php?.extensions,installNginx:G,optimizeForProduction:z.php?.optimizeForProduction,ini:z.php?.ini}),...G?D$():[]]:void 0,O=[],Q=V0($);if(!J&&Z)O.push(...Y);if(O.push(...C0($.notifications)),z.managedServices)O.push(...o0(z.managedServices),...E0(Q,z.managedServices));let q=$.infrastructure?.sftp;if(q)m1(q,_0($)),O.push(...g1({slug:$.project.slug,sftp:q}));if(O.push(...s0(z.firewall??(J?{enabled:!0}:{enabled:!1}))),O.push(...h1({ddos:z.ddos,waf:z.waf},z.firewall?.allowedPorts??[])),O.push(...J0(z.autoUpdates??J)),O.push(...Z0(z.monitoring??J)),O.push(...R0(z.sshKeys)),z.backups?.enabled)O.push(...e0({database:Q,backups:z.backups}));return{runtime:z.runtime||"bun",runtimeVersion:z.runtimeVersion||"latest",phpBox:J,phpProvision:j,servicesProvision:O.length>0?O:void 0}}function i($={}){let{runtime:z="bun",runtimeVersion:J="latest",systemPackages:Z=[],database:Y,phpProvision:G,servicesProvision:j,caddyfile:O,rpxProvision:Q,baked:q=!1,swapGb:V=2}=$,W=new Set(Z);if(Y==="sqlite")W.add("sqlite3");else if(Y==="mysql")W.add("mysql-client");else if(Y==="postgres")W.add("postgresql-client");let H=`#!/bin/bash
|
|
111
|
-
set -euo pipefail
|
|
112
|
-
`,M=Math.floor(V);if(M>0)H+=`
|
|
113
|
-
# Swap: a swapless box under memory pressure lets the kernel OOM killer choose
|
|
114
|
-
# victims box-wide (the gateway, a tenant app, postgres). A modest swapfile
|
|
115
|
-
# with low swappiness gives the kernel headroom without hurting responsiveness.
|
|
116
|
-
if ! swapon --show=NAME --noheadings 2>/dev/null | grep -qx '/swapfile'; then
|
|
117
|
-
if [ ! -f /swapfile ]; then
|
|
118
|
-
fallocate -l ${M}G /swapfile || dd if=/dev/zero of=/swapfile bs=1M count=${M*1024} status=none
|
|
119
|
-
chmod 600 /swapfile
|
|
120
|
-
mkswap /swapfile >/dev/null
|
|
121
|
-
fi
|
|
122
|
-
swapon /swapfile
|
|
123
|
-
fi
|
|
124
|
-
grep -qE '^/swapfile\\s' /etc/fstab || echo '/swapfile none swap sw 0 0' >> /etc/fstab
|
|
125
|
-
echo 'vm.swappiness=10' > /etc/sysctl.d/99-ts-cloud-swap.conf
|
|
126
|
-
sysctl -w vm.swappiness=10 >/dev/null
|
|
127
|
-
`;if(!q){if(H+=`
|
|
128
|
-
export DEBIAN_FRONTEND=noninteractive
|
|
129
|
-
apt-get update -y
|
|
130
|
-
apt-get upgrade -y
|
|
131
|
-
apt-get install -y curl tar gzip unzip git ca-certificates
|
|
132
|
-
`,W.size>0)H+=`
|
|
133
|
-
apt-get install -y ${[...W].join(" ")}
|
|
134
|
-
`;if(G&&G.length>0)H+=`
|
|
135
|
-
${G.join(`
|
|
136
|
-
`)}
|
|
137
|
-
`;if(j&&j.length>0)H+=`
|
|
138
|
-
${j.join(`
|
|
139
|
-
`)}
|
|
140
|
-
`;if(z==="bun")H+=`
|
|
141
|
-
# cloud-init runs this with \`set -u\` and NO $HOME set. bun's install.sh
|
|
142
|
-
# dereferences $HOME even when BUN_INSTALL is set, so without this the install
|
|
143
|
-
# aborts with "HOME: unbound variable" and /usr/local/bin/bun never appears —
|
|
144
|
-
# breaking a from-scratch provision (adopting an existing box masked it).
|
|
145
|
-
export HOME="\${HOME:-/root}"
|
|
146
|
-
export BUN_INSTALL="/root/.bun"
|
|
147
|
-
# bun.sh's installer references $HOME internally and runs under this
|
|
148
|
-
# script's \`set -u\` (inherited by the piped bash) — cloud-init's runcmd
|
|
149
|
-
# environment doesn't export HOME by default, so without this the
|
|
150
|
-
# installer dies with "HOME: unbound variable" partway through (after
|
|
151
|
-
# the binary is already downloaded, so it looks like a partial success)
|
|
152
|
-
# and \`set -e\` aborts everything after it: the bun symlink, /var/www +
|
|
153
|
-
# /var/ts-cloud dirs, and the whole rpx gateway install/systemd setup
|
|
154
|
-
# never run. Confirmed against a real Hetzner box (stacksjs/status#1
|
|
155
|
-
# Phase 9 e2e deploy) — cloud-init reported success with none of that
|
|
156
|
-
# actually done.
|
|
157
|
-
export HOME="\${HOME:-/root}"
|
|
158
|
-
curl -fsSL https://bun.sh/install | bash${J==="latest"?"":` -s "bun-v${J}"`}
|
|
159
|
-
ln -sf /root/.bun/bin/bun /usr/local/bin/bun
|
|
160
|
-
echo 'export BUN_INSTALL="/root/.bun"' > /etc/profile.d/bun.sh
|
|
161
|
-
echo 'export PATH="$BUN_INSTALL/bin:$PATH"' >> /etc/profile.d/bun.sh
|
|
162
|
-
`;else if(z==="node"){let X=J==="latest"||!J?"20":J.split(".")[0];H+=`
|
|
163
|
-
curl -fsSL https://deb.nodesource.com/setup_${X}.x | bash -
|
|
164
|
-
apt-get install -y nodejs
|
|
165
|
-
ln -sf /usr/bin/node /usr/local/bin/node
|
|
166
|
-
ln -sf /usr/bin/npm /usr/local/bin/npm
|
|
167
|
-
`}else if(z==="deno")H+=`
|
|
168
|
-
curl -fsSL https://deno.land/install.sh | sh
|
|
169
|
-
ln -sf /root/.deno/bin/deno /usr/local/bin/deno
|
|
170
|
-
`}if(H+=`
|
|
171
|
-
mkdir -p /var/www /var/ts-cloud/staging /var/ts-cloud/releases
|
|
172
|
-
`,O)H+=`
|
|
173
|
-
ARCH=$(uname -m | sed 's/x86_64/amd64/;s/aarch64/arm64/')
|
|
174
|
-
curl -fsSL "https://caddyserver.com/api/download?os=linux&arch=\${ARCH}" -o /usr/local/bin/caddy
|
|
175
|
-
chmod +x /usr/local/bin/caddy
|
|
176
|
-
|
|
177
|
-
getent group caddy >/dev/null || groupadd --system caddy
|
|
178
|
-
getent passwd caddy >/dev/null || useradd --system --gid caddy \\
|
|
179
|
-
--create-home --home-dir /var/lib/caddy \\
|
|
180
|
-
--shell /usr/sbin/nologin --comment "Caddy web server" caddy
|
|
181
|
-
|
|
182
|
-
mkdir -p /etc/caddy /var/lib/caddy /var/log/caddy
|
|
183
|
-
chown -R caddy:caddy /var/lib/caddy /var/log/caddy
|
|
184
|
-
|
|
185
|
-
cat > /etc/systemd/system/caddy.service <<'CADDY_UNIT_EOF'
|
|
186
|
-
[Unit]
|
|
187
|
-
Description=Caddy
|
|
188
|
-
Documentation=https://caddyserver.com/docs/
|
|
189
|
-
After=network.target network-online.target
|
|
190
|
-
Requires=network-online.target
|
|
191
|
-
|
|
192
|
-
[Service]
|
|
193
|
-
Type=notify
|
|
194
|
-
User=caddy
|
|
195
|
-
Group=caddy
|
|
196
|
-
ExecStart=/usr/local/bin/caddy run --environ --config /etc/caddy/Caddyfile
|
|
197
|
-
ExecReload=/usr/local/bin/caddy reload --config /etc/caddy/Caddyfile --force
|
|
198
|
-
TimeoutStopSec=5s
|
|
199
|
-
LimitNOFILE=1048576
|
|
200
|
-
PrivateTmp=true
|
|
201
|
-
ProtectSystem=full
|
|
202
|
-
AmbientCapabilities=CAP_NET_BIND_SERVICE
|
|
203
|
-
|
|
204
|
-
[Install]
|
|
205
|
-
WantedBy=multi-user.target
|
|
206
|
-
CADDY_UNIT_EOF
|
|
207
|
-
|
|
208
|
-
cat > /etc/caddy/Caddyfile <<'CADDY_CONFIG_EOF'
|
|
209
|
-
${O}
|
|
210
|
-
CADDY_CONFIG_EOF
|
|
211
|
-
|
|
212
|
-
systemctl daemon-reload
|
|
213
|
-
systemctl enable caddy
|
|
214
|
-
systemctl start caddy
|
|
215
|
-
`;if(Q&&Q.length>0){let X=Q[0]==="set -euo pipefail"?Q.slice(1):Q;H+=`
|
|
216
|
-
${X.join(`
|
|
217
|
-
`)}
|
|
218
|
-
`}return H+=`
|
|
219
|
-
echo "ts-cloud bootstrap complete — instance is ready for site deploys"
|
|
220
|
-
`,H}var d1="/aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id";function c1($){let z=[{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"}],J=new Set;for(let Z of Object.values($.sites||{}))if(Z&&typeof Z.port==="number"&&![22,80,443].includes(Z.port))J.add(Z.port);for(let Z of J)z.push({port:Z,protocol:"tcp",cidr:"0.0.0.0/0"});return z}function l1($){let z=$.infrastructure?.compute??{},J=v0($),Z=z.proxy?.engine==="rpx"?Q0({proxy:z.proxy,config:O0($.sites??{},{proxy:z.proxy,slug:$.project.slug}),slug:$.project.slug,bunBin:z.runtime==="node"||z.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0;return i({runtime:J.runtime,runtimeVersion:J.runtimeVersion,systemPackages:z.systemPackages,database:$.infrastructure?.database,phpProvision:J.phpProvision,servicesProvision:J.servicesProvision,rpxProvision:Z,baked:z.bakedImage===!0,swapGb:z.swapGb})}function p1($){return Buffer.from($,"utf8").toString("base64")}function a1($){return $.infrastructure?.compute?.image??null}function $$($,z){return`${$}-${z}-app-sg`}function P$($,z,J="app"){return[{Key:"Project",Value:$},{Key:"Environment",Value:z},{Key:"Role",Value:J},{Key:"ManagedBy",Value:"ts-cloud"}]}function mz($,z,J){if(!$?.length)return!1;let Z=(Y)=>$.find((G)=>G.Key===Y)?.Value;return Z("Project")===z&&Z("Environment")===J}function r1($,z){let J=$$(z.slug,z.environment);return $.find((Z)=>{if(Z.GroupName!==J)return!1;if(z.vpcId&&Z.VpcId&&Z.VpcId!==z.vpcId)return!1;if(!!Z.Tags?.some((G)=>G.Key==="Project"))return mz(Z.Tags,z.slug,z.environment);return!!z.vpcId&&Z.VpcId===z.vpcId})}function uz($){try{let z=s1(gz(process.cwd(),"storage/cloud/state",`${$}.json`),"utf8"),J=JSON.parse(z);return typeof J.instanceId==="string"&&J.instanceId.length>0?J.instanceId:null}catch{return null}}class z${name="aws";usesCloudFormation=!0;region;ec2Client;cfnClient;constructor($={}){this.region=$.region||"us-east-1",this.ec2Client=$.ec2Client??((z)=>new t1(z)),this.cfnClient=$.cfnClient??((z)=>new i1(z))}resolveRegion($){return $.project.region||this.region}async provisionComputeInfrastructure($){let{config:z,environment:J}=$,Z=this.resolveRegion(z),Y=z.project.slug,G=z.infrastructure?.compute;if(!G)throw Error("infrastructure.compute is required to provision AWS compute");let j=this.ec2Client(Z),O=await this.findComputeTargets({slug:Y,environment:J,role:"app",region:Z});if(O.length>0){let C=O[0];return{appInstanceId:C.id,appPublicIp:C.publicIp,appPublicIpv6:C.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}let Q=a1(z);if(!Q){if(Q=(await new a0(Z).getParameter({Name:d1})).Parameter?.Value??null,!Q)throw Error("Could not resolve the Ubuntu 24.04 AMI from SSM")}let q=await j.describeVpcs(),V=(q.Vpcs||[]).find((C)=>C.IsDefault)||(q.Vpcs||[])[0];if(!V?.VpcId)throw Error("No VPC found to launch the instance into");let W=(await j.describeSubnets({Filters:[{Name:"vpc-id",Values:[V.VpcId]}]})).Subnets||[],H=W.find((C)=>C.MapPublicIpOnLaunch)||W[0],M=H?.SubnetId;if(!H?.MapPublicIpOnLaunch)console.warn("ts-cloud: no public subnet found; the instance may not get a public IP (deploys/SSL need one).");let X=$$(Y,J),F=(await j.describeSecurityGroups({Filters:[{Name:"group-name",Values:[X]},{Name:"vpc-id",Values:[V.VpcId]}]})).SecurityGroups?.[0]?.GroupId;if(!F)F=(await j.createSecurityGroup({GroupName:X,Description:`ts-cloud ${Y}/${J} app`,VpcId:V.VpcId,TagSpecifications:[{ResourceType:"security-group",Tags:P$(Y,J)}]})).GroupId;let B=c1(z);await j.authorizeSecurityGroupIngress({GroupId:F,IpPermissions:B.map((C)=>({IpProtocol:C.protocol,FromPort:C.port,ToPort:C.port,IpRanges:[{CidrIp:C.cidr}]}))}).catch((C)=>{if(!/InvalidPermission\.Duplicate/.test(C instanceof Error?C.message:""))throw C});let K=p1(l1(z)),R=G.server?.instanceType||"t3.small",U=(await j.runInstances({ImageId:Q,InstanceType:R,MinCount:1,MaxCount:1,SecurityGroupIds:F?[F]:void 0,SubnetId:M,UserData:K,IamInstanceProfile:G.server?.iamInstanceProfile?{Name:G.server.iamInstanceProfile}:void 0,TagSpecifications:[{ResourceType:"instance",Tags:[{Key:"Name",Value:`${Y}-${J}-app`},...P$(Y,J)]}]})).Instances?.[0]?.InstanceId;if(!U)throw Error("RunInstances did not return an instance id");let _=await j.waitForInstanceState(U,"running");if(!_)throw Error(`Instance ${U} did not reach 'running' before timeout`);return{appInstanceId:U,appPublicIp:_.PublicIpAddress,appPublicIpv6:z0(_.Ipv6Address),sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}async destroyCompute($){let{config:z,environment:J}=$,Z=z.project.slug,Y=this.resolveRegion(z),G=this.ec2Client(Y),j=[],Q=(await this.findComputeTargets({slug:Z,environment:J,role:"app",region:Y})).map((X)=>X.id),q;if(Q.length>0)q=(await G.describeInstances({InstanceIds:Q}).catch(()=>({Reservations:[]}))).Reservations?.flatMap((A)=>A.Instances??[]).find((A)=>A.VpcId)?.VpcId;if(Q.length>0)await G.terminateInstances(Q),j.push(...Q.map((X)=>`instance ${X}`)),await Promise.all(Q.map((X)=>G.waitForInstanceState(X,"terminated").catch(()=>{return})));let V=$$(Z,J),W=[{Name:"group-name",Values:[V]}];if(q)W.push({Name:"vpc-id",Values:[q]});let H=await G.describeSecurityGroups({Filters:W}).catch(()=>({SecurityGroups:[]})),M=r1(H.SecurityGroups??[],{slug:Z,environment:J,vpcId:q});if(M?.GroupId)for(let X=0;X<10;X++)try{await G.deleteSecurityGroup(M.GroupId),j.push(`security group ${V}`);break}catch{await new Promise((A)=>setTimeout(A,3000))}return{destroyed:j}}async getComputeOutputs($){let z=this.resolveRegion($.config),J=I($.config,$.environment),Z=this.cfnClient(z);try{let Y=await Z.getStackOutputs(J);return{deployBucketName:Y.deployBucketName,appInstanceId:Y.appInstanceId,appPublicIp:Y.appPublicIp,sshUser:"ec2-user"}}catch(Y){if(!/does not exist|ValidationError/i.test(Y instanceof Error?Y.message:""))throw Y;let j=(await this.findComputeTargets({slug:$.config.project.slug,environment:$.environment,role:"app",region:z}))[0];return{appInstanceId:j?.id,appPublicIp:j?.publicIp,appPublicIpv6:j?.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}}async uploadRelease($){let z=this.resolveRegion($.config),Z=(await this.getComputeOutputs({config:$.config,environment:$.environment})).deployBucketName;if(!Z)throw Error("No deployBucketName in stack outputs. Re-deploy infrastructure to add the staging bucket.");return await new n1(z).putObject({bucket:Z,key:$.remoteKey,body:s1($.localPath),contentType:"application/gzip"}),{artifactRef:`s3://${Z}/${$.remoteKey}`}}async findComputeTargets($){let z=$.region??this.region,J=this.ec2Client(z),Z=[{Name:"tag:Project",Values:[$.slug]},{Name:"tag:Environment",Values:[$.environment]},{Name:"tag:Role",Values:[$.role||"app"]},{Name:"instance-state-name",Values:["running","pending"]}],Y=await J.describeInstances({Filters:Z}),G=this.reservationsToTargets(Y.Reservations);if(G.length>0||($.role||"app")!=="app")return G;let j=$.stackName??`${$.slug}-${$.environment}`,O=uz(j);if(!O)try{O=(await this.cfnClient(z).getStackOutputs(j)).appInstanceId??null}catch{O=null}if(!O)return[];try{let Q=await J.describeInstances({InstanceIds:[O],Filters:[{Name:"instance-state-name",Values:["running","pending"]}]});return this.reservationsToTargets(Q.Reservations)}catch{return[]}}reservationsToTargets($){let z=[];for(let J of $||[])for(let Z of J.Instances||[]){if(!Z.InstanceId)continue;let Y=Z.Tags?.find((G)=>G.Key==="Name")?.Value;z.push({id:Z.InstanceId,name:Y,publicIp:Z.PublicIpAddress,publicIpv6:z0(Z.Ipv6Address),privateIp:Z.PrivateIpAddress,status:Z.State?.Name})}return z}bashWrap($){return["bash <<'TS_CLOUD_BASH_EOF'",$.join(`
|
|
221
|
-
`),"TS_CLOUD_BASH_EOF"]}async runRemoteDeploy($){let z=this.region,J=new a0(z);if($.targets.length>0){let Y=await J.sendCommand({InstanceIds:$.targets.map((G)=>G.id),DocumentName:"AWS-RunShellScript",Parameters:{commands:this.bashWrap($.commands)},TimeoutSeconds:$.timeoutSeconds||600,Comment:$.comment});if(!Y.CommandId)return{success:!1,instanceCount:0,perInstance:[],error:"Failed to send SSM command"};return this.pollSsmCommand(J,Y.CommandId,$.targets.length,(($.timeoutSeconds||600)+30)*1000)}if(!$.tags||Object.keys($.tags).length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets or tags provided for AWS deploy"};let Z=await J.sendCommandByTags({tags:$.tags,commands:this.bashWrap($.commands),timeoutSeconds:$.timeoutSeconds||600,comment:$.comment});return{success:Z.success,instanceCount:Z.instanceCount,perInstance:Z.perInstance.map((Y)=>({instanceId:Y.instanceId,status:Y.status,output:Y.output,error:Y.error})),error:Z.error}}async pollSsmCommand($,z,J,Z=600000){let G=Date.now(),j=new Set(["Success","Failed","Cancelled","TimedOut"]),O=[];while(Date.now()-G<Z){await new Promise((V)=>setTimeout(V,3000));try{if(O=await $.listCommandInvocations({CommandId:z,Details:!0}),O.length>=J&&O.every((W)=>j.has(W.Status||"")))break}catch{}}let Q=O.map((V)=>({instanceId:V.InstanceId,status:V.Status||"Unknown",output:V.StandardOutputContent,error:V.StandardErrorContent})),q=Q.length>0&&Q.every((V)=>V.status==="Success");return{success:q,instanceCount:Q.length,perInstance:Q,error:q?void 0:"One or more SSM command invocations failed"}}}import{execFileSync as oz,execSync as G2}from"node:child_process";import{createHash as ez,randomUUID as j2}from"node:crypto";import{createReadStream as $4,existsSync as z4,readFileSync as J4}from"node:fs";function o1($={}){let z=Math.max(1,$.appServers??$.instances??1),J=!!$.servicesServer||z>1,Z=z>1||!!$.server?.loadBalancer;return{appServers:z,loadBalancer:Z,dedicatedServices:J,servicesOnApp:!J}}function e1($,z){let J={REDIS_HOST:$,MEILISEARCH_HOST:`http://${$}:7700`};if(z?.name){if(J.DB_CONNECTION=z.engine==="postgres"?"pgsql":"mysql",J.DB_HOST=$,J.DB_PORT=String(z.port??(z.engine==="postgres"?5432:3306)),J.DB_DATABASE=z.name,z.username)J.DB_USERNAME=z.username;if(z.password)J.DB_PASSWORD=z.password}return J}function I$($){let z=$.infrastructure?.compute??{},J=V0($);return[...o0(z.managedServices??{mysql:!0,redis:!0},{bindPrivate:!0}),...E0(J,z.managedServices??{mysql:!0}),...J0(!0),...Z0(!0),...R0(z.sshKeys),...C0($.notifications),...z.backups?.enabled?[...e0({database:J,backups:z.backups})]:[]]}import{homedir as dz}from"node:os";import{join as cz}from"node:path";var J$={location:"fsn1",image:"ubuntu-24.04",sshUser:"root",sshPrivateKeyPath:"~/.ssh/id_ed25519"};function $2($){return $.startsWith("~/")?cz(dz(),$.slice(2)):$}function w0(...$){for(let z of $){let J=process.env[z]?.trim();if(J)return J}return}function x0(...$){for(let z of $){let J=z?.trim();if(J)return J}return}function m0($,z){return x0($,z?.hetzner?.apiToken,w0("HCLOUD_TOKEN","HETZNER_API_TOKEN"))}function y$($,z){return x0(z,$?.hetzner?.location,w0("HCLOUD_LOCATION","HETZNER_LOCATION"))??J$.location}function g0($,z){let J=$?.infrastructure?.compute;return x0(z,J?.image,$?.hetzner?.image,w0("HCLOUD_IMAGE","HETZNER_IMAGE"))??J$.image}function lz($,z){return x0(z,$?.hetzner?.sshUser,w0("HCLOUD_SSH_USER","HETZNER_SSH_USER"))??J$.sshUser}function z2($,z){return $2(x0(z,$?.hetzner?.sshPrivateKeyPath,w0("HCLOUD_SSH_KEY","HETZNER_SSH_KEY"))??J$.sshPrivateKeyPath)}function pz($,z,J){let Z=x0(z,$?.hetzner?.sshPublicKeyPath,w0("HCLOUD_SSH_PUBLIC_KEY","HETZNER_SSH_PUBLIC_KEY"));if(Z)return $2(Z);return`${J??z2($)}.pub`}function J2($,z={}){let J=z2($,z.sshPrivateKeyPath);return{apiToken:m0(z.apiToken,$),location:y$($,z.location),image:g0($,z.image),sshUser:lz($,z.sshUser),sshPrivateKeyPath:J,sshPublicKeyPath:pz($,z.sshPublicKeyPath,J)}}var az="https://api.hetzner.cloud/v1";class Z$ extends Error{status;code;details;constructor($,z,J,Z){super($);this.status=z;this.code=J;this.details=Z;this.name="HetznerApiError"}}class Y$ extends Error{action;constructor($,z){super($);this.action=z;this.name="HetznerActionError"}}class G${name="hetzner";apiToken;baseUrl;fetchImpl;constructor($){this.apiToken=$.apiToken,this.baseUrl=$.baseUrl??az,this.fetchImpl=$.fetchImpl??fetch}async request($,z,J){let Z=await this.fetchImpl(`${this.baseUrl}${z}`,{method:$,headers:{Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},body:J===void 0?void 0:JSON.stringify(J)}),Y=await Z.text(),G;try{G=Y?JSON.parse(Y):{}}catch{if(!Z.ok){let j=Y.trim().slice(0,200)||Z.statusText||"Hetzner API error";throw Error(`Hetzner API ${$} ${z} (${Z.status}): ${j}`)}throw Error(`Hetzner API ${$} ${z}: unexpected non-JSON response`)}if(!Z.ok){let j=G.error?.message||Z.statusText||"Hetzner API error",O=G.error?.code?` [${G.error.code}]`:"";throw new Z$(`Hetzner API ${$} ${z} (${Z.status})${O}: ${j}`,Z.status,G.error?.code,G.error?.details)}return G}async requestAll($,z){let J=[],Z=1;for(;;){let Y=$.includes("?")?"&":"?",G=await this.request("GET",`${$}${Y}per_page=50&page=${Z}`);J.push(...G[z]??[]);let j=G.meta?.pagination?.next_page;if(!j)return J;Z=j}}async listServers(){return this.requestAll("/servers","servers")}async getServer($){return(await this.request("GET",`/servers/${$}`)).server}async getServerMetrics($,z){let J=new URLSearchParams({type:z.types.join(","),start:z.start.toISOString(),end:z.end.toISOString(),step:String(Math.max(60,Math.floor(z.step??60)))});return(await this.request("GET",`/servers/${$}/metrics?${J}`)).metrics}async listServerTypes($){let z=$?`?name=${encodeURIComponent($)}`:"";return this.requestAll(`/server_types${z}`,"server_types")}async getServerType($){return(await this.listServerTypes($)).find((z)=>z.name===$)??null}async createServer($){let z=await this.request("POST","/servers",{name:$.name,server_type:$.serverType,image:$.image,location:$.location,datacenter:$.datacenter,ssh_keys:$.sshKeys,user_data:$.userData,labels:$.labels,firewalls:$.firewalls,networks:$.networks,start_after_create:!0});return{server:z.server,action:z.action}}async listNetworks(){return this.requestAll("/networks","networks")}async createNetwork($){let z=$.ipRange??"10.0.0.0/16";return(await this.request("POST","/networks",{name:$.name,ip_range:z,subnets:[{type:"cloud",ip_range:z,network_zone:"eu-central"}],labels:$.labels})).network}async deleteNetwork($){await this.request("DELETE",`/networks/${$}`)}async listLoadBalancers(){return this.requestAll("/load_balancers","load_balancers")}async createLoadBalancer($){return(await this.request("POST","/load_balancers",{name:$.name,load_balancer_type:$.type??"lb11",location:$.location,network_zone:$.network?void 0:$.networkZone??"eu-central",network:$.network,labels:$.labels,targets:[{type:"label_selector",label_selector:{selector:$.labelSelector},use_private_ip:!!$.network}],services:$.services.map((J)=>({protocol:J.protocol??"tcp",listen_port:J.listenPort,destination_port:J.destinationPort,health_check:{protocol:"http",port:80,interval:15,timeout:10,retries:3,http:{path:"/",status_codes:["2??","3??"]}}}))})).load_balancer}async deleteLoadBalancer($){await this.request("DELETE",`/load_balancers/${$}`)}async deleteServer($){return(await this.request("DELETE",`/servers/${$}`)).action}async listFirewalls(){return this.requestAll("/firewalls","firewalls")}async createFirewall($){let z=await this.request("POST","/firewalls",{name:$.name,rules:$.rules,labels:$.labels,apply_to:$.applyTo});return{firewall:z.firewall,actions:z.actions}}async setFirewallRules($,z){return(await this.request("POST",`/firewalls/${$}/actions/set_rules`,{rules:z})).actions??[]}async deleteFirewall($){await this.request("DELETE",`/firewalls/${$}`)}async applyFirewallToResources($,z){return(await this.request("POST",`/firewalls/${$}/actions/apply_to_resources`,{apply_to:z})).actions}async listSshKeys(){return this.requestAll("/ssh_keys","ssh_keys")}async createSshKey($){return(await this.request("POST","/ssh_keys",{name:$.name,public_key:$.publicKey,labels:$.labels})).ssh_key}async deleteSshKey($){await this.request("DELETE",`/ssh_keys/${$}`)}async getAction($){return(await this.request("GET",`/actions/${$}`)).action}async shutdownServer($){return(await this.request("POST",`/servers/${$}/actions/shutdown`,{})).action}async powerOnServer($){return(await this.request("POST",`/servers/${$}/actions/poweron`,{})).action}async changeServerType($,z,J){return(await this.request("POST",`/servers/${$}/actions/change_type`,{server_type:z,upgrade_disk:J})).action}async powerOffServer($){return(await this.request("POST",`/servers/${$}/actions/poweroff`,{})).action}async stopServer($,z){if((await this.getServer($)).status==="off")return;await this.shutdownServer($);let Z=z?.gracefulWaitMs??120000,Y=z?.pollIntervalMs??3000,G=Date.now();while(Date.now()-G<Z){if((await this.getServer($)).status==="off")return;await new Promise((O)=>setTimeout(O,Y))}let j=await this.powerOffServer($);await this.waitForAction(j.id),await this.waitForServerStatus($,"off")}async renameServer($,z){return(await this.request("PUT",`/servers/${$}`,{name:z})).server}async listImages($){let z=$?.type?`?type=${encodeURIComponent($.type)}`:"";return this.requestAll(`/images${z}`,"images")}async getImage($){return(await this.request("GET",`/images/${$}`)).image}async createImage($,z){return this.request("POST",`/servers/${$}/actions/create_image`,{description:z.description,type:z.type??"snapshot",labels:z.labels})}async deleteImage($){await this.request("DELETE",`/images/${$}`)}async rebuildServer($,z){return(await this.request("POST",`/servers/${$}/actions/rebuild`,{image:z})).action}async listPrimaryIps(){return this.requestAll("/primary_ips","primary_ips")}async unassignPrimaryIp($){return(await this.request("POST",`/primary_ips/${$}/actions/unassign`,{})).action}async assignPrimaryIp($,z){return(await this.request("POST",`/primary_ips/${$}/actions/assign`,{assignee_id:z,assignee_type:"server"})).action}async waitForAction($,z){let J=z?.pollIntervalMs??2000,Z=z?.maxWaitMs??300000,Y=Date.now();while(Date.now()-Y<Z){let G=await this.getAction($);if(G.status==="success")return G;if(G.status==="error")throw new Y$(G.error?.message||"Hetzner action failed",G);await new Promise((j)=>setTimeout(j,J))}throw Error(`Timed out waiting for Hetzner action ${$}`)}async waitForServerRunning($,z){let J=z?.pollIntervalMs??3000,Z=z?.maxWaitMs??600000,Y=Date.now();while(Date.now()-Y<Z){let G=await this.getServer($);if(G.status==="running")return G;await new Promise((j)=>setTimeout(j,J))}throw Error(`Timed out waiting for server ${$} to reach running state`)}async waitForServerStatus($,z,J){let Z=J?.pollIntervalMs??3000,Y=J?.maxWaitMs??600000,G=Date.now();while(Date.now()-G<Y){let j=await this.getServer($);if(j.status===z)return j;await new Promise((O)=>setTimeout(O,Z))}throw Error(`Timed out waiting for server ${$} to reach ${z} state`)}}function rz($,z){let J=m0($,z);if(!J)throw Error("Hetzner API token required. Set hetzner.apiToken in cloud.config.ts or HCLOUD_TOKEN / HETZNER_API_TOKEN.");return J}function u0($){let[z,J]=$.trim().split(/\s+/);return J?`${z} ${J}`:z}function q0($){return`#cloud-config
|
|
222
|
-
write_files:
|
|
223
|
-
- path: /var/lib/cloud/ts-cloud-bootstrap.sh
|
|
224
|
-
permissions: '0755'
|
|
225
|
-
owner: root:root
|
|
226
|
-
content: |
|
|
227
|
-
${$.split(`
|
|
228
|
-
`).map((Z)=>` ${Z}`).join(`
|
|
229
|
-
`)}
|
|
230
|
-
runcmd:
|
|
231
|
-
- [ bash, /var/lib/cloud/ts-cloud-bootstrap.sh ]
|
|
232
|
-
`}function j$($){let z=new Set([80,443,...$.sitePorts,...$.allowedPorts??[]]);if($.allowSsh)z.add(22);return[...z].map((J)=>{return{direction:"in",protocol:"tcp",port:String(J),source_ips:["0.0.0.0/0","::/0"],description:`ts-cloud port ${J}`}})}var S$={micro:"cpx11",small:"cx23",medium:"cx33",large:"cx43",xlarge:"cx53","2xlarge":"ccx33"};function X0($){if(!$)return S$.micro;if($ in S$)return S$[$];return $}var f="ts-cloud";function y($,z,J="app"){return{[`${f}/project`]:$,[`${f}/environment`]:z,[`${f}/role`]:J,[`${f}/managed-by`]:"ts-cloud"}}function d($,z,J,Z="app"){return b$($,z,J)&&$[`${f}/role`]===Z}function b$($,z,J){if(!$)return!1;return $[`${f}/project`]===z&&$[`${f}/environment`]===J}import{mkdir as nz,readFile as iz,rename as tz,writeFile as sz}from"node:fs/promises";import{join as Z2}from"node:path";var K0="storage/cloud/state";function Y2($){return Z2(process.cwd(),K0,`${$}.json`)}async function F0($){try{let z=await iz(Y2($),"utf8");return JSON.parse(z)}catch{return null}}async function B0($,z){let J=Y2($);await nz(Z2(process.cwd(),K0),{recursive:!0});let Z=`${J}.${process.pid}.tmp`;await sz(Z,`${JSON.stringify(z,null,2)}
|
|
233
|
-
`,"utf8"),await tz(Z,J)}var f$=268435456,Z4=8000;function t($){return`'${$.replace(/'/g,`'"'"'`)}'`}async function Y4($){let z=ez("sha256");for await(let J of $4($))z.update(J);return z.digest("hex")}function O2($){return(Buffer.isBuffer($)?$.toString("utf8"):typeof $==="string"?$:"").replace(/(^|\n)(\s*(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*=).*$/gm,"$1$2[redacted]").replace(/encrypted:[A-Za-z0-9+/=]+/g,"encrypted:[redacted]").trim().slice(-Z4)}function Q2($){let z=$,J=typeof z?.status==="number"?` (exit ${z.status})`:"",Z=z?.signal?` (signal ${z.signal})`:"",Y=[O2(z?.stderr),O2(z?.stdout)].filter(Boolean).join(`
|
|
234
|
-
`);return`Remote SSH command failed${J}${Z}${Y?`
|
|
235
|
-
${Y}`:""}`}class W0{name="hetzner";usesCloudFormation=!1;client;sshPrivateKeyPath;sshPublicKeyPath;sshUser;location;stateOnly;waitForBoot;bootWait;constructor($={}){let z=m0($.apiToken);if(this.stateOnly=!$.client&&!z&&$.allowStateOnly===!0,!$.client&&!z&&!this.stateOnly)throw Error("Hetzner API token required. Set hetzner.apiToken in cloud.config.ts or HCLOUD_TOKEN / HETZNER_API_TOKEN.");this.client=$.client??new G$({apiToken:z??""});let J=J2(void 0,{sshPrivateKeyPath:$.sshPrivateKeyPath,sshPublicKeyPath:$.sshPublicKeyPath,sshUser:$.sshUser,location:$.location});this.sshPrivateKeyPath=J.sshPrivateKeyPath,this.sshPublicKeyPath=J.sshPublicKeyPath,this.sshUser=J.sshUser,this.location=J.location,this.waitForBoot=$.waitForBoot??!0,this.bootWait={sshIntervalMs:$.bootWait?.sshIntervalMs??5000,sshTimeoutMs:$.bootWait?.sshTimeoutMs??300000,cloudInitIntervalMs:$.bootWait?.cloudInitIntervalMs??5000,cloudInitTimeoutMs:$.bootWait?.cloudInitTimeoutMs??600000}}async provisionComputeInfrastructure($){let{config:z,environment:J}=$,Z=z.project.slug,Y=z.infrastructure?.compute;if(!Y)throw Error("infrastructure.compute is required to provision Hetzner compute");if(z.cloud?.attachTo)return this.attachToComputeInfrastructure(z.cloud.attachTo,z,J);let G=I(z,J),j=`${Z}-${J}-app`,O=Y.runtime==="php"||!!Y.php,Q=o1(Y);if(Q.dedicatedServices||Q.appServers>1)return O?this.provisionFleet($,Q):this.provisionBunFleet($,Q);let q=y(Z,J,"app"),V=z.sites||{},W=n(Y)?[]:this.collectUpstreamPorts(V),H=`${Z}-${J}-app-fw`,{firewall:M}=await this.ensureFirewall(H,q,j$({allowSsh:Y.allowSsh!==!1,sitePorts:W,allowedPorts:[...Y.firewall?.allowedPorts??[],...u1(z.infrastructure?.sftp)]})),X=await this.ensureSshKey(Z,J,q),A=await F0(G);if(A?.serverId){let E=await this.tryGetServer(A.serverId);if(E&&E.status!=="off")return this.outputsFromState(A,E)}let F=await this.findExistingServer(Z,J,j);if(F&&F.status!=="off"){let E={provider:"hetzner",stackName:G,serverId:F.id,serverName:F.name,publicIp:F.public_net.ipv4?.ip,publicIpv6:z0(F.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await B0(G,E),this.outputsFromState(E,F)}let B=Y.proxy?.engine==="rpx"?Q0({proxy:Y.proxy,config:O0(V,{proxy:Y.proxy,slug:z.project.slug}),slug:z.project.slug,bunBin:Y.runtime==="node"||Y.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,K=v0(z),R=Y.bakedImage===!0,L=i({runtime:K.runtime,runtimeVersion:K.runtimeVersion,systemPackages:Y.systemPackages,database:z.infrastructure?.database,phpProvision:K.phpProvision,servicesProvision:K.servicesProvision,rpxProvision:B,baked:R,swapGb:Y.swapGb}),U=q0(L),_=X0(Y.size),C=g0(z),{server:N,action:l}=await this.client.createServer({name:j,serverType:_,image:C,location:z.hetzner?.location||this.location,userData:U,labels:q,sshKeys:X?[X]:void 0,firewalls:[{firewall:M.id}]});await this.client.waitForAction(l.id);let S=await this.client.waitForServerRunning(N.id),v={provider:"hetzner",stackName:G,serverId:S.id,serverName:S.name,firewallId:M.id,publicIp:S.public_net.ipv4?.ip,publicIpv6:z0(S.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};await B0(G,v);let b=S.public_net.ipv4?.ip;if(b&&this.waitForBoot)await this.waitForSshReady(b),await this.waitForCloudInit(b);return this.outputsFromState(v,S)}async provisionFleet($,z){let{config:J,environment:Z}=$,Y=J.project.slug,G=J.infrastructure.compute,j=I(J,Z),O=X0(G.size),Q=g0(J),q=J.hetzner?.location||this.location,V=G.bakedImage===!0,W=await F0(j);if(W?.loadBalancerId){let T=(await this.client.listLoadBalancers().catch(()=>[])).find((D)=>D.id===W.loadBalancerId);if(T)return{appPublicIp:T.public_net?.ipv4?.ip,loadBalancerIp:T.public_net?.ipv4?.ip,servicesPrivateIp:W.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}let H=await this.ensureSshKey(Y,Z,y(Y,Z,"app")),M=`${Y}-${Z}-net`,A=(await this.client.listNetworks().catch(()=>[])).find((w)=>w.name===M)??await this.client.createNetwork({name:M,labels:y(Y,Z,"app")}),{firewall:F}=await this.ensureFirewall(`${Y}-${Z}-app-fw`,y(Y,Z,"app"),j$({allowSsh:!0,sitePorts:[],allowedPorts:G.firewall?.allowedPorts})),{firewall:B}=await this.ensureFirewall(`${Y}-${Z}-services-fw`,y(Y,Z,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[A.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[A.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[A.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[A.ip_range]}]),K=I$(J),R=q0(i({runtime:"php",servicesProvision:K,baked:V,swapGb:G.swapGb})),L=await this.client.listServers().catch(()=>[]),U=[],_=L.find((w)=>d(w.labels,Y,Z,"services"));if(!_){let{server:w,action:T}=await this.client.createServer({name:`${Y}-${Z}-services`,serverType:X0(typeof G.servicesServer==="object"?G.servicesServer.size:G.size),image:Q,location:q,userData:R,labels:y(Y,Z,"services"),sshKeys:H?[H]:void 0,firewalls:[{firewall:B.id}],networks:[A.id]});await this.client.waitForAction(T.id),_=await this.client.waitForServerRunning(w.id),U.push(w.id)}let C=_.id,N=_.private_net?.[0]?.ip??(await this.client.getServer(C)).private_net?.[0]?.ip,l=[...J0(!0),...Z0(!0),...R0(G.sshKeys),...C0(J.notifications)],S=i0({versions:G.php?.versions,default:G.php?.default,extensions:G.php?.extensions,installNginx:!n(G),optimizeForProduction:G.php?.optimizeForProduction,ini:G.php?.ini}),v=q0(i({runtime:"php",phpProvision:S,servicesProvision:l,baked:V,swapGb:G.swapGb})),b=L.filter((w)=>d(w.labels,Y,Z,"app")),E=b.map((w)=>w.id);if(b.length>z.appServers)for(let w of b.slice(z.appServers))await this.client.deleteServer(w.id).catch(()=>{}),E.splice(E.indexOf(w.id),1);for(let w=b.length;w<z.appServers;w++){let{server:T,action:D}=await this.client.createServer({name:`${Y}-${Z}-app-${w+1}`,serverType:O,image:Q,location:q,userData:v,labels:y(Y,Z,"app"),sshKeys:H?[H]:void 0,firewalls:[{firewall:F.id}],networks:[A.id]});await this.client.waitForAction(D.id),E.push(T.id),U.push(T.id)}if(this.waitForBoot&&U.length>0)await Promise.all(U.map(async(w)=>{let D=(await this.client.waitForServerRunning(w)).public_net.ipv4?.ip;if(D)await this.waitForSshReady(D),await this.waitForCloudInit(D)}));let m=`${Y}-${Z}-lb`,k,s;if(z.loadBalancer){let T=(await this.client.listLoadBalancers().catch(()=>[])).find((D)=>D.name===m)??await this.client.createLoadBalancer({name:m,location:q,network:A.id,labels:y(Y,Z,"lb"),labelSelector:`ts-cloud/project=${Y},ts-cloud/environment=${Z},ts-cloud/role=app`,services:[{listenPort:80,destinationPort:80},{listenPort:443,destinationPort:443}]});s=T.id,k=T.public_net?.ipv4?.ip}let p=k??(await this.client.getServer(E[0]).catch(()=>{return}))?.public_net.ipv4?.ip,H0={provider:"hetzner",stackName:j,networkId:A.id,loadBalancerId:s,servicesServerId:C,servicesPrivateIp:N,publicIp:p,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await B0(j,H0),{appPublicIp:p,loadBalancerIp:k,servicesPrivateIp:N,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async provisionBunFleet($,z){let{config:J,environment:Z}=$,Y=J.project.slug,G=J.infrastructure.compute,j=I(J,Z),O=X0(G.size),Q=g0(J),q=J.hetzner?.location||this.location,V=G.bakedImage===!0,W=J.sites||{},H=await F0(j);if(H?.lbServerId){let D=await this.tryGetServer(H.lbServerId);if(D&&D.status!=="off"){let x=G.proxy?.engine==="rpx"?G.proxy:{engine:"rpx"},P=await this.findComputeTargets({slug:Y,environment:Z,role:"app",stackName:j});return this.refreshLbRoutes(D,W,P.map((a)=>({privateIp:a.privateIp,publicIp:a.publicIp})),x,Y),{appPublicIp:D.public_net.ipv4?.ip??H.publicIp,loadBalancerIp:D.public_net.ipv4?.ip??H.publicIp,servicesPrivateIp:H.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}}let M=await this.ensureSshKey(Y,Z,y(Y,Z,"app")),X=`${Y}-${Z}-net`,F=(await this.client.listNetworks().catch(()=>[])).find((D)=>D.name===X)??await this.client.createNetwork({name:X,labels:y(Y,Z,"app")}),B=this.collectUpstreamPorts(W),{firewall:K}=await this.ensureFirewall(`${Y}-${Z}-app-fw`,y(Y,Z,"app"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},...B.map((D)=>({direction:"in",protocol:"tcp",port:String(D),source_ips:[F.ip_range],description:`ts-cloud port ${D} (private, LB-only)`}))]),{firewall:R}=await this.ensureFirewall(`${Y}-${Z}-lb-fw`,y(Y,Z,"lb"),j$({allowSsh:!0,sitePorts:[],allowedPorts:G.firewall?.allowedPorts})),L=await this.client.listServers().catch(()=>[]),U=[],_,C,N=!!G.servicesServer||!!G.managedServices,l=z.dedicatedServices&&N;if(l){let{firewall:D}=await this.ensureFirewall(`${Y}-${Z}-services-fw`,y(Y,Z,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[F.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[F.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[F.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[F.ip_range]}]),x=I$(J),P=q0(i({runtime:"bun",servicesProvision:x,baked:V,swapGb:G.swapGb})),a=L.find(($0)=>d($0.labels,Y,Z,"services"));if(!a){let{server:$0,action:y0}=await this.client.createServer({name:`${Y}-${Z}-services`,serverType:X0(typeof G.servicesServer==="object"?G.servicesServer.size:G.size),image:Q,location:q,userData:P,labels:y(Y,Z,"services"),sshKeys:M?[M]:void 0,firewalls:[{firewall:D.id}],networks:[F.id]});await this.client.waitForAction(y0.id),a=await this.client.waitForServerRunning($0.id),U.push($0.id)}_=a.id,C=a.private_net?.[0]?.ip??(await this.client.getServer(_)).private_net?.[0]?.ip}let S=l?{...G,managedServices:void 0,backups:void 0}:G,v=v0({...J,infrastructure:{...J.infrastructure,compute:S}}),b=q0(i({runtime:v.runtime,runtimeVersion:v.runtimeVersion,systemPackages:G.systemPackages,database:J.infrastructure?.database,servicesProvision:v.servicesProvision,baked:V,swapGb:G.swapGb})),E=L.filter((D)=>d(D.labels,Y,Z,"app")),m=E.map((D)=>D.id);if(E.length>z.appServers)for(let D of E.slice(z.appServers))await this.client.deleteServer(D.id).catch(()=>{}),m.splice(m.indexOf(D.id),1);for(let D=E.length;D<z.appServers;D++){let{server:x,action:P}=await this.client.createServer({name:`${Y}-${Z}-app-${D+1}`,serverType:O,image:Q,location:q,userData:b,labels:y(Y,Z,"app"),sshKeys:M?[M]:void 0,firewalls:[{firewall:K.id}],networks:[F.id]});await this.client.waitForAction(P.id),m.push(x.id),U.push(x.id)}if(this.waitForBoot&&U.length>0)await Promise.all(U.map(async(D)=>{let P=(await this.client.waitForServerRunning(D)).public_net.ipv4?.ip;if(P)await this.waitForSshReady(P),await this.waitForCloudInit(P)}));let k=[];for(let D of m){let x=L.find((P)=>P.id===D);if(!x||!x.private_net?.[0]?.ip)x=await this.client.getServer(D).catch(()=>x);k.push({privateIp:x?.private_net?.[0]?.ip,publicIp:x?.public_net.ipv4?.ip})}let s=`${Y}-${Z}-lb`,p,H0;if(z.loadBalancer){let D=L.find((P)=>d(P.labels,Y,Z,"lb")),x=G.proxy?.engine==="rpx"?G.proxy:{engine:"rpx"};if(!D){let P=Q0({proxy:x,config:A0(W,k,{proxy:x,slug:Y}),slug:Y,bunBin:v.runtime==="node"||v.runtime==="deno"?void 0:"/usr/local/bin/bun"}),a=q0(i({runtime:"bun",rpxProvision:P,baked:!1})),$0=typeof G.loadBalancer==="object"?G.loadBalancer.size:void 0,{server:y0,action:C$}=await this.client.createServer({name:s,serverType:X0($0??"micro"),image:Q,location:q,userData:a,labels:y(Y,Z,"lb"),sshKeys:M?[M]:void 0,firewalls:[{firewall:R.id}],networks:[F.id]});if(await this.client.waitForAction(C$.id),D=await this.client.waitForServerRunning(y0.id),this.waitForBoot){let r=D.public_net.ipv4?.ip;if(r)await this.waitForSshReady(r),await this.waitForCloudInit(r)}}else this.refreshLbRoutes(D,W,k,x,Y);p=D.id,H0=D.public_net.ipv4?.ip}let w=H0??(await this.client.getServer(m[0]).catch(()=>{return}))?.public_net.ipv4?.ip,T={provider:"hetzner",stackName:j,networkId:F.id,lbServerId:p,appServerIds:m,servicesServerId:_,servicesPrivateIp:C,publicIp:w,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await B0(j,T),{appPublicIp:w,loadBalancerIp:H0,servicesPrivateIp:C,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async destroyCompute($){let{config:z,environment:J}=$,Z=z.project.slug,Y=I(z,J),G=await F0(Y),j=[],O=`${Z}-${J}-lb`,q=(await this.client.listLoadBalancers().catch(()=>[])).find((K)=>K.name===O);if(q)try{await this.client.deleteLoadBalancer(q.id),j.push(`load balancer ${O}`)}catch{}let V=await this.client.listServers().catch(()=>[]),W=new Set;for(let K of V)if(d(K.labels,Z,J,"app")||d(K.labels,Z,J,"services")||d(K.labels,Z,J,"lb"))W.add(K.id);if(G?.serverId)W.add(G.serverId);if(G?.servicesServerId)W.add(G.servicesServerId);if(G?.lbServerId)W.add(G.lbServerId);for(let K of G?.appServerIds??[])W.add(K);for(let K of W)try{await this.client.deleteServer(K),j.push(`server ${K}`)}catch{}let H=await this.client.listFirewalls().catch(()=>[]);for(let K of[`${Z}-${J}-app-fw`,`${Z}-${J}-services-fw`,`${Z}-${J}-lb-fw`]){let R=H.find((L)=>L.name===K);if(!R)continue;for(let L=0;L<12;L++)try{await this.client.deleteFirewall(R.id),j.push(`firewall ${K}`);break}catch{await this.sleep(3000)}}let M=`${Z}-${J}-net`,A=(await this.client.listNetworks().catch(()=>[])).find((K)=>K.name===M);if(A)for(let K=0;K<12;K++)try{await this.client.deleteNetwork(A.id),j.push(`network ${M}`);break}catch{await this.sleep(3000)}let B=(await this.client.listSshKeys().catch(()=>[])).filter((K)=>b$(K.labels,Z,J));for(let K of B)try{await this.client.deleteSshKey(K.id),j.push(`ssh key ${K.name}`)}catch{}return await B0(Y,{provider:"hetzner",stackName:Y}).catch(()=>{}),{destroyed:j}}async getComputeOutputs($){let z=I($.config,$.environment),J=await F0(z);if(J?.serverId){let G=await this.tryGetServer(J.serverId);if(G)return this.outputsFromState(J,G)}if(J?.lbServerId){let j=(await this.tryGetServer(J.lbServerId))?.public_net.ipv4?.ip??J.publicIp;return{...this.outputsFromState(J),appPublicIp:j,loadBalancerIp:j}}if(J?.loadBalancerId||J?.servicesPrivateIp)return this.outputsFromState(J);let Y=(await this.findComputeTargets({slug:$.config.project.slug,environment:$.environment,role:"app",stackName:I($.config,$.environment)}))[0];return{deployStoragePath:"/var/ts-cloud/staging",appInstanceId:Y?.id,appPublicIp:Y?.publicIp,sshUser:this.sshUser}}async uploadRelease($){let z=$.targets?.length?$.targets:await this.findComputeTargets({slug:$.config.project.slug,environment:$.environment,role:"app",stackName:I($.config,$.environment)});if(z.length===0)throw Error("No Hetzner compute targets found for release upload");let Y=`/var/ts-cloud/staging/${`${$.remoteKey.replace(/^releases\//,"").replace(/\.tar\.gz$/,"").replace(/\//g,"-")}-${j2()}.tar.gz`}`,G=await Y4($.localPath),j="/var/ts-cloud/artifacts",O=`${j}/${G}.tar.gz`;for(let Q of z){if(!Q.publicIp)throw Error(`Target ${Q.id} has no public IP for SCP upload`);let q=["set -euo pipefail",`mkdir -p ${t(j)} /var/ts-cloud/staging`,`test -s ${t(O)}`,`cp -- ${t(O)} ${t(Y)}`].join(`
|
|
236
|
-
`);try{this.sshExec(Q.publicIp,q);continue}catch{}let V=`${j}/.${G}-${j2()}.tmp`;this.scpToHost(Q.publicIp,$.localPath,V),this.sshExec(Q.publicIp,["set -euo pipefail",`chmod 600 ${t(V)}`,`mv -f -- ${t(V)} ${t(O)}`,`cp -- ${t(O)} ${t(Y)}`,`find ${t(j)} -type f -name '*.tar.gz' -mtime +7 -delete 2>/dev/null || true`].join(`
|
|
237
|
-
`))}return{artifactRef:Y}}async findComputeTargets($){let z=$.role||"app",J=(G)=>({id:String(G.id),name:G.name,publicIp:G.public_net.ipv4?.ip,publicIpv6:z0(G.public_net.ipv6?.ip),privateIp:G.private_net?.[0]?.ip,status:G.status});if(z==="app"||z==="lb"||z==="services"){let G=await F0($.stackName??`${$.slug}-${$.environment}`),j=[...new Set(z==="app"?[G?.serverId,...G?.appServerIds??[]]:z==="lb"?[G?.lbServerId]:[G?.servicesServerId])].filter((q)=>typeof q==="number");if(this.stateOnly){if(j.length>0&&G?.publicIp)return j.map((q)=>({id:String(q),name:q===G.serverId?G.serverName:void 0,publicIp:G.publicIp,publicIpv6:G.publicIpv6,status:"running"}));if(z!=="app")return[];throw Error(`Hetzner API token required because '${$.stackName??`${$.slug}-${$.environment}`}' has no complete local compute state pin.`)}let O=await this.client.listServers();if(j.length>0){let q=[];for(let V of j){let W=O.find((H)=>H.id===V)??await this.tryGetServer(V);if(V===G?.serverId&&G.serverName&&W?.name!==G.serverName)continue;if(W&&W.status!=="off")q.push(W)}if(q.length>0)return q.map(J)}let Q=O.filter((q)=>d(q.labels,$.slug,$.environment,z));if(Q.length>0)return Q.map(J);if(z==="app"){let q=O.filter((V)=>V.status!=="off"&&V.labels?.[`${f}/managed-by`]==="ts-cloud"&&V.labels?.[`${f}/environment`]===$.environment&&V.labels?.[`${f}/role`]==="app");if(q.length===1)return q.map(J)}return[]}if(this.stateOnly)throw Error(`Hetzner API token required to discover '${z}' compute targets.`);let Y=(await this.client.listServers()).filter((G)=>d(G.labels,$.slug,$.environment,z));if(Y.length>0)return Y.map(J);return[]}async attachToComputeInfrastructure($,z,J){let Z=await this.client.listServers(),Y=(H)=>Z.filter((M)=>M.status!=="off"&&d(M.labels,$,J,H)),G=Y("app");if(G.length===0)throw Error(`Cannot attach '${z.project.slug}' to '${$}': no running Hetzner app server is labeled for ${$}/${J}. Deploy the owner project first.`);let j=Y("lb")[0],O=Y("services")[0],Q=G[0],q=j??Q,V=I(z,J),W={provider:"hetzner",stackName:V,serverId:Q.id,serverName:Q.name,appServerIds:G.map((H)=>H.id),lbServerId:j?.id,servicesServerId:O?.id,servicesPrivateIp:O?.private_net?.[0]?.ip,publicIp:q.public_net.ipv4?.ip,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await B0(V,W),this.outputsFromState(W)}async runRemoteDeploy($){if($.targets.length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets provided"};let z=$.commands.join(`
|
|
238
|
-
`),J=[];for(let Y of $.targets){if(!Y.publicIp){J.push({instanceId:Y.id,status:"Failed",error:"Missing public IP"});continue}try{let G=this.sshExec(Y.publicIp,z);J.push({instanceId:Y.id,status:"Success",output:G})}catch(G){J.push({instanceId:Y.id,status:"Failed",error:G.message})}}let Z=J.every((Y)=>Y.status==="Success");return{success:Z,instanceCount:$.targets.length,perInstance:J,error:Z?void 0:"One or more SSH deploy commands failed"}}async ensureSshKey($,z,J){if(!z4(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 Z=J4(this.sshPublicKeyPath,"utf8").trim(),Y=u0(Z),j=(await this.client.listSshKeys()).find((Q)=>u0(Q.public_key)===Y);if(j)return j.id;return(await this.client.createSshKey({name:`${$}-${z}-deploy`,publicKey:Z,labels:J})).id}async tryGetServer($){try{return await this.client.getServer($)}catch{return null}}refreshLbRoutes($,z,J,Z,Y){let G=$.public_net.ipv4?.ip;if(!G){console.warn(`[ts-cloud] LB server '${$.name}' has no public IP — skipping the rpx route refresh; its routes may be stale.`);return}let j=J.filter((Q)=>Q.privateIp||Q.publicIp);if(j.length===0){console.warn(`[ts-cloud] No routable app boxes found for LB '${$.name}' — leaving its current rpx routes untouched.`);return}let O=A0(z,j,{proxy:Z,slug:Y});this.sshExec(G,h0({config:O,slug:Y}).join(`
|
|
239
|
-
`))}async findExistingServer($,z,J){let Z=await this.client.listServers(),Y=Z.find((j)=>d(j.labels,$,z,"app")||j.name===J);if(Y)return Y;let G=Z.filter((j)=>j.status!=="off"&&j.labels?.[`${f}/managed-by`]==="ts-cloud"&&j.labels?.[`${f}/environment`]===z&&j.labels?.[`${f}/role`]==="app");if(G.length===1){let j=G[0],O=j.labels?.[`${f}/project`]??"unknown";return console.warn(`[ts-cloud] No server named '${J}' found; adopting existing ts-cloud app server '${j.name}' (project label '${O}') for project '${$}' — `+"updating it in place instead of provisioning a new server."),j}return}async ensureFirewall($,z,J){let Y=(await this.client.listFirewalls()).find((j)=>j.name===$);if(Y)return await this.client.setFirewallRules(Y.id,J),{firewall:Y};let{firewall:G}=await this.client.createFirewall({name:$,labels:z,rules:J});return{firewall:G}}collectUpstreamPorts($){let z=new Set;for(let J of Object.values($))if(typeof J.port==="number")z.add(J.port);return[...z].filter((J)=>![80,443].includes(J))}async sleep($){await new Promise((z)=>setTimeout(z,$))}async waitForSshReady($){let{sshIntervalMs:z,sshTimeoutMs:J}=this.bootWait,Z=Date.now(),Y;while(Date.now()-Z<J)try{G2(`ssh ${this.sshBaseArgs($,["-o","ConnectTimeout=5"]).map(t).join(" ")} true`,{stdio:"pipe",maxBuffer:f$});return}catch(G){Y=G,await this.sleep(z)}throw Error(`Timed out waiting for SSH on ${$} after ${J}ms: ${Y?.message??"unknown error"}`)}async waitForCloudInit($){let{cloudInitIntervalMs:z,cloudInitTimeoutMs:J}=this.bootWait,Z=Date.now();while(Date.now()-Z<J){try{let Y=this.sshExec($,"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(Y))throw Error(`cloud-init reported an error on ${$}:
|
|
240
|
-
${Y}`);if(/status:\s*(?:done|degraded)/.test(Y))return}catch(Y){if(Y instanceof Error&&/cloud-init reported an error/.test(Y.message))throw Y}await this.sleep(z)}throw Error(`Timed out waiting for cloud-init to finish on ${$} after ${J}ms`)}outputsFromState($,z){return{deployStoragePath:$.deployStoragePath||"/var/ts-cloud/staging",appInstanceId:$.serverId?String($.serverId):void 0,appPublicIp:z?.public_net.ipv4?.ip||$.publicIp,appPublicIpv6:z0(z?.public_net.ipv6?.ip)||$.publicIpv6,sshUser:$.sshUser||this.sshUser,servicesPrivateIp:$.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($,z=[]){return["-i",this.sshPrivateKeyPath,...W0.SSH_HOST_KEY_OPTS,...W0.SSH_KEEPALIVE_OPTS,"-o","BatchMode=yes",...z,`${this.sshUser}@${$}`]}scpToHost($,z,J){let Z=["scp","-i",this.sshPrivateKeyPath,...W0.SSH_HOST_KEY_OPTS,...W0.SSH_KEEPALIVE_OPTS,"-o","BatchMode=yes",z,`${this.sshUser}@${$}:${J}`].map((G)=>`"${G.replace(/"/g,"\\\"")}"`).join(" "),Y=3;for(let G=1;G<=3;G++)try{G2(Z,{stdio:"pipe",maxBuffer:f$});return}catch(j){if(G===3)throw Error(Q2(j))}}sshExec($,z){try{return oz("ssh",[...this.sshBaseArgs($),"bash -s"],{encoding:"utf8",input:z,stdio:["pipe","pipe","pipe"],maxBuffer:f$})}catch(J){throw Error(Q2(J))}}}class O${name="hetzner";usesCloudFormation=!1;async getComputeOutputs(){return{appPublicIp:"127.0.0.1",sshUser:"root"}}async uploadRelease($){return{artifactRef:$.localPath}}async findComputeTargets($){if(($.role||"app")!=="app")return[];return[{id:"localhost",name:"localhost",publicIp:"127.0.0.1",status:"running"}]}async runRemoteDeploy($){let z=$.commands.join(`
|
|
241
|
-
`);try{let J=Bun.spawn(["bash","-c",z],{stdout:"pipe",stderr:"pipe",env:process.env}),[Z,Y,G]=await Promise.all([new Response(J.stdout).text(),new Response(J.stderr).text(),J.exited]);return{success:G===0,instanceCount:1,perInstance:[{instanceId:"localhost",status:G===0?"Success":"Failed",output:Z,error:Y}]}}catch(J){return{success:!1,instanceCount:1,perInstance:[{instanceId:"localhost",status:"Failed",error:J?.message??String(J)}],error:J?.message??String(J)}}}}function h$(){let $=process.env.TS_CLOUD_DASHBOARD_BOX;return $!=null&&$!==""&&$!=="0"&&$.toLowerCase()!=="false"}function v$($){if(h$())return new O$;switch($.provider??_0($.config)){case"aws":return new z$({region:$.config.project.region});case"hetzner":return new W0({apiToken:$.config.hetzner?.apiToken,allowStateOnly:Boolean($.config.cloud?.attachTo),sshPrivateKeyPath:$.config.hetzner?.sshPrivateKeyPath,sshPublicKeyPath:$.config.hetzner?.sshPublicKeyPath,sshUser:$.config.hetzner?.sshUser,location:$.config.hetzner?.location});default:throw Error(`Unknown cloud provider: ${$.provider??_0($.config)}`)}}class V2{drivers=new Map;getDriver($,z){let J=z??_0($),Z=`${J}:${$.project.slug}:${$.project.region||"default"}`,Y=this.drivers.get(Z);if(Y)return Y;let G=v$({config:$,provider:J});return this.drivers.set(Z,G),G}}var h9=new V2;function G4($){return $.location?.name??$.datacenter?.location.name??"unknown"}function T0($){return typeof $==="number"&&Number.isFinite($)?$:0}function j4($,z){if($.architecture&&z.architecture&&$.architecture!==z.architecture)throw Error(`Cannot resize ${$.name} (${$.architecture}) to ${z.name} (${z.architecture}) in place.`);let J=[];if(T0(z.cores)<T0($.cores))J.push("CPU");if(T0(z.memory)<T0($.memory))J.push("memory");if(T0(z.disk)<T0($.disk))J.push("disk");if(J.length>0)throw Error(`Refusing an in-place downgrade from ${$.name} to ${z.name}: ${J.join(", ")} would shrink.`)}async function q2($,z,J,Z=!0){let[Y,G]=await Promise.all([$.getServer(z),$.getServerType(J)]);if(!G)throw Error(`Hetzner server type ${J} was not found.`);let j=Y.server_type,O=j.name===G.name;if(!O)j4(j,G);let Q=G4(Y),q=G.locations?.find((V)=>V.name===Q);return{serverId:z,serverName:Y.name,location:Q,currentType:j,targetType:G,capacityAvailable:q?.available!==!1,alreadyComplete:O,upgradeDisk:Z}}function W2($){if($ instanceof Z$&&$.code==="resource_unavailable")return!0;if($ instanceof Y$){if($.action.error?.code==="resource_unavailable")return!0;if(/no fitting vhost|placement|free resources/i.test($.action.error?.message??""))return!0}return/resource_unavailable|no fitting vhost|error during placement|free resources/i.test($ instanceof Error?$.message:String($))}async function o($,z,J){await $?.onPhase?.(z,J)}async function m$($,z,J){await $.waitForAction(z.id,{pollIntervalMs:J.actionPollIntervalMs,maxWaitMs:J.actionTimeoutMs})}var Q$=async({client:$,hooks:z,actionPollIntervalMs:J,actionTimeoutMs:Z,serverPollIntervalMs:Y,serverTimeoutMs:G},j,O,Q)=>{let q=await $.getServer(j.serverId);if(q.status!=="running"){await o(z,Q?"recovering":"powering-on",{serverId:j.serverId});let W=await $.powerOnServer(j.serverId);await m$($,W,{actionPollIntervalMs:J,actionTimeoutMs:Z}),q=await $.waitForServerRunning(j.serverId,{pollIntervalMs:Y,maxWaitMs:G})}await o(z,"verifying",{serverId:j.serverId,recovered:Q});let V=await z?.afterBoot?.(q,j.targetType,O,{recovered:Q});return{server:q,verification:V}};async function O4($){let{client:z,hooks:J}=$,Z=$.upgradeDisk??!0;await o(J,"planning",{serverId:$.serverId,targetType:$.targetType});let Y=await q2(z,$.serverId,$.targetType,Z),G=await z.getServer(Y.serverId);if(Y.alreadyComplete){let Q=await Q$($,Y,$.manifest,!1);return await o(J,"complete",{alreadyComplete:!0}),{status:"already-complete",plan:Y,verification:Q.verification}}if(!Y.capacityAvailable&&!$.attemptUnavailable)return await o(J,"waiting-capacity",{location:Y.location,targetType:Y.targetType.name}),{status:"waiting-capacity",plan:Y};let j=$.manifest;if(G.status==="off"&&!$.resumeFromOff){let Q=await Q$($,Y,void 0,!0);return{status:"recovered",plan:Y,server:Q.server,verification:Q.verification,retryable:!0,error:"Server was already off without a resumable resize checkpoint; powered it back on."}}if(G.status==="running"){await o(J,"preflight",{serverId:Y.serverId}),j=await J?.preflight?.(G,Y.targetType),await o(J,"shutting-down",{serverId:Y.serverId});let Q=await z.shutdownServer(Y.serverId);await m$(z,Q,$),G=await z.waitForServerStatus(Y.serverId,"off",{pollIntervalMs:$.serverPollIntervalMs,maxWaitMs:$.serverTimeoutMs})}try{await o(J,"resizing",{serverId:Y.serverId,from:Y.currentType.name,to:Y.targetType.name,upgradeDisk:Z});let Q=await z.changeServerType(Y.serverId,Y.targetType.name,Z);await m$(z,Q,$)}catch(Q){let q=await Q$($,Y,j,!0);return{status:"recovered",plan:Y,server:q.server,manifest:j,verification:q.verification,retryable:W2(Q),error:Q instanceof Error?Q.message:String(Q)}}let O=await Q$($,Y,j,!1);if(O.verification&&!O.verification.ok)throw Error(`Resize completed but verification failed: ${(O.verification.failures??[]).join("; ")}`);return await o(J,"complete",{serverId:Y.serverId,targetType:Y.targetType.name}),{status:"completed",plan:Y,server:O.server,manifest:j,verification:O.verification}}function H2($={}){let z=[];if($.identityFile)z.push("-i",$.identityFile);return z.push("-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR","-o",`ConnectTimeout=${$.connectTimeoutSec??10}`),z}async function g$($,z,J={}){let Z=Bun.spawn(["ssh",...H2(J),`${J.user??"root"}@${$}`,z],{stdout:"pipe",stderr:"pipe"}),[Y,G]=await Promise.all([new Response(Z.stdout).text(),new Response(Z.stderr).text()]);return{code:await Z.exited,stdout:Y,stderr:G}}async function e($,z,J={}){let Z=await g$($,z,J);if(Z.code!==0)throw Error(`ssh \`${z}\` on ${$} failed (${Z.code}): ${Z.stderr.trim()||Z.stdout.trim()}`);return Z.stdout}async function u$($,z={}){let J=z.timeoutMs??180000,Z=z.pollIntervalMs??5000,Y=Date.now();while(Date.now()-Y<J){let G=await g$($,"echo ready",z);if(G.code===0&&G.stdout.includes("ready"))return;await new Promise((j)=>setTimeout(j,Z))}throw Error(`SSH not ready on ${$} after ${J}ms`)}var Q4=String.raw`
|
|
242
|
-
const { readdir, readFile, readlink, stat } = await import('node:fs/promises')
|
|
243
|
-
|
|
244
|
-
const text = (command) => {
|
|
245
|
-
const result = Bun.spawnSync(['bash', '-lc', command], { stdout: 'pipe', stderr: 'pipe' })
|
|
246
|
-
return result.exitCode === 0 ? result.stdout.toString().trim() : ''
|
|
247
|
-
}
|
|
248
|
-
const lines = (command) => text(command).split('\n').map(value => value.trim()).filter(Boolean).sort()
|
|
249
|
-
const number = (value) => Number.parseInt(value || '0', 10) || 0
|
|
250
|
-
|
|
251
|
-
const root = text('findmnt -n -o SOURCE,FSTYPE /').split(/\s+/)
|
|
252
|
-
const rootSource = root[0] || ''
|
|
253
|
-
const rootFsType = root[1] || ''
|
|
254
|
-
const rootParent = text('lsblk -n -o PKNAME ' + rootSource + ' | head -1')
|
|
255
|
-
const rootDiskBytes = number(text('lsblk -b -n -o SIZE /dev/' + rootParent + ' | head -1'))
|
|
256
|
-
const rootFilesystemBytes = number(text("df -B1 --output=size / | tail -1"))
|
|
257
|
-
const memoryBytes = number(text("awk '/MemTotal/{print $2 * 1024}' /proc/meminfo"))
|
|
258
|
-
const allRunningServices = lines("systemctl list-units --type=service --state=running --no-legend --plain | awk '{print $1}'")
|
|
259
|
-
const runningServices = allRunningServices.filter((unit) => {
|
|
260
|
-
if (/^(containerd|docker|localtunnel|mail|mysql|mariadb|meilisearch|postgresql|redis|rpx-gateway)\b/.test(unit)) return true
|
|
261
|
-
const source = text('systemctl cat ' + unit + ' 2>/dev/null')
|
|
262
|
-
return /\/var\/www|\/usr\/local\/bin\/rpx|\/opt\/ts-cloud/.test(source)
|
|
263
|
-
})
|
|
264
|
-
const failedUnits = lines("systemctl --failed --type=service --no-legend --plain | awk '{print $1}'")
|
|
265
|
-
const releaseLinks = []
|
|
266
|
-
for (const path of lines("find /var/www -mindepth 2 -maxdepth 2 -type l -name current -print 2>/dev/null")) {
|
|
267
|
-
try {
|
|
268
|
-
releaseLinks.push(path + '=' + await readlink(path))
|
|
269
|
-
} catch {}
|
|
270
|
-
}
|
|
271
|
-
releaseLinks.sort()
|
|
272
|
-
|
|
273
|
-
const routeFragments = []
|
|
274
|
-
const routeIds = []
|
|
275
|
-
const routeDomains = new Set()
|
|
276
|
-
for (const path of lines("find /etc/rpx/sites.d -maxdepth 1 -type f -name '*.json' -print 2>/dev/null")) {
|
|
277
|
-
try {
|
|
278
|
-
const source = await readFile(path, 'utf8')
|
|
279
|
-
const digest = new Bun.CryptoHasher('sha256').update(source).digest('hex')
|
|
280
|
-
routeFragments.push(path + '=' + digest)
|
|
281
|
-
const value = JSON.parse(source)
|
|
282
|
-
for (const route of value.proxies || []) {
|
|
283
|
-
if (typeof route.to === 'string' && route.to) {
|
|
284
|
-
routeDomains.add(route.to)
|
|
285
|
-
routeIds.push(path + ':' + (route.id || route.to) + ':' + (route.path || '/'))
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
} catch {}
|
|
289
|
-
}
|
|
290
|
-
routeFragments.sort()
|
|
291
|
-
routeIds.sort()
|
|
292
|
-
|
|
293
|
-
const persistentData = []
|
|
294
|
-
for (const path of ['/var/lib/postgresql', '/var/lib/mysql', '/var/lib/redis', '/var/lib/docker', '/var/mail', '/var/vmail']) {
|
|
295
|
-
try {
|
|
296
|
-
const value = await stat(path)
|
|
297
|
-
if (value.isDirectory()) {
|
|
298
|
-
const bytes = number(text('du -sx --block-size=1 ' + path + " 2>/dev/null | awk '{print $1}'"))
|
|
299
|
-
persistentData.push(path + '=' + bytes)
|
|
300
|
-
}
|
|
301
|
-
} catch {}
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
const dataCatalog = []
|
|
305
|
-
for (const database of lines("command -v psql >/dev/null && sudo -u postgres psql -Atqc 'select datname from pg_database where datistemplate = false order by datname' 2>/dev/null || true")) {
|
|
306
|
-
dataCatalog.push('postgres:' + database)
|
|
307
|
-
}
|
|
308
|
-
for (const database of lines("command -v mysql >/dev/null && mysql -NBe 'show databases' 2>/dev/null || true")) {
|
|
309
|
-
dataCatalog.push('mysql:' + database)
|
|
310
|
-
}
|
|
311
|
-
for (const volume of lines("command -v docker >/dev/null && docker volume ls --format '{{.Name}}' 2>/dev/null || true")) {
|
|
312
|
-
dataCatalog.push('docker-volume:' + volume)
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
console.log(JSON.stringify({
|
|
316
|
-
capturedAt: new Date().toISOString(),
|
|
317
|
-
hostname: text('hostname'),
|
|
318
|
-
cpuCores: number(text('nproc')),
|
|
319
|
-
memoryBytes,
|
|
320
|
-
rootSource,
|
|
321
|
-
rootFsType,
|
|
322
|
-
rootDiskBytes,
|
|
323
|
-
rootFilesystemBytes,
|
|
324
|
-
failedUnits,
|
|
325
|
-
runningServices,
|
|
326
|
-
releaseLinks,
|
|
327
|
-
routeFragments,
|
|
328
|
-
routeIds,
|
|
329
|
-
routeDomains: [...routeDomains].sort(),
|
|
330
|
-
persistentData: persistentData.sort(),
|
|
331
|
-
dataCatalog: dataCatalog.sort(),
|
|
332
|
-
}))
|
|
333
|
-
`;function V4($){return`printf %s ${Buffer.from($).toString("base64")} | base64 -d | bun -`}async function q4($){let z=await e($.host,V4(Q4),$);return JSON.parse(z)}async function W4($,z){let J="";for(let Z=1;Z<=3;Z++){let Y=Bun.spawn(["curl","--location","--silent","--show-error","--output","/dev/null","--max-time",String(Math.max(1,Math.ceil(z/1000))),"--write-out","%{http_code}",`https://${$}/`],{stdout:"pipe",stderr:"pipe"}),[G,j,O]=await Promise.all([new Response(Y.stdout).text(),new Response(Y.stderr).text(),Y.exited]),Q=Number.parseInt(G.trim(),10);if(O===0&&Q>0)return{domain:$,ok:Q<500,status:Q};if(J=j.trim()||`curl exited ${O}`,Z<3)await Bun.sleep(500*Z)}return{domain:$,ok:!1,error:J}}async function H4($,z){let J=[],Z=0,Y=Array.from({length:Math.min(4,$.length)},async()=>{for(;;){let G=Z++,j=$[G];if(!j)return;J[G]=await W4(j,z)}});return await Promise.all(Y),J}async function d$($){let z=await q4($),J=await H4(z.routeDomains,$.routeTimeoutMs??15000);return{...z,routeProbes:J}}async function M4($){let z=await d$($),J=z.routeProbes.filter((Z)=>!Z.ok);if(z.failedUnits.length>0)throw Error(`Preflight found failed services: ${z.failedUnits.join(", ")}`);if(J.length>0)throw Error(`Preflight found unhealthy routes: ${J.map((Z)=>Z.domain).join(", ")}`);return await e($.host,String.raw`systemctl list-units --type=service --state=running --no-legend --plain | awk '{print $1}' | while read -r unit; do if systemctl cat "$unit" 2>/dev/null | grep -Eq '/var/www|/usr/local/bin/rpx|/opt/ts-cloud'; then systemctl enable "$unit" >/dev/null 2>&1 || true; fi; done; systemctl daemon-reload; sync`,$),z}function N0($,z){let J=new Set(z);return $.filter((Z)=>!J.has(Z))}function X4($){return Math.floor(($.memory??0)*1024*1024*1024)}async function K4($){await e($.host,String.raw`set -e
|
|
334
|
-
root_source="$(findmnt -n -o SOURCE /)"
|
|
335
|
-
root_fs="$(findmnt -n -o FSTYPE /)"
|
|
336
|
-
parent="$(lsblk -n -o PKNAME "$root_source" | head -1)"
|
|
337
|
-
partition="$(lsblk -n -o PARTN "$root_source" | head -1)"
|
|
338
|
-
if [ -n "$parent" ] && [ -n "$partition" ]; then
|
|
339
|
-
growpart "/dev/$parent" "$partition" || true
|
|
340
|
-
fi
|
|
341
|
-
case "$root_fs" in
|
|
342
|
-
ext2|ext3|ext4) resize2fs "$root_source" ;;
|
|
343
|
-
xfs) xfs_growfs / ;;
|
|
344
|
-
*) echo "Unsupported root filesystem: $root_fs" >&2; exit 1 ;;
|
|
345
|
-
esac`,$)}async function F4($,z){let J=Buffer.from(z.join(`
|
|
346
|
-
`)).toString("base64");await e($.host,`printf %s ${J} | base64 -d | while read -r unit; do [ -z "$unit" ] || systemctl is-active --quiet "$unit" || systemctl start "$unit"; done`,$)}async function B4($,z,J,Z={recovered:!1}){if(await u$($.host,{...$,timeoutMs:$.sshTimeoutMs??600000}),!Z.recovered)await K4($);if(J)await F4($,J.runningServices);let Y=await d$($),G=[],j=J?N0(J.runningServices,Y.runningServices):[],O=J?N0(J.releaseLinks,Y.releaseLinks):[],Q=J?N0(J.routeFragments,Y.routeFragments):[],q=J?N0(J.routeIds,Y.routeIds):[],V=J?.persistentData.map((L)=>L.split("=")[0])??[],W=Y.persistentData.map((L)=>L.split("=")[0]),H=N0(V,W),M=J?N0(J.dataCatalog,Y.dataCatalog):[],X=Y.routeProbes.filter((L)=>!L.ok),A=Z.recovered&&J?J.cpuCores:z.cores??0,F=Z.recovered&&J?J.memoryBytes:X4(z),B=Y.cpuCores>=A,K=Y.memoryBytes>=F*0.9,R=Z.recovered||Y.rootDiskBytes>=(z.disk??0)*1e9*0.95;if(Y.failedUnits.length>0)G.push(`Failed services: ${Y.failedUnits.join(", ")}`);if(j.length>0)G.push(`Services did not return: ${j.join(", ")}`);if(O.length>0)G.push(`Release links changed: ${O.join(", ")}`);if(Q.length>0)G.push(`Route manifests changed: ${Q.join(", ")}`);if(q.length>0)G.push(`Routes disappeared: ${q.join(", ")}`);if(H.length>0)G.push(`Persistent data paths disappeared: ${H.join(", ")}`);if(M.length>0)G.push(`Databases or volumes disappeared: ${M.join(", ")}`);if(X.length>0)G.push(`Unhealthy routes: ${X.map((L)=>L.domain).join(", ")}`);if(!B)G.push(`Expected at least ${A} CPU cores, found ${Y.cpuCores}`);if(!K)G.push(`Expected at least ${F} bytes of RAM`);if(!R)G.push(`Expected approximately ${z.disk??0} GB root disk`);return{ok:G.length===0,checks:{cpuCores:Y.cpuCores,memoryBytes:Y.memoryBytes,rootDiskBytes:Y.rootDiskBytes,rootFilesystemBytes:Y.rootFilesystemBytes,runningServices:Y.runningServices.length,releaseLinks:Y.releaseLinks.length,routeFragments:Y.routeFragments.length,routes:Y.routeIds.length,healthyRoutes:Y.routeProbes.filter((L)=>L.ok).length,persistentDataPaths:Y.persistentData.length,databasesAndVolumes:Y.dataCatalog.length,failedUnits:Y.failedUnits.length},failures:G}}function V$($){return $.split("=",1)[0]??$}function M2($){return $.replace(/@[^.]+(?=\.service$)/,"")}function i9($,z){let J=new Set(z.runningServices.map(M2)),Z=new Set(z.routeFragments.map(V$)),Y=new Set(z.releaseLinks.map(V$)),G=new Set(z.routeIds),j=new Set(z.dataCatalog);return{stoppedServices:$.runningServices.filter((O)=>!J.has(M2(O))),changedRouteFragments:$.routeFragments.filter((O)=>!Z.has(V$(O))),missingRouteIds:$.routeIds.filter((O)=>!G.has(O)),changedReleaseLinks:$.releaseLinks.filter((O)=>!Y.has(V$(O))),missingData:$.dataCatalog.filter((O)=>!j.has(O))}}function X2($){return $.infrastructure?.compute??{}}function K2($){let z=X2($),J=z.monitoring;return{firewallPorts:[...new Set([22,80,443,...z.firewall?.allowedPorts??[]])].filter((Y)=>Number.isInteger(Y)&&Y>=1&&Y<=65535).sort((Y,G)=>Y-G),monitoring:J!==!1&&(typeof J!=="object"||J.enabled!==!1),autoUpdates:z.autoUpdates!==!1,swapGb:Math.max(0,Math.floor(z.swapGb??2)),sshPasswordAuthentication:!1,journalMaxUse:"256M",journalRetention:"14day"}}function U4($){return["install -d -m 0755 /etc/ssh/sshd_config.d /etc/systemd/journald.conf.d /etc/sysctl.d /etc/fail2ban/jail.d","cat > /etc/ssh/sshd_config.d/99-ts-cloud-hardening.conf <<'TS_CLOUD_SSH_EOF'","# Managed by ts-cloud host optimization.","PasswordAuthentication no","KbdInteractiveAuthentication no","PermitRootLogin prohibit-password","MaxAuthTries 4","LoginGraceTime 30","TS_CLOUD_SSH_EOF","sshd -t","systemctl reload ssh","cat > /etc/systemd/journald.conf.d/99-ts-cloud-retention.conf <<'TS_CLOUD_JOURNAL_EOF'","[Journal]",`SystemMaxUse=${$.journalMaxUse}`,`MaxRetentionSec=${$.journalRetention}`,"Compress=yes","TS_CLOUD_JOURNAL_EOF","systemctl restart systemd-journald","journalctl --vacuum-size=256M --vacuum-time=14d >/dev/null","cat > /etc/sysctl.d/99-ts-cloud-production.conf <<'TS_CLOUD_SYSCTL_EOF'","# Managed by ts-cloud host optimization.","vm.swappiness=10","vm.dirty_background_ratio=5","vm.dirty_ratio=15","net.core.somaxconn=4096","net.ipv4.tcp_max_syn_backlog=4096","net.ipv4.tcp_fin_timeout=30","net.ipv4.tcp_keepalive_time=300","net.ipv4.tcp_keepalive_intvl=30","net.ipv4.tcp_keepalive_probes=5","fs.inotify.max_user_watches=524288","TS_CLOUD_SYSCTL_EOF","sysctl --system >/dev/null","export DEBIAN_FRONTEND=noninteractive","command -v fail2ban-client >/dev/null 2>&1 || apt-get install -y fail2ban","cat > /etc/fail2ban/jail.d/99-ts-cloud-sshd.conf <<'TS_CLOUD_FAIL2BAN_EOF'","[sshd]","enabled = true","backend = systemd","bantime = 1h","findtime = 10m","maxretry = 5","TS_CLOUD_FAIL2BAN_EOF","systemctl enable --now fail2ban","systemctl restart fail2ban"]}function C4($){if($===0)return[];return["if ! swapon --show=NAME --noheadings 2>/dev/null | grep -qx '/swapfile'; then",` if [ ! -f /swapfile ]; then fallocate -l ${$}G /swapfile || dd if=/dev/zero of=/swapfile bs=1M count=${$*1024} status=none; fi`," chmod 600 /swapfile"," mkswap /swapfile >/dev/null"," swapon /swapfile","fi","grep -qE '^/swapfile\\s' /etc/fstab || echo '/swapfile none swap sw 0 0' >> /etc/fstab"]}function F2($){let z=X2($),J=K2($),Z=z.monitoring??!0,Y=z.firewall??{enabled:!0};return["set -euo pipefail",...n(z)?["systemctl disable --now nginx.service bun-gateway.service ts-cloud-nginx.service 2>/dev/null || true","systemctl reset-failed nginx.service bun-gateway.service ts-cloud-nginx.service 2>/dev/null || true"]:[],...C4(J.swapGb),...J0(J.autoUpdates),...Z0(Z),...U4(J),...s0(Y),"systemctl daemon-reload","systemctl reset-failed"]}var L4=String.raw`
|
|
347
|
-
const text = (command) => {
|
|
348
|
-
const result = Bun.spawnSync(['bash', '-lc', command], { stdout: 'pipe', stderr: 'pipe' })
|
|
349
|
-
return result.stdout.toString().trim()
|
|
350
|
-
}
|
|
351
|
-
const lines = command => text(command).split('\n').map(value => value.trim()).filter(Boolean)
|
|
352
|
-
const number = value => Number.parseInt(value || '0', 10) || 0
|
|
353
|
-
const ssh = Object.fromEntries(lines("sshd -T 2>/dev/null | grep -E '^(passwordauthentication|permitrootlogin) '").map(line => line.split(/\s+/, 2)))
|
|
354
|
-
const firewallPorts = lines("ufw status 2>/dev/null | awk '/ALLOW/{print $1}'")
|
|
355
|
-
.flatMap(value => value.startsWith('OpenSSH') ? [22] : (value.match(/^\d+/) ? [number(value)] : []))
|
|
356
|
-
const publicTcpPorts = lines("ss -lntH | awk '{print $4}'")
|
|
357
|
-
.filter(address => !address.startsWith('127.') && !address.startsWith('[::1]'))
|
|
358
|
-
.flatMap(address => {
|
|
359
|
-
const match = address.match(/:(\d+)$/)
|
|
360
|
-
return match ? [number(match[1])] : []
|
|
361
|
-
})
|
|
362
|
-
const metricsMtime = number(text("stat -c %Y /var/lib/ts-cloud/metrics.json 2>/dev/null"))
|
|
363
|
-
console.log(JSON.stringify({
|
|
364
|
-
firewallActive: text("ufw status 2>/dev/null | head -1").includes('active'),
|
|
365
|
-
firewallPorts: [...new Set(firewallPorts)].sort((a, b) => a - b),
|
|
366
|
-
passwordAuthentication: ssh.passwordauthentication !== 'no',
|
|
367
|
-
rootPasswordLogin: ssh.permitrootlogin === 'yes',
|
|
368
|
-
fail2banActive: text('systemctl is-active fail2ban 2>/dev/null') === 'active',
|
|
369
|
-
unattendedUpgradesActive: text('systemctl is-active unattended-upgrades 2>/dev/null') === 'active',
|
|
370
|
-
metricsTimerActive: text('systemctl is-active ts-cloud-metrics.timer 2>/dev/null') === 'active',
|
|
371
|
-
metricsSnapshotFresh: metricsMtime > 0 && Math.floor(Date.now() / 1000) - metricsMtime < 180,
|
|
372
|
-
swapBytes: number(text("free -b | awk '/^Swap:/{print $2}'")),
|
|
373
|
-
journalBytes: number(text("journalctl --disk-usage 2>/dev/null | grep -Eo '[0-9.]+[KMG]' | tail -1 | numfmt --from=iec 2>/dev/null")),
|
|
374
|
-
failedUnits: lines("systemctl --failed --type=service --no-legend --plain | awk '{print $1}'"),
|
|
375
|
-
publicTcpPorts: [...new Set(publicTcpPorts)].sort((a, b) => a - b),
|
|
376
|
-
}))
|
|
377
|
-
`;function A4($){return`printf %s ${Buffer.from($).toString("base64")} | base64 -d | bun -`}async function R4($,z){let J=F2($).join(`
|
|
378
|
-
`),Z=`printf %s ${Buffer.from(J).toString("base64")} | base64 -d | bash`;await e(z.host,Z,z)}async function D4($){let z=await e($.host,A4(L4),$);return JSON.parse(z)}function _4($,z){let J=[],Z=new Set(z.firewallPorts),Y=$.firewallPorts.filter((j)=>!Z.has(j)),G=z.firewallPorts.filter((j)=>!$.firewallPorts.includes(j));if(!z.firewallActive)J.push("UFW is not active");if(Y.length>0)J.push(`UFW is missing ports: ${Y.join(", ")}`);if(G.length>0)J.push(`UFW has unexpected ports: ${G.join(", ")}`);if(z.passwordAuthentication)J.push("SSH password authentication remains enabled");if(z.rootPasswordLogin)J.push("SSH root password login remains enabled");if(!z.fail2banActive)J.push("fail2ban is not active");if($.autoUpdates&&!z.unattendedUpgradesActive)J.push("unattended upgrades are not active");if($.monitoring&&!z.metricsTimerActive)J.push("metrics timer is not active");if($.monitoring&&!z.metricsSnapshotFresh)J.push("metrics snapshot is stale");if($.swapGb>0&&z.swapBytes<$.swapGb*1073741824*0.9)J.push("configured swap is missing");if(z.failedUnits.length>0)J.push(`failed services: ${z.failedUnits.join(", ")}`);return J}import{mkdir as q$,readFile as E4,rename as B2,rmdir as w4,stat as x4,unlink as T4,writeFile as U2}from"node:fs/promises";import{join as k0}from"node:path";function c$($){return k0(process.cwd(),K0,`${$}-resize.json`)}function C2($){return k0(process.cwd(),K0,`${$}-resize.lock`)}async function N4($){try{return JSON.parse(await E4(c$($),"utf8"))}catch{return null}}async function k4($){let z=c$($.stackName);await q$(k0(process.cwd(),K0),{recursive:!0});let J=`${z}.${process.pid}.tmp`;await U2(J,`${JSON.stringify($,null,2)}
|
|
379
|
-
`,"utf8"),await B2(J,z)}async function P4($,z=1800000){let J=C2($);await q$(k0(process.cwd(),K0),{recursive:!0});try{await q$(J)}catch(Z){if(Date.now()-(await x4(J)).mtimeMs<=z)throw Error(`Another resize process holds ${J}.`);await B2(J,`${J}.stale-${Date.now()}`),await q$(J)}return await U2(k0(J,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
|
|
380
|
-
`,"utf8"),async()=>{await T4(k0(J,"owner.json")).catch(()=>{}),await w4(J).catch(()=>{})}}function W$($){return Object.entries($).map(([z,J])=>`${z}=${f4(String(J))}`).join(`
|
|
381
|
-
`)}function f4($){return`"${$.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}function n$($,z){let J=z==="bun"?"/usr/local/bin/bun":z==="deno"?"/usr/local/bin/deno":"/usr/local/bin/node",Z=$.replace(/^(bun|node|deno)\s+/,"");return`${J} ${Z}`}function i$($){let{siteName:z,slug:J,artifactFetch:Z,releaseId:Y,execStart:G,envEntries:j,port:O,keepReleases:Q=d0,preStartCommands:q=[],healthCheckPath:V,healthGateSeconds:W=5,memoryHigh:H="2G",memoryMax:M,cpuWeight:X,ioWeight:A,tasksMax:F,stopTimeout:B}=$,K=[...X!=null?[`CPUWeight=${X}`]:[],...A!=null?[`IOWeight=${A}`]:[],...F!=null?[`TasksMax=${F}`]:[],...B?[`TimeoutStopSec=${B}`]:[]],R=$.zeroDowntime??O!=null,L=$.appDir??`/var/www/${z}`,U=c0(L,Y),_=`${J}-${z}`,C=`${_}.service`,N=p0(J,z,Y),l=L2([".env",...$.sharedPaths??[]]),S=W$(j),v=q.length>0?[`cd ${U.release}`,...q]:[],b=["set -euo pipefail",...l$(U),a$(U),...Z,...l0(U,l),...p$(U),`tar xzf ${N} -C "$TS_CLOUD_STAGED"`,`rm -f ${N}`,`cat > ${U.shared}/.env <<'TS_CLOUD_ENV_EOF'`,S,"TS_CLOUD_ENV_EOF",`chmod 600 ${U.shared}/.env`,...r$(U),`find ${U.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' ${U.shared}/.env 2>/dev/null || true`,...H$(U,l),...v];if(R&&O!=null){let E=`${_}@${Y}.service`,m=V?V.startsWith("/")?V:`/${V}`:null,k=`{ echo "[ts-cloud] release ${Y} failed its health gate — previous release keeps serving" >&2; journalctl -u ${E} -n 50 --no-pager >&2 || true; systemctl stop ${E} 2>/dev/null || true; exit 1; }`;return[...b,`cat > /etc/systemd/system/${_}@.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${z} release %i (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${U.releases}/%i`,`ExecStart=${G}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...H?[`MemoryHigh=${H}`]:[],...M?[`MemoryMax=${M}`]:[],...K,`EnvironmentFile=${U.releases}/%i/.env`,`Environment=PORT=${O}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",`TS_CLOUD_OLD_UNITS=$(systemctl list-units --plain --no-legend --type=service "${_}@*.service" 2>/dev/null | awk '{print $1}' | grep -v "^${E}$" || true)`,`if [ -f /etc/systemd/system/${C} ] && systemctl is-active --quiet ${C}; then echo "[ts-cloud] retiring pre-zero-downtime unit ${C} (one-time restart cutover)"; systemctl stop ${C}; fi`,`systemctl restart ${E}`,`TS_CLOUD_GATE_OK=1; for TS_CLOUD_I in $(seq 1 ${Math.max(1,W)}); do sleep 1; systemctl is-active --quiet ${E} || { TS_CLOUD_GATE_OK=0; break; }; done`,`if [ "$TS_CLOUD_GATE_OK" -ne 1 ]; then echo "[ts-cloud] release ${Y} 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 ${E}; for TS_CLOUD_I in $(seq 1 ${Math.max(1,W)}); do sleep 1; systemctl is-active --quiet ${E} || ${k}; done; fi`,...m?[`curl -sf -o /dev/null --max-time 10 "http://127.0.0.1:${O}${m}" || ${k}`]:[],...P0(U),`systemctl enable ${E} 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,W)}); do if ss -ltnH "sport = :${O}" 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 ${O} after retiring the previous release — restarting ${E} on the now-free port" >&2; systemctl restart ${E}; for TS_CLOUD_I in $(seq 1 ${Math.max(1,W)}); do if ss -ltnH "sport = :${O}" 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] ${E} is active but never bound ${O}" >&2; journalctl -u ${E} -n 50 --no-pager >&2 || true; exit 1; fi`,`systemctl list-unit-files --plain --no-legend "${_}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v -e "^${E}$" -e "^${_}@\\.service$" || true; } | while read -r TS_CLOUD_U; do systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done`,`if [ -f /etc/systemd/system/${C} ]; then systemctl disable ${C} 2>/dev/null || true; rm -f /etc/systemd/system/${C}; systemctl daemon-reload; fi`,...I0(U,Q)]}return[...b,`cat > /etc/systemd/system/${C} <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${z} (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${U.current}`,`ExecStart=${G}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...H?[`MemoryHigh=${H}`]:[],...M?[`MemoryMax=${M}`]:[],...K,`EnvironmentFile=${U.current}/.env`,...O?[`Environment=PORT=${O}`]:[],"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",`systemctl enable ${C}`,...P0(U),`systemctl restart ${C}`,`systemctl is-active ${C}`,...I0(U,Q)]}function t$($){let{siteName:z,artifactFetch:J,releaseId:Z,keepReleases:Y=d0,preStartCommands:G=[]}=$,j=$.appDir??`/var/www/${z}`,O=c0(j,Z),Q=p0($.slug,z,Z),q=G.length>0?[`cd ${O.release}`,...G]:[];return["set -euo pipefail",...l$(O),a$(O),...J,...l0(O,[]),...p$(O),`tar xzf ${Q} -C "$TS_CLOUD_STAGED"`,...r$(O),`rm -f ${Q}`,...q,...P0(O),...I0(O,Y)]}function p0($,z,J){return`/tmp/${[$,z,J].filter(Boolean).join("-")}-release.tar.gz`}function s$($,z,J,Z){return[`aws s3 cp "s3://${$}/${z}" ${Z} --region ${J}`]}function o$($,z){return[`mv "${$}" ${z}`]}function e$(){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 Y6}from"node:fs";import{tmpdir as G6}from"node:os";import{join as j6}from"node:path";var h4=new Set(["laravel","php","statamic","wordpress"]);function D2($){if($.framework)return $.framework;if($.type&&h4.has($.type))return"laravel";return"stacks"}var A2=`eval "$(cd ${Y0} && pantry env 2>/dev/null)"`,R2="/usr/local/bin/bun",v4="storage/framework/core/buddy/src/cli.ts",m4="node_modules/@stacksjs/ts-cloud/dist/bin/stacks-scheduler.js",_2={id:"stacks",wrapExec:($)=>$,execEnv:{PATH:"/usr/local/bin:/usr/bin:/bin",BUN_INSTALL:"/root/.bun",APP_ENV:"production",NODE_ENV:"production"},schedulerMode:"daemon",schedulerCommand:()=>`${R2} ${m4}`,queueWorkerCommand:($,{current:z})=>{let J=[`--queue=${$.queue||"default"}`,`--sleep=${$.sleep??3}`,`--tries=${$.tries??3}`,`--timeout=${$.timeout??60}`];return`${R2} ${z}/${v4} queue:work ${J.join(" ")}`}},g4={id:"laravel",wrapExec:($)=>`/bin/sh -lc '${A2}; exec ${$}'`,schedulerMode:"cron",schedulerCommand:({current:$})=>`cd ${$} && ${A2} && php artisan schedule:run`,queueWorkerCommand:($,{current:z})=>{let J=`${z}/artisan`;if($.horizon)return`php ${J} horizon`;let Z=[$.connection||"default",`--queue=${$.queue||"default"}`,`--sleep=${$.sleep??3}`,`--tries=${$.tries??3}`,`--timeout=${$.timeout??60}`,`--memory=${$.memory??128}`];if($.maxJobs)Z.push(`--max-jobs=${$.maxJobs}`);if($.maxTime)Z.push(`--max-time=${$.maxTime}`);return`php ${J} queue:work ${Z.join(" ")}`}},u4={stacks:_2,laravel:g4};function E2($){return u4[$]??_2}function w2($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function d4($){return`'${$.split("'").join("'\\''")}'`}function x2($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"unnamed"}function c4($,z,J){return`${$}-${z}-queue-${J}`}function l4($,z,J,Z){return`${$}-${z}-daemon-${J.name?x2(J.name):x2(J.command).slice(0,32)||String(Z)}`}function $1($){let z=["[Unit]",`Description=${$.description}`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${$.workingDir}`,...Object.entries($.environment??{}).map(([J,Z])=>`Environment="${J}=${Z}"`),`ExecStart=${$.execStart}`,`Restart=${$.restart||"always"}`,"RestartSec=5","MemoryAccounting=true",`MemoryHigh=${$.memoryHigh??"2G"}`,...$.memoryMax?[`MemoryMax=${$.memoryMax}`]:[]];if($.user)z.push(`User=${$.user}`);if(typeof $.stopWaitSecs==="number")z.push(`TimeoutStopSec=${$.stopWaitSecs}`);return z.push("","[Install]","WantedBy=multi-user.target"),`${z.join(`
|
|
382
|
-
`)}
|
|
383
|
-
`}function z1($,z){return[`cat > /etc/systemd/system/${$}.service <<'TS_CLOUD_UNIT_EOF'`,z.replace(/\n$/,""),"TS_CLOUD_UNIT_EOF"]}function p4($,z){return`/etc/cron.d/${$}-${z}-scheduler`}function J1($){let{slug:z,siteName:J,site:Z}=$,G=`${$.appBase??`/var/www/${J}`}/current`,j=E2(D2(Z)),O={current:G},Q=[],q=[];(Z.queues||[]).forEach((B,K)=>{let R=Math.max(1,B.processes??1);for(let L=0;L<R;L++){let U=c4(z,J,q.length);q.push(U),Q.push(...z1(U,$1({description:`${J} queue worker ${K}.${L} (managed by ts-cloud)`,workingDir:G,execStart:j.wrapExec(j.queueWorkerCommand(B,O)),environment:j.execEnv,stopWaitSecs:B.stopWaitSecs??90})))}}),(Z.daemons||[]).forEach((B,K)=>{let R=Math.max(1,B.processes??1);for(let L=0;L<R;L++){let U=`${l4(z,J,B,K)}-${L}`;q.push(U),Q.push(...z1(U,$1({description:`${J} daemon ${B.name||B.command} (managed by ts-cloud)`,workingDir:B.directory||G,execStart:j.wrapExec(B.command),environment:j.execEnv,restart:B.restart,user:B.user})))}});let H=Z.scheduler,M=H===!0||typeof H==="object"&&H!==null,X=`${z}-${J}-scheduler`;if(M&&j.schedulerMode==="daemon")q.push(X),Q.push(...z1(X,$1({description:`${J} scheduler (managed by ts-cloud)`,workingDir:G,execStart:j.wrapExec(j.schedulerCommand(O)),environment:j.execEnv})));let A=q.map((B)=>`${B}.service`).join(" ");Q.push("systemctl daemon-reload",`TS_CLOUD_DESIRED="${A}"`,`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E '^${w2(z)}-${w2(J)}-((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 q)Q.push(`systemctl enable ${B}.service`,`systemctl restart ${B}.service`);let F=p4(z,J);if(M&&j.schedulerMode==="cron"){let B=typeof H==="object"&&H!==null?H:void 0,K=`${j.schedulerCommand(O)} >> /dev/null 2>&1`;if(B?.heartbeatUrl){let L=B.heartbeatMethod||"GET",U=L==="GET"?"":`-X ${L} `;K+=` && curl -fsS -m 10 ${U}${d4(B.heartbeatUrl)} >/dev/null 2>&1`}let R=`* * * * * root ${K}
|
|
384
|
-
`.replace(/%/g,"\\%");Q.push(`cat > ${F} <<'TS_CLOUD_CRON_EOF'`,R.replace(/\n$/,""),"TS_CLOUD_CRON_EOF",`chmod 644 ${F}`)}else Q.push(`rm -f ${F}`);return Q}function Z1($){return!!($.queues?.length||$.daemons?.length||$.scheduler)}function Y1($){if($.ssl?.provider)return $.ssl.provider;return $.domain?"letsencrypt":"none"}var T2={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 N2($){return`/etc/letsencrypt/ts-cloud-${$}.ini`}function a4($){let z=$?T2[$.provider]:void 0,J=["certbot","python3-certbot-nginx",...z?[z.pkg]:[]].join(" ");return["export DEBIAN_FRONTEND=noninteractive",z?`apt-get update -y && apt-get install -y ${J}`:`command -v certbot >/dev/null 2>&1 || { apt-get update -y && apt-get install -y ${J}; }`,"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 r4($){if(!$.credentials||Object.keys($.credentials).length===0)return[];let z=N2($.provider),J=Object.entries($.credentials).map(([Z,Y])=>`${Z} = ${Y}`).join(`
|
|
385
|
-
`);return[`cat > ${z} <<'TS_CLOUD_DNSCREDS_EOF'`,J,"TS_CLOUD_DNSCREDS_EOF",`chmod 600 ${z}`]}function n4($){let z=$.dns,J=$.wildcard?[`*.${$.domain}`,$.domain]:[$.domain,...$.aliases||[]].filter(Boolean),Z=["certbot","--non-interactive","--agree-tos","--keep-until-expiring"];if(z){let Y=T2[z.provider].plugin;if(Z.push(`--${Y}`),z.provider!=="route53"&&z.credentials)Z.push(`--${Y}-credentials ${N2(z.provider)}`);if(typeof z.propagationSeconds==="number"&&z.provider!=="route53")Z.push(`--${Y}-propagation-seconds ${z.propagationSeconds}`);Z.push("certonly")}else Z.push("--nginx",`--nginx-ctl ${G0}`,$.redirect===!1?"--no-redirect":"--redirect");if($.email)Z.push(`-m ${$.email}`);else Z.push("--register-unsafely-without-email");for(let Y of J)Z.push(`-d ${Y}`);return[Z.join(" ")]}function G1($){if(Y1($)!=="letsencrypt"||!$.domain)return[];let z=$.ssl,J=z?.dns,Z=z?.wildcard===!0;if(Z&&!J)return[];return[...a4(J),...J?r4(J):[],...n4({domain:$.domain,aliases:$.aliases,email:z?.email,wildcard:Z,dns:J})]}function k2($){let{repository:z,releaseDir:J,commit:Z}=$,Y=z.branch||"main",G=z.url,j=[`rm -rf ${J}`,`mkdir -p ${J}`];if(z.strategy==="tag")if(z.tag)j.push(`git clone -q --depth 1 --branch ${c(z.tag)} ${c(G)} ${J}`),j.push(`printf '%s' ${c(z.tag)} > ${J}/.ts-cloud-tag`);else{let O=z.tagPattern||"v*";j.push(`TS_CLOUD_TAG="$(git ls-remote --tags --refs --sort=-v:refname ${c(G)} ${c(`refs/tags/${O}`)} | head -n1 | sed 's#.*refs/tags/##')"`,`test -n "$TS_CLOUD_TAG" || { echo "no tags matching" ${c(O)} "found in" ${c(G)} >&2; exit 1; }`,`git clone -q --depth 1 --branch "$TS_CLOUD_TAG" ${c(G)} ${J}`,`printf '%s' "$TS_CLOUD_TAG" > ${J}/.ts-cloud-tag`)}else if(Z)j.push(`git -C ${J} init -q`,`git -C ${J} remote add origin ${c(G)}`,`git -C ${J} fetch -q --depth 1 origin ${c(Z)}`,`git -C ${J} checkout -q FETCH_HEAD`);else j.push(`git clone -q --depth 1 --branch ${c(Y)} ${c(G)} ${J}`);return j.push(`git -C ${J} rev-parse HEAD > ${J}/.ts-cloud-sha`),j}function c($){return`'${$.split("'").join("'\\''")}'`}var M$="$CREATE_RELEASE",X$="$ACTIVATE_RELEASE",S2="$RESTART_QUEUES",P2="composer install --no-interaction --prefer-dist --optimize-autoloader --no-dev",i4=["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 t4($){switch($){case"laravel":case"statamic":return[M$,P2,...i4,X$,S2];case"php":case"wordpress":return[M$,`${P2} || true`,X$];case"static":case"spa":return[M$,X$]}}function s4($,z){return $.replace(/^php\s+/,`${z} `).replace(/(\s)php\s+artisan\s+/g,`$1${z} artisan `)}function o4($,z){let J=W$(z);return[`cat > ${$} <<'TS_CLOUD_ENV_EOF'`,J,"TS_CLOUD_ENV_EOF",`chmod 600 ${$}`]}function I2($,z,J){return[`cat > ${$} <<'${J}'`,z.replace(/\n$/,""),J,`chmod 600 ${$}`]}function e4($,z){if(!z)return[];let J=[];if(z.composerAuth){let Z=typeof z.composerAuth==="string"?z.composerAuth:JSON.stringify(z.composerAuth,null,2);J.push(...I2(`${$}/auth.json`,Z,"TS_CLOUD_AUTHJSON_EOF"))}if(z.npmrc)J.push(...I2(`${$}/.npmrc`,z.npmrc,"TS_CLOUD_NPMRC_EOF"));return J}function b2($){let z=$.healthCheck?.path;if(!z||!$.domain)return[];let Z=`http://127.0.0.1${z.startsWith("/")?z:`/${z}`}`;return[`echo "[ts-cloud] health check ${Z} (Host: ${$.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: ${$.domain}" -m 10 "${Z}" 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 f2($){let{siteName:z,site:J,releaseId:Z,commit:Y}=$;if(!J.repository?.url)throw Error(`Site '${z}' is a PHP/git site but has no repository.url to clone`);let G=$.appBase??`/var/www/${z}`,j="php",O=c0(G,Z),Q=J.sharedPaths??y2,q=J.keepReleases??d0,V=J.deployScript?.length?J.deployScript:t4(J.type??"laravel"),W=["set -euo pipefail",'export HOME="${HOME:-/root}"','export COMPOSER_HOME="${COMPOSER_HOME:-/root/.composer}"',"export COMPOSER_ALLOW_SUPERUSER=1",r0()];if(W.push(...K$(G,{releaseId:Z,commit:Y,branch:J.repository.branch,keepLogs:q})),W.push(...l0(O,Q)),J.env&&Object.keys(J.env).length>0)W.push(...o4(`${O.shared}/.env`,J.env));for(let H of V){let M=H.trim();if(M===M$)W.push(...k2({repository:J.repository,releaseDir:O.release,commit:Y})),W.push(...H$(O,Q)),W.push(`cd ${O.release}`),W.push(...e4(O.release,J.credentials)),W.push(`chown -R www-data:www-data ${O.shared}/storage 2>/dev/null || true`,`[ -d ${O.release}/bootstrap/cache ] && chown -R www-data:www-data ${O.release}/bootstrap/cache 2>/dev/null || true`,`chmod -R ug+rwX ${O.shared}/storage 2>/dev/null || true`);else if(M===X$)W.push(...P0(O)),W.push(...I0(O,q)),W.push(`(cd ${Y0} && pantry restart php-fpm) 2>/dev/null || true`);else if(M===S2)W.push(`${j} artisan queue:restart || true`);else W.push(s4(H,j))}return W}var h2="/var/lib/pantry/php-fpm/pool.d",$6=9100,z6=400;function F$($){return($.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"site").slice(0,28)}function v2($){return`web_${F$($)}`}function J6($){let z=F$($),J=0;for(let Z=0;Z<z.length;Z++)J=J*31+z.charCodeAt(Z)>>>0;return $6+J%z6}function j1($){return`127.0.0.1:${J6($)}`}function Z6($){let z=F$($.siteName),J=v2($.siteName),Z=$.maxChildren??10;return[`; ts-cloud-managed pool for ${$.siteName} (site isolation)`,`[${z}]`,`user = ${J}`,`group = ${J}`,`listen = ${j1($.siteName)}`,"pm = dynamic",`pm.max_children = ${Z}`,"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] = ${$.appBase}:/tmp`,""].join(`
|
|
386
|
-
`)}function m2($){let z=v2($.siteName),J=F$($.siteName),Z=`${h2}/${J}.conf`;return[`getent group ${z} >/dev/null || groupadd --system ${z}`,`id -u ${z} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin -g ${z} ${z}`,`usermod -aG ${z} www-data 2>/dev/null || true`,`chown -R ${z}:${z} ${$.appBase} || true`,`chmod -R g+rX ${$.appBase} || true`,`chmod 600 ${$.appBase}/shared/.env 2>/dev/null || true`,`mkdir -p ${h2}`,`cat > ${Z} <<'TS_CLOUD_FPMPOOL_EOF'`,Z6($).replace(/\n$/,""),"TS_CLOUD_FPMPOOL_EOF",`(cd ${Y0} && pantry restart php-fpm) 2>/dev/null || true`]}var U$={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};function O6($){return`'${$.replace(/'/g,`'"'"'`)}'`}async function d2($,z,J=U$){let{config:Z,environment:Y,siteName:G,site:j,slug:O,sha:Q,runtime:q,localTarballPath:V}=z,W=`releases/${G}/${Q}.tar.gz`,H=I(Z,Y),M=await $.getComputeOutputs({config:Z,environment:Y}),X=await $.findComputeTargets({slug:O,environment:Y,role:"app",stackName:H});if(X.length===0)return{success:!1,error:$.name==="aws"?`Stack '${H}' has no EC2 instances tagged Project=${O} Environment=${Y} Role=app, and storage/cloud/state/${H}.json pins no live instance. For a shared box, record its instanceId there.`:`No Hetzner servers labeled ts-cloud/project=${O} ts-cloud/environment=${Y} ts-cloud/role=app, and storage/cloud/state/${H}.json pins no live server. For a shared box, record its serverId there.`};let A=M.servicesPrivateIp?e1(M.servicesPrivateIp,V0(Z)):g2(V0(Z)),F=Z.infrastructure?.compute,B=n(F)?{HOST:"127.0.0.1"}:{},K=Y==="production"?{APP_ENV:"production",NODE_ENV:"production"}:{},R={...A,...B,...j.env||{},...K};if(H1(j)){let s=j.phpVersion??F?.php?.default??F?.php?.versions?.[0],p=U0(O,G),H0=Object.keys(A).length>0?{...j,env:R}:j,w=f2({siteName:G,site:H0,releaseId:Q,appBase:p,defaultPhpVersion:s}),T=!n(F),x=Y1(j)==="custom"&&j.ssl?.certPath&&j.ssl?.keyPath?{certPath:j.ssl.certPath,keyPath:j.ssl.keyPath}:void 0,P=j.isolation?m2({siteName:G,appBase:p}):[],a=T?R$({siteName:G,domain:j.domain||G,aliases:j.aliases,type:j.type,appDir:`${p}/current`,webDirectory:j.webDirectory,phpVersion:s,fastcgiPass:j.isolation?j1(G):void 0,redirects:j.redirects,ssl:x,auth:j.auth&&j.auth.enabled!==!1&&j.auth.password?{username:j.auth.username||"admin",password:j.auth.password,realm:j.auth.realm}:void 0,serverSnippet:A$(j.nginx,F?.nginxTemplates),clientMaxBodySize:j.nginx?.clientMaxBodySize,hsts:j.ssl?.hsts,tlsProtocols:j.ssl?.tlsProtocols,security:j.security}):[],$0=T?G1(j):[],y0=Z1(j)?J1({slug:O,siteName:G,site:j,phpVersion:s,appBase:p}):[],C$=T?b2(j):[];J.step(`Deploying PHP site '${G}' to ${X.length} target(s)...`);let r=await $.runRemoteDeploy({targets:X,commands:[...Q1(p,O),...w,...P,...a,...$0,...y0,...C$],comment:`ts-cloud deploy ${O}/${G}@${Q}`,tags:{Project:O,Environment:Y,Role:"app"}}),L1=w1(Z.notifications,j.notifications);if(!r.success)return await _$(L1,"deploy-failed",`❌ Deploy of ${O}/${G}@${Q} failed: ${r.error||"unknown error"}`),{success:!1,error:r.error||"Remote PHP deploy failed",instanceCount:r.instanceCount,perInstance:r.perInstance};let Jz=j.domain?` → https://${j.domain}`:"";return await _$(L1,"deploy",`✅ Deployed ${O}/${G}@${Q}${Jz}`),{success:!0,instanceCount:r.instanceCount,perInstance:r.perInstance}}if(!V)return{success:!1,error:`Site '${G}' requires a release tarball but none was provided`};let L=await $.uploadRelease({config:Z,environment:Y,localPath:V,remoteKey:W,targets:X}),U=p0(O,G,Q),_=$.name==="aws"?s$(M.deployBucketName,W,Z.project.region||"us-east-1",U):o$(L.artifactRef,U),C=u(j),N=U0(O,G),l=C==="server-static"?t$({siteName:G,slug:O,appDir:N,artifactFetch:_,releaseId:Q,preStartCommands:j.preStart}):i$({siteName:G,slug:O,appDir:N,artifactFetch:_,releaseId:Q,execStart:n$(j.start,q),envEntries:R,port:j.port,preStartCommands:j.preStart,sharedPaths:j.sharedPaths,zeroDowntime:j.zeroDowntime!==!1,healthCheckPath:j.healthCheck?.path,memoryHigh:j.memoryHigh,memoryMax:j.memoryMax,cpuWeight:j.cpuWeight,ioWeight:j.ioWeight,tasksMax:j.tasksMax,stopTimeout:j.stopTimeout}),S=C==="server-static"&&!n(F)&&!!j.domain,v=S?R$({siteName:G,domain:j.domain,aliases:j.aliases,type:j.type==="spa"?"spa":"static",appDir:`${N}/current`,webDirectory:"",redirects:j.redirects,auth:j.auth&&j.auth.enabled!==!1&&j.auth.password?{username:j.auth.username||"admin",password:j.auth.password,realm:j.auth.realm}:void 0,serverSnippet:A$(j.nginx,F?.nginxTemplates),clientMaxBodySize:j.nginx?.clientMaxBodySize,hsts:j.ssl?.hsts,tlsProtocols:j.ssl?.tlsProtocols,security:j.security}):[],b=S?G1(j):[],E=Z1(j)?J1({slug:O,siteName:G,site:j,appBase:N}):[],m=[...K$(N,{releaseId:Q,commit:Q,branch:j.repository?.branch??"main"}),...Q1(N,O),...l,...v,...b,...E,...e$()];J.step(`Deploying to ${X.length} target(s)...`);let k=await $.runRemoteDeploy({targets:X,commands:m,comment:`ts-cloud deploy ${O}/${G}@${Q}`,tags:{Project:O,Environment:Y,Role:"app"}});if(!k.success)return{success:!1,error:k.error||"Remote deploy failed",instanceCount:k.instanceCount,perInstance:k.perInstance};return{success:!0,instanceCount:k.instanceCount,perInstance:k.perInstance}}function B$($){return`'${$.replaceAll("'","'\\''")}'`}function Q6($,z,J=!1,Z=[]){let Y=`${$}-dashboard-`,G=z.map((O)=>`${$}-${O}.service`),j=J?[`export TS_CLOUD_DASHBOARD_KEEP_DOMAINS=${B$(JSON.stringify(Z))}`,"rm -f /run/ts-cloud-dashboard-routes-changed",`/usr/local/bin/bun --bun -e ${B$(`
|
|
387
|
-
const { chmodSync, existsSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } = require('node:fs')
|
|
388
|
-
const { basename, join } = require('node:path')
|
|
389
|
-
const root = '/etc/rpx/sites.d'
|
|
390
|
-
const keep = new Set(JSON.parse(process.env.TS_CLOUD_DASHBOARD_KEEP_DOMAINS || '[]'))
|
|
391
|
-
let changed = false
|
|
392
|
-
for (const name of existsSync(root) ? readdirSync(root) : []) {
|
|
393
|
-
if (!name.endsWith('.json')) continue
|
|
394
|
-
const file = join(root, name)
|
|
395
|
-
let config
|
|
396
|
-
try { config = JSON.parse(readFileSync(file, 'utf8')) } catch { continue }
|
|
397
|
-
if (!Array.isArray(config.proxies)) continue
|
|
398
|
-
const project = basename(name, '.json')
|
|
399
|
-
const proxies = config.proxies.filter((route) => {
|
|
400
|
-
const domain = typeof route?.to === 'string' ? route.to.toLowerCase() : ''
|
|
401
|
-
if (!/^(?:dashboard|cloud)\\./.test(domain) || keep.has(domain)) return true
|
|
402
|
-
const siteName = domain.replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')
|
|
403
|
-
return !existsSync('/var/www/' + project + '-' + siteName)
|
|
404
|
-
})
|
|
405
|
-
if (proxies.length === config.proxies.length) continue
|
|
406
|
-
const temporary = file + '.tmp-' + process.pid
|
|
407
|
-
const mode = statSync(file).mode & 0o777
|
|
408
|
-
writeFileSync(temporary, JSON.stringify({ ...config, proxies }, null, 2) + '\\n', { mode })
|
|
409
|
-
chmodSync(temporary, mode)
|
|
410
|
-
renameSync(temporary, file)
|
|
411
|
-
changed = true
|
|
412
|
-
}
|
|
413
|
-
if (changed) writeFileSync('/run/ts-cloud-dashboard-routes-changed', '')
|
|
414
|
-
`)}`,"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=${B$(Y)}`,`TS_CLOUD_DASHBOARD_SERVER_OWNER=${J?"1":"0"}`,`TS_CLOUD_DASHBOARD_DESIRED=${B$(` ${G.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",...j]}async function V6($,z,J,Z){let{config:Y,environment:G}=z,j=Y.project.slug,O=I(Y,G),Q=await $.findComputeTargets({slug:j,environment:G,role:"app",stackName:O});if(Q.length===0)return!0;let q=await $.runRemoteDeploy({targets:Q,commands:Q6(j,J,!Y.cloud?.attachTo,J.map((V)=>Y.sites?.[V]?.domain).filter((V)=>typeof V==="string")),comment:`ts-cloud reconcile management dashboard ${j}`,tags:{Project:j,Environment:G,Role:"app"}});if(!q.success)return Z.error(`Management dashboard reconciliation failed: ${q.error||"unknown error"}`),!1;return!0}async function q6($,z,J){let{config:Z,environment:Y}=z;if(!Z.cloud?.attachTo)return!0;let G=Z.infrastructure?.compute,j=V0(Z),O=E0(j,G?.managedServices??{});if(O.length===0)return!0;let Q=Z.project.slug,q=I(Z,Y),V=await $.findComputeTargets({slug:Q,environment:Y,role:"app",stackName:q});if(V.length===0)return!0;J.step(`Ensuring database '${j?.name}' + role exist on the shared box...`);let W=await $.runRemoteDeploy({targets:V,commands:O,comment:`ts-cloud ensure database ${Q}/${j?.name}`,tags:{Project:Q,Environment:Y,Role:"app"}});if(!W.success)return J.error(`Ensuring database '${j?.name}' failed: ${W.error||"unknown error"}`),!1;return J.success(`Database '${j?.name}' is ready on ${W.instanceCount} target(s)`),!0}async function W6($){let{config:z,environment:J,driver:Z,sha:Y,runtime:G,tarballForSite:j,logger:O=U$}=$,Q=z.project.slug,q=$.cwd??process.cwd(),V=$.managementDashboard!==!1,W=O1(z);if(V)V1(z,{cwd:q,logger:{info:O.info,warn:O.warn}});let H=!V||W?[]:q1(z);if(V&&$.rpxConfig&&$.rpxConfig!==z&&!O1($.rpxConfig))V1($.rpxConfig,{cwd:q,logger:{info:()=>{},warn:()=>{}}});if(V&&!await V6(Z,$,q1(z),O))return!1;let M=null,X=new Map;if(H.length>0)if(M=u2(z.sites?.[H[0]],{cwd:q,slug:Q,sha:Y,siteName:H[0],logger:{info:O.info,warn:O.warn}}),!M){O.warn("Management dashboard: no artifact available — skipping dashboard site(s) for this deploy.");for(let R of H)if(z.sites)delete z.sites[R]}else for(let R of H){if(R===H[0]){X.set(R,M);continue}try{let L=j6(G6(),`${Q}-${R}-${Y}.tar.gz`);Y6(M,L),X.set(R,L)}catch{X.set(R,M)}}let A=z.sites||{},F=Object.entries(A).filter(([R,L])=>{if(!L)return!1;let U=u(L);if(U==="bucket")return O.warn(`Site '${R}' targets a bucket — skipping (handled by the static-site path, not compute).`),!1;if(U==="redirect")return!1;if(U==="proxy")return!1;return!0});if(F.length===0)return W1($);if(!await q6(Z,$,O))return!1;let B=(R)=>X.get(R)??j(R);for(let[R,L]of F){O.step(`Deploying site: ${R}`);let U=H1(L)?void 0:B(R),_=await d2(Z,{config:z,environment:J,siteName:R,site:L,slug:Q,sha:Y,runtime:G,localTarballPath:U},O);if(!_.success){if(O.error(`Deploy of '${R}' failed: ${_.error||"unknown error"}`),_.perInstance)for(let C of _.perInstance)O.error(` ${C.instanceId}: ${C.status}${C.error?` — ${C.error}`:""}`);return!1}if(O.success(`Deployed ${Q}/${R}@${Y} to ${_.instanceCount} target(s)`),_.perInstance)for(let C of _.perInstance)O.info(` ✓ ${C.instanceId}: ${C.status}`)}if(!await W1($))return!1;return!0}async function W1($){let{config:z,environment:J,driver:Z,logger:Y=U$}=$,G=$.rpxConfig??z,j=G.infrastructure?.compute?.proxy??z.infrastructure?.compute?.proxy;if(j?.engine!=="rpx")return!0;let O=G.sites||{},Q=z.project.slug,q=I(z,J),V=await Z.findComputeTargets({slug:Q,environment:J,role:"lb",stackName:q});if(V.length>0){let F=(await Z.findComputeTargets({slug:Q,environment:J,role:"app",stackName:q})).map((R)=>({privateIp:R.privateIp,publicIp:R.publicIp})),B=A0(O,F,{proxy:j,slug:Q});if(B.proxies.length===0)return Y.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;Y.step(`Reloading the load balancer's rpx gateway with ${B.proxies.length} route(s)...`);let K=await Z.runRemoteDeploy({targets:V,commands:h0({config:B,slug:Q,preserveManagementDashboardRoutes:$.managementDashboard===!1}),comment:`ts-cloud rpx gateway reload ${Q}`,tags:{Project:Q,Environment:J,Role:"lb"}});if(!K.success)return Y.error(`rpx gateway reload failed: ${K.error||"unknown error"}`),!1;return Y.success(`rpx gateway reloaded on ${K.instanceCount} load balancer(s)`),!0}let W=O0(O,{proxy:j,slug:Q});if(W.proxies.length===0)return Y.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;let H=await Z.findComputeTargets({slug:Q,environment:J,role:"app",stackName:q});if(H.length===0)return Y.warn("rpx gateway: no compute targets found — skipping gateway reload."),!0;Y.step(`Reloading rpx gateway with ${W.proxies.length} route(s)...`);let M=Q0({proxy:j,config:W,slug:Q,preserveManagementDashboardRoutes:$.managementDashboard===!1}),X=await Z.runRemoteDeploy({targets:H,commands:M,comment:`ts-cloud rpx gateway reload ${Q}`,tags:{Project:Q,Environment:J,Role:"app"}});if(!X.success)return Y.error(`rpx gateway reload failed: ${X.error||"unknown error"}`),!1;return Y.success(`rpx gateway reloaded on ${X.instanceCount} target(s)`),!0}async function H6($){let{config:z,environment:J,driver:Z,logger:Y=U$}=$,G=$.rpxConfig??z,j=G.infrastructure?.compute?.proxy??z.infrastructure?.compute?.proxy;if(j?.engine!=="rpx"||!j.onDemandTls)return!0;let O=O0(G.sites||{},{proxy:j,slug:z.project.slug});if(O.proxies.length===0)return!0;let Q=k$(O);if(Q.length===0)return!0;let q=z.project.slug,V=I(z,J),W="lb",H=await Z.findComputeTargets({slug:q,environment:J,role:W,stackName:V});if(H.length===0)W="app",H=await Z.findComputeTargets({slug:q,environment:J,role:W,stackName:V});if(H.length===0)return Y.warn("rpx TLS: no gateway targets found - skipping certificate issuance."),!0;Y.step("Issuing rpx TLS certificates after DNS reconciliation...");let M=Q.map((A)=>`test -s ${O6(`${O.productionCerts.certsDir}/${A}.crt`)}`).join(" && "),X=await Z.runRemoteDeploy({targets:H,commands:[`systemctl start ${N$(q)}`,M],comment:`ts-cloud rpx TLS issuance ${q}`,tags:{Project:q,Environment:J,Role:W}});if(!X.success)return Y.error(`rpx TLS issuance failed: ${X.error||"unknown error"}`),!1;return Y.success(`rpx TLS certificates reconciled on ${X.instanceCount} gateway target(s)`),!0}import{createHash as M6}from"node:crypto";function C5($){let z=X1($.name),J=K1($.publicKey),Z=K6([...$.existingKeys??[],{name:z,publicKey:J}]);return l2($.configText,Z)}function L5($){let z=X1($.name),J=($.existingKeys??[]).filter((Z)=>Z.name!==z);if(($.existingKeys??[]).length===J.length)throw Error(`SSH key '${z}' does not exist in compute.sshKeys`);return l2($.configText,J)}function M1($=[]){return $.map((z)=>({name:z.name,publicKey:z.publicKey,type:F6(z.publicKey),fingerprint:B6(z.publicKey),added:"configured"}))}function l2($,z){let J=U6($,"compute"),Z=X6(z),Y=C6($,J.start,J.end,"sshKeys");if(Y){let Q=Y.propertyStart;while(Q>0&&$[Q-1]!==`
|
|
415
|
-
`&&/\s/.test($[Q-1]))Q--;return`${$.slice(0,Q)}${Z}${$.slice(Y.end+1)}`}let G=$.slice(0,J.end).trimEnd(),j=$.slice(J.end),O=G.endsWith(",")||G.endsWith("{")?"":",";return`${G}${O}
|
|
416
|
-
${Z},
|
|
417
|
-
${j}`}function X6($){if($.length===0)return" sshKeys: []";return` sshKeys: [
|
|
418
|
-
${$.map((J)=>[" {",` name: '${c2(J.name)}',`,` publicKey: '${c2(K1(J.publicKey))}',`," },"].join(`
|
|
419
|
-
`)).join(`
|
|
420
|
-
`)}
|
|
421
|
-
]`}function K6($){let z=new Map;for(let J of $){let Z=X1(J.name);if(z.has(Z))throw Error(`SSH key '${Z}' already exists in compute.sshKeys`);z.set(Z,{name:Z,publicKey:K1(J.publicKey)})}return[...z.values()]}function X1($){let z=$.trim();if(!/^[\w@.+-]{2,80}$/.test(z))throw Error("SSH key name must be 2-80 characters and use letters, numbers, @, ., +, _, or -.");return z}function K1($){let z=$.trim().replace(/\s+/g," "),[J,Z]=z.split(" ");if(!/^(?:ssh-(?:ed25519|rsa)|ecdsa-sha2-nistp(?:256|384|521))$/.test(J??"")||!Z)throw Error("Public key must be an OpenSSH public key, e.g. ssh-ed25519 AAAA... name@host.");return z}function F6($){return $.trim().split(/\s+/)[0]||"ssh"}function B6($){let z=$.trim().split(/\s+/)[1];if(!z)return"-";try{return`SHA256:${M6("sha256").update(Buffer.from(z,"base64")).digest("base64").replace(/=+$/,"")}`}catch{return"-"}}function c2($){return $.replace(/\\/g,"\\\\").replaceAll(String.fromCharCode(39),"\\'")}function U6($,z){let J=new RegExp(`\\b${z}\\s*:\\s*{`,"g").exec($);if(!J)throw Error(`Could not find ${z}: { ... } in cloud config.`);let Z=$.indexOf("{",J.index);return{propertyStart:J.index,start:Z,end:p2($,Z,"{","}")}}function C6($,z,J,Z){let Y=$.slice(z+1,J),G=new RegExp(`\\b${Z}\\s*:\\s*\\[`,"g").exec(Y);if(!G)return null;let j=z+1+G.index,O=$.indexOf("[",j);return{propertyStart:j,start:O,end:p2($,O,"[","]")}}function p2($,z,J,Z){let Y=0,G,j=!1,O=!1,Q=!1;for(let q=z;q<$.length;q++){let V=$[q],W=$[q+1];if(O){if(V===`
|
|
422
|
-
`)O=!1;continue}if(Q){if(V==="*"&&W==="/")Q=!1,q++;continue}if(G){if(j){j=!1;continue}if(V==="\\"){j=!0;continue}if(V===G)G=void 0;continue}if(V==="/"&&W==="/"){O=!0,q++;continue}if(V==="/"&&W==="*"){Q=!0,q++;continue}if(V==='"'||V==="'"||V==="`"){G=V;continue}if(V===J)Y++;if(V===Z){if(Y--,Y===0)return q}}throw Error(`Could not find matching ${Z} in cloud config.`)}var D6=["rpx-gateway","nginx","php8.3-fpm","php8.2-fpm","mysql","mariadb","postgresql","redis","redis-server","meilisearch"],h="-";function _6($){let z=String.raw`
|
|
423
|
-
import { X509Certificate } from 'node:crypto'
|
|
424
|
-
import { existsSync, readdirSync, readFileSync, readlinkSync, statSync } from 'node:fs'
|
|
425
|
-
import { basename, join } from 'node:path'
|
|
426
|
-
|
|
427
|
-
const fragmentsRoot = '/etc/rpx/sites.d'
|
|
428
|
-
const certsRoot = '/etc/rpx/certs'
|
|
429
|
-
const projectFilter = ${JSON.stringify($??"")}
|
|
430
|
-
const configuredRoutes = []
|
|
431
|
-
if (existsSync(fragmentsRoot)) {
|
|
432
|
-
for (const file of readdirSync(fragmentsRoot).filter(name => name.endsWith('.json')).sort()) {
|
|
433
|
-
try {
|
|
434
|
-
const fragment = JSON.parse(readFileSync(join(fragmentsRoot, file), 'utf8'))
|
|
435
|
-
const project = String(fragment.slug || basename(file, '.json'))
|
|
436
|
-
if (projectFilter && project !== projectFilter) continue
|
|
437
|
-
for (const route of Array.isArray(fragment.proxies) ? fragment.proxies : []) {
|
|
438
|
-
if (!route || !route.to) continue
|
|
439
|
-
const path = route.path || '/'
|
|
440
|
-
const staticRoot = typeof route.static === 'string' ? route.static : route.static?.dir
|
|
441
|
-
const kind = route.redirect ? 'redirect' : staticRoot ? 'static' : 'app'
|
|
442
|
-
const install = staticRoot || ''
|
|
443
|
-
const installName = install.match(/^\/var\/www\/(.+?)\/current(?:\/|$)/)?.[1]
|
|
444
|
-
const siteName = installName?.startsWith(project + '-') ? installName.slice(project.length + 1) : String(route.id || route.to)
|
|
445
|
-
const href = 'https://' + route.to + (path === '/' ? '' : path)
|
|
446
|
-
configuredRoutes.push({
|
|
447
|
-
name: siteName,
|
|
448
|
-
project,
|
|
449
|
-
route: path === '/' ? route.to : route.to + path,
|
|
450
|
-
href,
|
|
451
|
-
domain: route.to,
|
|
452
|
-
path,
|
|
453
|
-
kind,
|
|
454
|
-
runtime: kind === 'app' ? 'service' : kind,
|
|
455
|
-
deploy: kind === 'app' ? 'service' : kind === 'static' ? 'server static' : 'redirect',
|
|
456
|
-
tls: 'https',
|
|
457
|
-
root: install || (Array.isArray(route.from) ? route.from.join(', ') : route.from || 'gateway'),
|
|
458
|
-
branch: kind === 'static' ? 'build artifact' : 'main',
|
|
459
|
-
install,
|
|
460
|
-
})
|
|
461
|
-
}
|
|
462
|
-
}
|
|
463
|
-
catch {}
|
|
464
|
-
}
|
|
465
|
-
}
|
|
466
|
-
|
|
467
|
-
async function mapWithConcurrency(values, limit, mapper) {
|
|
468
|
-
const results = new Array(values.length)
|
|
469
|
-
let next = 0
|
|
470
|
-
const workers = Array.from({ length: Math.min(limit, values.length) }, async () => {
|
|
471
|
-
while (next < values.length) {
|
|
472
|
-
const index = next++
|
|
473
|
-
results[index] = await mapper(values[index])
|
|
474
|
-
}
|
|
475
|
-
})
|
|
476
|
-
await Promise.all(workers)
|
|
477
|
-
return results
|
|
478
|
-
}
|
|
479
|
-
|
|
480
|
-
const routes = await mapWithConcurrency(configuredRoutes, 8, async route => {
|
|
481
|
-
const started = performance.now()
|
|
482
|
-
let httpStatus = 0
|
|
483
|
-
const probe = async (href) => {
|
|
484
|
-
const response = await fetch(href, {
|
|
485
|
-
method: 'GET',
|
|
486
|
-
redirect: 'manual',
|
|
487
|
-
headers: { 'user-agent': 'ts-cloud-monitor/1.0' },
|
|
488
|
-
signal: AbortSignal.timeout(6000),
|
|
489
|
-
})
|
|
490
|
-
const status = response.status
|
|
491
|
-
await response.arrayBuffer()
|
|
492
|
-
return status
|
|
493
|
-
}
|
|
494
|
-
try {
|
|
495
|
-
httpStatus = await probe(route.href)
|
|
496
|
-
if (httpStatus === 404 && route.kind === 'app') {
|
|
497
|
-
const healthHref = route.href.replace(/\/$/, '') + '/health'
|
|
498
|
-
httpStatus = await probe(healthHref)
|
|
499
|
-
}
|
|
500
|
-
}
|
|
501
|
-
catch {}
|
|
502
|
-
const responseMs = Math.max(0, Math.round(performance.now() - started))
|
|
503
|
-
let tlsDaysRemaining
|
|
504
|
-
const cert = join(certsRoot, route.domain + '.crt')
|
|
505
|
-
if (existsSync(cert)) {
|
|
506
|
-
try {
|
|
507
|
-
const expiresAt = Date.parse(new X509Certificate(readFileSync(cert)).validTo)
|
|
508
|
-
if (Number.isFinite(expiresAt)) tlsDaysRemaining = Math.floor((expiresAt - Date.now()) / 86400000)
|
|
509
|
-
}
|
|
510
|
-
catch {}
|
|
511
|
-
}
|
|
512
|
-
let release
|
|
513
|
-
let deployedAt
|
|
514
|
-
if (route.install) {
|
|
515
|
-
try {
|
|
516
|
-
release = basename(readlinkSync(route.install))
|
|
517
|
-
deployedAt = statSync(route.install).mtime.toISOString()
|
|
518
|
-
}
|
|
519
|
-
catch {}
|
|
520
|
-
}
|
|
521
|
-
const status = httpStatus === 0 || httpStatus >= 500 ? 'failed' : httpStatus === 404 ? 'degraded' : 'live'
|
|
522
|
-
const { install, ...site } = route
|
|
523
|
-
return {
|
|
524
|
-
...site,
|
|
525
|
-
status,
|
|
526
|
-
httpStatus,
|
|
527
|
-
responseMs,
|
|
528
|
-
tlsDaysRemaining,
|
|
529
|
-
checkedAt: new Date().toISOString(),
|
|
530
|
-
release,
|
|
531
|
-
deployedAt,
|
|
532
|
-
}
|
|
533
|
-
})
|
|
534
|
-
for (const route of routes) console.log('DISCOVERED_SITE=' + Buffer.from(JSON.stringify(route)).toString('base64'))
|
|
535
|
-
|
|
536
|
-
const serviceOutput = Bun.spawnSync([
|
|
537
|
-
'systemctl', 'list-units', '--type=service', '--state=running', '--no-legend', '--plain',
|
|
538
|
-
]).stdout.toString()
|
|
539
|
-
const runningUnits = serviceOutput
|
|
540
|
-
.split('\n')
|
|
541
|
-
.map(line => line.trim().split(/\s+/)[0])
|
|
542
|
-
.filter(Boolean)
|
|
543
|
-
if (runningUnits.length > 0) {
|
|
544
|
-
const propertiesOutput = Bun.spawnSync([
|
|
545
|
-
'systemctl',
|
|
546
|
-
'show',
|
|
547
|
-
...runningUnits,
|
|
548
|
-
'--property=Id,WorkingDirectory,ExecStart,MemoryCurrent,UnitFileState,ActiveEnterTimestamp',
|
|
549
|
-
]).stdout.toString()
|
|
550
|
-
for (const properties of propertiesOutput.split(/\n\n+/)) {
|
|
551
|
-
const values = Object.fromEntries(properties.split('\n').filter(Boolean).map(value => {
|
|
552
|
-
const separator = value.indexOf('=')
|
|
553
|
-
return separator < 0 ? [value, ''] : [value.slice(0, separator), value.slice(separator + 1)]
|
|
554
|
-
}))
|
|
555
|
-
const unit = values.Id
|
|
556
|
-
if (!unit) continue
|
|
557
|
-
if (!/^\/var\/www\/|^\/opt\/ts-cloud\//.test(values.WorkingDirectory || '') && !/\/var\/www\/|\/opt\/ts-cloud\//.test(values.ExecStart || '')) continue
|
|
558
|
-
console.log([
|
|
559
|
-
'SVC',
|
|
560
|
-
unit,
|
|
561
|
-
'active',
|
|
562
|
-
values.MemoryCurrent || '0',
|
|
563
|
-
values.UnitFileState || '-',
|
|
564
|
-
values.ActiveEnterTimestamp || '-',
|
|
565
|
-
].join('='))
|
|
566
|
-
}
|
|
567
|
-
}
|
|
568
|
-
`;return`echo '${Buffer.from(z).toString("base64")}' | base64 -d | bun -`}function E6($={}){let z=["set +e",'echo "CPUS=$(nproc 2>/dev/null || echo 1)"',`read TS_TOTAL_1 TS_IDLE_1 <<EOF
|
|
569
|
-
$(awk '/^cpu /{idle=$5+$6; total=0; for(i=2;i<=NF;i++) total+=$i; print total, idle; exit}' /proc/stat 2>/dev/null)
|
|
570
|
-
EOF`,"sleep 0.2",`read TS_TOTAL_2 TS_IDLE_2 <<EOF
|
|
571
|
-
$(awk '/^cpu /{idle=$5+$6; total=0; for(i=2;i<=NF;i++) total+=$i; print total, idle; exit}' /proc/stat 2>/dev/null)
|
|
572
|
-
EOF`,`echo "CPUUSED=$(awk -v t1="$TS_TOTAL_1" -v i1="$TS_IDLE_1" -v t2="$TS_TOTAL_2" -v i2="$TS_IDLE_2" 'BEGIN { dt=t2-t1; di=i2-i1; if (dt>0) printf "%.1f", 100*(dt-di)/dt; else print 0 }')"`,`echo "LOAD=$(cut -d' ' -f1 /proc/loadavg 2>/dev/null || echo 0)"`,`echo "LOAD5=$(cut -d' ' -f2 /proc/loadavg 2>/dev/null || echo 0)"`,`echo "LOAD15=$(cut -d' ' -f3 /proc/loadavg 2>/dev/null || echo 0)"`,`read MEMTOTAL MEMUSED MEMAVAILABLE MEMCACHE SWAPTOTAL SWAPUSED <<EOF
|
|
573
|
-
$(free -m 2>/dev/null | awk '/^Mem:/{total=$2; used=$3; available=$7; cache=$6} /^Swap:/{print total, used, available, cache, $2, $3}')
|
|
574
|
-
EOF`,'echo "MEMTOTAL=${MEMTOTAL:-0}"','echo "MEMUSED=${MEMUSED:-0}"','echo "MEMAVAILABLE=${MEMAVAILABLE:-0}"','echo "MEMCACHE=${MEMCACHE:-0}"','echo "SWAPTOTAL=${SWAPTOTAL:-0}"','echo "SWAPUSED=${SWAPUSED:-0}"',`read DISKTOTG DISKUSEDG DISKPCT <<EOF
|
|
575
|
-
$(df -BG -P / 2>/dev/null | awk 'NR==2{gsub("G","",$2); gsub("G","",$3); gsub("%","",$5); print $2, $3, $5}')
|
|
576
|
-
EOF`,'echo "DISKPCT=${DISKPCT:-0}"','echo "DISKUSEDG=${DISKUSEDG:-0}"','echo "DISKTOTG=${DISKTOTG:-0}"',`echo "INODEPCT=$(df -Pi / 2>/dev/null | awk 'NR==2{gsub("%","",$5);print $5}')"`,`echo "NETRX=$(awk -F'[: ]+' 'NR>2 && $2!="lo"{sum+=$3} END{print sum+0}' /proc/net/dev 2>/dev/null)"`,`echo "NETTX=$(awk -F'[: ]+' 'NR>2 && $2!="lo"{sum+=$11} END{print sum+0}' /proc/net/dev 2>/dev/null)"`,". /var/lib/ts-cloud/bandwidth-state 2>/dev/null || true",'echo "NETRXRATE=${RX_RATE:-0}"','echo "NETTXRATE=${TX_RATE:-0}"','echo "NETRXTODAY=${DAY_RX:-0}"','echo "NETTXTODAY=${DAY_TX:-0}"','echo "NETRXMONTH=${MONTH_RX:-0}"','echo "NETTXMONTH=${MONTH_TX:-0}"','echo "NETMONTHKEY=${MONTH_KEY:-}"',`echo "PROCESSES=$(ps -e --no-headers 2>/dev/null | awk 'END{print NR+0}')"`,`echo "UPTIME=$(uptime -p 2>/dev/null | sed 's/^up //' || echo unknown)"`,`echo "UPTIME_SECONDS=$(cut -d' ' -f1 /proc/uptime 2>/dev/null || echo 0)"`,'echo "OS=$(. /etc/os-release 2>/dev/null; echo "$PRETTY_NAME")"'];if($.includeServices!==!1)z.push(`for s in ${D6.join(" ")}; do st=$(systemctl is-active "$s" 2>/dev/null); if [ -n "$st" ] && [ "$st" != "inactive" ] && [ "$st" != "unknown" ]; then mem=$(systemctl show "$s" -p MemoryCurrent --value 2>/dev/null); en=$(systemctl is-enabled "$s" 2>/dev/null); since=$(systemctl show "$s" -p ActiveEnterTimestamp --value 2>/dev/null); echo "SVC=$s=$st=$mem=$en=$since"; fi; done`);if($.includeSites!==!1)z.push(_6($.projectFilter));return z.push("true"),z}function w6($){let z={services:[],discoveredSites:[]};for(let J of $.split(`
|
|
577
|
-
`)){let Z=J.trim();if(Z.startsWith("DISCOVERED_SITE="))try{let Y=JSON.parse(Buffer.from(Z.slice(16),"base64").toString("utf8"));if(Y?.domain&&Y?.route)z.discoveredSites.push(Y)}catch{}else if(Z.startsWith("SVC=")){let[,Y,G,j,O,Q]=/^SVC=([^=]+)=([^=]+)(?:=([^=]*)(?:=([^=]*)(?:=(.*))?)?)?$/.exec(Z)??[];if(Y)z.services.push({name:Y,status:G,memBytes:Number(j||0),enabled:O||h,since:Q||h})}else{let Y=Z.indexOf("=");if(Y>0)z[Z.slice(0,Y)]=Z.slice(Y+1)}}return z}function r2($){let z=$.infrastructure?.compute,J=[];if(z?.webServer==="rpx"||z?.proxy?.engine==="rpx")J.push({name:"rpx-gateway",status:"configured"});else if(z?.webServer==="nginx"||z?.webServer==null)J.push({name:"ts-cloud-nginx",status:"configured"});let Z=z?.php?.versions??(z?.runtime==="php"?["8.3"]:[]);for(let j of Z)J.push({name:`php${j}-fpm`,status:"configured"});let Y=z?.managedServices??{},G=[["mysql","mysql"],["mariadb","mariadb"],["postgres","postgresql"],["redis","redis"],["memcached","memcached"],["meilisearch","meilisearch"]];for(let[j,O]of G)if(Y[j])J.push({name:O,status:"configured"});return J}function x6($){let z=$.infrastructure?.compute?.backups,J=!!z?.enabled,Z=z?.schedule??"0 2 * * *";return{enabled:J,schedule:Z,destination:J?z?.bucket??"local":"off",retention:J?z?.retentionCount??5:0,last:J?"pending first run":"not configured",size:J?h:"0 MB"}}function n2($){return $.infrastructure?.compute?.provider??$.cloud?.provider??$.provider??"aws"}function T6($){if(n2($)==="hetzner")return y$($);return $.project.region??"us-east-1"}function N6($){let z=$.infrastructure?.compute?.monitoring,J=Number(typeof z==="object"?z?.alerts?.bandwidthTb??0:0);return Number.isFinite(J)&&J>0?Math.round(J*1000000000000):0}function k6($,z){let J=R6(process.cwd(),"storage","cloud","state",`${$.project.slug}-${z}.json`);if(!L6(J))return null;try{return JSON.parse(A6(J,"utf8"))}catch{return null}}function P6($){let z=$.sites??{},J=[];for(let[Z,Y]of Object.entries(z)){let G=Y.queues??Y.workers;if(Array.isArray(G)){for(let j of G)if(typeof j==="string")J.push({name:`${Z}:${j}`,site:Z,processes:1,status:"configured"});else if(j?.name)J.push({name:`${Z}:${j.name}`,site:Z,processes:j.processes??1,status:"configured"})}}return J}function i2($){if(!$||$==="")return"/";return $.startsWith("/")?$:`/${$}`}function I6($){let z=i2($.path);if(!$.domain)return{route:"internal"};return{route:z==="/"?$.domain:`${$.domain}${z}`,href:`https://${$.domain}${z==="/"?"":z}`}}function a2($,z){let J=u(z);if(J==="redirect")return"redirect";if(J==="proxy")return"proxy";let Z=String(z.build??"").toLowerCase(),Y=String(z.start??"").toLowerCase();if($==="main"||Y.includes("buddy/src/cli.ts serve"))return"stacks";if($==="api"||Y.includes("/serve/api"))return"api";if(Z.includes("buildblog"))return"bunpress blog";if(Z.includes("bunpress"))return"bunpress";if(Z.includes("site:build")||Z.includes("stx"))return"stx static";if(J==="server-static")return z.spa?"spa":"static";if(J==="server-app")return"app";if(J==="server-php")return z.type??"php";return"bucket"}function y6($){let z=u($);if(z==="redirect"||z==="proxy")return"—";let J=`${$.start??""} ${$.build??""}`.toLowerCase();if(z==="server-static")return J.includes("bunpress")||J.includes("bun ")||J.includes("bunx ")?"static/bun":"static";if(z==="server-app")return J.includes("bun")?"bun":"node";if(z==="server-php")return`php ${$.php??$.phpVersion??"8.3"}`;return"static"}function S6($){let z=u($);if(z==="redirect")return"redirect";if(z==="proxy")return"proxy";if(z==="server-app")return"service";if(z==="server-static")return"server static";if(z==="server-php")return"php release";return"bucket"}function b6($){let z=new Map;return Object.entries($.sites??{}).map(([J,Z])=>{let Y=i2(Z.path),{route:G,href:j}=I6(Z),O=Z.domain?`${Z.domain}${Y}`:"",Q=O?z.get(O):void 0;if(O&&!Q)z.set(O,J);return{name:J,route:G,href:j,domain:Z.domain??"internal",path:Y,kind:a2(J,Z),type:a2(J,Z),runtime:y6(Z),deploy:S6(Z),tls:Z.domain?Z.ssl===!1?"http":"https":"loopback",ssl:Z.domain?Z.ssl!==!1:!1,status:Q?"shadowed":"live",shadowedBy:Q,lastDeploy:h}})}function f6($,z,J){let Z=new Map($.map((Y)=>[String(Y.route),{...Y,project:J,managedBy:"owner"}]));for(let Y of z){let G=Z.get(Y.route),j=G?.name??`${Y.project}:${Y.name}`;Z.set(Y.route,{...G,...Y,name:j,kind:G?.kind??Y.kind,type:G?.type??Y.kind,runtime:G?.runtime??Y.runtime,deploy:G?.deploy??Y.deploy,root:G?.root??Y.root,branch:G?.branch??Y.branch,managedBy:Y.project===J?"owner":"attached"})}return[...Z.values()].sort((Y,G)=>{if(Y.managedBy!==G.managedBy)return Y.managedBy==="owner"?-1:1;return String(Y.route).localeCompare(String(G.route))})}function B1($){return`'${$.replaceAll("'","'\\''")}'`}function t2($){return $.replace(/[\\&/]/g,"\\$&")}function h6($,z){if($.length===0)return["true"];return["set +e",...$.map((J)=>{let Z=B1(`${U0(z,J)}/.ts-cloud/deploy-history.log`),Y=t2(J);return`TS_CLOUD_HISTORY=${Z}; { [ -f "$TS_CLOUD_HISTORY" ] && tail -n 24 "$TS_CLOUD_HISTORY" | sed "s/^/DEPLOY=${Y}\\t/"; } || true`}),"true"]}function s2($){return[...new Set(Object.values($.sites??{}).map((z)=>z.domain).filter((z)=>typeof z==="string"&&z.length>0))]}function v6($){return["set +e",'if command -v ss >/dev/null 2>&1; then ss -H -lntup 2>/dev/null | while read -r proto _state _recv _send local _peer rest; do [ -n "$proto" ] && [ -n "$local" ] && printf "PORT=%s\\t%s\\t%s\\n" "$proto" "$local" "$rest"; done; fi','if command -v ufw >/dev/null 2>&1; then ufw status numbered 2>/dev/null | sed "s/^/FIREWALL=/"; else echo "FIREWALL=ufw unavailable"; fi','journalctl _COMM=sshd --no-pager -n 30 -o short-iso 2>/dev/null | sed "s/^/AUTH=/" || true',...s2($).map((J)=>{return`TS_CLOUD_DOMAIN=${B1(J)}; TS_CLOUD_EXPIRY=$(echo | timeout 8 openssl s_client -servername "$TS_CLOUD_DOMAIN" -connect "$TS_CLOUD_DOMAIN:443" 2>/dev/null | openssl x509 -noout -enddate 2>/dev/null | cut -d= -f2-); [ -n "$TS_CLOUD_EXPIRY" ] && printf "CERT=%s\\t%s\\n" "$TS_CLOUD_DOMAIN" "$TS_CLOUD_EXPIRY" || printf "CERT=%s\\tunavailable\\n" "$TS_CLOUD_DOMAIN"`}),"true"]}function m6($){let z=new Map,J=(G,j)=>{if(G&&j&&!z.has(j))z.set(j,{pattern:G,label:j})},Z=$.infrastructure?.compute,Y=$.project.slug;if(Z?.webServer==="rpx"||Z?.proxy?.engine==="rpx")J("rpx-gateway","rpx-gateway");else J("nginx","nginx");for(let G of r2($))J(G.name,G.name);for(let[G,j]of Object.entries($.sites??{})){if(u(j)!=="server-app")continue;if(J(`${Y}-${G}`,`${Y}-${G}`),Array.isArray(j.queues??j.workers)&&(j.queues??j.workers).length)J(`${Y}-${G}-queue-*`,`${Y}-${G}-queues`);if(Array.isArray(j.daemons)&&j.daemons.length)J(`${Y}-${G}-daemon-*`,`${Y}-${G}-daemons`)}return[...z.values()]}function g6($){let z=m6($);if(z.length===0)return["true"];return["set +e",...z.map((J)=>{let Z=B1(J.pattern),Y=t2(J.label);return`journalctl -u ${Z} --no-pager -n 150 -o short-iso 2>/dev/null | sed "s/^/LOG=${Y}\\t/" || true`}),'[ -f /var/log/ts-cloud-backup.log ] && tail -n 60 /var/log/ts-cloud-backup.log 2>/dev/null | sed "s/^/LOG=backups\\t/" || true',"true"]}function U1($){let z=new Date($);if(Number.isNaN(z.getTime()))return $||h;let J=Math.max(0,Math.round((Date.now()-z.getTime())/1000));if(J<60)return`${J}s ago`;let Z=Math.round(J/60);if(Z<60)return`${Z}m ago`;let Y=Math.round(Z/60);if(Y<48)return`${Y}h ago`;return`${Math.round(Y/24)}d ago`}function o2($){if(/(?:error|failed|panic|fatal|exception|denied|unhealthy)/i.test($))return"error";if(/(?:warn|warning|retry|restart|deprecated|timeout)/i.test($))return"warn";return"info"}function u6($){let z=[];for(let J of $.split(`
|
|
578
|
-
`)){let Z=J.trim();if(!Z.startsWith("LOG="))continue;let Y=Z.indexOf("\t");if(Y<0)continue;let G=Z.slice(4,Y),j=Z.slice(Y+1),O=/^(\d{4}-\d{2}-\d{2}T[^\s]+)\s+(\S+)\s+(.*)$/.exec(j),Q=O?.[1]??"",q=O?.[2]??"",V=(O?.[3]??j).trim();if(!V)continue;z.push({source:G,timestamp:Q,when:Q?U1(Q):h,host:q,message:V,level:o2(V)})}return z.sort((J,Z)=>String(Z.timestamp).localeCompare(String(J.timestamp))).slice(0,600)}function e2($){if(/^(?:127\.|localhost:|\[?::1\]?)/.test($))return"loopback";if(/^(?:10\.|192\.168\.|172\.(?:1[6-9]|2\d|3[01])\.|169\.254\.|\[?f[cd][0-9a-f:])/i.test($))return"private";return"public"}function d6($){if(e2($)!=="public")return"ok";if(/:(?:22|80|443)$/.test($)||/^\*:(?:22|80|443)$/.test($))return"ok";return"warn"}function c6($){if($==null)return"warn";if($<8)return"bad";if($<30)return"warn";return"ok"}function l6($){let z=[],J=[],Z=[],Y=[];for(let O of $.split(`
|
|
579
|
-
`)){let Q=O.trim();if(Q.startsWith("PORT=")){let[q="",V="",W=""]=Q.slice(5).split("\t");if(q&&V)z.push({proto:q,listen:V,processName:W||h,exposure:e2(V),tone:d6(V)})}else if(Q.startsWith("FIREWALL=")){let q=Q.slice(9).trim();if(q)J.push(q)}else if(Q.startsWith("AUTH=")){let q=Q.slice(5),V=/^(\d{4}-\d{2}-\d{2}T[^\s]+)\s+(\S+)\s+(.*)$/.exec(q),W=(V?.[3]??q).trim();if(W)Z.push({timestamp:V?.[1]??"",when:V?.[1]?U1(V[1]):h,host:V?.[2]??"",message:W,level:o2(W)})}else if(Q.startsWith("CERT=")){let[q="",V=""]=Q.slice(5).split("\t");if(!q)continue;let W=new Date(V),H=Number.isNaN(W.getTime())?null:Math.ceil((W.getTime()-Date.now())/86400000);Y.push({domain:q,expires:Number.isNaN(W.getTime())?V||h:W.toISOString().slice(0,10),daysRemaining:H,status:c6(H)})}}let G=J.some((O)=>/Status:\s*active/i.test(O)),j=J.some((O)=>/unavailable/i.test(O));return{ports:z.slice(0,80),firewall:{status:G?"active":j?"unavailable":"inactive",summary:G?"ufw active":j?"ufw unavailable":"ufw inactive or not configured",rules:J.filter((O)=>O&&!/^Status:/i.test(O)).slice(0,60)},tlsCertificates:Y,authEvents:Z.sort((O,Q)=>String(Q.timestamp).localeCompare(String(O.timestamp))).slice(0,30)}}function C1($){let J=$.infrastructure?.compute?.firewall??{},Z=[...new Set([22,80,443,...J.allowedPorts??[]])],Y=s2($);return{ports:Z.map((G)=>({proto:"tcp",listen:`0.0.0.0:${G}`,processName:"configured firewall",exposure:"public",tone:[22,80,443].includes(Number(G))?"ok":"warn"})),firewall:{status:J.enabled===!1?"disabled":"configured",summary:J.enabled===!1?"host firewall disabled in config":"host firewall configured declaratively",rules:Z.map((G)=>`ALLOW ${G}/tcp`)},tlsCertificates:Y.map((G)=>({domain:G,expires:h,daysRemaining:null,status:"warn"})),authEvents:[]}}function $z($,z){let J=z.security??C1($),Z=!!z._serverReachable&&!z.metricsUnavailable,Y=z.sites??[],G=Y.filter((q)=>q.status==="shadowed"),j=(z.services??[]).filter((q)=>["failed","stopped"].includes(q.status)),O=(J.tlsCertificates??[]).filter((q)=>q.status!=="ok"),Q=z.sshKeys??[];return[{name:"Live server probe",status:Z?"pass":"warn",detail:Z?"Metrics and remote checks are coming from the compute box.":"The dashboard is rendering config/state data until the box probe succeeds."},{name:"Managed services",status:j.length?"fail":"pass",detail:j.length?`${j.length} service(s) need attention.`:`${(z.services??[]).length} service(s) reported healthy or configured.`},{name:"Route conflicts",status:G.length?"warn":"pass",detail:G.length?`${G.map((q)=>q.name).join(", ")} is shadowed by an earlier route.`:`${Y.length} site route(s) are unshadowed.`},{name:"SSH access",status:Q.length?"pass":"warn",detail:Q.length?`${Q.length} declarative authorized key(s) configured.`:"No declarative SSH keys are configured."},{name:"Firewall",status:["active","configured"].includes(J.firewall?.status)?"pass":"warn",detail:J.firewall?.summary??"Firewall status unavailable."},{name:"TLS certificates",status:O.length?"warn":"pass",detail:O.length?`${O.length} certificate(s) need renewal visibility.`:`${(J.tlsCertificates??[]).length} certificate(s) look healthy.`}]}function zz($){let z=[];for(let J of $.serverDeploymentsDetail??$.serverDeployments??[])z.push({type:"deploy",tone:J.status==="failed"?"bad":"ok",title:`${J.site} deployed ${J.sha}`,detail:`${J.branch} · ${J.status}`,when:J.when,timestamp:J.timestamp});for(let J of $.serverLogs??[])if(J.level==="error"||J.level==="warn")z.push({type:"log",tone:J.level==="error"?"bad":"warn",title:`${J.source} ${J.level}`,detail:J.message,when:J.when,timestamp:J.timestamp});for(let J of $.sshKeys??[])z.push({type:"ssh",tone:"ok",title:`${J.name} authorized`,detail:J.fingerprint,when:J.added??h,timestamp:""});return z.sort((J,Z)=>String(Z.timestamp).localeCompare(String(J.timestamp))).slice(0,80)}function p6($,z={}){let J=[];for(let Z of $.split(`
|
|
580
|
-
`)){let Y=Z.trim();if(!Y.startsWith("DEPLOY="))continue;let G=Y.split("\t"),j=G[0]?.replace(/^DEPLOY=/,"")??"",[O,Q,q,V,W]=G.slice(1);if(!j||!O||!Q)continue;let H=z[j]??{},M=u(H),X=(q||Q).slice(0,7);J.push({sha:X,release:Q,commit:q||Q,site:j,branch:H.branch??(M==="server-static"?"build artifact":"main"),status:V||"unknown",when:U1(O),timestamp:O,took:"-",by:"ts-cloud",rc:W?.replace(/^rc=/,"")??"",steps:M==="server-static"?["upload artifact","publish static files"]:["upload artifact","restart service"]})}return J.sort((Z,Y)=>String(Y.timestamp).localeCompare(String(Z.timestamp)))}function a6($,z){let J=k6($,z),Z=r2($),Y=b6($),G=Math.max(1,Number($.infrastructure?.compute?.disk?.size??1)),j={server:{name:J?.serverName??`${$.project.slug}-${z}-app`,provider:J?.provider??n2($),region:T6($),ip:J?.publicIp??h,os:"Linux",uptime:h,probeStatus:"unavailable"},systemMetrics:{load:0,load5:0,load15:0,cpuUsedPct:0,cpus:Math.max(1,Number($.infrastructure?.compute?.instances??1)),memUsedMb:0,memTotalMb:0,memAvailableMb:0,memCacheMb:0,swapUsedMb:0,swapTotalMb:0,diskUsedPct:0,diskUsedGb:0,diskTotalGb:G,inodeUsedPct:0,networkRxBytes:0,networkTxBytes:0,networkRxBytesPerSec:0,networkTxBytesPerSec:0,networkRxBytesToday:0,networkTxBytesToday:0,networkRxBytesMonth:0,networkTxBytesMonth:0,networkMonthKey:"",processes:0,uptimeSeconds:0},metricsUnavailable:!0,bandwidthBudgetBytes:N6($),services:Z,servicesDetail:Z.map((O)=>({...O,since:h,memMb:0,auto:!0})),backup:x6($),backupHistory:[],workers:P6($),serverScheduler:{enabled:!1,lastRun:"not configured"},serverDeployments:[],serverDeploymentsDetail:[],deploymentsEmptyReason:"No deployment history has been recorded yet. Future server deploys will write /var/www/<site>/.ts-cloud/deploy-history.log.",serverLogs:[],serverLogsEmptyReason:"Live server logs are unavailable until the dashboard can reach the compute box.",security:C1($),securityEmptyReason:"Live security checks are unavailable until the dashboard can reach the compute box.",sites:Y,sitesDetail:Y.map((O)=>{let Q=$.sites?.[O.name]??{},q=u(Q);return{...O,root:q==="server-static"?U0($.project.slug,O.name):`${U0($.project.slug,O.name)}/current`,branch:q==="server-static"?"build artifact":"main",build:Q.build,php:Q.php??Q.phpVersion,aliases:Array.isArray(Q.aliases)?Q.aliases:[],redirects:Q.redirects&&typeof Q.redirects==="object"?Q.redirects:{},envKeys:Object.keys(Q.env??Q.environment??{})}}),siteHealth:[],sshKeys:M1($.infrastructure?.compute?.sshKeys??[]),_serverReachable:!1,_metricsStatus:"unavailable"};return j.diagnostics=$z($,j),j.activity=zz(j),j.topology=F1(j,{project:$.project.name,environment:z}),j}async function N5($,z,J={}){if(!$.infrastructure?.compute)return null;let Z=null;try{Z=v$({config:$})}catch{Z=null}let Y=null,G=0,j=[];if(Z)try{if(j=await Z.findComputeTargets({slug:$.project.slug,environment:z,role:"app"}),G=j.length,j.length){let W=(await Z.runRemoteDeploy({targets:[j[0]],commands:E6({includeServices:!J.telemetryOnly,includeSites:J.includeSiteHealth!==!1,projectFilter:$.cloud?.attachTo?$.project.slug:void 0}),comment:`ts-cloud dashboard:build ${$.project.slug}`,tags:{Project:$.project.slug,Environment:z,Role:"app"}})).perInstance?.[0]?.output;if(W)Y=w6(W)}}catch{}let O=a6($,z),Q=(V,W=0)=>{let H=Number(V);return Number.isFinite(H)?H:W};if(O.server.os=Y?.OS||O.server.os,O.server.uptime=Y?.UPTIME||O.server.uptime,Y){if(O.server.probeStatus="live",O.metricsUnavailable=!1,O._metricsStatus="live",O.systemMetrics={load:Q(Y.LOAD),load5:Q(Y.LOAD5),load15:Q(Y.LOAD15),cpuUsedPct:Q(Y.CPUUSED),cpus:Q(Y.CPUS,1),memUsedMb:Q(Y.MEMUSED),memTotalMb:Q(Y.MEMTOTAL,1),memAvailableMb:Q(Y.MEMAVAILABLE),memCacheMb:Q(Y.MEMCACHE),swapUsedMb:Q(Y.SWAPUSED),swapTotalMb:Q(Y.SWAPTOTAL),diskUsedPct:Q(Y.DISKPCT),diskUsedGb:Q(Y.DISKUSEDG),diskTotalGb:Q(Y.DISKTOTG,1),inodeUsedPct:Q(Y.INODEPCT),networkRxBytes:Q(Y.NETRX),networkTxBytes:Q(Y.NETTX),networkRxBytesPerSec:Q(Y.NETRXRATE),networkTxBytesPerSec:Q(Y.NETTXRATE),networkRxBytesToday:Q(Y.NETRXTODAY),networkTxBytesToday:Q(Y.NETTXTODAY),networkRxBytesMonth:Q(Y.NETRXMONTH),networkTxBytesMonth:Q(Y.NETTXMONTH),networkMonthKey:Y.NETMONTHKEY||"",processes:Q(Y.PROCESSES),uptimeSeconds:Q(Y.UPTIME_SECONDS)},Y.services.length){let V=[...new Map(Y.services.map((W)=>[W.name,W])).values()];O.services=V.map((W)=>({name:W.name,status:W.status==="active"?"running":W.status})),O.servicesDetail=V.map((W)=>({name:W.name,status:W.status==="active"?"running":W.status,since:W.since&&W.since!==h?W.since:O.server.uptime,memMb:Math.max(0,Math.round(Number(W.memBytes??0)/1024/1024)),auto:W.enabled?!["disabled","static","masked"].includes(W.enabled):!0}))}if(Y.discoveredSites.length)O.sitesDetail=f6(O.sitesDetail,Y.discoveredSites,$.project.slug),O.sites=O.sitesDetail.map((V)=>({name:V.name,project:V.project,managedBy:V.managedBy,route:V.route,href:V.href,domain:V.domain,path:V.path,kind:V.kind,type:V.type,runtime:V.runtime,deploy:V.deploy,tls:V.tls,status:V.status,httpStatus:V.httpStatus,responseMs:V.responseMs,tlsDaysRemaining:V.tlsDaysRemaining,checkedAt:V.checkedAt})),O.siteHealth=O.sitesDetail.map((V)=>({name:V.name,project:V.project,route:V.route,status:V.status,httpStatus:V.httpStatus,responseMs:V.responseMs,tlsDaysRemaining:V.tlsDaysRemaining,checkedAt:V.checkedAt}))}if(Z&&j.length&&!J.telemetryOnly)await Promise.all([(async()=>{try{let V=Object.keys($.sites??{}),H=(await Z.runRemoteDeploy({targets:[j[0]],commands:h6(V,$.project.slug),comment:`ts-cloud dashboard:deploy-history ${$.project.slug}`,tags:{Project:$.project.slug,Environment:z,Role:"app"}})).perInstance?.[0]?.output??"",M=p6(H,$.sites);O.serverDeployments=M.slice(0,5),O.serverDeploymentsDetail=M.slice(0,50),O.deploymentsEmptyReason=M.length?void 0:"No deployment history was found on the server yet. Deploy again to populate this timeline."}catch{O.deploymentsEmptyReason="Deployment history could not be read from the server."}})(),(async()=>{try{let W=(await Z.runRemoteDeploy({targets:[j[0]],commands:g6($),comment:`ts-cloud dashboard:server-logs ${$.project.slug}`,tags:{Project:$.project.slug,Environment:z,Role:"app"}})).perInstance?.[0]?.output??"",H=u6(W);O.serverLogs=H,O.serverLogsEmptyReason=H.length?void 0:"No recent journal entries were found for the managed server units."}catch{O.serverLogsEmptyReason="Server logs could not be read from the box."}})(),(async()=>{try{let W=(await Z.runRemoteDeploy({targets:[j[0]],commands:v6($),comment:`ts-cloud dashboard:security ${$.project.slug}`,tags:{Project:$.project.slug,Environment:z,Role:"app"}})).perInstance?.[0]?.output??"",H=l6(W),M=C1($);if(!H.ports.length)H.ports=M.ports;if(!H.tlsCertificates.length)H.tlsCertificates=M.tlsCertificates;O.security=H,O.securityEmptyReason=void 0}catch{O.securityEmptyReason="Server security checks could not be read from the box."}})()]);else if(Z&&G===0)O.deploymentsEmptyReason="No app server target was found for this environment.";let q=$.infrastructure?.compute?.sshKeys??$.infrastructure?.ssh?.keys??$.infrastructure?.sshKeys;if(Array.isArray(q)&&q.length)O.sshKeys=M1(q);return O._serverReachable=G>0&&!!Y,O.diagnostics=$z($,O),O.activity=zz(O),O.topology=F1(O,{project:$.project.name,environment:z}),O}
|
|
581
|
-
export{a0 as Sd,J2 as Td,G$ as Ud,rz as Vd,j$ as Wd,e as Xd,_z as Yd,n as Zd,i9 as _d,K2 as $d,R4 as ae,D4 as be,_4 as ce,X0 as de,q2 as ee,O4 as fe,d$ as ge,M4 as he,B4 as ie,F0 as je,N4 as ke,k4 as le,P4 as me,r6 as ne,z0 as oe,jz as pe,n6 as qe,v$ as re,D2 as se,W6 as te,H6 as ue,C5 as ve,L5 as we,M1 as xe,p2 as ye,_6 as ze,E6 as Ae,w6 as Be,f6 as Ce,m6 as De,u6 as Ee,l6 as Fe,p6 as Ge,a6 as He,N5 as Ie};
|