@stacksjs/ts-cloud 0.16.40 → 0.16.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/dist/aws/ec2-launch.test.d.ts +1 -0
  2. package/dist/aws/ec2.d.ts +47 -0
  3. package/dist/aws/index.js +1 -1
  4. package/dist/bin/{chunk-az504aqf.js → chunk-040x6j9v.js} +1 -1
  5. package/dist/bin/{chunk-0716rh6x.js → chunk-2b9e10db.js} +1 -1
  6. package/dist/bin/chunk-2tvtr5fy.js +1 -0
  7. package/dist/bin/{chunk-22x7vxxw.js → chunk-4azcshw6.js} +1 -1
  8. package/dist/bin/{chunk-t5kqyr8m.js → chunk-5dqnj5n9.js} +1 -1
  9. package/dist/bin/chunk-6kt12934.js +1 -0
  10. package/dist/bin/chunk-7nsjehvx.js +1 -0
  11. package/dist/bin/{chunk-w9rx90s2.js → chunk-89hvgp5e.js} +1 -1
  12. package/dist/bin/{chunk-8fxksvw4.js → chunk-8e4ck7cg.js} +1 -1
  13. package/dist/bin/{chunk-f2q239cy.js → chunk-a06d7cyt.js} +1 -1
  14. package/dist/bin/{chunk-7453cepa.js → chunk-aptdpa3m.js} +1 -1
  15. package/dist/bin/{chunk-w232tc20.js → chunk-c23r6gjb.js} +1 -1
  16. package/dist/bin/{chunk-1jwmkbzx.js → chunk-ddwp5np9.js} +9 -9
  17. package/dist/bin/{chunk-jmkfx9th.js → chunk-e8jwnsee.js} +2 -2
  18. package/dist/bin/{chunk-pj5svs6q.js → chunk-eaet154r.js} +1 -1
  19. package/dist/bin/{chunk-9vszh4dj.js → chunk-f7jpzyhr.js} +2 -2
  20. package/dist/bin/{chunk-sfzdr2b3.js → chunk-f8689v5g.js} +2 -2
  21. package/dist/bin/chunk-fhq31xzt.js +1 -0
  22. package/dist/bin/chunk-gj26v5hg.js +1 -0
  23. package/dist/bin/{chunk-b2kdxqd5.js → chunk-gn03w47w.js} +2 -2
  24. package/dist/bin/{chunk-1dqn0y04.js → chunk-grwth4nw.js} +2 -2
  25. package/dist/bin/{chunk-4g1z81pt.js → chunk-k0p394bn.js} +4 -4
  26. package/dist/bin/{chunk-h0s69e9p.js → chunk-ky4xdskt.js} +1 -1
  27. package/dist/bin/{chunk-js888a3w.js → chunk-kzgt05w5.js} +1 -1
  28. package/dist/bin/{chunk-bmj1d9xc.js → chunk-ndf3t76p.js} +11 -11
  29. package/dist/bin/{chunk-v9wf266f.js → chunk-p8xy9qm7.js} +2 -2
  30. package/dist/bin/chunk-pf9dbm3b.js +4 -0
  31. package/dist/bin/chunk-s64d5nw2.js +1 -0
  32. package/dist/bin/{chunk-5k3npcm6.js → chunk-x6w8jvs1.js} +3 -3
  33. package/dist/bin/{chunk-nqn983fx.js → chunk-xe9p2q8f.js} +17 -17
  34. package/dist/bin/{chunk-mex7tac5.js → chunk-xq7ngz6q.js} +1 -1
  35. package/dist/bin/cli.js +29 -29
  36. package/dist/bin/dashboard-server.js +1 -1
  37. package/dist/{chunk-bez9ytaz.js → chunk-ckqjqw4w.js} +1 -1
  38. package/dist/chunk-fwcf0n8f.js +4 -0
  39. package/dist/{chunk-yjh3y68t.js → chunk-jaswfk6g.js} +1 -1
  40. package/dist/deploy/index.js +1 -1
  41. package/dist/drivers/index.js +1 -1
  42. package/dist/index.js +1 -1
  43. package/dist/ui/404.html +1 -1
  44. package/dist/ui/accept-invitation.html +1 -1
  45. package/dist/ui/access-denied.html +1 -1
  46. package/dist/ui/account/automation.html +6 -6
  47. package/dist/ui/account/security.html +2 -2
  48. package/dist/ui/applications/compose.html +6 -6
  49. package/dist/ui/applications/new.html +2 -2
  50. package/dist/ui/data/backups.html +6 -6
  51. package/dist/ui/data/services.html +5 -5
  52. package/dist/ui/data/volumes.html +6 -6
  53. package/dist/ui/index.html +5 -5
  54. package/dist/ui/infrastructure/topology.html +5 -5
  55. package/dist/ui/integrations.html +1 -1
  56. package/dist/ui/operations/alerts.html +6 -6
  57. package/dist/ui/operations/configuration.html +6 -6
  58. package/dist/ui/operations/jobs.html +6 -6
  59. package/dist/ui/operations/maintenance.html +6 -6
  60. package/dist/ui/operations/observability.html +6 -6
  61. package/dist/ui/operations/previews.html +6 -6
  62. package/dist/ui/operations/queue.html +5 -5
  63. package/dist/ui/operations/regions.html +6 -6
  64. package/dist/ui/operations/releases.html +6 -6
  65. package/dist/ui/operations/spend.html +6 -6
  66. package/dist/ui/operations/workloads.html +6 -6
  67. package/dist/ui/security.html +1 -1
  68. package/dist/ui/server/actions.html +6 -6
  69. package/dist/ui/server/activity.html +1 -1
  70. package/dist/ui/server/capacity.html +6 -6
  71. package/dist/ui/server/database.html +6 -6
  72. package/dist/ui/server/deployments.html +5 -5
  73. package/dist/ui/server/diagnostics.html +1 -1
  74. package/dist/ui/server/firewall.html +6 -6
  75. package/dist/ui/server/fleet.html +6 -6
  76. package/dist/ui/server/logs.html +6 -6
  77. package/dist/ui/server/metrics.html +5 -5
  78. package/dist/ui/server/security.html +2 -2
  79. package/dist/ui/server/services.html +2 -2
  80. package/dist/ui/server/sites.html +6 -6
  81. package/dist/ui/server/ssh-keys.html +6 -6
  82. package/dist/ui/server/team.html +6 -6
  83. package/dist/ui/server/terminal.html +2 -2
  84. package/dist/ui/serverless/alarms.html +6 -6
  85. package/dist/ui/serverless/assets.html +2 -2
  86. package/dist/ui/serverless/cost.html +2 -2
  87. package/dist/ui/serverless/data.html +6 -6
  88. package/dist/ui/serverless/deployments.html +2 -2
  89. package/dist/ui/serverless/firewall.html +1 -1
  90. package/dist/ui/serverless/functions.html +6 -6
  91. package/dist/ui/serverless/logs.html +6 -6
  92. package/dist/ui/serverless/metrics.html +2 -2
  93. package/dist/ui/serverless/queues.html +6 -6
  94. package/dist/ui/serverless/secrets.html +6 -6
  95. package/dist/ui/serverless/traces.html +6 -6
  96. package/dist/ui/serverless.html +5 -5
  97. package/package.json +3 -3
  98. package/dist/bin/chunk-0scywedn.js +0 -4
  99. package/dist/bin/chunk-459waehf.js +0 -1
  100. package/dist/bin/chunk-4y8zhe38.js +0 -1
  101. package/dist/bin/chunk-68tgx5j2.js +0 -1
  102. package/dist/bin/chunk-jxfgkhkc.js +0 -1
  103. package/dist/bin/chunk-k2mdcb66.js +0 -1
  104. package/dist/bin/chunk-kva8aybv.js +0 -1
  105. package/dist/chunk-ysx5m6cs.js +0 -4
@@ -1,4 +1,4 @@
1
- import{oa,A,w,ki,aa,ca,F,T,Wt,Lr}from"./chunk-1jwmkbzx.js";import{p}from"./chunk-dkf2kcsc.js";import{v}from"./chunk-7593hjcq.js";import{Q}from"./chunk-0scywedn.js";import{g}from"./chunk-nmqjmx30.js";import{J,Ei,zs,P,U,Ir,St,et,No,wi,_o,vt,Hc,Oo,$o,Ii,Lo,Vt,Ws,Gc,Pi,Ks,Js,Xs,Qs,Mo,pn,Ys,mn,Zs,Uo}from"./chunk-5k3npcm6.js";import{Ao,Ro,xs}from"./chunk-4g1z81pt.js";import{ps}from"./chunk-n7yefy09.js";import{rn}from"./chunk-5nmt4s5w.js";import{Cr}from"./chunk-k343q24p.js";import{existsSync as Wl,readFileSync as Gl}from"node:fs";import{readFileSync as es}from"node:fs";import{join as Oa}from"node:path";function rs(e={}){let t=new Set;for(let r of Object.values(e)){if(!r.domain)continue;if(r.redirect||r.deploy==="server"||r.start)t.add(r.domain)}return t}function tr(e){return e.replace(/\.$/,"").toLowerCase()}function Ho(e,t,r){let n=tr(e.name),s=tr(t),i=tr(r),o=i===s?"@":i.endsWith(`.${s}`)?i.slice(0,-(s.length+1)):i;return n===i||n===o||o==="@"&&(n===""||n===s)}async function ko(e,t,r,n,s="A"){let i=await e.listRecords(t);if(!i.success)return[`could not list ${s} records: ${i.message||"unknown provider error"}`];let o=i.records.filter((l)=>l.type===s&&Ho(l,t,r)),a=o.findIndex((l)=>l.content===n);if(o.length<=1||a===-1)return[];let c=[];for(let[l,u]of o.entries()){if(l===a)continue;let d=await e.deleteRecord(t,u);if(!d.success)c.push(`could not remove stale ${u.name} ${s} ${u.content}: ${d.message||"unknown provider error"}`)}return c}function ue(e){if(!e)return;let t=e.trim();if(!t)return;if(!t.includes("/"))return t;let[r]=t.split("/");if(!r.endsWith("::"))return r||void 0;return`${r}1`}var Fo=new Set(["mail","smtp","imap","mx"]);function Wi(e){return!Fo.has(e.split(".")[0]??"")}async function ai(e){let{provider:t,zone:r,fqdn:n,ipv4:s,ipv6:i,ttl:o=600}=e,a={published:[],warnings:[]},c=[{type:"A",content:s}];if(i&&Wi(n))c.push({type:"AAAA",content:i});for(let{type:l,content:u}of c){let d=await t.upsertRecord(r,{name:n,type:l,content:u,ttl:o});if(d?.success===!1){a.warnings.push(`${n} → ${u} failed: ${d.error||d.message||"unknown error"}`);continue}if(a.warnings.push(...(await ko(t,r,n,u,l)).map((m)=>`${n} cleanup: ${m}`)),await Ki(t,r,n,u,l))a.published.push({fqdn:n,type:l,content:u});else a.warnings.push(`${n} → ${u} reported success at ${t.name} but no matching ${l} record exists — create it manually: ${l} ${n} → ${u}`)}return a}async function Ki(e,t,r,n,s){try{if(typeof e?.listRecords!=="function")return!0;let i=await e.listRecords(t);if(!i?.success||!Array.isArray(i.records))return!0;return i.records.some((o)=>{let a=typeof o?.name==="string"?o.name.replace(/\.$/,""):"";return o?.type===s&&a===r&&o?.content===n})}catch{return!0}}function rr(e){return(Buffer.isBuffer(e)?e.toString("utf8"):typeof e==="string"?e:"").replace(/(^|\n)(\s*(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*=).*$/gm,"$1$2[redacted]").replace(/encrypted:[A-Za-z0-9+/=]+/g,"encrypted:[redacted]").trim().slice(-8000)}function st(e,t){let r=rr(e?.stderr),n=/line (\d+): syntax error/.exec(r);if(!n)return"";let s=Number(n[1]),i=t.split(`
1
+ import{oa,A,w,ki,aa,ca,F,T,Wt,Lr}from"./chunk-ddwp5np9.js";import{p}from"./chunk-dkf2kcsc.js";import{v}from"./chunk-7593hjcq.js";import{Q}from"./chunk-pf9dbm3b.js";import{g}from"./chunk-nmqjmx30.js";import{J,Ei,zs,P,U,Ir,St,et,No,wi,_o,vt,Hc,Oo,$o,Ii,Lo,Vt,Ws,qc,Pi,Ks,Js,Xs,Qs,Mo,pn,Ys,mn,Zs,Uo}from"./chunk-x6w8jvs1.js";import{Ao,Ro,xs}from"./chunk-k0p394bn.js";import{ps}from"./chunk-n7yefy09.js";import{rn}from"./chunk-5nmt4s5w.js";import{Cr}from"./chunk-k343q24p.js";import{existsSync as Wl,readFileSync as Gl}from"node:fs";import{readFileSync as es}from"node:fs";import{join as Oa}from"node:path";function rs(e={}){let t=new Set;for(let r of Object.values(e)){if(!r.domain)continue;if(r.redirect||r.deploy==="server"||r.start)t.add(r.domain)}return t}function tr(e){return e.replace(/\.$/,"").toLowerCase()}function Ho(e,t,r){let n=tr(e.name),s=tr(t),i=tr(r),o=i===s?"@":i.endsWith(`.${s}`)?i.slice(0,-(s.length+1)):i;return n===i||n===o||o==="@"&&(n===""||n===s)}async function ko(e,t,r,n,s="A"){let i=await e.listRecords(t);if(!i.success)return[`could not list ${s} records: ${i.message||"unknown provider error"}`];let o=i.records.filter((l)=>l.type===s&&Ho(l,t,r)),a=o.findIndex((l)=>l.content===n);if(o.length<=1||a===-1)return[];let c=[];for(let[l,u]of o.entries()){if(l===a)continue;let d=await e.deleteRecord(t,u);if(!d.success)c.push(`could not remove stale ${u.name} ${s} ${u.content}: ${d.message||"unknown provider error"}`)}return c}function ue(e){if(!e)return;let t=e.trim();if(!t)return;if(!t.includes("/"))return t;let[r]=t.split("/");if(!r.endsWith("::"))return r||void 0;return`${r}1`}var Fo=new Set(["mail","smtp","imap","mx"]);function Wi(e){return!Fo.has(e.split(".")[0]??"")}async function ai(e){let{provider:t,zone:r,fqdn:n,ipv4:s,ipv6:i,ttl:o=600}=e,a={published:[],warnings:[]},c=[{type:"A",content:s}];if(i&&Wi(n))c.push({type:"AAAA",content:i});for(let{type:l,content:u}of c){let d=await t.upsertRecord(r,{name:n,type:l,content:u,ttl:o});if(d?.success===!1){a.warnings.push(`${n} → ${u} failed: ${d.error||d.message||"unknown error"}`);continue}if(a.warnings.push(...(await ko(t,r,n,u,l)).map((m)=>`${n} cleanup: ${m}`)),await Ki(t,r,n,u,l))a.published.push({fqdn:n,type:l,content:u});else a.warnings.push(`${n} → ${u} reported success at ${t.name} but no matching ${l} record exists — create it manually: ${l} ${n} → ${u}`)}return a}async function Ki(e,t,r,n,s){try{if(typeof e?.listRecords!=="function")return!0;let i=await e.listRecords(t);if(!i?.success||!Array.isArray(i.records))return!0;return i.records.some((o)=>{let a=typeof o?.name==="string"?o.name.replace(/\.$/,""):"";return o?.type===s&&a===r&&o?.content===n})}catch{return!0}}function rr(e){return(Buffer.isBuffer(e)?e.toString("utf8"):typeof e==="string"?e:"").replace(/(^|\n)(\s*(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*=).*$/gm,"$1$2[redacted]").replace(/encrypted:[A-Za-z0-9+/=]+/g,"encrypted:[redacted]").trim().slice(-8000)}function st(e,t){let r=rr(e?.stderr),n=/line (\d+): syntax error/.exec(r);if(!n)return"";let s=Number(n[1]),i=t.split(`
2
2
  `),o=Math.max(1,s-12),a=Math.min(i.length,s+2),c=i.slice(o-1,a).map((l,u)=>{let d=o+u,m=/^[A-Z_][A-Z0-9_]*=/.test(l)?l.replace(/=.*/,"=<redacted>"):l;return` ${String(d).padStart(4)}${d===s?" >":" "} ${m}`});return["",`The deploy script bash rejected is ${i.length} lines; it stopped at ${s}.`,...c].join(`
3
3
  `)}function Pe(e){let t=e,r=typeof t?.status==="number"?` (exit ${t.status})`:"",n=t?.signal?` (signal ${t.signal})`:"",s=[rr(t?.stderr),rr(t?.stdout)].filter(Boolean).join(`
4
4
  `);return`Remote SSH command failed${r}${n}${s?`
@@ -6,7 +6,7 @@ ${s}`:""}`}function Le(e){for(let t of e.split(`
6
6
  `)){let r=t.trim();if(!r.startsWith("[ts-cloud]"))continue;console.warn(r)}}var Rn=4000,zo=3;function Bo(e){return e.length>Rn?`…
7
7
  ${e.slice(-Rn)}`:e}function xe(e,t){let r=e.filter((o)=>o.status!=="Success");if(r.length===0)return t;let n=r.slice(0,zo).map((o)=>{let a=(o.error||o.output||"").trim(),c=`${o.instanceId}: ${o.status}`;return a?`${c}
8
8
  ${Bo(a)}`:c}),s=r.length-n.length,i=s>0?[`(+${s} more instance${s===1?"":"s"} failed)`]:[];return[t,...n,...i].join(`
9
- `)}class Ge{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new p}async putParameter(e){let t={Name:e.Name,Value:e.Value};if(e.Type)t.Type=e.Type;if(e.Description)t.Description=e.Description;if(e.KeyId)t.KeyId=e.KeyId;if(e.Overwrite!==void 0)t.Overwrite=e.Overwrite;if(e.AllowedPattern)t.AllowedPattern=e.AllowedPattern;if(e.Tags&&e.Tags.length>0)t.Tags=e.Tags;if(e.Tier)t.Tier=e.Tier;if(e.DataType)t.DataType=e.DataType;let r=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(t)});return{Version:r.Version,Tier:r.Tier}}async getParameter(e){let t={Name:e.Name};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;let r=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(t)});return{Parameter:r.Parameter?this.parseParameter(r.Parameter):void 0}}async getParameters(e){let t={Names:e.Names};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;let r=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(t)});return{Parameters:r.Parameters?.map((n)=>this.parseParameter(n)),InvalidParameters:r.InvalidParameters}}async getParametersByPath(e){let t={Path:e.Path};if(e.Recursive!==void 0)t.Recursive=e.Recursive;if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;if(e.MaxResults)t.MaxResults=e.MaxResults;if(e.NextToken)t.NextToken=e.NextToken;if(e.ParameterFilters&&e.ParameterFilters.length>0)t.ParameterFilters=e.ParameterFilters;let r=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(t)});return{Parameters:r.Parameters?.map((n)=>this.parseParameter(n)),NextToken:r.NextToken}}async deleteParameter(e){let t={Name:e.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(t)})}async deleteParameters(e){let t={Names:e},r=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(t)});return{DeletedParameters:r.DeletedParameters,InvalidParameters:r.InvalidParameters}}async describeParameters(e){let t={};if(e?.Filters&&e.Filters.length>0)t.Filters=e.Filters;if(e?.ParameterFilters&&e.ParameterFilters.length>0)t.ParameterFilters=e.ParameterFilters;if(e?.MaxResults)t.MaxResults=e.MaxResults;if(e?.NextToken)t.NextToken=e.NextToken;let r=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(t)});return{Parameters:r.Parameters?.map((n)=>this.parseParameter(n)),NextToken:r.NextToken}}async getParameterHistory(e){let t={Name:e.Name};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;if(e.MaxResults)t.MaxResults=e.MaxResults;if(e.NextToken)t.NextToken=e.NextToken;let r=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(t)});return{Parameters:r.Parameters?.map((n)=>({Name:n.Name,Type:n.Type,KeyId:n.KeyId,LastModifiedDate:n.LastModifiedDate,LastModifiedUser:n.LastModifiedUser,Description:n.Description,Value:n.Value,Version:n.Version,Labels:n.Labels,Tier:n.Tier})),NextToken:r.NextToken}}async labelParameterVersion(e){let t={Name:e.Name,Labels:e.Labels};if(e.ParameterVersion!==void 0)t.ParameterVersion=e.ParameterVersion;let r=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(t)});return{InvalidLabels:r.InvalidLabels,ParameterVersion:r.ParameterVersion}}async addTagsToResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId,Tags:e.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(t)})}async removeTagsFromResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId,TagKeys:e.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(t)})}async listTagsForResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.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(t)})).TagList}}async setString(e,t,r){return this.putParameter({Name:e,Value:t,Type:"String",Description:r?.description,Overwrite:r?.overwrite??!0,Tags:r?.tags})}async setSecureString(e,t,r){return this.putParameter({Name:e,Value:t,Type:"SecureString",Description:r?.description,Overwrite:r?.overwrite??!0,KeyId:r?.kmsKeyId,Tags:r?.tags})}async getValue(e){return(await this.getParameter({Name:e,WithDecryption:!0})).Parameter?.Value}async getAllByPath(e,t=!0){let r=[],n;do{let s=await this.getParametersByPath({Path:e,Recursive:t,WithDecryption:!0,NextToken:n});if(s.Parameters)r.push(...s.Parameters);n=s.NextToken}while(n);return r}parseParameter(e){return{Name:e.Name,Type:e.Type,Value:e.Value,Version:e.Version,LastModifiedDate:e.LastModifiedDate,ARN:e.ARN,DataType:e.DataType,Description:e.Description,AllowedPattern:e.AllowedPattern,KeyId:e.KeyId,Tier:e.Tier}}async sendCommand(e){if(!e.InstanceIds&&!e.Targets)throw Error("SendCommand requires either InstanceIds or Targets");let t={DocumentName:e.DocumentName};if(e.InstanceIds)t.InstanceIds=e.InstanceIds;if(e.Targets)t.Targets=e.Targets;if(e.Parameters)t.Parameters=e.Parameters;if(e.TimeoutSeconds)t.TimeoutSeconds=e.TimeoutSeconds;if(e.Comment)t.Comment=e.Comment;if(e.OutputS3BucketName)t.OutputS3BucketName=e.OutputS3BucketName;if(e.OutputS3KeyPrefix)t.OutputS3KeyPrefix=e.OutputS3KeyPrefix;let r=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(t)});return{CommandId:r.Command?.CommandId,Status:r.Command?.Status,StatusDetails:r.Command?.StatusDetails}}async getCommandInvocation(e){let t={CommandId:e.CommandId,InstanceId:e.InstanceId},r=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(t)});return{Status:r.Status,StatusDetails:r.StatusDetails,StandardOutputContent:r.StandardOutputContent,StandardErrorContent:r.StandardErrorContent,ResponseCode:r.ResponseCode}}async runShellCommand(e,t,r){let n=await this.sendCommand({InstanceIds:[e],DocumentName:"AWS-RunShellScript",Parameters:{commands:t},TimeoutSeconds:r?.timeoutSeconds||600});if(!n.CommandId)return{success:!1,error:"Failed to send command"};if(r?.waitForCompletion===!1)return{success:!0,status:"Pending"};let s=r?.pollIntervalMs||2000,i=r?.maxWaitMs||300000,o=Date.now();while(Date.now()-o<i){await new Promise((a)=>setTimeout(a,s));try{let a=await this.getCommandInvocation({CommandId:n.CommandId,InstanceId:e});if(a.Status==="Success")return{success:!0,output:a.StandardOutputContent,error:a.StandardErrorContent,status:a.Status};if(a.Status==="Failed"||a.Status==="Cancelled"||a.Status==="TimedOut")return{success:!1,output:a.StandardOutputContent,error:a.StandardErrorContent||a.StatusDetails,status:a.Status}}catch(a){if(!a.message?.includes("InvocationDoesNotExist"))return{success:!1,error:a.message}}}return{success:!1,error:"Command timed out waiting for completion"}}async listCommandInvocations(e){let t={CommandId:e.CommandId};if(e.Details)t.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(t)})).CommandInvocations||[]).map((s)=>({InstanceId:s.InstanceId,Status:s.Status,StatusDetails:s.StatusDetails,StandardOutputContent:s.CommandPlugins?.[0]?.Output,StandardErrorContent:s.CommandPlugins?.[0]?.StandardErrorUrl}))}async sendCommandByTags(e){let t=Object.entries(e.tags).map(([c,l])=>({Key:`tag:${c}`,Values:[l]})),r=await this.sendCommand({Targets:t,DocumentName:"AWS-RunShellScript",Parameters:{commands:e.commands},TimeoutSeconds:e.timeoutSeconds||600,Comment:e.comment});if(!r.CommandId)return{success:!1,instanceCount:0,perInstance:[],error:"Failed to send command"};let n=e.pollIntervalMs||3000,s=e.maxWaitMs||600000,i=Date.now(),o=new Set(["Success","Failed","Cancelled","TimedOut"]),a=[];while(Date.now()-i<s){await new Promise((c)=>setTimeout(c,n));try{if(a=await this.listCommandInvocations({CommandId:r.CommandId,Details:!0}),a.length===0)continue;if(a.every((l)=>o.has(l.Status||""))){let l=a.map((d)=>({instanceId:d.InstanceId,status:d.Status||"Unknown",output:d.StandardOutputContent,error:d.StandardErrorContent||d.StatusDetails})),u=a.every((d)=>d.Status==="Success");return{success:u,instanceCount:a.length,perInstance:l,error:u?void 0:"One or more instances reported a non-success status"}}}catch(c){if(!c.message?.includes("InvocationDoesNotExist"))return{success:!1,instanceCount:0,perInstance:[],error:c.message}}}return{success:!1,instanceCount:a.length,perInstance:a.map((c)=>({instanceId:c.InstanceId,status:c.Status||"Unknown"})),error:"Command timed out waiting for all instances to complete"}}}function Ko(e){return`/etc/ts-cloud/${e}-upgrade.env`}function jo(e){return`${e}-upgrade`}function Ji(e){if(!e||e.length===0)return[];let t=["mkdir -p /etc/ts-cloud"],r=[];for(let n of e){if(n.enabled===!1)continue;if(!n.service||!n.binary)continue;let{service:s,binary:i,command:o="upgrade",channel:a="stable",schedule:c="daily",randomizedDelay:l="4h",args:u=[]}=n,d=jo(s),m=Ko(s),f=[`--path ${i}`,`--service ${s}`,...a==="canary"?["--canary"]:[],...u].join(" ");t.push(`if [ ! -f ${m} ]; then`,` cat > ${m} <<'TS_CLOUD_APPUPD_ENV_EOF'`,"# Set to false to pause automatic updates without disabling the timer.","ENABLED=true","# Extra flags appended to the update command.","ARGS=","TS_CLOUD_APPUPD_ENV_EOF","fi",`chmod 644 ${m}`,`cat > /etc/systemd/system/${d}.service <<'TS_CLOUD_APPUPD_SVC_EOF'`,"[Unit]",`Description=Check for and install ${s} updates`,"After=network-online.target","Wants=network-online.target","","[Service]","Type=oneshot",`EnvironmentFile=-${m}`,`ExecStart=/bin/sh -c 'if [ "\${ENABLED:-true}" != "true" ]; then echo "auto-update disabled via ${m}"; exit 0; fi; exec ${i} ${o} ${f} $ARGS'`,"TS_CLOUD_APPUPD_SVC_EOF",`cat > /etc/systemd/system/${d}.timer <<'TS_CLOUD_APPUPD_TMR_EOF'`,"[Unit]",`Description=Scheduled ${s} update check`,"","[Timer]",`OnCalendar=${c}`,`RandomizedDelaySec=${l}`,"Persistent=true","","[Install]","WantedBy=timers.target","TS_CLOUD_APPUPD_TMR_EOF"),r.push(`systemctl enable --now ${d}.timer`)}if(r.length===0)return[];return[...t,"systemctl daemon-reload",...r]}function he(e=!0){if(!e)return[];return["export DEBIAN_FRONTEND=noninteractive","dpkg-query -W -f='${Status}' unattended-upgrades 2>/dev/null | grep -q 'ok installed' || apt-get install -y unattended-upgrades","cat > /etc/apt/apt.conf.d/20auto-upgrades <<'TS_CLOUD_AUTOUPD_EOF'",'APT::Periodic::Update-Package-Lists "1";','APT::Periodic::Unattended-Upgrade "1";','APT::Periodic::Download-Upgradeable-Packages "1";','APT::Periodic::AutocleanInterval "7";',"TS_CLOUD_AUTOUPD_EOF","systemctl enable --now unattended-upgrades 2>/dev/null || true"]}var En=[["nginx",80],["https",443],["phpFpm",9074],["mysql",3306],["postgres",5432],["redis",6379],["meilisearch",7700],["typesense",8108],["smtp",25]];function Wo(e=!0){let t=typeof e==="object"?e:{},r=typeof e==="boolean"?e:e.enabled!==!1,n=Number(t.alerts?.bandwidthTb??0);return{enabled:r,cpuLoadPerCore:t.alerts?.cpuLoadPerCore??2,memPercent:t.alerts?.memPercent??90,diskPercent:t.alerts?.diskPercent??90,bandwidthTb:Number.isFinite(n)&&n>0?n:0,bandwidthPercent:t.alerts?.bandwidthPercent??80}}function ye(e=!0){let{enabled:t,cpuLoadPerCore:r,memPercent:n,diskPercent:s,bandwidthTb:i,bandwidthPercent:o}=Wo(e);if(!t)return[];let a=Math.round(i*1000000000000),c=En.map(([u,d])=>`SVC_${u.toUpperCase()}=$(probe ${d})`),l=En.map(([u])=>`"${u}":"$SVC_${u.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
9
+ `)}class qe{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new p}async putParameter(e){let t={Name:e.Name,Value:e.Value};if(e.Type)t.Type=e.Type;if(e.Description)t.Description=e.Description;if(e.KeyId)t.KeyId=e.KeyId;if(e.Overwrite!==void 0)t.Overwrite=e.Overwrite;if(e.AllowedPattern)t.AllowedPattern=e.AllowedPattern;if(e.Tags&&e.Tags.length>0)t.Tags=e.Tags;if(e.Tier)t.Tier=e.Tier;if(e.DataType)t.DataType=e.DataType;let r=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(t)});return{Version:r.Version,Tier:r.Tier}}async getParameter(e){let t={Name:e.Name};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;let r=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(t)});return{Parameter:r.Parameter?this.parseParameter(r.Parameter):void 0}}async getParameters(e){let t={Names:e.Names};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;let r=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(t)});return{Parameters:r.Parameters?.map((n)=>this.parseParameter(n)),InvalidParameters:r.InvalidParameters}}async getParametersByPath(e){let t={Path:e.Path};if(e.Recursive!==void 0)t.Recursive=e.Recursive;if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;if(e.MaxResults)t.MaxResults=e.MaxResults;if(e.NextToken)t.NextToken=e.NextToken;if(e.ParameterFilters&&e.ParameterFilters.length>0)t.ParameterFilters=e.ParameterFilters;let r=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(t)});return{Parameters:r.Parameters?.map((n)=>this.parseParameter(n)),NextToken:r.NextToken}}async deleteParameter(e){let t={Name:e.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(t)})}async deleteParameters(e){let t={Names:e},r=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(t)});return{DeletedParameters:r.DeletedParameters,InvalidParameters:r.InvalidParameters}}async describeParameters(e){let t={};if(e?.Filters&&e.Filters.length>0)t.Filters=e.Filters;if(e?.ParameterFilters&&e.ParameterFilters.length>0)t.ParameterFilters=e.ParameterFilters;if(e?.MaxResults)t.MaxResults=e.MaxResults;if(e?.NextToken)t.NextToken=e.NextToken;let r=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(t)});return{Parameters:r.Parameters?.map((n)=>this.parseParameter(n)),NextToken:r.NextToken}}async getParameterHistory(e){let t={Name:e.Name};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;if(e.MaxResults)t.MaxResults=e.MaxResults;if(e.NextToken)t.NextToken=e.NextToken;let r=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(t)});return{Parameters:r.Parameters?.map((n)=>({Name:n.Name,Type:n.Type,KeyId:n.KeyId,LastModifiedDate:n.LastModifiedDate,LastModifiedUser:n.LastModifiedUser,Description:n.Description,Value:n.Value,Version:n.Version,Labels:n.Labels,Tier:n.Tier})),NextToken:r.NextToken}}async labelParameterVersion(e){let t={Name:e.Name,Labels:e.Labels};if(e.ParameterVersion!==void 0)t.ParameterVersion=e.ParameterVersion;let r=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(t)});return{InvalidLabels:r.InvalidLabels,ParameterVersion:r.ParameterVersion}}async addTagsToResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId,Tags:e.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(t)})}async removeTagsFromResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId,TagKeys:e.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(t)})}async listTagsForResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.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(t)})).TagList}}async setString(e,t,r){return this.putParameter({Name:e,Value:t,Type:"String",Description:r?.description,Overwrite:r?.overwrite??!0,Tags:r?.tags})}async setSecureString(e,t,r){return this.putParameter({Name:e,Value:t,Type:"SecureString",Description:r?.description,Overwrite:r?.overwrite??!0,KeyId:r?.kmsKeyId,Tags:r?.tags})}async getValue(e){return(await this.getParameter({Name:e,WithDecryption:!0})).Parameter?.Value}async getAllByPath(e,t=!0){let r=[],n;do{let s=await this.getParametersByPath({Path:e,Recursive:t,WithDecryption:!0,NextToken:n});if(s.Parameters)r.push(...s.Parameters);n=s.NextToken}while(n);return r}parseParameter(e){return{Name:e.Name,Type:e.Type,Value:e.Value,Version:e.Version,LastModifiedDate:e.LastModifiedDate,ARN:e.ARN,DataType:e.DataType,Description:e.Description,AllowedPattern:e.AllowedPattern,KeyId:e.KeyId,Tier:e.Tier}}async sendCommand(e){if(!e.InstanceIds&&!e.Targets)throw Error("SendCommand requires either InstanceIds or Targets");let t={DocumentName:e.DocumentName};if(e.InstanceIds)t.InstanceIds=e.InstanceIds;if(e.Targets)t.Targets=e.Targets;if(e.Parameters)t.Parameters=e.Parameters;if(e.TimeoutSeconds)t.TimeoutSeconds=e.TimeoutSeconds;if(e.Comment)t.Comment=e.Comment;if(e.OutputS3BucketName)t.OutputS3BucketName=e.OutputS3BucketName;if(e.OutputS3KeyPrefix)t.OutputS3KeyPrefix=e.OutputS3KeyPrefix;let r=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(t)});return{CommandId:r.Command?.CommandId,Status:r.Command?.Status,StatusDetails:r.Command?.StatusDetails}}async getCommandInvocation(e){let t={CommandId:e.CommandId,InstanceId:e.InstanceId},r=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(t)});return{Status:r.Status,StatusDetails:r.StatusDetails,StandardOutputContent:r.StandardOutputContent,StandardErrorContent:r.StandardErrorContent,ResponseCode:r.ResponseCode}}async runShellCommand(e,t,r){let n=await this.sendCommand({InstanceIds:[e],DocumentName:"AWS-RunShellScript",Parameters:{commands:t},TimeoutSeconds:r?.timeoutSeconds||600});if(!n.CommandId)return{success:!1,error:"Failed to send command"};if(r?.waitForCompletion===!1)return{success:!0,status:"Pending"};let s=r?.pollIntervalMs||2000,i=r?.maxWaitMs||300000,o=Date.now();while(Date.now()-o<i){await new Promise((a)=>setTimeout(a,s));try{let a=await this.getCommandInvocation({CommandId:n.CommandId,InstanceId:e});if(a.Status==="Success")return{success:!0,output:a.StandardOutputContent,error:a.StandardErrorContent,status:a.Status};if(a.Status==="Failed"||a.Status==="Cancelled"||a.Status==="TimedOut")return{success:!1,output:a.StandardOutputContent,error:a.StandardErrorContent||a.StatusDetails,status:a.Status}}catch(a){if(!a.message?.includes("InvocationDoesNotExist"))return{success:!1,error:a.message}}}return{success:!1,error:"Command timed out waiting for completion"}}async listCommandInvocations(e){let t={CommandId:e.CommandId};if(e.Details)t.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(t)})).CommandInvocations||[]).map((s)=>({InstanceId:s.InstanceId,Status:s.Status,StatusDetails:s.StatusDetails,StandardOutputContent:s.CommandPlugins?.[0]?.Output,StandardErrorContent:s.CommandPlugins?.[0]?.StandardErrorUrl}))}async sendCommandByTags(e){let t=Object.entries(e.tags).map(([c,l])=>({Key:`tag:${c}`,Values:[l]})),r=await this.sendCommand({Targets:t,DocumentName:"AWS-RunShellScript",Parameters:{commands:e.commands},TimeoutSeconds:e.timeoutSeconds||600,Comment:e.comment});if(!r.CommandId)return{success:!1,instanceCount:0,perInstance:[],error:"Failed to send command"};let n=e.pollIntervalMs||3000,s=e.maxWaitMs||600000,i=Date.now(),o=new Set(["Success","Failed","Cancelled","TimedOut"]),a=[];while(Date.now()-i<s){await new Promise((c)=>setTimeout(c,n));try{if(a=await this.listCommandInvocations({CommandId:r.CommandId,Details:!0}),a.length===0)continue;if(a.every((l)=>o.has(l.Status||""))){let l=a.map((d)=>({instanceId:d.InstanceId,status:d.Status||"Unknown",output:d.StandardOutputContent,error:d.StandardErrorContent||d.StatusDetails})),u=a.every((d)=>d.Status==="Success");return{success:u,instanceCount:a.length,perInstance:l,error:u?void 0:"One or more instances reported a non-success status"}}}catch(c){if(!c.message?.includes("InvocationDoesNotExist"))return{success:!1,instanceCount:0,perInstance:[],error:c.message}}}return{success:!1,instanceCount:a.length,perInstance:a.map((c)=>({instanceId:c.InstanceId,status:c.Status||"Unknown"})),error:"Command timed out waiting for all instances to complete"}}}function Ko(e){return`/etc/ts-cloud/${e}-upgrade.env`}function jo(e){return`${e}-upgrade`}function Ji(e){if(!e||e.length===0)return[];let t=["mkdir -p /etc/ts-cloud"],r=[];for(let n of e){if(n.enabled===!1)continue;if(!n.service||!n.binary)continue;let{service:s,binary:i,command:o="upgrade",channel:a="stable",schedule:c="daily",randomizedDelay:l="4h",args:u=[]}=n,d=jo(s),m=Ko(s),f=[`--path ${i}`,`--service ${s}`,...a==="canary"?["--canary"]:[],...u].join(" ");t.push(`if [ ! -f ${m} ]; then`,` cat > ${m} <<'TS_CLOUD_APPUPD_ENV_EOF'`,"# Set to false to pause automatic updates without disabling the timer.","ENABLED=true","# Extra flags appended to the update command.","ARGS=","TS_CLOUD_APPUPD_ENV_EOF","fi",`chmod 644 ${m}`,`cat > /etc/systemd/system/${d}.service <<'TS_CLOUD_APPUPD_SVC_EOF'`,"[Unit]",`Description=Check for and install ${s} updates`,"After=network-online.target","Wants=network-online.target","","[Service]","Type=oneshot",`EnvironmentFile=-${m}`,`ExecStart=/bin/sh -c 'if [ "\${ENABLED:-true}" != "true" ]; then echo "auto-update disabled via ${m}"; exit 0; fi; exec ${i} ${o} ${f} $ARGS'`,"TS_CLOUD_APPUPD_SVC_EOF",`cat > /etc/systemd/system/${d}.timer <<'TS_CLOUD_APPUPD_TMR_EOF'`,"[Unit]",`Description=Scheduled ${s} update check`,"","[Timer]",`OnCalendar=${c}`,`RandomizedDelaySec=${l}`,"Persistent=true","","[Install]","WantedBy=timers.target","TS_CLOUD_APPUPD_TMR_EOF"),r.push(`systemctl enable --now ${d}.timer`)}if(r.length===0)return[];return[...t,"systemctl daemon-reload",...r]}function he(e=!0){if(!e)return[];return["export DEBIAN_FRONTEND=noninteractive","dpkg-query -W -f='${Status}' unattended-upgrades 2>/dev/null | grep -q 'ok installed' || apt-get install -y unattended-upgrades","cat > /etc/apt/apt.conf.d/20auto-upgrades <<'TS_CLOUD_AUTOUPD_EOF'",'APT::Periodic::Update-Package-Lists "1";','APT::Periodic::Unattended-Upgrade "1";','APT::Periodic::Download-Upgradeable-Packages "1";','APT::Periodic::AutocleanInterval "7";',"TS_CLOUD_AUTOUPD_EOF","systemctl enable --now unattended-upgrades 2>/dev/null || true"]}var En=[["nginx",80],["https",443],["phpFpm",9074],["mysql",3306],["postgres",5432],["redis",6379],["meilisearch",7700],["typesense",8108],["smtp",25]];function Wo(e=!0){let t=typeof e==="object"?e:{},r=typeof e==="boolean"?e:e.enabled!==!1,n=Number(t.alerts?.bandwidthTb??0);return{enabled:r,cpuLoadPerCore:t.alerts?.cpuLoadPerCore??2,memPercent:t.alerts?.memPercent??90,diskPercent:t.alerts?.diskPercent??90,bandwidthTb:Number.isFinite(n)&&n>0?n:0,bandwidthPercent:t.alerts?.bandwidthPercent??80}}function ye(e=!0){let{enabled:t,cpuLoadPerCore:r,memPercent:n,diskPercent:s,bandwidthTb:i,bandwidthPercent:o}=Wo(e);if(!t)return[];let a=Math.round(i*1000000000000),c=En.map(([u,d])=>`SVC_${u.toUpperCase()}=$(probe ${d})`),l=En.map(([u])=>`"${u}":"$SVC_${u.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
10
10
  $(free -m | awk '/^Mem:/{total=$2; used=$3} /^Swap:/{print total, used, $2, $3}')
11
11
  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; }",...c,"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":${a}},"services":{`+l+"}}","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=${r} 'BEGIN{exit !(c>0 && l/c > t)}'; then ALERTS="$ALERTS load=$LOAD/${r}xCPU"; fi`,`if [ "\${MEM_PCT:-0}" -ge ${n} ]; then ALERTS="$ALERTS mem=\${MEM_PCT}%"; fi`,`if [ "\${DISK_PCT:-0}" -ge ${s} ]; 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",...a>0?["BW_TOTAL=$(( MONTH_RX + MONTH_TX ))",`BW_PCT=$(( BW_TOTAL * 100 / ${a} ))`,"BW_PREV=$(cat /var/lib/ts-cloud/bandwidth-alert-state 2>/dev/null || echo ok)",`if [ "$BW_PCT" -ge ${o} ]; 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 ${i} 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 Go={"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"},Vo="127.0.0.1:9074";function On(e){return Vo}function qo(e={}){let t=e.versions?.length?e.versions:["8.3"];return e.default&&t.includes(e.default)?e.default:t[0]}function Xo(e={}){return{...e.optimizeForProduction===!1?{}:{...Go},...e.ini||{}}}function Yo(e={}){let t=Xo(e),r=Object.keys(t);if(r.length===0)return[];let n=r.map((i)=>`${i}=${t[i]}`),s="ts-cloud-managed";return[St(),"TS_CLOUD_SCAN_DIR=$(php -i 2>/dev/null | awk -F' => ' '/^Scan this dir for additional .ini files/{print $2}' | head -1)",`TS_CLOUD_LOADED_INI=$(php -r 'echo php_ini_loaded_file() ?: "";' 2>/dev/null)`,'if [ -n "$TS_CLOUD_SCAN_DIR" ] && [ "$TS_CLOUD_SCAN_DIR" != "(none)" ]; then',' mkdir -p "$TS_CLOUD_SCAN_DIR"',' TS_CLOUD_PHP_INI="$TS_CLOUD_SCAN_DIR/zz-ts-cloud.ini"',` cat > "$TS_CLOUD_PHP_INI" <<'TS_CLOUD_PHPINI_EOF'`,`; ${s} — production PHP tuning`,...n,"TS_CLOUD_PHPINI_EOF","else",' if [ -z "$TS_CLOUD_LOADED_INI" ]; then'," TS_CLOUD_INI_DIR=$(php -i 2>/dev/null | awk -F' => ' '/^Configuration File \\(php.ini\\) Path/{print $2}' | head -1)",' TS_CLOUD_LOADED_INI="$TS_CLOUD_INI_DIR/php.ini"',' mkdir -p "$TS_CLOUD_INI_DIR"',' touch "$TS_CLOUD_LOADED_INI"'," fi",` sed -i '/; ${s} BEGIN/,/; ${s} END/d' "$TS_CLOUD_LOADED_INI"`,` cat >> "$TS_CLOUD_LOADED_INI" <<'TS_CLOUD_PHPINI_EOF'`,`; ${s} BEGIN`,...n,`; ${s} END`,"TS_CLOUD_PHPINI_EOF","fi",`(cd ${U} && pantry restart php-fpm) 2>/dev/null || true`]}function Ct(e={}){let t=qo(e),r=e.installNginx!==!1,n=e.installComposer!==!1,s=[`php.net@${t}`];if(n)s.push("getcomposer.org");if(r)s.push("nginx.org");return[...et(s),...No(["php-fpm"]),...Yo(e)]}function nr(e,t){if(!e)return[];let r=[];if(e.template&&t?.[e.template])r.push(...t[e.template]);if(e.serverSnippet)r.push(...e.serverSnippet);return r}function Jo(e){if(!e)return"";let t=typeof e==="object"?e:{},n=[`max-age=${t.maxAge??31536000}`];if(t.includeSubDomains??!0)n.push("includeSubDomains");if(t.preload)n.push("preload");return` add_header Strict-Transport-Security "${n.join("; ")}" always;`}function Qo(e){if(!e||!e.allow?.length&&!e.deny?.length)return[];let t=[];for(let r of e.deny||[])t.push(` deny ${r};`);if(e.allow?.length){for(let r of e.allow)t.push(` allow ${r};`);t.push(" deny all;")}return t}function Dn(e){return`/etc/nginx/.htpasswd-${e}`}var Zo=new Set(["laravel","php","statamic","wordpress"]);function ea(e){return Zo.has(e)}function ta(e){return e==="laravel"||e==="statamic"?"public":""}function ra(e,t){let r=e.replace(/\/+$/,""),n=t.replace(/^\/+|\/+$/g,"");return n?`${r}/${n}`:r}function na(e){let t=e.type??"laravel",r=e.webDirectory??ta(t),n=ra(e.appDir,r),s=ea(t),i=e.phpVersion??"8.3",o=[` root ${n};`,"",' add_header X-Frame-Options "SAMEORIGIN";',' add_header X-Content-Type-Options "nosniff";'],a=Jo(e.hsts);if(a)o.push(a);for(let c of Qo(e.security))o.push(c);if(o.push("",` index ${s?"index.php index.html":"index.html index.htm"};`,""," charset utf-8;",""),e.clientMaxBodySize)o.push(` client_max_body_size ${e.clientMaxBodySize};`,"");if(e.auth)o.push(` auth_basic "${e.auth.realm||"Restricted"}";`,` auth_basic_user_file ${Dn(e.siteName)};`,"");for(let[c,l]of Object.entries(e.redirects||{}))o.push(` location = ${c} { return 301 ${l}; }`);if(Object.keys(e.redirects||{}).length>0)o.push("");if(s){if(o.push(" location / {"," try_files $uri $uri/ /index.php?$query_string;"," }",""," location = /favicon.ico { access_log off; log_not_found off; }"," location = /robots.txt { access_log off; log_not_found off; }",""," error_page 404 /index.php;",""," location ~ \\.php$ {",` fastcgi_pass ${e.fastcgiPass??On(i)};`," fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;"," include fastcgi_params;"," }",""," location ~ /\\.(?!well-known).* {"," deny all;"," }"),t==="wordpress")o.push(""," location = /xmlrpc.php { deny all; }"," location ~* /(?:wp-config\\.php|readme\\.html|license\\.txt)$ { deny all; }"," location ~* /wp-content/uploads/.*\\.php$ { deny all; }")}else if(t==="spa")o.push(" location / {"," try_files $uri $uri/ /index.html;"," }");else o.push(" location / {"," try_files $uri $uri/ =404;"," }");if(e.serverSnippet&&e.serverSnippet.length>0){o.push("");for(let c of e.serverSnippet)o.push(c?` ${c}`:"")}return o}function sa(e){let t=[e.domain,...e.aliases||[]].filter(Boolean);for(let i of t)if(!/^(?=.{1,253}$)(?:\*\.)?[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i.test(i.trim()))throw Error(`Refusing to build a vhost: '${i}' is not a valid hostname.`);if(!t.length)throw Error("Refusing to build a vhost: no server_name (domain) was given.");let r=t.join(" "),n=na(e);if(e.ssl){let i=["server {"," listen 80;"," listen [::]:80;",` server_name ${r};`," return 301 https://$host$request_uri;","}"],o=["server {"," listen 443 ssl;"," listen [::]:443 ssl;",` server_name ${r};`,` ssl_certificate ${e.ssl.certPath};`,` ssl_certificate_key ${e.ssl.keyPath};`,...e.tlsProtocols?.length?[` ssl_protocols ${e.tlsProtocols.join(" ")};`]:[],"",...n,"}"];return`${[...i,"",...o].join(`
12
12
  `)}
@@ -139,7 +139,7 @@ writeFileSync(candidatePath, JSON.stringify(candidate, null, 2) + '\\n', { mode:
139
139
  `),y=["[Unit]",`Description=Issue/renew rpx gateway TLS certs for ${m} (tlsx http-01)`,`After=network-online.target ${ce}`,"Wants=network-online.target","","[Service]","Type=oneshot",`ExecStart=${f}`].join(`
140
140
  `),S=["[Unit]",`Description=Daily rpx gateway TLS cert issuance/renewal for ${m}`,"","[Timer]","OnCalendar=*-*-* 03:30:00","RandomizedDelaySec=1h","Persistent=true","","[Install]","WantedBy=timers.target"].join(`
141
141
  `);return[`mkdir -p ${n}`,...e.tenant?[]:[`(cd ${G} && ${i} add @stacksjs/tlsx@${o}) || true`],...Ue(f,_,"TS_CLOUD_RENEW_EOF"),`chmod +x ${f}`,...Ue(`/etc/systemd/system/${h}`,y,"TS_CLOUD_RENEW_SVC_EOF"),...Ue(`/etc/systemd/system/${x}`,S,"TS_CLOUD_RENEW_TIMER_EOF"),"systemctl daemon-reload",`systemctl enable --now ${x} || true`,`${f} || true`]}function le(e){let{config:t,proxy:r}=e,n=e.bunBin??"/usr/local/bin/bun",s=r.version??"latest",i=t.productionCerts.certsDir,o=(e.slug||"app").replace(/[^a-z0-9._-]+/gi,"-"),a=JSON.stringify({slug:o,...t},null,2),c=va(Y,i);if(e.tenant)return["set -euo pipefail",`if [ ! -x ${Ne} ] || [ ! -d ${G}/node_modules/@stacksjs/rpx ]; then`,` echo "ts-cloud: no rpx gateway on this box. This project attaches to another project's compute, so it does not provision one - deploy the owning project first." >&2`," exit 1","fi",`mkdir -p ${Y} ${i}`,`__tsc_rpx_before="$(sha256sum ${Y}/${o}.json 2>/dev/null | cut -d' ' -f1 || true)"`,...hr(`${Y}/${o}.json`,a,"TS_CLOUD_RPX_FRAGMENT_EOF",{bunBin:n,preserveManagementDashboardRoutes:e.preserveManagementDashboardRoutes}),`__tsc_rpx_after="$(sha256sum ${Y}/${o}.json 2>/dev/null | cut -d' ' -f1 || true)"`,`if [ "$__tsc_rpx_before" != "$__tsc_rpx_after" ] || ! systemctl is-active --quiet ${ce}; then`,` systemctl restart ${ce}`,"else",` echo "[ts-cloud] rpx routes for ${o} unchanged - leaving the shared gateway alone"`,"fi",...An(e)];let u=[`Environment=RPX_UPSTREAM_TIMEOUT=${r.upstreamTimeout??60}`];if(typeof r.maxUpstreamConns==="number")u.push(`Environment=RPX_MAX_UPSTREAM_CONNS=${r.maxUpstreamConns}`);let d=e.profile==="raspberry-pi"?_a:wa,m=r.memoryHigh??d.high,f=r.memoryMax??d.max;return["set -euo pipefail",`mkdir -p ${ot} ${Y} ${i} ${G}`,`rm -rf ${G}.next ${G}.prev`,`mkdir -p ${G}.next`,`(cd ${G}.next && ${n} add @stacksjs/rpx@${s})`,`mv ${G} ${G}.prev`,`mv ${G}.next ${G}`,`rm -rf ${G}.prev`,`ln -sfn ${G}/node_modules ${ot}/node_modules`,...hr(`${Y}/${o}.json`,a,"TS_CLOUD_RPX_FRAGMENT_EOF",{bunBin:n,preserveManagementDashboardRoutes:e.preserveManagementDashboardRoutes}),...Ue(cr,c,"TS_CLOUD_RPX_EOF"),`${n} build --production --compile --outfile ${Ne}.next ${cr}`,`chmod 0755 ${Ne}.next`,`mv -f ${Ne}.next ${Ne}`,...Ue(`/etc/systemd/system/${ce}`,["[Unit]","Description=rpx reverse-proxy gateway (managed by ts-cloud)","After=network.target network-online.target","Wants=network-online.target","","[Service]","Type=simple",`ExecStart=${Ne}`,`WorkingDirectory=${G}`,"Environment=BUN_INSTALL=/root/.bun","Environment=APP_ENV=production","Environment=NODE_ENV=production",...u,"MemoryAccounting=true",`MemoryHigh=${m}`,`MemoryMax=${f}`,"CPUWeight=500","IOWeight=500","OOMPolicy=stop","Restart=always","RestartSec=5","StartLimitIntervalSec=120","StartLimitBurst=5",`ExecStartPre=/bin/sh -c 'for p in 80 443; do fuser -k -n tcp "$p" 2>/dev/null || true; done; sleep 1'`,"LimitNOFILE=1048576","AmbientCapabilities=CAP_NET_BIND_SERVICE","","[Install]","WantedBy=multi-user.target"].join(`
142
- `),"TS_CLOUD_RPX_UNIT_EOF"),"systemctl daemon-reload","systemctl disable --now bun-gateway.service 2>/dev/null || true","systemctl disable --now bun-gateway-renew.timer bun-gateway-renew.service 2>/dev/null || true","rm -f /etc/systemd/system/bun-gateway-renew.timer /etc/systemd/system/bun-gateway-renew.service","systemctl disable --now ts-cloud-nginx.service 2>/dev/null || true",`for timer in /etc/systemd/system/rpx-cert-renew-*.timer; do [ -e "$timer" ] || continue; unit="$(basename "$timer")"; tenant="\${unit#rpx-cert-renew-}"; tenant="\${tenant%.timer}"; [ -f "${Y}/$tenant.json" ] && continue; systemctl disable --now "$unit" 2>/dev/null || true; rm -f "$timer" "/etc/systemd/system/rpx-cert-renew-$tenant.service" "${ot}/renew-certs-$tenant.sh"; done`,`systemctl enable ${ce}`,`systemctl restart ${ce}`,...An(e)]}function qe(e){let t=(e.slug||"app").replace(/[^a-z0-9._-]+/gi,"-"),r=JSON.stringify({slug:t,...e.config},null,2);return["set -euo pipefail",`mkdir -p ${Y}`,...hr(`${Y}/${t}.json`,r,"TS_CLOUD_RPX_FRAGMENT_EOF",{bunBin:"/usr/local/bin/bun",preserveManagementDashboardRoutes:e.preserveManagementDashboardRoutes}),`systemctl restart ${ce}`]}function Fe(e=[],t={}){let r=t.path??"/root/.ssh/authorized_keys",s=[`mkdir -p ${r.replace(/\/[^/]*$/,"")}`,`touch ${r}`,`sed -i '/^${Mn("# >>> ts-cloud managed keys >>>")}$/,/^${Mn("# <<< ts-cloud managed keys <<<")}$/d' ${r}`];if(e.length>0){let i=["# >>> ts-cloud managed keys >>>",...e.map((o)=>`${o.publicKey.trim()} ${o.name}`),"# <<< ts-cloud managed keys <<<"].join(`
142
+ `),"TS_CLOUD_RPX_UNIT_EOF"),"systemctl daemon-reload","systemctl disable --now bun-gateway.service 2>/dev/null || true","systemctl disable --now bun-gateway-renew.timer bun-gateway-renew.service 2>/dev/null || true","rm -f /etc/systemd/system/bun-gateway-renew.timer /etc/systemd/system/bun-gateway-renew.service","systemctl disable --now ts-cloud-nginx.service 2>/dev/null || true",`for timer in /etc/systemd/system/rpx-cert-renew-*.timer; do [ -e "$timer" ] || continue; unit="$(basename "$timer")"; tenant="\${unit#rpx-cert-renew-}"; tenant="\${tenant%.timer}"; [ -f "${Y}/$tenant.json" ] && continue; systemctl disable --now "$unit" 2>/dev/null || true; rm -f "$timer" "/etc/systemd/system/rpx-cert-renew-$tenant.service" "${ot}/renew-certs-$tenant.sh"; done`,`systemctl enable ${ce}`,`systemctl restart ${ce}`,...An(e)]}function Ge(e){let t=(e.slug||"app").replace(/[^a-z0-9._-]+/gi,"-"),r=JSON.stringify({slug:t,...e.config},null,2);return["set -euo pipefail",`mkdir -p ${Y}`,...hr(`${Y}/${t}.json`,r,"TS_CLOUD_RPX_FRAGMENT_EOF",{bunBin:"/usr/local/bin/bun",preserveManagementDashboardRoutes:e.preserveManagementDashboardRoutes}),`systemctl restart ${ce}`]}function Fe(e=[],t={}){let r=t.path??"/root/.ssh/authorized_keys",s=[`mkdir -p ${r.replace(/\/[^/]*$/,"")}`,`touch ${r}`,`sed -i '/^${Mn("# >>> ts-cloud managed keys >>>")}$/,/^${Mn("# <<< ts-cloud managed keys <<<")}$/d' ${r}`];if(e.length>0){let i=["# >>> ts-cloud managed keys >>>",...e.map((o)=>`${o.publicKey.trim()} ${o.name}`),"# <<< ts-cloud managed keys <<<"].join(`
143
143
  `);s.push(`cat >> ${r} <<'TS_CLOUD_KEYS_EOF'`,i,"TS_CLOUD_KEYS_EOF",`chmod 600 ${r}`)}return s}function Mn(e){return e.replace(/[.*[\]\\/^$]/g,"\\$&")}function zn(e,t){let r=`/tmp/ts-cloud-${e}.sh`,n=`TS_CLOUD_${e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}_EOF`;return[`cat > ${r} <<'${n}'`,t.replace(/\n$/,""),n,`chmod +x ${r}`,`bash ${r} || echo "ts-cloud: ${e} setup did not complete; continuing" >&2`,`rm -f ${r}`]}function Bn(e,t){if(e===!1)return;if(e===!0||e===void 0)return t;return e}var Fn={enabled:!0,ports:[80,443]},Ta={mode:"detection",paranoiaLevel:1};function $a(e=!0,t=[]){let r=Bn(e,Fn);if(!r||r.enabled===!1)return[];let n=[...new Set([...r.ports??Fn.ports??[],...t])].sort((s,i)=>s-i);return zn("ddos",Cr({...r,ports:n}))}function Ca(e=!0){let t=Bn(e,Ta);if(!t||t.mode==="off")return[];return zn("waf",ps(t))}function Kn(e={},t=[]){return[...$a(e.ddos,t),...Ca(e.waf)]}function Pa(e){return`${e}-sftp`}function jn(e){return e.port??2222}function xa(e){let t=e.sftp.storage;if(t?.type==="efs"&&t.path)return t.path;return`/var/sftp/${e.slug}`}function ze(e){return`'${e.split("'").join("'\\''")}'`}function Wn(e,t){if(t==="aws")return;let r=e.storage;if(r?.type==="s3"||!r&&!!e.bucket)throw Error(`sftp: bucket-backed storage is only available on the aws provider (Transfer Family). On ${t}, use storage: { type: 'efs' } to serve a directory on the server.`);for(let[s,i]of Object.entries(e.users))if(!i.sshPublicKeys?.length)throw Error(`sftp: user ${s} needs at least one SSH public key`)}function Gn(e){let{slug:t,sftp:r}=e,n=Pa(t),s=xa(e),i=jn(r),o="/etc/ts-sftp/host_key",a="/etc/ts-sftp/users",c=r.serviceUser??"ts-sftp",l=[`# --- ts-sftp (${n}) ---`,`id -u ${c} >/dev/null 2>&1 || useradd --system --home-dir ${ze(s)} --shell /usr/sbin/nologin ${c}`,'export HOME="${HOME:-/root}"','command -v bun >/dev/null 2>&1 || (curl -fsSL https://bun.sh/install | bash && ln -sf "$HOME/.bun/bin/bun" /usr/local/bin/bun)',`mkdir -p ${ze(s)} /etc/ts-sftp /etc/ts-sftp/users /opt/ts-sftp`,"chmod 750 /etc/ts-sftp",`cd /opt/ts-sftp && [ -f package.json ] || printf '{"name":"ts-sftp-host","private":true}' > package.json`,`cd /opt/ts-sftp && bun add ts-sftp@${r.version??"latest"} --no-save --production || bun add ts-sftp@${r.version??"latest"}`,`[ -f /etc/ts-sftp/host_key ] || bun /opt/ts-sftp/node_modules/ts-sftp/dist/bin/cli.js keygen --out /etc/ts-sftp/host_key --comment ${ze(`${t}-sftp`)}`,"chmod 600 /etc/ts-sftp/host_key",'BUN_REAL=$(readlink -f "$(command -v bun)")','case "$BUN_REAL" in /root/*) install -m 0755 "$BUN_REAL" /usr/local/bin/ts-sftp-bun; BUN_BIN=/usr/local/bin/ts-sftp-bun;; *) BUN_BIN="$BUN_REAL";; esac'],u=[];for(let[d,m]of Object.entries(r.users)){let f=(m.homeDirectory??d).replace(/^\/+|\/+$/g,"");if(!f||f.split("/").includes(".."))throw Error(`sftp: invalid homeDirectory for user ${d}`);let h=`/etc/ts-sftp/users/${d}.pub`;l.push(`mkdir -p ${ze(`${s}/${f}`)}`,`printf '%s\\n' ${ze(m.sshPublicKeys.join(`
144
144
  `))} > ${h}`,`chmod 644 ${h}`),u.push(`--user ${d}:${h}`)}return l.push(`chown -R ${c}:${c} ${ze(s)} /etc/ts-sftp`,`cat > /etc/systemd/system/${n}.service <<TSCLOUD_SFTP_UNIT`,"[Unit]","Description=ts-sftp file transfer server","After=network.target","","[Service]",`User=${c}`,`ExecStart=$BUN_BIN /opt/ts-sftp/node_modules/ts-sftp/dist/bin/cli.js serve --root ${s} --host-key /etc/ts-sftp/host_key --port ${i}${r.readOnly?" --read-only":""} ${u.join(" ")}`,"Restart=always","RestartSec=2","NoNewPrivileges=true","PrivateTmp=true","ProtectSystem=strict",`ReadWritePaths=${s}`,"","[Install]","WantedBy=multi-user.target","TSCLOUD_SFTP_UNIT","systemctl daemon-reload",`systemctl enable ${n}.service`,`systemctl restart ${n}.service`),l}function Vn(e){return e?[jn(e)]:[]}var Ra=[80,443];function xt(e={}){if(e.enabled===!1)return[];let t=[...new Set([...Ra,...e.allowedPorts||[]])].filter((n)=>Number.isInteger(n)&&n>=1&&n<=65535).sort((n,s)=>n-s),r=["export DEBIAN_FRONTEND=noninteractive","command -v ufw >/dev/null 2>&1 || apt-get install -y ufw","ufw --force reset","ufw default deny incoming","ufw default allow outgoing","ufw allow OpenSSH"];for(let n of t)r.push(`ufw allow ${n}/tcp`);return r.push("ufw --force enable"),r}function Re(e,t){let r=e.infrastructure?.compute??{},n=r.runtime==="php"||!!r.php,s=ki(e,{environment:t?.environment}),i=n||!!r.managedServices,o=i?Ir():[],a=!Z(r),c=n?[...o,...Ct({versions:r.php?.versions,default:r.php?.default,extensions:r.php?.extensions,installNginx:a,optimizeForProduction:r.php?.optimizeForProduction,ini:r.php?.ini}),...a?ir():[]]:void 0,l=[],u=w(e);if(!n&&i)l.push(...o);if(l.push(...He(e.notifications)),r.managedServices)l.push(..._o(r.managedServices,{mail:s.enabled?s:void 0}),...vt(u,r.managedServices));let d=e.infrastructure?.sftp;if(d)Wn(d,F(e)),l.push(...Gn({slug:e.project.slug,sftp:d}));let m=r.firewall??(n?{enabled:!0}:{enabled:!1}),f=aa(s);if(l.push(...xt(f.length>0?{...m,allowedPorts:[...m.allowedPorts??[],...f]}:m)),l.push(...Kn({ddos:r.ddos,waf:r.waf},[...r.firewall?.allowedPorts??[],...f])),l.push(...he(r.autoUpdates??n)),l.push(...Ji(r.appUpdates)),l.push(...ye(r.monitoring??n)),l.push(...Fe(r.sshKeys,{path:t?.authorizedKeysPath})),r.backups?.enabled)l.push(...Oo({database:u,backups:r.backups}));return{runtime:r.runtime||"bun",runtimeVersion:r.runtimeVersion||"latest",phpBox:n,phpProvision:c,servicesProvision:l.length>0?l:void 0}}function ee(e={}){let{runtime:t="bun",runtimeVersion:r="latest",systemPackages:n=[],database:s,phpProvision:i,servicesProvision:o,caddyfile:a,rpxProvision:c,baked:l=!1,swapGb:u=2}=e,d=new Set(n);if(s==="sqlite")d.add("sqlite3");else if(s==="mysql")d.add("mysql-client");else if(s==="postgres")d.add("postgresql-client");let m=`#!/bin/bash
145
145
  set -euo pipefail
@@ -251,15 +251,15 @@ ${h.join(`
251
251
  `)}
252
252
  `}return m+=`
253
253
  echo "ts-cloud bootstrap complete — instance is ready for site deploys"
254
- `,m}var qn="/aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id";function Xn(e){let t=[{port:22,protocol:"tcp",cidr:"0.0.0.0/0"},{port:80,protocol:"tcp",cidr:"0.0.0.0/0"},{port:443,protocol:"tcp",cidr:"0.0.0.0/0"}],r=new Set;for(let n of Object.values(e.sites||{}))if(n&&typeof n.port==="number"&&![22,80,443].includes(n.port))r.add(n.port);for(let n of r)t.push({port:n,protocol:"tcp",cidr:"0.0.0.0/0"});return t}function Yn(e){let t=e.infrastructure?.compute??{},r=Re(e),n=t.proxy?.engine==="rpx"?le({proxy:t.proxy,config:Se(e.sites??{},{proxy:t.proxy,slug:e.project.slug}),slug:e.project.slug,bunBin:t.runtime==="node"||t.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0;return ee({runtime:r.runtime,runtimeVersion:r.runtimeVersion,systemPackages:t.systemPackages,database:e.infrastructure?.database,phpProvision:r.phpProvision,servicesProvision:r.servicesProvision,rpxProvision:n,baked:t.bakedImage===!0,swapGb:t.swapGb})}function Jn(e){return Buffer.from(e,"utf8").toString("base64")}function Qn(e){return e.infrastructure?.compute?.image??null}function Rt(e,t){return`${e}-${t}-app-sg`}function _r(e,t,r="app"){return[{Key:"Project",Value:e},{Key:"Environment",Value:t},{Key:"Role",Value:r},{Key:"ManagedBy",Value:"ts-cloud"}]}function Ea(e,t,r){if(!e?.length)return!1;let n=(s)=>e.find((i)=>i.Key===s)?.Value;return n("Project")===t&&n("Environment")===r}function Zn(e,t){let r=Rt(t.slug,t.environment);return e.find((n)=>{if(n.GroupName!==r)return!1;if(t.vpcId&&n.VpcId&&n.VpcId!==t.vpcId)return!1;if(!!n.Tags?.some((i)=>i.Key==="Project"))return Ea(n.Tags,t.slug,t.environment);return!!t.vpcId&&n.VpcId===t.vpcId})}function Da(e){try{let t=es(Oa(process.cwd(),"storage/cloud/state",`${e}.json`),"utf8"),r=JSON.parse(t);return typeof r.instanceId==="string"&&r.instanceId.length>0?r.instanceId:null}catch{return null}}class Et{name="aws";usesCloudFormation=!0;region;ec2Client;cfnClient;constructor(e={}){this.region=e.region||"us-east-1",this.ec2Client=e.ec2Client??((t)=>new Q(t)),this.cfnClient=e.cfnClient??((t)=>new v(t))}resolveRegion(e){return e.project.region||this.region}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e,n=this.resolveRegion(t),s=t.project.slug,i=t.infrastructure?.compute;if(!i)throw Error("infrastructure.compute is required to provision AWS compute");let o=this.ec2Client(n),a=await this.findComputeTargets({slug:s,environment:r,role:"app",region:n});if(a.length>0){let E=a[0];return{appInstanceId:E.id,appPublicIp:E.publicIp,appPublicIpv6:E.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}let c=Qn(t);if(!c){if(c=(await new Ge(n).getParameter({Name:qn})).Parameter?.Value??null,!c)throw Error("Could not resolve the Ubuntu 24.04 AMI from SSM")}let l=await o.describeVpcs(),u=(l.Vpcs||[]).find((E)=>E.IsDefault)||(l.Vpcs||[])[0];if(!u?.VpcId)throw Error("No VPC found to launch the instance into");let d=(await o.describeSubnets({Filters:[{Name:"vpc-id",Values:[u.VpcId]}]})).Subnets||[],m=d.find((E)=>E.MapPublicIpOnLaunch)||d[0],f=m?.SubnetId;if(!m?.MapPublicIpOnLaunch)console.warn("ts-cloud: no public subnet found; the instance may not get a public IP (deploys/SSL need one).");let h=Rt(s,r),_=(await o.describeSecurityGroups({Filters:[{Name:"group-name",Values:[h]},{Name:"vpc-id",Values:[u.VpcId]}]})).SecurityGroups?.[0]?.GroupId;if(!_)_=(await o.createSecurityGroup({GroupName:h,Description:`ts-cloud ${s}/${r} app`,VpcId:u.VpcId,TagSpecifications:[{ResourceType:"security-group",Tags:_r(s,r)}]})).GroupId;let y=Xn(t);await o.authorizeSecurityGroupIngress({GroupId:_,IpPermissions:y.map((E)=>({IpProtocol:E.protocol,FromPort:E.port,ToPort:E.port,IpRanges:[{CidrIp:E.cidr}]}))}).catch((E)=>{if(!/InvalidPermission\.Duplicate/.test(E instanceof Error?E.message:""))throw E});let S=Jn(Yn(t)),R=i.server?.instanceType||"t3.small",I=(await o.runInstances({ImageId:c,InstanceType:R,MinCount:1,MaxCount:1,SecurityGroupIds:_?[_]:void 0,SubnetId:f,UserData:S,IamInstanceProfile:i.server?.iamInstanceProfile?{Name:i.server.iamInstanceProfile}:void 0,TagSpecifications:[{ResourceType:"instance",Tags:[{Key:"Name",Value:`${s}-${r}-app`},..._r(s,r)]}]})).Instances?.[0]?.InstanceId;if(!I)throw Error("RunInstances did not return an instance id");let C=await o.waitForInstanceState(I,"running");if(!C)throw Error(`Instance ${I} did not reach 'running' before timeout`);return{appInstanceId:I,appPublicIp:C.PublicIpAddress,appPublicIpv6:ue(C.Ipv6Address),sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}async destroyCompute(e){let{config:t,environment:r}=e,n=t.project.slug,s=this.resolveRegion(t),i=this.ec2Client(s),o=[],c=(await this.findComputeTargets({slug:n,environment:r,role:"app",region:s})).map((h)=>h.id),l;if(c.length>0)l=(await i.describeInstances({InstanceIds:c}).catch(()=>({Reservations:[]}))).Reservations?.flatMap((x)=>x.Instances??[]).find((x)=>x.VpcId)?.VpcId;if(c.length>0)await i.terminateInstances(c),o.push(...c.map((h)=>`instance ${h}`)),await Promise.all(c.map((h)=>i.waitForInstanceState(h,"terminated").catch(()=>{return})));let u=Rt(n,r),d=[{Name:"group-name",Values:[u]}];if(l)d.push({Name:"vpc-id",Values:[l]});let m=await i.describeSecurityGroups({Filters:d}).catch(()=>({SecurityGroups:[]})),f=Zn(m.SecurityGroups??[],{slug:n,environment:r,vpcId:l});if(f?.GroupId)for(let h=0;h<10;h++)try{await i.deleteSecurityGroup(f.GroupId),o.push(`security group ${u}`);break}catch{await new Promise((x)=>setTimeout(x,3000))}return{destroyed:o}}async getComputeOutputs(e){let t=this.resolveRegion(e.config),r=T(e.config,e.environment),n=this.cfnClient(t);try{let s=await n.getStackOutputs(r);return{deployBucketName:s.deployBucketName,appInstanceId:s.appInstanceId,appPublicIp:s.appPublicIp,sshUser:"ec2-user"}}catch(s){if(!/does not exist|ValidationError/i.test(s instanceof Error?s.message:""))throw s;let o=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",region:t}))[0];return{appInstanceId:o?.id,appPublicIp:o?.publicIp,appPublicIpv6:o?.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}}async uploadRelease(e){let t=this.resolveRegion(e.config),n=(await this.getComputeOutputs({config:e.config,environment:e.environment})).deployBucketName;if(!n)throw Error("No deployBucketName in stack outputs. Re-deploy infrastructure to add the staging bucket.");return await new g(t).putObject({bucket:n,key:e.remoteKey,body:es(e.localPath),contentType:"application/gzip"}),{artifactRef:`s3://${n}/${e.remoteKey}`}}async findComputeTargets(e){let t=e.region??this.region,r=this.ec2Client(t),n=[{Name:"tag:Project",Values:[e.slug]},{Name:"tag:Environment",Values:[e.environment]},{Name:"tag:Role",Values:[e.role||"app"]},{Name:"instance-state-name",Values:["running","pending"]}],s=await r.describeInstances({Filters:n}),i=this.reservationsToTargets(s.Reservations);if(i.length>0||(e.role||"app")!=="app")return i;let o=e.stackName??`${e.slug}-${e.environment}`,a=Da(o);if(!a)try{a=(await this.cfnClient(t).getStackOutputs(o)).appInstanceId??null}catch{a=null}if(!a)return[];try{let c=await r.describeInstances({InstanceIds:[a],Filters:[{Name:"instance-state-name",Values:["running","pending"]}]});return this.reservationsToTargets(c.Reservations)}catch{return[]}}reservationsToTargets(e){let t=[];for(let r of e||[])for(let n of r.Instances||[]){if(!n.InstanceId)continue;let s=n.Tags?.find((i)=>i.Key==="Name")?.Value;t.push({id:n.InstanceId,name:s,publicIp:n.PublicIpAddress,publicIpv6:ue(n.Ipv6Address),privateIp:n.PrivateIpAddress,status:n.State?.Name})}return t}bashWrap(e){return["bash <<'TS_CLOUD_BASH_EOF'",e.join(`
255
- `),"TS_CLOUD_BASH_EOF"]}async runRemoteDeploy(e){let t=this.region,r=new Ge(t);if(e.targets.length>0){let s=await r.sendCommand({InstanceIds:e.targets.map((i)=>i.id),DocumentName:"AWS-RunShellScript",Parameters:{commands:this.bashWrap(e.commands)},TimeoutSeconds:e.timeoutSeconds||600,Comment:e.comment});if(!s.CommandId)return{success:!1,instanceCount:0,perInstance:[],error:"Failed to send SSM command"};return this.pollSsmCommand(r,s.CommandId,e.targets.length,((e.timeoutSeconds||600)+30)*1000)}if(!e.tags||Object.keys(e.tags).length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets or tags provided for AWS deploy"};let n=await r.sendCommandByTags({tags:e.tags,commands:this.bashWrap(e.commands),timeoutSeconds:e.timeoutSeconds||600,comment:e.comment});return{success:n.success,instanceCount:n.instanceCount,perInstance:n.perInstance.map((s)=>({instanceId:s.instanceId,status:s.status,output:s.output,error:s.error})),error:n.error}}async pollSsmCommand(e,t,r,n=600000){let i=Date.now(),o=new Set(["Success","Failed","Cancelled","TimedOut"]),a=[];while(Date.now()-i<n){await new Promise((u)=>setTimeout(u,3000));try{if(a=await e.listCommandInvocations({CommandId:t,Details:!0}),a.length>=r&&a.every((d)=>o.has(d.Status||"")))break}catch{}}let c=a.map((u)=>({instanceId:u.InstanceId,status:u.Status||"Unknown",output:u.StandardOutputContent,error:u.StandardErrorContent})),l=c.length>0&&c.every((u)=>u.status==="Success");return{success:l,instanceCount:c.length,perInstance:c,error:l?void 0:xe(c,"One or more SSM command invocations failed")}}}function ts(e={},t="ssh"){let r=[];if(e.identityFile)r.push("-i",e.identityFile);if(e.port)r.push(t==="scp"?"-P":"-p",String(e.port));return r.push("-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR","-o",`ConnectTimeout=${e.connectTimeoutSec??10}`),r}async function wr(e,t,r={}){let n=Bun.spawn(["ssh",...ts(r),`${r.user??"root"}@${e}`,t],{stdout:"pipe",stderr:"pipe"}),[s,i]=await Promise.all([new Response(n.stdout).text(),new Response(n.stderr).text()]);return{code:await n.exited,stdout:s,stderr:i}}async function ke(e,t,r={}){let n=await wr(e,t,r);if(n.code!==0)throw Error(`ssh \`${t}\` on ${e} failed (${n.code}): ${n.stderr.trim()||n.stdout.trim()}`);return n.stdout}async function Tr(e,t={}){let r=t.timeoutMs??180000,n=t.pollIntervalMs??5000,s=Date.now();while(Date.now()-s<r){let i=await wr(e,"echo ready",t);if(i.code===0&&i.stdout.includes("ready"))return;await new Promise((o)=>setTimeout(o,n))}throw Error(`SSH not ready on ${e} after ${r}ms`)}function at(e={}){return["set -e","ts_cloud_script=$(mktemp /tmp/ts-cloud-deploy.XXXXXXXX)",`trap 'rm -f "$ts_cloud_script"' EXIT`,'cat > "$ts_cloud_script"',e.sudo?'sudo -n -H bash "$ts_cloud_script" < /dev/null':'bash "$ts_cloud_script" < /dev/null'].join(`
254
+ `,m}var qn="/aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id";function Xn(e){let t=[{port:22,protocol:"tcp",cidr:"0.0.0.0/0"},{port:80,protocol:"tcp",cidr:"0.0.0.0/0"},{port:443,protocol:"tcp",cidr:"0.0.0.0/0"}],r=new Set;for(let n of Object.values(e.sites||{}))if(n&&typeof n.port==="number"&&![22,80,443].includes(n.port))r.add(n.port);for(let n of r)t.push({port:n,protocol:"tcp",cidr:"0.0.0.0/0"});return t}function Yn(e){let t=e.infrastructure?.compute??{},r=Re(e),n=t.proxy?.engine==="rpx"?le({proxy:t.proxy,config:Se(e.sites??{},{proxy:t.proxy,slug:e.project.slug}),slug:e.project.slug,bunBin:t.runtime==="node"||t.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0;return ee({runtime:r.runtime,runtimeVersion:r.runtimeVersion,systemPackages:t.systemPackages,database:e.infrastructure?.database,phpProvision:r.phpProvision,servicesProvision:r.servicesProvision,rpxProvision:n,baked:t.bakedImage===!0,swapGb:t.swapGb})}function Jn(e){return Buffer.from(e,"utf8").toString("base64")}function Qn(e){return e.infrastructure?.compute?.image??null}function Rt(e,t){return`${e}-${t}-app-sg`}function _r(e,t,r="app"){return[{Key:"Project",Value:e},{Key:"Environment",Value:t},{Key:"Role",Value:r},{Key:"ManagedBy",Value:"ts-cloud"}]}function Ea(e,t,r){if(!e?.length)return!1;let n=(s)=>e.find((i)=>i.Key===s)?.Value;return n("Project")===t&&n("Environment")===r}function Zn(e,t){let r=Rt(t.slug,t.environment);return e.find((n)=>{if(n.GroupName!==r)return!1;if(t.vpcId&&n.VpcId&&n.VpcId!==t.vpcId)return!1;if(!!n.Tags?.some((i)=>i.Key==="Project"))return Ea(n.Tags,t.slug,t.environment);return!!t.vpcId&&n.VpcId===t.vpcId})}function Da(e){try{let t=es(Oa(process.cwd(),"storage/cloud/state",`${e}.json`),"utf8"),r=JSON.parse(t);return typeof r.instanceId==="string"&&r.instanceId.length>0?r.instanceId:null}catch{return null}}class Et{name="aws";usesCloudFormation=!0;region;ec2Client;cfnClient;constructor(e={}){this.region=e.region||"us-east-1",this.ec2Client=e.ec2Client??((t)=>new Q(t)),this.cfnClient=e.cfnClient??((t)=>new v(t))}resolveRegion(e){return e.project.region||this.region}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e,n=this.resolveRegion(t),s=t.project.slug,i=t.infrastructure?.compute;if(!i)throw Error("infrastructure.compute is required to provision AWS compute");let o=this.ec2Client(n),a=await this.findComputeTargets({slug:s,environment:r,role:"app",region:n});if(a.length>0){let E=a[0];return{appInstanceId:E.id,appPublicIp:E.publicIp,appPublicIpv6:E.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}let c=Qn(t);if(!c){if(c=(await new qe(n).getParameter({Name:qn})).Parameter?.Value??null,!c)throw Error("Could not resolve the Ubuntu 24.04 AMI from SSM")}let l=await o.describeVpcs(),u=(l.Vpcs||[]).find((E)=>E.IsDefault)||(l.Vpcs||[])[0];if(!u?.VpcId)throw Error("No VPC found to launch the instance into");let d=(await o.describeSubnets({Filters:[{Name:"vpc-id",Values:[u.VpcId]}]})).Subnets||[],m=d.find((E)=>E.MapPublicIpOnLaunch)||d[0],f=m?.SubnetId;if(!m?.MapPublicIpOnLaunch)console.warn("ts-cloud: no public subnet found; the instance may not get a public IP (deploys/SSL need one).");let h=Rt(s,r),_=(await o.describeSecurityGroups({Filters:[{Name:"group-name",Values:[h]},{Name:"vpc-id",Values:[u.VpcId]}]})).SecurityGroups?.[0]?.GroupId;if(!_)_=(await o.createSecurityGroup({GroupName:h,Description:`ts-cloud ${s}/${r} app`,VpcId:u.VpcId,TagSpecifications:[{ResourceType:"security-group",Tags:_r(s,r)}]})).GroupId;let y=Xn(t);await o.authorizeSecurityGroupIngress({GroupId:_,IpPermissions:y.map((E)=>({IpProtocol:E.protocol,FromPort:E.port,ToPort:E.port,IpRanges:[{CidrIp:E.cidr}]}))}).catch((E)=>{if(!/InvalidPermission\.Duplicate/.test(E instanceof Error?E.message:""))throw E});let S=Jn(Yn(t)),R=i.server?.instanceType||"t3.small",I=(await o.runInstances({ImageId:c,InstanceType:R,MinCount:1,MaxCount:1,SecurityGroupIds:_?[_]:void 0,SubnetId:f,UserData:S,IamInstanceProfile:i.server?.iamInstanceProfile?{Name:i.server.iamInstanceProfile}:void 0,TagSpecifications:[{ResourceType:"instance",Tags:[{Key:"Name",Value:`${s}-${r}-app`},..._r(s,r)]}]})).Instances?.[0]?.InstanceId;if(!I)throw Error("RunInstances did not return an instance id");let C=await o.waitForInstanceState(I,"running");if(!C)throw Error(`Instance ${I} did not reach 'running' before timeout`);return{appInstanceId:I,appPublicIp:C.PublicIpAddress,appPublicIpv6:ue(C.Ipv6Address),sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}async destroyCompute(e){let{config:t,environment:r}=e,n=t.project.slug,s=this.resolveRegion(t),i=this.ec2Client(s),o=[],c=(await this.findComputeTargets({slug:n,environment:r,role:"app",region:s})).map((h)=>h.id),l;if(c.length>0)l=(await i.describeInstances({InstanceIds:c}).catch(()=>({Reservations:[]}))).Reservations?.flatMap((x)=>x.Instances??[]).find((x)=>x.VpcId)?.VpcId;if(c.length>0)await i.terminateInstances(c),o.push(...c.map((h)=>`instance ${h}`)),await Promise.all(c.map((h)=>i.waitForInstanceState(h,"terminated").catch(()=>{return})));let u=Rt(n,r),d=[{Name:"group-name",Values:[u]}];if(l)d.push({Name:"vpc-id",Values:[l]});let m=await i.describeSecurityGroups({Filters:d}).catch(()=>({SecurityGroups:[]})),f=Zn(m.SecurityGroups??[],{slug:n,environment:r,vpcId:l});if(f?.GroupId)for(let h=0;h<10;h++)try{await i.deleteSecurityGroup(f.GroupId),o.push(`security group ${u}`);break}catch{await new Promise((x)=>setTimeout(x,3000))}return{destroyed:o}}async getComputeOutputs(e){let t=this.resolveRegion(e.config),r=T(e.config,e.environment),n=this.cfnClient(t);try{let s=await n.getStackOutputs(r);return{deployBucketName:s.deployBucketName,appInstanceId:s.appInstanceId,appPublicIp:s.appPublicIp,sshUser:"ec2-user"}}catch(s){if(!/does not exist|ValidationError/i.test(s instanceof Error?s.message:""))throw s;let o=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",region:t}))[0];return{appInstanceId:o?.id,appPublicIp:o?.publicIp,appPublicIpv6:o?.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}}async uploadRelease(e){let t=this.resolveRegion(e.config),n=(await this.getComputeOutputs({config:e.config,environment:e.environment})).deployBucketName;if(!n)throw Error("No deployBucketName in stack outputs. Re-deploy infrastructure to add the staging bucket.");return await new g(t).putObject({bucket:n,key:e.remoteKey,body:es(e.localPath),contentType:"application/gzip"}),{artifactRef:`s3://${n}/${e.remoteKey}`}}async findComputeTargets(e){let t=e.region??this.region,r=this.ec2Client(t),n=[{Name:"tag:Project",Values:[e.slug]},{Name:"tag:Environment",Values:[e.environment]},{Name:"tag:Role",Values:[e.role||"app"]},{Name:"instance-state-name",Values:["running","pending"]}],s=await r.describeInstances({Filters:n}),i=this.reservationsToTargets(s.Reservations);if(i.length>0||(e.role||"app")!=="app")return i;let o=e.stackName??`${e.slug}-${e.environment}`,a=Da(o);if(!a)try{a=(await this.cfnClient(t).getStackOutputs(o)).appInstanceId??null}catch{a=null}if(!a)return[];try{let c=await r.describeInstances({InstanceIds:[a],Filters:[{Name:"instance-state-name",Values:["running","pending"]}]});return this.reservationsToTargets(c.Reservations)}catch{return[]}}reservationsToTargets(e){let t=[];for(let r of e||[])for(let n of r.Instances||[]){if(!n.InstanceId)continue;let s=n.Tags?.find((i)=>i.Key==="Name")?.Value;t.push({id:n.InstanceId,name:s,publicIp:n.PublicIpAddress,publicIpv6:ue(n.Ipv6Address),privateIp:n.PrivateIpAddress,status:n.State?.Name})}return t}bashWrap(e){return["bash <<'TS_CLOUD_BASH_EOF'",e.join(`
255
+ `),"TS_CLOUD_BASH_EOF"]}async runRemoteDeploy(e){let t=this.region,r=new qe(t);if(e.targets.length>0){let s=await r.sendCommand({InstanceIds:e.targets.map((i)=>i.id),DocumentName:"AWS-RunShellScript",Parameters:{commands:this.bashWrap(e.commands)},TimeoutSeconds:e.timeoutSeconds||600,Comment:e.comment});if(!s.CommandId)return{success:!1,instanceCount:0,perInstance:[],error:"Failed to send SSM command"};return this.pollSsmCommand(r,s.CommandId,e.targets.length,((e.timeoutSeconds||600)+30)*1000)}if(!e.tags||Object.keys(e.tags).length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets or tags provided for AWS deploy"};let n=await r.sendCommandByTags({tags:e.tags,commands:this.bashWrap(e.commands),timeoutSeconds:e.timeoutSeconds||600,comment:e.comment});return{success:n.success,instanceCount:n.instanceCount,perInstance:n.perInstance.map((s)=>({instanceId:s.instanceId,status:s.status,output:s.output,error:s.error})),error:n.error}}async pollSsmCommand(e,t,r,n=600000){let i=Date.now(),o=new Set(["Success","Failed","Cancelled","TimedOut"]),a=[];while(Date.now()-i<n){await new Promise((u)=>setTimeout(u,3000));try{if(a=await e.listCommandInvocations({CommandId:t,Details:!0}),a.length>=r&&a.every((d)=>o.has(d.Status||"")))break}catch{}}let c=a.map((u)=>({instanceId:u.InstanceId,status:u.Status||"Unknown",output:u.StandardOutputContent,error:u.StandardErrorContent})),l=c.length>0&&c.every((u)=>u.status==="Success");return{success:l,instanceCount:c.length,perInstance:c,error:l?void 0:xe(c,"One or more SSM command invocations failed")}}}function ts(e={},t="ssh"){let r=[];if(e.identityFile)r.push("-i",e.identityFile);if(e.port)r.push(t==="scp"?"-P":"-p",String(e.port));return r.push("-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR","-o",`ConnectTimeout=${e.connectTimeoutSec??10}`),r}async function wr(e,t,r={}){let n=Bun.spawn(["ssh",...ts(r),`${r.user??"root"}@${e}`,t],{stdout:"pipe",stderr:"pipe"}),[s,i]=await Promise.all([new Response(n.stdout).text(),new Response(n.stderr).text()]);return{code:await n.exited,stdout:s,stderr:i}}async function ke(e,t,r={}){let n=await wr(e,t,r);if(n.code!==0)throw Error(`ssh \`${t}\` on ${e} failed (${n.code}): ${n.stderr.trim()||n.stdout.trim()}`);return n.stdout}async function Tr(e,t={}){let r=t.timeoutMs??180000,n=t.pollIntervalMs??5000,s=Date.now();while(Date.now()-s<r){let i=await wr(e,"echo ready",t);if(i.code===0&&i.stdout.includes("ready"))return;await new Promise((o)=>setTimeout(o,n))}throw Error(`SSH not ready on ${e} after ${r}ms`)}function at(e={}){return["set -e","ts_cloud_script=$(mktemp /tmp/ts-cloud-deploy.XXXXXXXX)",`trap 'rm -f "$ts_cloud_script"' EXIT`,'cat > "$ts_cloud_script"',e.sudo?'sudo -n -H bash "$ts_cloud_script" < /dev/null':'bash "$ts_cloud_script" < /dev/null'].join(`
256
256
  `)}var $r=at();import{execFileSync as Za,execSync as Ds}from"node:child_process";import{createHash as ec,randomUUID as Is}from"node:crypto";import{createReadStream as tc,existsSync as rc,readFileSync as nc}from"node:fs";function Ot(e){return Object.entries(e).map(([t,r])=>`${t}=${Ia(String(r))}`).join(`
257
257
  `)}function Ia(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}var Aa=new Set(["sqlite","sqlite3"]),La=new Set([":memory:","memory"]);function Ha(e){let t=e?.DB_CONNECTION?.trim().toLowerCase();return t!=null&&Aa.has(t)}function Na(e){let t=e.trim().replace(/^\.\//,"");if(t===""||t.startsWith("/")||t.startsWith("~"))return;if(t.split("/").includes(".."))return;return t.replace(/\/+$/,"")}function Pr(e,t=[]){if(!Ha(e))return{};let r=e?.DB_DATABASE_PATH?.trim()||e?.DB_DATABASE?.trim();if(r&&La.has(r.toLowerCase()))return{};if(!r)return{warning:"DB_CONNECTION is sqlite but neither DB_DATABASE_PATH nor DB_DATABASE names a file, so ts-cloud cannot tell where the database lives. If it is written inside the release directory, the next deploy discards it. Set DB_DATABASE_PATH, or list the file in the site's `sharedPaths`."};let n=Na(r);if(!n)return{};if(t.some((s)=>Ws(s)===n))return{};return{path:n}}function Dt(e,t=[]){let{path:r}=Pr(e,t);return r?[r]:[]}var Be="/var/ts-cloud/artifacts";var ys=Object.freeze({stagingMaxAgeMinutes:60,artifactMaxAgeDays:2,artifactUploadMaxAgeMinutes:60,bunCacheMaxAgeDays:7,journalMaxAgeDays:14,journalMaxSizeMb:512,containerImageMaxAgeHours:168}),vs=Object.freeze({artifactMaxAgeDays:0,bunCacheMaxAgeDays:1,journalMaxAgeDays:3,journalMaxSizeMb:256,containerImageMaxAgeHours:24});function us(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function Oe(e,t,r=0){if(!Number.isInteger(t)||t<r)throw Error(`hostCleanup: ${e} must be a whole number >= ${r} (got ${t})`)}function ms(e,t){for(let[r,n]of Object.entries(t))Oe(`${e}.${r}`,n);Oe(`${e}.stagingMaxAgeMinutes`,t.stagingMaxAgeMinutes,15),Oe(`${e}.artifactUploadMaxAgeMinutes`,t.artifactUploadMaxAgeMinutes,15),Oe(`${e}.journalMaxSizeMb`,t.journalMaxSizeMb,1)}function Ua(e,t){let r=`hostCleanup.paths[${t}]`,n=e.path?.replace(/\/+$/,"")??"";if(!n.startsWith("/")||n===""||/[\s'"`$\\]/.test(n)||n.split("/").includes(".."))throw Error(`${r}.path must be an absolute directory with no spaces, quotes or '..' (got ${JSON.stringify(e.path)})`);if(n==="/var/www"||n.startsWith("/var/www/"))throw Error(`${r}.path must not be under /var/www: releases are pruned by keepReleases`);if(!e.pattern||/^[*?]+$/.test(e.pattern)||e.pattern.includes("/")||/[\n'"`]/.test(e.pattern))throw Error(`${r}.pattern must be a file-name glob naming something, not a bare wildcard (got ${JSON.stringify(e.pattern)})`);if(Oe(`${r}.maxAgeDays`,e.maxAgeDays),e.type!==void 0&&e.type!=="file"&&e.type!=="directory")throw Error(`${r}.type must be 'file' or 'directory'`)}function It(e){let t=typeof e==="object"&&e!==null?e:{},r=e!==!1,n={...ys,...fs(t.retention)};ms("hostCleanup.retention",n);let s=null;if(t.pressure!==!1){let a=typeof t.pressure==="object"?t.pressure:{},c=a.lowWaterPercent??50,l=a.highWaterPercent??85;if(Oe("hostCleanup.pressure.lowWaterPercent",c),Oe("hostCleanup.pressure.highWaterPercent",l,1),l>100||c>=l)throw Error(`hostCleanup.pressure: need 0 <= lowWaterPercent < highWaterPercent <= 100 (got ${c} and ${l})`);let u={...vs,...fs(a.escalated)},d=Object.fromEntries(Object.keys(n).map((m)=>[m,Math.min(n[m],u[m]??n[m])]));ms("hostCleanup.pressure.escalated",d),s={lowWaterPercent:c,highWaterPercent:l,escalated:d}}let i=t.schedule??"daily";if(!/^[\w*:,./~ -]+$/.test(i))throw Error(`hostCleanup.schedule must be a systemd OnCalendar expression (got ${JSON.stringify(i)})`);let o=t.paths??[];return o.forEach(Ua),{enabled:r,timer:r&&t.timer!==!1,schedule:i,retention:n,pressure:s,paths:o}}function fs(e){return Object.fromEntries(Object.entries(e??{}).filter(([,t])=>t!==void 0))}var ct={stagingMaxAgeMinutes:"TS_CLOUD_HC_STAGING_MIN",artifactMaxAgeDays:"TS_CLOUD_HC_ARTIFACT_DAYS",artifactUploadMaxAgeMinutes:"TS_CLOUD_HC_UPLOAD_MIN",bunCacheMaxAgeDays:"TS_CLOUD_HC_BUN_DAYS",journalMaxAgeDays:"TS_CLOUD_HC_JOURNAL_DAYS",journalMaxSizeMb:"TS_CLOUD_HC_JOURNAL_MB",containerImageMaxAgeHours:"TS_CLOUD_HC_IMAGE_HOURS"};function xr(e){return Object.keys(ct).map((t)=>`${ct[t]}=${e[t]}`).join(" ")}var Ee=(e)=>`"$${ct[e]}"`;function gs(e){return[`find /var/ts-cloud/staging -xdev -maxdepth 1 -type f -mmin +${Ee("stagingMaxAgeMinutes")} -delete 2>/dev/null || true`,`find /tmp -xdev -maxdepth 1 -type f -name "*-release.tar.gz" -mmin +${Ee("stagingMaxAgeMinutes")} -delete 2>/dev/null || true`,`find /var/ts-cloud/artifacts -xdev -maxdepth 1 -type f -name "*.tar.gz" -mtime +${Ee("artifactMaxAgeDays")} -delete 2>/dev/null || true`,`find /var/ts-cloud/artifacts -xdev -maxdepth 1 -type f -name ".*.tmp" -mmin +${Ee("artifactUploadMaxAgeMinutes")} -delete 2>/dev/null || true`,...e.map(ka),`journalctl --vacuum-time=${Ee("journalMaxAgeDays")}d --vacuum-size=${Ee("journalMaxSizeMb")}M >/dev/null 2>&1 || true`]}function ka(e){let t=us(e.path.replace(/\/+$/,"")),r=us(e.pattern);return e.type==="directory"?`find ${t} -xdev -mindepth 1 -maxdepth 1 -type d -name ${r} -mtime +${e.maxAgeDays} -exec rm -rf -- {} + 2>/dev/null || true`:`find ${t} -xdev -mindepth 1 -maxdepth 1 -type f -name ${r} -mtime +${e.maxAgeDays} -delete 2>/dev/null || true`}function hs(){return[`find /root/.bun/install/cache -xdev -type f -mtime +${Ee("bunCacheMaxAgeDays")} -delete 2>/dev/null || true`,"find /root/.bun/install/cache -xdev -depth -type d -empty -delete 2>/dev/null || true",`if command -v docker >/dev/null 2>&1; then docker image prune --all --force --filter "until=\${${ct.containerImageMaxAgeHours}}h" >/dev/null 2>&1 || true; fi`,`if command -v podman >/dev/null 2>&1; then podman image prune --all --force --filter "until=\${${ct.containerImageMaxAgeHours}}h" >/dev/null 2>&1 || true; fi`,"if command -v apt-get >/dev/null 2>&1; then apt-get clean >/dev/null 2>&1 || true; fi"]}function Ss(e){return[`${e}="$(df -P / 2>/dev/null | awk 'NR==2 {sub(/%/, "", $5); print $5}' || true)"`,`case "$${e}" in ''|*[!0-9]*) ${e}=-1 ;; esac`]}function Er(e){let{retention:t,pressure:r,paths:n}=It(e),s='echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',i='echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"';if(!r)return['echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',xr(t),...gs(n),...hs(),'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"'];let{lowWaterPercent:o,highWaterPercent:a,escalated:c}=r;return['echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',...Ss("TS_CLOUD_HC_BEFORE"),"TS_CLOUD_HC_TIER=normal",xr(t),`if [ "$TS_CLOUD_HC_BEFORE" -ge 0 ] && [ "$TS_CLOUD_HC_BEFORE" -lt ${o} ]; then`," TS_CLOUD_HC_TIER=light",` echo "[ts-cloud] host cleanup: / at \${TS_CLOUD_HC_BEFORE}% (under ${o}%), skipping cache and image pruning"`,`elif [ "$TS_CLOUD_HC_BEFORE" -ge ${a} ]; then`," TS_CLOUD_HC_TIER=pressure",` ${xr(c)}`,` echo "[ts-cloud] warning: / at \${TS_CLOUD_HC_BEFORE}% (at or above ${a}%), host cleanup is using shortened retention windows" >&2`,"fi",...gs(n),'if [ "$TS_CLOUD_HC_TIER" != light ]; then',...hs().map((l)=>` ${l}`),"fi",'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"',...Ss("TS_CLOUD_HC_AFTER"),`echo "[ts-cloud] host-cleanup {\\"event\\":\\"host-cleanup\\",\\"tier\\":\\"$TS_CLOUD_HC_TIER\\",\\"diskBeforePercent\\":$TS_CLOUD_HC_BEFORE,\\"diskAfterPercent\\":$TS_CLOUD_HC_AFTER,\\"lowWaterPercent\\":${o},\\"highWaterPercent\\":${a}}"`,"mkdir -p /var/lib/ts-cloud 2>/dev/null || true",'TS_CLOUD_HC_PREV="$(cat /var/lib/ts-cloud/host-cleanup.alert 2>/dev/null || echo ok)"',`if [ "$TS_CLOUD_HC_AFTER" -ge ${a} ]; then`,` echo "[ts-cloud] warning: / still at \${TS_CLOUD_HC_AFTER}% after host cleanup (high-water ${a}%); something outside ts-cloud's retention rules is filling the disk" >&2`,` if [ "$TS_CLOUD_HC_PREV" != alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "⚠️ $(hostname): / at \${TS_CLOUD_HC_AFTER}% after host cleanup (high-water ${a}%)" >/dev/null 2>&1 || true; fi`," echo alert > /var/lib/ts-cloud/host-cleanup.alert 2>/dev/null || true","else",` if [ "$TS_CLOUD_HC_PREV" = alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "✅ $(hostname): / back under ${a}% after host cleanup (\${TS_CLOUD_HC_AFTER}%)" >/dev/null 2>&1 || true; fi`," echo ok > /var/lib/ts-cloud/host-cleanup.alert 2>/dev/null || true","fi"]}function bs(e){return["#!/usr/bin/env bash","# Managed by ts-cloud: rewritten on every deploy. Configure compute.hostCleanup instead of editing.","set -uo pipefail","TS_CLOUD_HC_LOCK=/run/lock/ts-cloud-host-cleanup.lock","[ -d /run/lock ] || TS_CLOUD_HC_LOCK=/tmp/ts-cloud-host-cleanup.lock",'if command -v flock >/dev/null 2>&1 && exec 9>"$TS_CLOUD_HC_LOCK"; then',' if ! flock -n 9; then echo "[ts-cloud] host cleanup already running; skipping"; exit 0; fi',"fi",...Er(e),"exit 0"]}function Rr(e,t,r,n,s){return[`cat > ${e}.ts-cloud-new <<'${r}' || true`,...t,r,`if [ -s ${e}.ts-cloud-new ] && ! cmp -s ${e}.ts-cloud-new ${e}; then chmod ${n} ${e}.ts-cloud-new && mv -f ${e}.ts-cloud-new ${e}${s?` && ${s}=1`:""} || true; else rm -f ${e}.ts-cloud-new; fi`]}function _s(e){let t=It(e),r="/etc/systemd/system/ts-cloud-host-cleanup",n=["if [ -f /etc/systemd/system/ts-cloud-host-cleanup.timer ]; then"," systemctl disable --now ts-cloud-host-cleanup.timer >/dev/null 2>&1 || true"," rm -f /etc/systemd/system/ts-cloud-host-cleanup.timer /etc/systemd/system/ts-cloud-host-cleanup.service"," systemctl daemon-reload >/dev/null 2>&1 || true","fi"];if(!t.enabled)return[...n,"rm -f /usr/local/bin/ts-cloud-host-cleanup.sh"];let s=Rr("/usr/local/bin/ts-cloud-host-cleanup.sh",bs(e),"TS_CLOUD_HOST_CLEANUP_EOF","755");if(!t.timer)return[...s,...n];return[...s,"TS_CLOUD_HC_UNITS_CHANGED=0","if command -v systemctl >/dev/null 2>&1 && [ -d /etc/systemd/system ]; then",...Rr("/etc/systemd/system/ts-cloud-host-cleanup.service",["[Unit]","Description=ts-cloud host cleanup (bounded disk retention)","After=local-fs.target","","[Service]","Type=oneshot","ExecStart=/usr/local/bin/ts-cloud-host-cleanup.sh","Nice=19","IOSchedulingClass=idle"],"TS_CLOUD_HOST_CLEANUP_SVC_EOF","644","TS_CLOUD_HC_UNITS_CHANGED"),...Rr("/etc/systemd/system/ts-cloud-host-cleanup.timer",["[Unit]","Description=Run ts-cloud host cleanup on a schedule, independent of deploys","","[Timer]",`OnCalendar=${t.schedule}`,"RandomizedDelaySec=1h","Persistent=true","","[Install]","WantedBy=timers.target"],"TS_CLOUD_HOST_CLEANUP_TMR_EOF","644","TS_CLOUD_HC_UNITS_CHANGED"),' if [ "$TS_CLOUD_HC_UNITS_CHANGED" -eq 1 ]; then systemctl daemon-reload >/dev/null 2>&1 || true; fi'," systemctl enable --now ts-cloud-host-cleanup.timer >/dev/null 2>&1 || true","fi"]}function Or(e){let t=_s(e);if(!It(e).enabled)return t;return[...t,'if [ -x /usr/local/bin/ts-cloud-host-cleanup.sh ]; then /usr/local/bin/ts-cloud-host-cleanup.sh < /dev/null || echo "[ts-cloud] warning: host cleanup exited $?" >&2; fi']}var Ma=/\.(?:[cm]?[jt]sx?)$/;function Hr(e,t,r){let n=t==="bun"?"/usr/local/bin/bun":t==="deno"?"/usr/local/bin/deno":"/usr/local/bin/node",s=e.trim();if(/^(?:bun|node|deno)\s+/.test(s))return`${n} ${s.replace(/^(?:bun|node|deno)\s+/,"")}`;let[i="",...o]=s.split(/\s+/);if(i&&!Ma.test(i)){let a=i.startsWith("/")?i:r&&i.startsWith("./")?`${r.replace(/\/+$/,"")}/${i.replace(/^\.\//,"")}`:void 0;if(a)return[a,...o].join(" ")}return`${n} ${s}`}function ws(e){return["TS_CLOUD_MEM_MB=$(awk '/^MemTotal:/{print int($2/1024)}' /proc/meminfo)","TS_CLOUD_HIGH_MB=$((TS_CLOUD_MEM_MB / 8))",'[ "$TS_CLOUD_HIGH_MB" -lt 512 ] && TS_CLOUD_HIGH_MB=512','[ "$TS_CLOUD_HIGH_MB" -gt 4096 ] && TS_CLOUD_HIGH_MB=4096',`mkdir -p /etc/systemd/system/${e}.d`,`printf '# Written by ts-cloud: memoryHigh resolved from this box.
258
258
  # An eighth of %sMB RAM. Set memoryHigh in config to override.
259
259
  [Service]
260
260
  MemoryAccounting=true
261
261
  MemoryHigh=%sM
262
- ' "$TS_CLOUD_MEM_MB" "$TS_CLOUD_HIGH_MB" > /etc/systemd/system/${e}.d/50-ts-cloud-memory.conf`,"systemctl daemon-reload",'echo "[ts-cloud] memoryHigh=auto resolved to ${TS_CLOUD_HIGH_MB}M (one eighth of ${TS_CLOUD_MEM_MB}M)"',...Ar()]}function At(e,t={auto:!0}){let r=t.auto===!1?[]:[`/etc/systemd/system/${e}.d/50-ts-cloud-memory.conf`];for(let n of["/etc/systemd/system.control","/run/systemd/system.control"]){if(t.high)r.push(`${n}/${e}.d/50-MemoryHigh.conf`);if(t.max)r.push(`${n}/${e}.d/50-MemoryMax.conf`)}if(r.length===0)return[];return["TS_CLOUD_MEM_CLEARED=0",...r.map((n)=>`if [ -f ${n} ]; then rm -f ${n}; TS_CLOUD_MEM_CLEARED=1; echo "[ts-cloud] removed ${n}: memory limits now come from config"; fi`),'if [ "$TS_CLOUD_MEM_CLEARED" = 1 ]; then systemctl daemon-reload; fi']}function Ar(){return[`TS_CLOUD_COMMIT=$(for f in /sys/fs/cgroup/system.slice/*.service/memory.high /sys/fs/cgroup/system.slice/*.slice/*.service/memory.high; do [ -f "$f" ] || continue; v=$(cat "$f" 2>/dev/null); [ "$v" = "max" ] && continue; echo "$v"; done | awk '{s+=$1} END {print int(s/1048576)}')`,"TS_CLOUD_RAM=$(awk '/^MemTotal:/{print int($2/1024)}' /proc/meminfo)",'if [ -n "$TS_CLOUD_COMMIT" ] && [ "$TS_CLOUD_COMMIT" -gt 0 ] && [ "$TS_CLOUD_RAM" -gt 0 ]; then TS_CLOUD_PCT=$((TS_CLOUD_COMMIT * 100 / TS_CLOUD_RAM)); if [ "$TS_CLOUD_PCT" -gt 300 ]; then echo "[ts-cloud] WARNING: services on this box declare ${TS_CLOUD_COMMIT}M of MemoryHigh against ${TS_CLOUD_RAM}M of RAM (${TS_CLOUD_PCT}% committed). Soft ceilings, so this is not fatal - but no ceiling can protect the box once enough of them are drawn on at once."; else echo "[ts-cloud] memory commitment: ${TS_CLOUD_COMMIT}M declared against ${TS_CLOUD_RAM}M RAM (${TS_CLOUD_PCT}%)"; fi; fi']}function Fa(e){return[`TS_CLOUD_SLICE=$(systemctl show ${e} -p Slice --value 2>/dev/null || true)`,'if [ -n "$TS_CLOUD_SLICE" ] && [ "$TS_CLOUD_SLICE" != "system.slice" ]; then systemctl set-property --runtime "$TS_CLOUD_SLICE" MemoryHigh=infinity MemoryMax=infinity 2>/dev/null || true; systemctl set-property "$TS_CLOUD_SLICE" MemoryHigh=infinity MemoryMax=infinity 2>/dev/null || true; fi']}var De={path:"/",intervalSeconds:60,failuresBeforeRestart:3,timeoutSeconds:10,startupGraceSeconds:600,maxBackoffSeconds:3600,backoffBaseSeconds:300};function lt(e,t,r){return typeof e==="number"&&Number.isFinite(e)?Math.max(r,Math.floor(e)):t}function Ts(e){let{unitBase:t,unitPattern:r,port:n}=e,s=e.path&&e.path.startsWith("/")?e.path:De.path,i=lt(e.intervalSeconds,De.intervalSeconds,10),o=lt(e.failuresBeforeRestart,De.failuresBeforeRestart,1),a=lt(e.timeoutSeconds,De.timeoutSeconds,1),c=lt(e.startupGraceSeconds,De.startupGraceSeconds,0),l=lt(e.maxBackoffSeconds,De.maxBackoffSeconds,0),u=Math.min(De.backoffBaseSeconds,l),d=`/usr/local/sbin/${t}-liveness`,m=`/run/${t}-liveness`,f=`${t}-liveness`,h=`127.0.0.1:${n}${s}`,_=r.includes("@*")?`TS_CLOUD_UNIT=$(systemctl list-units --plain --no-legend --type=service '${r}' 2>/dev/null | awk '{print $1}' | head -1)`:`TS_CLOUD_UNIT=${r}`;return[`cat > ${d} <<'TS_CLOUD_LIVENESS_EOF'`,"#!/bin/sh",`# Liveness check for ${t}, written by ts-cloud on every deploy.`,`# Settings: interval=${i}s timeout=${a}s failures=${o} startup-grace=${c}s max-backoff=${l}s`,"set -eu",`TS_CLOUD_STATE=${m}`,'exec 9>"$TS_CLOUD_STATE.lock"',"flock -n 9 || exit 0",_,'[ -n "$TS_CLOUD_UNIT" ] || exit 0','systemctl is-active --quiet "$TS_CLOUD_UNIT" || exit 0',"TS_CLOUD_RC=0",`curl -s -o /dev/null --max-time ${a} "http://${h}" || TS_CLOUD_RC=$?`,'if [ "$TS_CLOUD_RC" -eq 0 ]; then',' rm -f "$TS_CLOUD_STATE.fail"',' if [ -f "$TS_CLOUD_STATE.restarts" ]; then',` TS_CLOUD_LAST=$(awk '{print $2}' "$TS_CLOUD_STATE.restarts" 2>/dev/null || true)`,` case "$TS_CLOUD_LAST" in ''|*[!0-9]*) TS_CLOUD_LAST=0 ;; esac`,` [ $(($(date +%s) - TS_CLOUD_LAST)) -lt ${l} ] || rm -f "$TS_CLOUD_STATE.restarts"`," fi"," exit 0","fi",'case "$TS_CLOUD_RC" in'," 7) TS_CLOUD_WHY='connection refused' ;;",` 28) TS_CLOUD_WHY='no response within ${a}s' ;;`,' *) TS_CLOUD_WHY="curl exit $TS_CLOUD_RC" ;;',"esac",'TS_CLOUD_SINCE=$(systemctl show "$TS_CLOUD_UNIT" -p ActiveEnterTimestampMonotonic --value 2>/dev/null || true)',"TS_CLOUD_UPTIME=$(cut -d' ' -f1 /proc/uptime 2>/dev/null || true)",`TS_CLOUD_AGE=$(awk -v up="$TS_CLOUD_UPTIME" -v since="$TS_CLOUD_SINCE" 'BEGIN { if (since + 0 > 0 && up + 0 > 0) print int(up - since / 1000000); else print -1 }')`,`case "$TS_CLOUD_AGE" in ''|*[!0-9-]*) TS_CLOUD_AGE=-1 ;; esac`,'if [ "$TS_CLOUD_AGE" -lt 0 ]; then',' TS_CLOUD_PID=$(systemctl show "$TS_CLOUD_UNIT" -p MainPID --value 2>/dev/null || true)',` case "$TS_CLOUD_PID" in ''|0|*[!0-9]*) ;; *) TS_CLOUD_AGE=$(ps -o etimes= -p "$TS_CLOUD_PID" 2>/dev/null | tr -d ' ' || true) ;; esac`,` case "$TS_CLOUD_AGE" in ''|*[!0-9]*) TS_CLOUD_AGE=-1 ;; esac`,"fi",`if [ "$TS_CLOUD_AGE" -ge 0 ] && [ "$TS_CLOUD_AGE" -lt ${c} ]; then`,' rm -f "$TS_CLOUD_STATE.fail"',` logger -t ${f} "$TS_CLOUD_UNIT is \${TS_CLOUD_AGE}s old, inside its ${c}s startup grace; not counting this failed check on ${h} ($TS_CLOUD_WHY)"`," exit 0","fi",'TS_CLOUD_FAILS=$(cat "$TS_CLOUD_STATE.fail" 2>/dev/null || echo 0)',`case "$TS_CLOUD_FAILS" in ''|*[!0-9]*) TS_CLOUD_FAILS=0 ;; esac`,"TS_CLOUD_FAILS=$((TS_CLOUD_FAILS + 1))",'echo "$TS_CLOUD_FAILS" > "$TS_CLOUD_STATE.fail"',`if [ "$TS_CLOUD_FAILS" -lt ${o} ]; then`,` logger -t ${f} "check $TS_CLOUD_FAILS of ${o} failed on ${h} ($TS_CLOUD_WHY)"`," exit 0","fi","TS_CLOUD_NOW=$(date +%s)","TS_CLOUD_STREAK=0","TS_CLOUD_LAST=0",'[ ! -f "$TS_CLOUD_STATE.restarts" ] || read -r TS_CLOUD_STREAK TS_CLOUD_LAST < "$TS_CLOUD_STATE.restarts" || true',`case "$TS_CLOUD_STREAK" in ''|*[!0-9]*) TS_CLOUD_STREAK=0 ;; esac`,`case "$TS_CLOUD_LAST" in ''|*[!0-9]*) TS_CLOUD_LAST=0 ;; esac`,'if [ "$TS_CLOUD_STREAK" -gt 0 ]; then',` TS_CLOUD_WAIT=${u}`," TS_CLOUD_I=1",` while [ "$TS_CLOUD_I" -lt "$TS_CLOUD_STREAK" ] && [ "$TS_CLOUD_WAIT" -lt ${l} ]; do TS_CLOUD_WAIT=$((TS_CLOUD_WAIT * 2)); TS_CLOUD_I=$((TS_CLOUD_I + 1)); done`,` [ "$TS_CLOUD_WAIT" -le ${l} ] || TS_CLOUD_WAIT=${l}`," TS_CLOUD_ELAPSED=$((TS_CLOUD_NOW - TS_CLOUD_LAST))",' if [ "$TS_CLOUD_ELAPSED" -lt "$TS_CLOUD_WAIT" ]; then',` logger -t ${f} "holding off: $TS_CLOUD_STREAK liveness restart(s) in a row have not brought $TS_CLOUD_UNIT back; next restart allowed in $((TS_CLOUD_WAIT - TS_CLOUD_ELAPSED))s ($TS_CLOUD_WHY on ${h})"`," exit 0"," fi","fi","TS_CLOUD_STREAK=$((TS_CLOUD_STREAK + 1))",`logger -t ${f} "no HTTP response on ${h} after $TS_CLOUD_FAILS checks ($TS_CLOUD_WHY); restarting $TS_CLOUD_UNIT (liveness restart $TS_CLOUD_STREAK in a row)"`,'echo "$TS_CLOUD_STREAK $TS_CLOUD_NOW" > "$TS_CLOUD_STATE.restarts"','rm -f "$TS_CLOUD_STATE.fail"','systemctl restart "$TS_CLOUD_UNIT"',"TS_CLOUD_LIVENESS_EOF",`chmod +x ${d}`,`rm -f ${m}.fail ${m}.restarts`,`cat > /etc/systemd/system/${t}-liveness.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=Liveness check for ${t} (managed by ts-cloud)`,"","[Service]","Type=oneshot",`ExecStart=${d}`,"TS_CLOUD_UNIT_EOF",`cat > /etc/systemd/system/${t}-liveness.timer <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=Run the ${t} liveness check every ${i}s`,"","[Timer]",`OnUnitActiveSec=${i}s`,`OnBootSec=${i}s`,"Persistent=true","","[Install]","WantedBy=timers.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",`systemctl enable --now ${t}-liveness.timer >/dev/null 2>&1 || true`]}var $s=20,Dr=3,za=5,Ba=60;function Ka(e){let{paths:t,unitBase:r,releaseId:n,port:s}=e,i=`${r}@${n}.service`,o=`${r}.service`,a=Math.max(1,e.healthGateSeconds??5),c=e.healthCheckPath?e.healthCheckPath.startsWith("/")?e.healthCheckPath:`/${e.healthCheckPath}`:null,l=c?`curl -sf -o /dev/null --max-time ${za} "http://127.0.0.1:${s}${c}"`:null,u=(d)=>`{ echo "[ts-cloud] release ${n} ${d}" >&2; ts_cloud_restore_previous; exit 1; }`;return[`TS_CLOUD_OLD_UNITS=$(systemctl list-units --plain --no-legend --type=service "${r}@*.service" 2>/dev/null | awk '{print $1}' | grep -v "^${i}$" || true)`,`TS_CLOUD_PREV_CURRENT="$(readlink ${t.current} 2>/dev/null || true)"`,"TS_CLOUD_LEGACY_STOPPED=0","ts_cloud_restore_previous() {",` journalctl -u ${i} -n 50 --no-pager >&2 || true`,` systemctl stop ${i} 2>/dev/null || true`,` systemctl disable ${i} 2>/dev/null || true`,` if [ -n "$TS_CLOUD_PREV_CURRENT" ] && [ -d "$TS_CLOUD_PREV_CURRENT" ]; then ln -sfn "$TS_CLOUD_PREV_CURRENT" ${t.current}.tmp && mv -Tf ${t.current}.tmp ${t.current}; fi`,' for TS_CLOUD_RU in ${TS_CLOUD_OLD_UNITS}; do systemctl enable "$TS_CLOUD_RU" 2>/dev/null || true; systemctl start "$TS_CLOUD_RU" 2>/dev/null || true; done',` if [ "$TS_CLOUD_LEGACY_STOPPED" -eq 1 ]; then systemctl start ${o} 2>/dev/null || true; fi`,' if [ -n "$TS_CLOUD_OLD_UNITS" ] || [ "$TS_CLOUD_LEGACY_STOPPED" -eq 1 ]; then echo "[ts-cloud] previous release restored and serving" >&2; else echo "[ts-cloud] there was no previous release to restore" >&2; fi',"}",`if [ -f /etc/systemd/system/${o} ] && systemctl is-active --quiet ${o}; then echo "[ts-cloud] retiring pre-zero-downtime unit ${o} (one-time restart cutover)"; systemctl stop ${o}; TS_CLOUD_LEGACY_STOPPED=1; fi`,'TS_CLOUD_STARTED_AT="@$(date +%s)"',`systemctl restart ${i}`,`TS_CLOUD_GATE_OK=1; for TS_CLOUD_I in $(seq 1 ${a}); do sleep 1; systemctl is-active --quiet ${i} || { TS_CLOUD_GATE_OK=0; break; }; done`,'if [ "$TS_CLOUD_GATE_OK" -ne 1 ]; then',` if journalctl -u ${i} --since "$TS_CLOUD_STARTED_AT" -o cat --no-pager 2>/dev/null | grep -iE 'EADDRINUSE|address already in use|port [0-9]+ (is )?in use|Failed to start server' >/dev/null; then`,` echo "[ts-cloud] release ${n} could not share :${s} with the previous release (no SO_REUSEPORT?) — retiring it and retrying" >&2`,' for TS_CLOUD_RU in ${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_RU" 2>/dev/null || true; done',` systemctl restart ${i}`,` for TS_CLOUD_I in $(seq 1 ${a}); do sleep 1; systemctl is-active --quiet ${i} || ${u("failed its health gate on the free port")}; done`," else",` ${u("crashed on start — the previous release was never stopped")}`," fi","fi",`if ss -ltnpH "sport = :${s}" >/dev/null 2>&1; then`," TS_CLOUD_BOUND=0",` for TS_CLOUD_I in $(seq 1 ${Ba}); do`,` TS_CLOUD_NEW_PID="$(systemctl show -p MainPID --value ${i} 2>/dev/null || true)"`,` if [ -n "$TS_CLOUD_NEW_PID" ] && [ "$TS_CLOUD_NEW_PID" != "0" ] && ss -ltnpH "sport = :${s}" 2>/dev/null | grep "pid=$TS_CLOUD_NEW_PID," >/dev/null; then TS_CLOUD_BOUND=1; break; fi`,` systemctl is-active --quiet ${i} || break`,` sleep ${Dr}`," done",` [ "$TS_CLOUD_BOUND" -eq 1 ] || ${u(`never took :${s}`)}`,"else",' echo "[ts-cloud] cannot read listener PIDs on this host — the response probes run without the bind check" >&2',"fi",...l?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${$s}); do if ${l}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${Dr}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${u(`never answered ${c}`)}`]:[],...pn(t),`systemctl enable ${i} 2>/dev/null || true`,'for TS_CLOUD_U in ${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done',`TS_CLOUD_LISTENING=0; for TS_CLOUD_I in $(seq 1 ${a}); do if ss -ltnH "sport = :${s}" 2>/dev/null | grep . >/dev/null; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done`,`if [ "$TS_CLOUD_LISTENING" -ne 1 ]; then echo "[ts-cloud] nothing is listening on ${s} after retiring the previous release — restarting ${i} on the now-free port" >&2; systemctl restart ${i}; for TS_CLOUD_I in $(seq 1 ${a}); do if ss -ltnH "sport = :${s}" 2>/dev/null | grep . >/dev/null; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done; fi`,`[ "$TS_CLOUD_LISTENING" -eq 1 ] || ${u(`is active but never bound :${s}`)}`,...l?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${$s}); do if ${l}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${Dr}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${u(`stopped answering ${c} once it served alone`)}`]:[],...Ys(t),`systemctl list-unit-files --plain --no-legend "${r}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v -e "^${i}$" -e "^${r}@\\.service$" || true; } | while read -r TS_CLOUD_U; do systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done`,`if [ -f /etc/systemd/system/${o} ]; then systemctl disable ${o} 2>/dev/null || true; rm -f /etc/systemd/system/${o}; systemctl daemon-reload; fi`]}function Nr(e){let{siteName:t,slug:r,artifactFetch:n,releaseId:s,execStart:i,envEntries:o,port:a,keepReleases:c=Ii,preStartCommands:l=[],healthCheckPath:u,healthGateSeconds:d=5,liveness:m,memoryHigh:f="auto",memoryMax:h,cpuWeight:x,ioWeight:_,tasksMax:y,stopTimeout:S}=e,R=[...x!=null?[`CPUWeight=${x}`]:[],..._!=null?[`IOWeight=${_}`]:[],...y!=null?[`TasksMax=${y}`]:[],...S?[`TimeoutStopSec=${S}`]:[]],b=e.zeroDowntime??a!=null,I=e.appDir??`/var/www/${t}`,C=Vt(I,s),E=`${r}-${t}`,H=`${E}.service`,re=mt(r,t,s),W=e.sharedPaths??[],N=Gc([".env",...W,...Dt(o,W)]),q=Ot(o),k=l.length>0?[`cd ${C.release}`,...l]:[],X=["set -euo pipefail",...Ks(C),Xs(C),...n,...Pi(C,N),...Js(C),`tar xzf ${re} -C "$TS_CLOUD_STAGED"`,`rm -f ${re}`,`cat > ${C.shared}/.env <<'TS_CLOUD_ENV_EOF'`,q,"TS_CLOUD_ENV_EOF",`chmod 600 ${C.shared}/.env`,...Qs(C),`find ${C.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' ${C.shared}/.env 2>/dev/null || true`,...Mo(C,N),...k];if(b&&a!=null){let oe=`${E}@${s}.service`,fe=u?u.startsWith("/")?u:`/${u}`:null;return[...X,`cat > /etc/systemd/system/${E}@.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} release %i (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${C.releases}/%i`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...f&&f!=="auto"?[`MemoryHigh=${f}`]:[],...h?[`MemoryMax=${h}`]:[],...R,`EnvironmentFile=${C.releases}/%i/.env`,`Environment=PORT=${a}`,`Environment=STX_IMAGE_CACHE_DIR=${Lo(C)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...f==="auto"?ws(`${E}@.service`):[...At(`${E}@.service`),...Ar()],...Fa(oe),...Ka({paths:C,unitBase:E,releaseId:s,port:a,healthCheckPath:fe,healthGateSeconds:d}),...mn(C,c),...m===!1?[]:Ts({...m,unitBase:E,unitPattern:`${E}@*.service`,port:a,path:m?.path??u})]}return[...X,`cat > /etc/systemd/system/${H} <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${C.current}`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...f&&f!=="auto"?[`MemoryHigh=${f}`]:[],...h?[`MemoryMax=${h}`]:[],...R,`EnvironmentFile=${C.current}/.env`,...a?[`Environment=PORT=${a}`]:[],`Environment=STX_IMAGE_CACHE_DIR=${Lo(C)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...At(H,{auto:f!=="auto",high:f!=="auto",max:Boolean(h)}),...f==="auto"?ws(H):Ar(),`systemctl enable ${H}`,`TS_CLOUD_PREV_CURRENT="$(readlink ${C.current} 2>/dev/null || true)"`,...pn(C),`systemctl restart ${H}`,`for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do sleep 1; systemctl is-active --quiet ${H} || { echo "[ts-cloud] release ${s} of ${H} did not stay up — restoring the previous release" >&2; journalctl -u ${H} -n 50 --no-pager >&2 || true; if [ -n "$TS_CLOUD_PREV_CURRENT" ] && [ -d "$TS_CLOUD_PREV_CURRENT" ] && [ "$(readlink -f "$TS_CLOUD_PREV_CURRENT")" != "$(readlink -f ${C.release})" ]; then ln -sfn "$TS_CLOUD_PREV_CURRENT" ${C.current}.tmp && mv -Tf ${C.current}.tmp ${C.current}; systemctl restart ${H} || true; fi; exit 1; }; done`,...Ys(C),...mn(C,c),...m===!1||!a?[]:Ts({...m,unitBase:E,unitPattern:H,port:a,path:m?.path??u})]}function Ur(e){let{siteName:t,artifactFetch:r,releaseId:n,keepReleases:s=Ii,preStartCommands:i=[]}=e,o=e.appDir??`/var/www/${t}`,a=Vt(o,n),c=mt(e.slug,t,n),l=i.length>0?[`cd ${a.release}`,...i]:[];return["set -euo pipefail",...Ks(a),Xs(a),...r,...Pi(a,[]),...Js(a),`tar xzf ${c} -C "$TS_CLOUD_STAGED"`,...Qs(a),`rm -f ${c}`,...l,...pn(a),...mn(a,s)]}function mt(e,t,r){return`/tmp/${[e,t,r].filter(Boolean).join("-")}-release.tar.gz`}function kr(e,t,r,n){return[`aws s3 cp "s3://${e}/${t}" ${n} --region ${r}`]}function Mr(e,t){return[`mv "${e}" ${t}`]}function Ke(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function Lt(e,t,r){return["set -euo pipefail",`chmod 600 ${Ke(e)}`,`mv -f -- ${Ke(e)} ${Ke(t)}`,`cp -- ${Ke(t)} ${Ke(r)}`].join(`
262
+ ' "$TS_CLOUD_MEM_MB" "$TS_CLOUD_HIGH_MB" > /etc/systemd/system/${e}.d/50-ts-cloud-memory.conf`,"systemctl daemon-reload",'echo "[ts-cloud] memoryHigh=auto resolved to ${TS_CLOUD_HIGH_MB}M (one eighth of ${TS_CLOUD_MEM_MB}M)"',...Ar()]}function At(e,t={auto:!0}){let r=t.auto===!1?[]:[`/etc/systemd/system/${e}.d/50-ts-cloud-memory.conf`];for(let n of["/etc/systemd/system.control","/run/systemd/system.control"]){if(t.high)r.push(`${n}/${e}.d/50-MemoryHigh.conf`);if(t.max)r.push(`${n}/${e}.d/50-MemoryMax.conf`)}if(r.length===0)return[];return["TS_CLOUD_MEM_CLEARED=0",...r.map((n)=>`if [ -f ${n} ]; then rm -f ${n}; TS_CLOUD_MEM_CLEARED=1; echo "[ts-cloud] removed ${n}: memory limits now come from config"; fi`),'if [ "$TS_CLOUD_MEM_CLEARED" = 1 ]; then systemctl daemon-reload; fi']}function Ar(){return[`TS_CLOUD_COMMIT=$(for f in /sys/fs/cgroup/system.slice/*.service/memory.high /sys/fs/cgroup/system.slice/*.slice/*.service/memory.high; do [ -f "$f" ] || continue; v=$(cat "$f" 2>/dev/null); [ "$v" = "max" ] && continue; echo "$v"; done | awk '{s+=$1} END {print int(s/1048576)}')`,"TS_CLOUD_RAM=$(awk '/^MemTotal:/{print int($2/1024)}' /proc/meminfo)",'if [ -n "$TS_CLOUD_COMMIT" ] && [ "$TS_CLOUD_COMMIT" -gt 0 ] && [ "$TS_CLOUD_RAM" -gt 0 ]; then TS_CLOUD_PCT=$((TS_CLOUD_COMMIT * 100 / TS_CLOUD_RAM)); if [ "$TS_CLOUD_PCT" -gt 300 ]; then echo "[ts-cloud] WARNING: services on this box declare ${TS_CLOUD_COMMIT}M of MemoryHigh against ${TS_CLOUD_RAM}M of RAM (${TS_CLOUD_PCT}% committed). Soft ceilings, so this is not fatal - but no ceiling can protect the box once enough of them are drawn on at once."; else echo "[ts-cloud] memory commitment: ${TS_CLOUD_COMMIT}M declared against ${TS_CLOUD_RAM}M RAM (${TS_CLOUD_PCT}%)"; fi; fi']}function Fa(e){return[`TS_CLOUD_SLICE=$(systemctl show ${e} -p Slice --value 2>/dev/null || true)`,'if [ -n "$TS_CLOUD_SLICE" ] && [ "$TS_CLOUD_SLICE" != "system.slice" ]; then systemctl set-property --runtime "$TS_CLOUD_SLICE" MemoryHigh=infinity MemoryMax=infinity 2>/dev/null || true; systemctl set-property "$TS_CLOUD_SLICE" MemoryHigh=infinity MemoryMax=infinity 2>/dev/null || true; fi']}var De={path:"/",intervalSeconds:60,failuresBeforeRestart:3,timeoutSeconds:10,startupGraceSeconds:600,maxBackoffSeconds:3600,backoffBaseSeconds:300};function lt(e,t,r){return typeof e==="number"&&Number.isFinite(e)?Math.max(r,Math.floor(e)):t}function Ts(e){let{unitBase:t,unitPattern:r,port:n}=e,s=e.path&&e.path.startsWith("/")?e.path:De.path,i=lt(e.intervalSeconds,De.intervalSeconds,10),o=lt(e.failuresBeforeRestart,De.failuresBeforeRestart,1),a=lt(e.timeoutSeconds,De.timeoutSeconds,1),c=lt(e.startupGraceSeconds,De.startupGraceSeconds,0),l=lt(e.maxBackoffSeconds,De.maxBackoffSeconds,0),u=Math.min(De.backoffBaseSeconds,l),d=`/usr/local/sbin/${t}-liveness`,m=`/run/${t}-liveness`,f=`${t}-liveness`,h=`127.0.0.1:${n}${s}`,_=r.includes("@*")?`TS_CLOUD_UNIT=$(systemctl list-units --plain --no-legend --type=service '${r}' 2>/dev/null | awk '{print $1}' | head -1)`:`TS_CLOUD_UNIT=${r}`;return[`cat > ${d} <<'TS_CLOUD_LIVENESS_EOF'`,"#!/bin/sh",`# Liveness check for ${t}, written by ts-cloud on every deploy.`,`# Settings: interval=${i}s timeout=${a}s failures=${o} startup-grace=${c}s max-backoff=${l}s`,"set -eu",`TS_CLOUD_STATE=${m}`,'exec 9>"$TS_CLOUD_STATE.lock"',"flock -n 9 || exit 0",_,'[ -n "$TS_CLOUD_UNIT" ] || exit 0','systemctl is-active --quiet "$TS_CLOUD_UNIT" || exit 0',"TS_CLOUD_RC=0",`curl -s -o /dev/null --max-time ${a} "http://${h}" || TS_CLOUD_RC=$?`,'if [ "$TS_CLOUD_RC" -eq 0 ]; then',' rm -f "$TS_CLOUD_STATE.fail"',' if [ -f "$TS_CLOUD_STATE.restarts" ]; then',` TS_CLOUD_LAST=$(awk '{print $2}' "$TS_CLOUD_STATE.restarts" 2>/dev/null || true)`,` case "$TS_CLOUD_LAST" in ''|*[!0-9]*) TS_CLOUD_LAST=0 ;; esac`,` [ $(($(date +%s) - TS_CLOUD_LAST)) -lt ${l} ] || rm -f "$TS_CLOUD_STATE.restarts"`," fi"," exit 0","fi",'case "$TS_CLOUD_RC" in'," 7) TS_CLOUD_WHY='connection refused' ;;",` 28) TS_CLOUD_WHY='no response within ${a}s' ;;`,' *) TS_CLOUD_WHY="curl exit $TS_CLOUD_RC" ;;',"esac",'TS_CLOUD_SINCE=$(systemctl show "$TS_CLOUD_UNIT" -p ActiveEnterTimestampMonotonic --value 2>/dev/null || true)',"TS_CLOUD_UPTIME=$(cut -d' ' -f1 /proc/uptime 2>/dev/null || true)",`TS_CLOUD_AGE=$(awk -v up="$TS_CLOUD_UPTIME" -v since="$TS_CLOUD_SINCE" 'BEGIN { if (since + 0 > 0 && up + 0 > 0) print int(up - since / 1000000); else print -1 }')`,`case "$TS_CLOUD_AGE" in ''|*[!0-9-]*) TS_CLOUD_AGE=-1 ;; esac`,'if [ "$TS_CLOUD_AGE" -lt 0 ]; then',' TS_CLOUD_PID=$(systemctl show "$TS_CLOUD_UNIT" -p MainPID --value 2>/dev/null || true)',` case "$TS_CLOUD_PID" in ''|0|*[!0-9]*) ;; *) TS_CLOUD_AGE=$(ps -o etimes= -p "$TS_CLOUD_PID" 2>/dev/null | tr -d ' ' || true) ;; esac`,` case "$TS_CLOUD_AGE" in ''|*[!0-9]*) TS_CLOUD_AGE=-1 ;; esac`,"fi",`if [ "$TS_CLOUD_AGE" -ge 0 ] && [ "$TS_CLOUD_AGE" -lt ${c} ]; then`,' rm -f "$TS_CLOUD_STATE.fail"',` logger -t ${f} "$TS_CLOUD_UNIT is \${TS_CLOUD_AGE}s old, inside its ${c}s startup grace; not counting this failed check on ${h} ($TS_CLOUD_WHY)"`," exit 0","fi",'TS_CLOUD_FAILS=$(cat "$TS_CLOUD_STATE.fail" 2>/dev/null || echo 0)',`case "$TS_CLOUD_FAILS" in ''|*[!0-9]*) TS_CLOUD_FAILS=0 ;; esac`,"TS_CLOUD_FAILS=$((TS_CLOUD_FAILS + 1))",'echo "$TS_CLOUD_FAILS" > "$TS_CLOUD_STATE.fail"',`if [ "$TS_CLOUD_FAILS" -lt ${o} ]; then`,` logger -t ${f} "check $TS_CLOUD_FAILS of ${o} failed on ${h} ($TS_CLOUD_WHY)"`," exit 0","fi","TS_CLOUD_NOW=$(date +%s)","TS_CLOUD_STREAK=0","TS_CLOUD_LAST=0",'[ ! -f "$TS_CLOUD_STATE.restarts" ] || read -r TS_CLOUD_STREAK TS_CLOUD_LAST < "$TS_CLOUD_STATE.restarts" || true',`case "$TS_CLOUD_STREAK" in ''|*[!0-9]*) TS_CLOUD_STREAK=0 ;; esac`,`case "$TS_CLOUD_LAST" in ''|*[!0-9]*) TS_CLOUD_LAST=0 ;; esac`,'if [ "$TS_CLOUD_STREAK" -gt 0 ]; then',` TS_CLOUD_WAIT=${u}`," TS_CLOUD_I=1",` while [ "$TS_CLOUD_I" -lt "$TS_CLOUD_STREAK" ] && [ "$TS_CLOUD_WAIT" -lt ${l} ]; do TS_CLOUD_WAIT=$((TS_CLOUD_WAIT * 2)); TS_CLOUD_I=$((TS_CLOUD_I + 1)); done`,` [ "$TS_CLOUD_WAIT" -le ${l} ] || TS_CLOUD_WAIT=${l}`," TS_CLOUD_ELAPSED=$((TS_CLOUD_NOW - TS_CLOUD_LAST))",' if [ "$TS_CLOUD_ELAPSED" -lt "$TS_CLOUD_WAIT" ]; then',` logger -t ${f} "holding off: $TS_CLOUD_STREAK liveness restart(s) in a row have not brought $TS_CLOUD_UNIT back; next restart allowed in $((TS_CLOUD_WAIT - TS_CLOUD_ELAPSED))s ($TS_CLOUD_WHY on ${h})"`," exit 0"," fi","fi","TS_CLOUD_STREAK=$((TS_CLOUD_STREAK + 1))",`logger -t ${f} "no HTTP response on ${h} after $TS_CLOUD_FAILS checks ($TS_CLOUD_WHY); restarting $TS_CLOUD_UNIT (liveness restart $TS_CLOUD_STREAK in a row)"`,'echo "$TS_CLOUD_STREAK $TS_CLOUD_NOW" > "$TS_CLOUD_STATE.restarts"','rm -f "$TS_CLOUD_STATE.fail"','systemctl restart "$TS_CLOUD_UNIT"',"TS_CLOUD_LIVENESS_EOF",`chmod +x ${d}`,`rm -f ${m}.fail ${m}.restarts`,`cat > /etc/systemd/system/${t}-liveness.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=Liveness check for ${t} (managed by ts-cloud)`,"","[Service]","Type=oneshot",`ExecStart=${d}`,"TS_CLOUD_UNIT_EOF",`cat > /etc/systemd/system/${t}-liveness.timer <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=Run the ${t} liveness check every ${i}s`,"","[Timer]",`OnUnitActiveSec=${i}s`,`OnBootSec=${i}s`,"Persistent=true","","[Install]","WantedBy=timers.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",`systemctl enable --now ${t}-liveness.timer >/dev/null 2>&1 || true`]}var $s=20,Dr=3,za=5,Ba=60;function Ka(e){let{paths:t,unitBase:r,releaseId:n,port:s}=e,i=`${r}@${n}.service`,o=`${r}.service`,a=Math.max(1,e.healthGateSeconds??5),c=e.healthCheckPath?e.healthCheckPath.startsWith("/")?e.healthCheckPath:`/${e.healthCheckPath}`:null,l=c?`curl -sf -o /dev/null --max-time ${za} "http://127.0.0.1:${s}${c}"`:null,u=(d)=>`{ echo "[ts-cloud] release ${n} ${d}" >&2; ts_cloud_restore_previous; exit 1; }`;return[`TS_CLOUD_OLD_UNITS=$(systemctl list-units --plain --no-legend --type=service "${r}@*.service" 2>/dev/null | awk '{print $1}' | grep -v "^${i}$" || true)`,`TS_CLOUD_PREV_CURRENT="$(readlink ${t.current} 2>/dev/null || true)"`,"TS_CLOUD_LEGACY_STOPPED=0","ts_cloud_restore_previous() {",` journalctl -u ${i} -n 50 --no-pager >&2 || true`,` systemctl stop ${i} 2>/dev/null || true`,` systemctl disable ${i} 2>/dev/null || true`,` if [ -n "$TS_CLOUD_PREV_CURRENT" ] && [ -d "$TS_CLOUD_PREV_CURRENT" ]; then ln -sfn "$TS_CLOUD_PREV_CURRENT" ${t.current}.tmp && mv -Tf ${t.current}.tmp ${t.current}; fi`,' for TS_CLOUD_RU in ${TS_CLOUD_OLD_UNITS}; do systemctl enable "$TS_CLOUD_RU" 2>/dev/null || true; systemctl start "$TS_CLOUD_RU" 2>/dev/null || true; done',` if [ "$TS_CLOUD_LEGACY_STOPPED" -eq 1 ]; then systemctl start ${o} 2>/dev/null || true; fi`,' if [ -n "$TS_CLOUD_OLD_UNITS" ] || [ "$TS_CLOUD_LEGACY_STOPPED" -eq 1 ]; then echo "[ts-cloud] previous release restored and serving" >&2; else echo "[ts-cloud] there was no previous release to restore" >&2; fi',"}",`if [ -f /etc/systemd/system/${o} ] && systemctl is-active --quiet ${o}; then echo "[ts-cloud] retiring pre-zero-downtime unit ${o} (one-time restart cutover)"; systemctl stop ${o}; TS_CLOUD_LEGACY_STOPPED=1; fi`,'TS_CLOUD_STARTED_AT="@$(date +%s)"',`systemctl restart ${i}`,`TS_CLOUD_GATE_OK=1; for TS_CLOUD_I in $(seq 1 ${a}); do sleep 1; systemctl is-active --quiet ${i} || { TS_CLOUD_GATE_OK=0; break; }; done`,'if [ "$TS_CLOUD_GATE_OK" -ne 1 ]; then',` if journalctl -u ${i} --since "$TS_CLOUD_STARTED_AT" -o cat --no-pager 2>/dev/null | grep -iE 'EADDRINUSE|address already in use|port [0-9]+ (is )?in use|Failed to start server' >/dev/null; then`,` echo "[ts-cloud] release ${n} could not share :${s} with the previous release (no SO_REUSEPORT?) — retiring it and retrying" >&2`,' for TS_CLOUD_RU in ${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_RU" 2>/dev/null || true; done',` systemctl restart ${i}`,` for TS_CLOUD_I in $(seq 1 ${a}); do sleep 1; systemctl is-active --quiet ${i} || ${u("failed its health gate on the free port")}; done`," else",` ${u("crashed on start — the previous release was never stopped")}`," fi","fi",`if ss -ltnpH "sport = :${s}" >/dev/null 2>&1; then`," TS_CLOUD_BOUND=0",` for TS_CLOUD_I in $(seq 1 ${Ba}); do`,` TS_CLOUD_NEW_PID="$(systemctl show -p MainPID --value ${i} 2>/dev/null || true)"`,` if [ -n "$TS_CLOUD_NEW_PID" ] && [ "$TS_CLOUD_NEW_PID" != "0" ] && ss -ltnpH "sport = :${s}" 2>/dev/null | grep "pid=$TS_CLOUD_NEW_PID," >/dev/null; then TS_CLOUD_BOUND=1; break; fi`,` systemctl is-active --quiet ${i} || break`,` sleep ${Dr}`," done",` [ "$TS_CLOUD_BOUND" -eq 1 ] || ${u(`never took :${s}`)}`,"else",' echo "[ts-cloud] cannot read listener PIDs on this host — the response probes run without the bind check" >&2',"fi",...l?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${$s}); do if ${l}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${Dr}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${u(`never answered ${c}`)}`]:[],...pn(t),`systemctl enable ${i} 2>/dev/null || true`,'for TS_CLOUD_U in ${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done',`TS_CLOUD_LISTENING=0; for TS_CLOUD_I in $(seq 1 ${a}); do if ss -ltnH "sport = :${s}" 2>/dev/null | grep . >/dev/null; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done`,`if [ "$TS_CLOUD_LISTENING" -ne 1 ]; then echo "[ts-cloud] nothing is listening on ${s} after retiring the previous release — restarting ${i} on the now-free port" >&2; systemctl restart ${i}; for TS_CLOUD_I in $(seq 1 ${a}); do if ss -ltnH "sport = :${s}" 2>/dev/null | grep . >/dev/null; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done; fi`,`[ "$TS_CLOUD_LISTENING" -eq 1 ] || ${u(`is active but never bound :${s}`)}`,...l?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${$s}); do if ${l}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${Dr}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${u(`stopped answering ${c} once it served alone`)}`]:[],...Ys(t),`systemctl list-unit-files --plain --no-legend "${r}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v -e "^${i}$" -e "^${r}@\\.service$" || true; } | while read -r TS_CLOUD_U; do systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done`,`if [ -f /etc/systemd/system/${o} ]; then systemctl disable ${o} 2>/dev/null || true; rm -f /etc/systemd/system/${o}; systemctl daemon-reload; fi`]}function Nr(e){let{siteName:t,slug:r,artifactFetch:n,releaseId:s,execStart:i,envEntries:o,port:a,keepReleases:c=Ii,preStartCommands:l=[],healthCheckPath:u,healthGateSeconds:d=5,liveness:m,memoryHigh:f="auto",memoryMax:h,cpuWeight:x,ioWeight:_,tasksMax:y,stopTimeout:S}=e,R=[...x!=null?[`CPUWeight=${x}`]:[],..._!=null?[`IOWeight=${_}`]:[],...y!=null?[`TasksMax=${y}`]:[],...S?[`TimeoutStopSec=${S}`]:[]],b=e.zeroDowntime??a!=null,I=e.appDir??`/var/www/${t}`,C=Vt(I,s),E=`${r}-${t}`,H=`${E}.service`,re=mt(r,t,s),W=e.sharedPaths??[],N=qc([".env",...W,...Dt(o,W)]),q=Ot(o),k=l.length>0?[`cd ${C.release}`,...l]:[],X=["set -euo pipefail",...Ks(C),Xs(C),...n,...Pi(C,N),...Js(C),`tar xzf ${re} -C "$TS_CLOUD_STAGED"`,`rm -f ${re}`,`cat > ${C.shared}/.env <<'TS_CLOUD_ENV_EOF'`,q,"TS_CLOUD_ENV_EOF",`chmod 600 ${C.shared}/.env`,...Qs(C),`find ${C.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' ${C.shared}/.env 2>/dev/null || true`,...Mo(C,N),...k];if(b&&a!=null){let oe=`${E}@${s}.service`,fe=u?u.startsWith("/")?u:`/${u}`:null;return[...X,`cat > /etc/systemd/system/${E}@.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} release %i (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${C.releases}/%i`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...f&&f!=="auto"?[`MemoryHigh=${f}`]:[],...h?[`MemoryMax=${h}`]:[],...R,`EnvironmentFile=${C.releases}/%i/.env`,`Environment=PORT=${a}`,`Environment=STX_IMAGE_CACHE_DIR=${Lo(C)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...f==="auto"?ws(`${E}@.service`):[...At(`${E}@.service`),...Ar()],...Fa(oe),...Ka({paths:C,unitBase:E,releaseId:s,port:a,healthCheckPath:fe,healthGateSeconds:d}),...mn(C,c),...m===!1?[]:Ts({...m,unitBase:E,unitPattern:`${E}@*.service`,port:a,path:m?.path??u})]}return[...X,`cat > /etc/systemd/system/${H} <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${C.current}`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...f&&f!=="auto"?[`MemoryHigh=${f}`]:[],...h?[`MemoryMax=${h}`]:[],...R,`EnvironmentFile=${C.current}/.env`,...a?[`Environment=PORT=${a}`]:[],`Environment=STX_IMAGE_CACHE_DIR=${Lo(C)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...At(H,{auto:f!=="auto",high:f!=="auto",max:Boolean(h)}),...f==="auto"?ws(H):Ar(),`systemctl enable ${H}`,`TS_CLOUD_PREV_CURRENT="$(readlink ${C.current} 2>/dev/null || true)"`,...pn(C),`systemctl restart ${H}`,`for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do sleep 1; systemctl is-active --quiet ${H} || { echo "[ts-cloud] release ${s} of ${H} did not stay up — restoring the previous release" >&2; journalctl -u ${H} -n 50 --no-pager >&2 || true; if [ -n "$TS_CLOUD_PREV_CURRENT" ] && [ -d "$TS_CLOUD_PREV_CURRENT" ] && [ "$(readlink -f "$TS_CLOUD_PREV_CURRENT")" != "$(readlink -f ${C.release})" ]; then ln -sfn "$TS_CLOUD_PREV_CURRENT" ${C.current}.tmp && mv -Tf ${C.current}.tmp ${C.current}; systemctl restart ${H} || true; fi; exit 1; }; done`,...Ys(C),...mn(C,c),...m===!1||!a?[]:Ts({...m,unitBase:E,unitPattern:H,port:a,path:m?.path??u})]}function Ur(e){let{siteName:t,artifactFetch:r,releaseId:n,keepReleases:s=Ii,preStartCommands:i=[]}=e,o=e.appDir??`/var/www/${t}`,a=Vt(o,n),c=mt(e.slug,t,n),l=i.length>0?[`cd ${a.release}`,...i]:[];return["set -euo pipefail",...Ks(a),Xs(a),...r,...Pi(a,[]),...Js(a),`tar xzf ${c} -C "$TS_CLOUD_STAGED"`,...Qs(a),`rm -f ${c}`,...l,...pn(a),...mn(a,s)]}function mt(e,t,r){return`/tmp/${[e,t,r].filter(Boolean).join("-")}-release.tar.gz`}function kr(e,t,r,n){return[`aws s3 cp "s3://${e}/${t}" ${n} --region ${r}`]}function Mr(e,t){return[`mv "${e}" ${t}`]}function Ke(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function Lt(e,t,r){return["set -euo pipefail",`chmod 600 ${Ke(e)}`,`mv -f -- ${Ke(e)} ${Ke(t)}`,`cp -- ${Ke(t)} ${Ke(r)}`].join(`
263
263
  `)}function Ht(e){return`rm -f -- ${Ke(e)} 2>/dev/null || true`}function Cs(e={}){let t=Math.max(1,e.appServers??e.instances??1),r=!!e.servicesServer||t>1,n=t>1||!!e.server?.loadBalancer;return{appServers:t,loadBalancer:n,dedicatedServices:r,servicesOnApp:!r}}function Ps(e,t){let r={REDIS_HOST:e,MEILISEARCH_HOST:`http://${e}:7700`};if(t?.name){if(r.DB_CONNECTION=t.engine==="postgres"?"pgsql":"mysql",r.DB_HOST=e,r.DB_PORT=String(t.port??(t.engine==="postgres"?5432:3306)),r.DB_DATABASE=t.name,t.username)r.DB_USERNAME=t.username;if(t.password)r.DB_PASSWORD=t.password}return r}function Fr(e){let t=e.infrastructure?.compute??{},r=w(e);return[..._o(t.managedServices??{mysql:!0,redis:!0},{bindPrivate:!0}),...vt(r,t.managedServices??{mysql:!0}),...he(!0),...ye(!0),...Fe(t.sshKeys),...He(e.notifications),...t.backups?.enabled?[...Oo({database:r,backups:t.backups})]:[]]}import{homedir as ja}from"node:os";import{join as Wa}from"node:path";var Nt={location:"fsn1",image:"ubuntu-24.04",sshUser:"root",sshPrivateKeyPath:"~/.ssh/id_ed25519"};function Qr(e){return e.startsWith("~/")?Wa(ja(),e.slice(2)):e}function je(...e){for(let t of e){let r=process.env[t]?.trim();if(r)return r}return}function Ve(...e){for(let t of e){let r=t?.trim();if(r)return r}return}function ft(e,t){return Ve(e,t?.hetzner?.apiToken,je("HCLOUD_TOKEN","HETZNER_API_TOKEN"))}function zr(e,t){return Ve(t,e?.hetzner?.location,je("HCLOUD_LOCATION","HETZNER_LOCATION"))??Nt.location}function gt(e,t){let r=e?.infrastructure?.compute;return Ve(t,r?.image,e?.hetzner?.image,je("HCLOUD_IMAGE","HETZNER_IMAGE"))??Nt.image}function Ga(e,t){return Ve(t,e?.hetzner?.sshUser,je("HCLOUD_SSH_USER","HETZNER_SSH_USER"))??Nt.sshUser}function Rs(e,t){return Qr(Ve(t,e?.hetzner?.sshPrivateKeyPath,je("HCLOUD_SSH_KEY","HETZNER_SSH_KEY"))??Nt.sshPrivateKeyPath)}function Va(e,t,r){let n=Ve(t,e?.hetzner?.sshPublicKeyPath,je("HCLOUD_SSH_PUBLIC_KEY","HETZNER_SSH_PUBLIC_KEY"));if(n)return Qr(n);return`${r??Rs(e)}.pub`}function lr(e,t={}){let r=Rs(e,t.sshPrivateKeyPath);return{apiToken:ft(t.apiToken,e),location:zr(e,t.location),image:gt(e,t.image),sshUser:Ga(e,t.sshUser),sshPrivateKeyPath:r,sshPublicKeyPath:Va(e,t.sshPublicKeyPath,r)}}var qa="https://api.hetzner.cloud/v1";class Ut extends Error{status;code;details;constructor(e,t,r,n){super(e);this.status=t;this.code=r;this.details=n;this.name="HetznerApiError"}}class kt extends Error{action;constructor(e,t){super(e);this.action=t;this.name="HetznerActionError"}}class We{name="hetzner";apiToken;baseUrl;fetchImpl;constructor(e){this.apiToken=e.apiToken,this.baseUrl=e.baseUrl??qa,this.fetchImpl=e.fetchImpl??fetch}async request(e,t,r){let n=await this.fetchImpl(`${this.baseUrl}${t}`,{method:e,headers:{Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},body:r===void 0?void 0:JSON.stringify(r)}),s=await n.text(),i;try{i=s?JSON.parse(s):{}}catch{if(!n.ok){let o=s.trim().slice(0,200)||n.statusText||"Hetzner API error";throw Error(`Hetzner API ${e} ${t} (${n.status}): ${o}`)}throw Error(`Hetzner API ${e} ${t}: unexpected non-JSON response`)}if(!n.ok){let o=i.error?.message||n.statusText||"Hetzner API error",a=i.error?.code?` [${i.error.code}]`:"";throw new Ut(`Hetzner API ${e} ${t} (${n.status})${a}: ${o}`,n.status,i.error?.code,i.error?.details)}return i}async requestAll(e,t){let r=[],n=1;for(;;){let s=e.includes("?")?"&":"?",i=await this.request("GET",`${e}${s}per_page=50&page=${n}`);r.push(...i[t]??[]);let o=i.meta?.pagination?.next_page;if(!o)return r;n=o}}async listServers(){return this.requestAll("/servers","servers")}async getServer(e){return(await this.request("GET",`/servers/${e}`)).server}async getServerMetrics(e,t){let r=new URLSearchParams({type:t.types.join(","),start:t.start.toISOString(),end:t.end.toISOString(),step:String(Math.max(60,Math.floor(t.step??60)))});return(await this.request("GET",`/servers/${e}/metrics?${r}`)).metrics}async listServerTypes(e){let t=e?`?name=${encodeURIComponent(e)}`:"";return this.requestAll(`/server_types${t}`,"server_types")}async getServerType(e){return(await this.listServerTypes(e)).find((t)=>t.name===e)??null}async createServer(e){let t=await this.request("POST","/servers",{name:e.name,server_type:e.serverType,image:e.image,location:e.location,datacenter:e.datacenter,ssh_keys:e.sshKeys,user_data:e.userData,labels:e.labels,firewalls:e.firewalls,networks:e.networks,start_after_create:!0});return{server:t.server,action:t.action}}async listNetworks(){return this.requestAll("/networks","networks")}async createNetwork(e){let t=e.ipRange??"10.0.0.0/16";return(await this.request("POST","/networks",{name:e.name,ip_range:t,subnets:[{type:"cloud",ip_range:t,network_zone:"eu-central"}],labels:e.labels})).network}async deleteNetwork(e){await this.request("DELETE",`/networks/${e}`)}async listLoadBalancers(){return this.requestAll("/load_balancers","load_balancers")}async createLoadBalancer(e){return(await this.request("POST","/load_balancers",{name:e.name,load_balancer_type:e.type??"lb11",location:e.location,network_zone:e.network?void 0:e.networkZone??"eu-central",network:e.network,labels:e.labels,targets:[{type:"label_selector",label_selector:{selector:e.labelSelector},use_private_ip:!!e.network}],services:e.services.map((r)=>({protocol:r.protocol??"tcp",listen_port:r.listenPort,destination_port:r.destinationPort,health_check:{protocol:"http",port:80,interval:15,timeout:10,retries:3,http:{path:"/",status_codes:["2??","3??"]}}}))})).load_balancer}async deleteLoadBalancer(e){await this.request("DELETE",`/load_balancers/${e}`)}async deleteServer(e){return(await this.request("DELETE",`/servers/${e}`)).action}async listFirewalls(){return this.requestAll("/firewalls","firewalls")}async createFirewall(e){let t=await this.request("POST","/firewalls",{name:e.name,rules:e.rules,labels:e.labels,apply_to:e.applyTo});return{firewall:t.firewall,actions:t.actions}}async setFirewallRules(e,t){return(await this.request("POST",`/firewalls/${e}/actions/set_rules`,{rules:t})).actions??[]}async deleteFirewall(e){await this.request("DELETE",`/firewalls/${e}`)}async applyFirewallToResources(e,t){return(await this.request("POST",`/firewalls/${e}/actions/apply_to_resources`,{apply_to:t})).actions}async listSshKeys(){return this.requestAll("/ssh_keys","ssh_keys")}async createSshKey(e){return(await this.request("POST","/ssh_keys",{name:e.name,public_key:e.publicKey,labels:e.labels})).ssh_key}async deleteSshKey(e){await this.request("DELETE",`/ssh_keys/${e}`)}async getAction(e){return(await this.request("GET",`/actions/${e}`)).action}async shutdownServer(e){return(await this.request("POST",`/servers/${e}/actions/shutdown`,{})).action}async powerOnServer(e){return(await this.request("POST",`/servers/${e}/actions/poweron`,{})).action}async changeServerType(e,t,r){return(await this.request("POST",`/servers/${e}/actions/change_type`,{server_type:t,upgrade_disk:r})).action}async powerOffServer(e){return(await this.request("POST",`/servers/${e}/actions/poweroff`,{})).action}async stopServer(e,t){if((await this.getServer(e)).status==="off")return;await this.shutdownServer(e);let n=t?.gracefulWaitMs??120000,s=t?.pollIntervalMs??3000,i=Date.now();while(Date.now()-i<n){if((await this.getServer(e)).status==="off")return;await new Promise((a)=>setTimeout(a,s))}let o=await this.powerOffServer(e);await this.waitForAction(o.id),await this.waitForServerStatus(e,"off")}async renameServer(e,t){return(await this.request("PUT",`/servers/${e}`,{name:t})).server}async listImages(e){let t=e?.type?`?type=${encodeURIComponent(e.type)}`:"";return this.requestAll(`/images${t}`,"images")}async getImage(e){return(await this.request("GET",`/images/${e}`)).image}async createImage(e,t){return this.request("POST",`/servers/${e}/actions/create_image`,{description:t.description,type:t.type??"snapshot",labels:t.labels})}async deleteImage(e){await this.request("DELETE",`/images/${e}`)}async rebuildServer(e,t){return(await this.request("POST",`/servers/${e}/actions/rebuild`,{image:t})).action}async listPrimaryIps(){return this.requestAll("/primary_ips","primary_ips")}async unassignPrimaryIp(e){return(await this.request("POST",`/primary_ips/${e}/actions/unassign`,{})).action}async assignPrimaryIp(e,t){return(await this.request("POST",`/primary_ips/${e}/actions/assign`,{assignee_id:t,assignee_type:"server"})).action}async waitForAction(e,t){let r=t?.pollIntervalMs??2000,n=t?.maxWaitMs??300000,s=Date.now();while(Date.now()-s<n){let i=await this.getAction(e);if(i.status==="success")return i;if(i.status==="error")throw new kt(i.error?.message||"Hetzner action failed",i);await new Promise((o)=>setTimeout(o,r))}throw Error(`Timed out waiting for Hetzner action ${e}`)}async waitForServerRunning(e,t){let r=t?.pollIntervalMs??3000,n=t?.maxWaitMs??600000,s=Date.now();while(Date.now()-s<n){let i=await this.getServer(e);if(i.status==="running")return i;await new Promise((o)=>setTimeout(o,r))}throw Error(`Timed out waiting for server ${e} to reach running state`)}async waitForServerStatus(e,t,r){let n=r?.pollIntervalMs??3000,s=r?.maxWaitMs??600000,i=Date.now();while(Date.now()-i<s){let o=await this.getServer(e);if(o.status===t)return o;await new Promise((a)=>setTimeout(a,n))}throw Error(`Timed out waiting for server ${e} to reach ${t} state`)}}function dr(e,t){let r=ft(e,t);if(!r)throw Error("Hetzner API token required. Set hetzner.apiToken in cloud.config.ts or HCLOUD_TOKEN / HETZNER_API_TOKEN.");return r}function ht(e){let[t,r]=e.trim().split(/\s+/);return r?`${t} ${r}`:t}function Es(e){if(!e)return"";return e.endsWith(`
264
264
  `)?e:`${e}
265
265
  `}function de(e,t={}){let r=t.scriptPath??"/var/lib/cloud/ts-cloud-bootstrap.sh",n=t.permissions??"0755",s=e.split(`
@@ -276,7 +276,7 @@ runcmd:
276
276
  ${Es(t.after)}`}function Yr(e){let t=new Set([80,443,...e.sitePorts,...e.allowedPorts??[]]);if(e.allowSsh)t.add(22);return[...t].map((r)=>({direction:"in",protocol:"tcp",port:String(r),source_ips:["0.0.0.0/0","::/0"],description:`ts-cloud port ${r}`}))}var Br={micro:"cpx11",small:"cx23",medium:"cx33",large:"cx43",xlarge:"cx53","2xlarge":"ccx33"};function dt(e){if(!e)return Br.micro;if(e in Br)return Br[e];return e}var K="ts-cloud";function j(e,t,r="app"){return{[`${K}/project`]:e,[`${K}/environment`]:t,[`${K}/role`]:r,[`${K}/managed-by`]:"ts-cloud"}}function te(e,t,r,n="app"){return Kr(e,t,r)&&e[`${K}/role`]===n}function Kr(e,t,r){if(!e)return!1;return e[`${K}/project`]===t&&e[`${K}/environment`]===r}import{mkdir as Xa,readFile as Ya,rename as Ja,writeFile as Qa}from"node:fs/promises";import{join as Os}from"node:path";var jr="storage/cloud/state";function be(e=process.cwd()){return oa()?A(e,"state"):Os(e,jr)}function Xe(e,t=process.cwd()){return Os(be(t),`${e}.json`)}async function Ie(e,t=process.cwd()){try{let r=await Ya(Xe(e,t),"utf8");return JSON.parse(r)}catch{return null}}async function Ye(e,t,r=process.cwd()){let n=Xe(e,r);await Xa(be(r),{recursive:!0});let s=`${n}.${process.pid}.tmp`;await Qa(s,`${JSON.stringify(t,null,2)}
277
277
  `,"utf8"),await Ja(s,n)}async function pe(e){return Ie(e)}async function ut(e,t){await Ye(e,t)}var Wr=268435456;function yt(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function sc(e){let t=ec("sha256");for await(let r of tc(e))t.update(r);return t.digest("hex")}class _e{name="hetzner";usesCloudFormation=!1;client;sshPrivateKeyPath;sshPublicKeyPath;sshUser;location;stateOnly;waitForBoot;bootWait;constructor(e={}){let t=ft(e.apiToken);if(this.stateOnly=!e.client&&!t&&e.allowStateOnly===!0,!e.client&&!t&&!this.stateOnly)throw Error("Hetzner API token required. Set hetzner.apiToken in cloud.config.ts or HCLOUD_TOKEN / HETZNER_API_TOKEN.");this.client=e.client??new We({apiToken:t??""});let r=lr(void 0,{sshPrivateKeyPath:e.sshPrivateKeyPath,sshPublicKeyPath:e.sshPublicKeyPath,sshUser:e.sshUser,location:e.location});this.sshPrivateKeyPath=r.sshPrivateKeyPath,this.sshPublicKeyPath=r.sshPublicKeyPath,this.sshUser=r.sshUser,this.location=r.location,this.waitForBoot=e.waitForBoot??!0,this.bootWait={sshIntervalMs:e.bootWait?.sshIntervalMs??5000,sshTimeoutMs:e.bootWait?.sshTimeoutMs??300000,cloudInitIntervalMs:e.bootWait?.cloudInitIntervalMs??5000,cloudInitTimeoutMs:e.bootWait?.cloudInitTimeoutMs??600000}}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e,n=t.project.slug,s=t.infrastructure?.compute;if(!s)throw Error("infrastructure.compute is required to provision Hetzner compute");if(t.cloud?.attachTo)return this.attachToComputeInfrastructure(t.cloud.attachTo,t,r);let i=T(t,r),o=`${n}-${r}-app`,a=s.runtime==="php"||!!s.php,c=Cs(s);if(c.dedicatedServices||c.appServers>1)return a?this.provisionFleet(e,c):this.provisionBunFleet(e,c);let l=j(n,r,"app"),u=t.sites||{},d=Z(s)?[]:this.collectUpstreamPorts(u),m=`${n}-${r}-app-fw`,{firewall:f}=await this.ensureFirewall(m,l,Yr({allowSsh:s.allowSsh!==!1,sitePorts:d,allowedPorts:[...s.firewall?.allowedPorts??[],...Vn(t.infrastructure?.sftp)]})),h=await this.ensureSshKey(n,r,l),x=await pe(i);if(x?.serverId){let k=await this.tryGetServer(x.serverId);if(k&&k.status!=="off")return this.outputsFromState(x,k)}let _=await this.findExistingServer(n,r,o);if(_&&_.status!=="off"){let k={provider:"hetzner",stackName:i,serverId:_.id,serverName:_.name,publicIp:_.public_net.ipv4?.ip,publicIpv6:ue(_.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await ut(i,k),this.outputsFromState(k,_)}let y=s.proxy?.engine==="rpx"?le({proxy:s.proxy,config:Se(u,{proxy:s.proxy,slug:t.project.slug}),slug:t.project.slug,bunBin:s.runtime==="node"||s.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,S=Re(t,{environment:r}),R=s.bakedImage===!0,b=ee({runtime:S.runtime,runtimeVersion:S.runtimeVersion,systemPackages:s.systemPackages,database:t.infrastructure?.database,phpProvision:S.phpProvision,servicesProvision:S.servicesProvision,rpxProvision:y,baked:R,swapGb:s.swapGb}),I=de(b),C=dt(s.size),E=gt(t),{server:H,action:re}=await this.client.createServer({name:o,serverType:C,image:E,location:t.hetzner?.location||this.location,userData:I,labels:l,sshKeys:h?[h]:void 0,firewalls:[{firewall:f.id}]});await this.client.waitForAction(re.id);let W=await this.client.waitForServerRunning(H.id),N={provider:"hetzner",stackName:i,serverId:W.id,serverName:W.name,firewallId:f.id,publicIp:W.public_net.ipv4?.ip,publicIpv6:ue(W.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};await ut(i,N);let q=W.public_net.ipv4?.ip;if(q&&this.waitForBoot)await this.waitForSshReady(q),await this.waitForCloudInit(q);return this.outputsFromState(N,W)}async provisionFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,i=r.infrastructure.compute,o=T(r,n),a=dt(i.size),c=gt(r),l=r.hetzner?.location||this.location,u=i.bakedImage===!0,d=await pe(o);if(d?.loadBalancerId){let M=(await this.client.listLoadBalancers().catch(()=>[])).find((D)=>D.id===d.loadBalancerId);if(M)return{appPublicIp:M.public_net?.ipv4?.ip,loadBalancerIp:M.public_net?.ipv4?.ip,servicesPrivateIp:d.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}let m=await this.ensureSshKey(s,n,j(s,n,"app")),f=`${s}-${n}-net`,x=(await this.client.listNetworks().catch(()=>[])).find((L)=>L.name===f)??await this.client.createNetwork({name:f,labels:j(s,n,"app")}),{firewall:_}=await this.ensureFirewall(`${s}-${n}-app-fw`,j(s,n,"app"),Yr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),{firewall:y}=await this.ensureFirewall(`${s}-${n}-services-fw`,j(s,n,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[x.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[x.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[x.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[x.ip_range]}]),S=Fr(r),R=de(ee({runtime:"php",servicesProvision:S,baked:u,swapGb:i.swapGb})),b=await this.client.listServers().catch(()=>[]),I=[],C=b.find((L)=>te(L.labels,s,n,"services"));if(!C){let{server:L,action:M}=await this.client.createServer({name:`${s}-${n}-services`,serverType:dt(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:c,location:l,userData:R,labels:j(s,n,"services"),sshKeys:m?[m]:void 0,firewalls:[{firewall:y.id}],networks:[x.id]});await this.client.waitForAction(M.id),C=await this.client.waitForServerRunning(L.id),I.push(L.id)}let E=C.id,H=C.private_net?.[0]?.ip??(await this.client.getServer(E)).private_net?.[0]?.ip,re=[...he(!0),...ye(!0),...Fe(i.sshKeys),...He(r.notifications)],W=Ct({versions:i.php?.versions,default:i.php?.default,extensions:i.php?.extensions,installNginx:!Z(i),optimizeForProduction:i.php?.optimizeForProduction,ini:i.php?.ini}),N=de(ee({runtime:"php",phpProvision:W,servicesProvision:re,baked:u,swapGb:i.swapGb})),q=b.filter((L)=>te(L.labels,s,n,"app")),k=q.map((L)=>L.id);if(q.length>t.appServers)for(let L of q.slice(t.appServers))await this.client.deleteServer(L.id).catch(()=>{}),k.splice(k.indexOf(L.id),1);for(let L=q.length;L<t.appServers;L++){let{server:M,action:D}=await this.client.createServer({name:`${s}-${n}-app-${L+1}`,serverType:a,image:c,location:l,userData:N,labels:j(s,n,"app"),sshKeys:m?[m]:void 0,firewalls:[{firewall:_.id}],networks:[x.id]});await this.client.waitForAction(D.id),k.push(M.id),I.push(M.id)}if(this.waitForBoot&&I.length>0)await Promise.all(I.map(async(L)=>{let D=(await this.client.waitForServerRunning(L)).public_net.ipv4?.ip;if(D)await this.waitForSshReady(D),await this.waitForCloudInit(D)}));let X=`${s}-${n}-lb`,oe,fe;if(t.loadBalancer){let M=(await this.client.listLoadBalancers().catch(()=>[])).find((D)=>D.name===X)??await this.client.createLoadBalancer({name:X,location:l,network:x.id,labels:j(s,n,"lb"),labelSelector:`ts-cloud/project=${s},ts-cloud/environment=${n},ts-cloud/role=app`,services:[{listenPort:80,destinationPort:80},{listenPort:443,destinationPort:443}]});fe=M.id,oe=M.public_net?.ipv4?.ip}let $e=oe??(await this.client.getServer(k[0]).catch(()=>{return}))?.public_net.ipv4?.ip,ne={provider:"hetzner",stackName:o,networkId:x.id,loadBalancerId:fe,servicesServerId:E,servicesPrivateIp:H,publicIp:$e,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await ut(o,ne),{appPublicIp:$e,loadBalancerIp:oe,servicesPrivateIp:H,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async provisionBunFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,i=r.infrastructure.compute,o=T(r,n),a=dt(i.size),c=gt(r),l=r.hetzner?.location||this.location,u=i.bakedImage===!0,d=r.sites||{},m=await pe(o);if(m?.lbServerId){let D=await this.tryGetServer(m.lbServerId);if(D&&D.status!=="off"){let z=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"},B=await this.findComputeTargets({slug:s,environment:n,role:"app",stackName:o});return this.refreshLbRoutes(D,d,B.map((ae)=>({privateIp:ae.privateIp,publicIp:ae.publicIp})),z,s),{appPublicIp:D.public_net.ipv4?.ip??m.publicIp,loadBalancerIp:D.public_net.ipv4?.ip??m.publicIp,servicesPrivateIp:m.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}}let f=await this.ensureSshKey(s,n,j(s,n,"app")),h=`${s}-${n}-net`,_=(await this.client.listNetworks().catch(()=>[])).find((D)=>D.name===h)??await this.client.createNetwork({name:h,labels:j(s,n,"app")}),y=this.collectUpstreamPorts(d),{firewall:S}=await this.ensureFirewall(`${s}-${n}-app-fw`,j(s,n,"app"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},...y.map((D)=>({direction:"in",protocol:"tcp",port:String(D),source_ips:[_.ip_range],description:`ts-cloud port ${D} (private, LB-only)`}))]),{firewall:R}=await this.ensureFirewall(`${s}-${n}-lb-fw`,j(s,n,"lb"),Yr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),b=await this.client.listServers().catch(()=>[]),I=[],C,E,H=!!i.servicesServer||!!i.managedServices,re=t.dedicatedServices&&H;if(re){let{firewall:D}=await this.ensureFirewall(`${s}-${n}-services-fw`,j(s,n,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[_.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[_.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[_.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[_.ip_range]}]),z=Fr(r),B=de(ee({runtime:"bun",servicesProvision:z,baked:u,swapGb:i.swapGb})),ae=b.find((ge)=>te(ge.labels,s,n,"services"));if(!ae){let{server:ge,action:rt}=await this.client.createServer({name:`${s}-${n}-services`,serverType:dt(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:c,location:l,userData:B,labels:j(s,n,"services"),sshKeys:f?[f]:void 0,firewalls:[{firewall:D.id}],networks:[_.id]});await this.client.waitForAction(rt.id),ae=await this.client.waitForServerRunning(ge.id),I.push(ge.id)}C=ae.id,E=ae.private_net?.[0]?.ip??(await this.client.getServer(C)).private_net?.[0]?.ip}let W=re?{...i,managedServices:void 0,backups:void 0}:i,N=Re({...r,infrastructure:{...r.infrastructure,compute:W}},{environment:n}),q=de(ee({runtime:N.runtime,runtimeVersion:N.runtimeVersion,systemPackages:i.systemPackages,database:r.infrastructure?.database,servicesProvision:N.servicesProvision,baked:u,swapGb:i.swapGb})),k=b.filter((D)=>te(D.labels,s,n,"app")),X=k.map((D)=>D.id);if(k.length>t.appServers)for(let D of k.slice(t.appServers))await this.client.deleteServer(D.id).catch(()=>{}),X.splice(X.indexOf(D.id),1);for(let D=k.length;D<t.appServers;D++){let{server:z,action:B}=await this.client.createServer({name:`${s}-${n}-app-${D+1}`,serverType:a,image:c,location:l,userData:q,labels:j(s,n,"app"),sshKeys:f?[f]:void 0,firewalls:[{firewall:S.id}],networks:[_.id]});await this.client.waitForAction(B.id),X.push(z.id),I.push(z.id)}if(this.waitForBoot&&I.length>0)await Promise.all(I.map(async(D)=>{let B=(await this.client.waitForServerRunning(D)).public_net.ipv4?.ip;if(B)await this.waitForSshReady(B),await this.waitForCloudInit(B)}));let oe=[];for(let D of X){let z=b.find((B)=>B.id===D);if(!z||!z.private_net?.[0]?.ip)z=await this.client.getServer(D).catch(()=>z);oe.push({privateIp:z?.private_net?.[0]?.ip,publicIp:z?.public_net.ipv4?.ip})}let fe=`${s}-${n}-lb`,$e,ne;if(t.loadBalancer){let D=b.find((B)=>te(B.labels,s,n,"lb")),z=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"};if(!D){let B=le({proxy:z,config:Me(d,oe,{proxy:z,slug:s}),slug:s,bunBin:N.runtime==="node"||N.runtime==="deno"?void 0:"/usr/local/bin/bun"}),ae=de(ee({runtime:"bun",rpxProvision:B,baked:!1})),ge=typeof i.loadBalancer==="object"?i.loadBalancer.size:void 0,{server:rt,action:er}=await this.client.createServer({name:fe,serverType:dt(ge??"micro"),image:c,location:l,userData:ae,labels:j(s,n,"lb"),sshKeys:f?[f]:void 0,firewalls:[{firewall:R.id}],networks:[_.id]});if(await this.client.waitForAction(er.id),D=await this.client.waitForServerRunning(rt.id),this.waitForBoot){let nt=D.public_net.ipv4?.ip;if(nt)await this.waitForSshReady(nt),await this.waitForCloudInit(nt)}}else this.refreshLbRoutes(D,d,oe,z,s);$e=D.id,ne=D.public_net.ipv4?.ip}let L=ne??(await this.client.getServer(X[0]).catch(()=>{return}))?.public_net.ipv4?.ip,M={provider:"hetzner",stackName:o,networkId:_.id,lbServerId:$e,appServerIds:X,servicesServerId:C,servicesPrivateIp:E,publicIp:L,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await ut(o,M),{appPublicIp:L,loadBalancerIp:ne,servicesPrivateIp:E,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async destroyCompute(e){let{config:t,environment:r}=e,n=t.project.slug,s=T(t,r),i=await pe(s),o=[],a=`${n}-${r}-lb`,l=(await this.client.listLoadBalancers().catch(()=>[])).find((S)=>S.name===a);if(l)try{await this.client.deleteLoadBalancer(l.id),o.push(`load balancer ${a}`)}catch{}let u=await this.client.listServers().catch(()=>[]),d=new Set;for(let S of u)if(te(S.labels,n,r,"app")||te(S.labels,n,r,"services")||te(S.labels,n,r,"lb"))d.add(S.id);if(i?.serverId)d.add(i.serverId);if(i?.servicesServerId)d.add(i.servicesServerId);if(i?.lbServerId)d.add(i.lbServerId);for(let S of i?.appServerIds??[])d.add(S);for(let S of d)try{await this.client.deleteServer(S),o.push(`server ${S}`)}catch{}let m=await this.client.listFirewalls().catch(()=>[]);for(let S of[`${n}-${r}-app-fw`,`${n}-${r}-services-fw`,`${n}-${r}-lb-fw`]){let R=m.find((b)=>b.name===S);if(!R)continue;for(let b=0;b<12;b++)try{await this.client.deleteFirewall(R.id),o.push(`firewall ${S}`);break}catch{await this.sleep(3000)}}let f=`${n}-${r}-net`,x=(await this.client.listNetworks().catch(()=>[])).find((S)=>S.name===f);if(x)for(let S=0;S<12;S++)try{await this.client.deleteNetwork(x.id),o.push(`network ${f}`);break}catch{await this.sleep(3000)}let y=(await this.client.listSshKeys().catch(()=>[])).filter((S)=>Kr(S.labels,n,r));for(let S of y)try{await this.client.deleteSshKey(S.id),o.push(`ssh key ${S.name}`)}catch{}return await ut(s,{provider:"hetzner",stackName:s}).catch(()=>{}),{destroyed:o}}async getComputeOutputs(e){let t=T(e.config,e.environment),r=await pe(t);if(r?.serverId){let i=await this.tryGetServer(r.serverId);if(i)return this.outputsFromState(r,i)}if(r?.lbServerId){let o=(await this.tryGetServer(r.lbServerId))?.public_net.ipv4?.ip??r.publicIp;return{...this.outputsFromState(r),appPublicIp:o,loadBalancerIp:o}}if(r?.loadBalancerId||r?.servicesPrivateIp)return this.outputsFromState(r);let s=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:T(e.config,e.environment)}))[0];return{deployStoragePath:"/var/ts-cloud/staging",appInstanceId:s?.id,appPublicIp:s?.publicIp,sshUser:this.sshUser}}async uploadRelease(e){let t=e.targets?.length?e.targets:await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:T(e.config,e.environment)});if(t.length===0)throw Error("No Hetzner compute targets found for release upload");let s=`/var/ts-cloud/staging/${`${e.remoteKey.replace(/^releases\//,"").replace(/\.tar\.gz$/,"").replace(/\//g,"-")}-${Is()}.tar.gz`}`,i=await sc(e.localPath),o=Be,a=`${o}/${i}.tar.gz`;for(let c of t){if(!c.publicIp)throw Error(`Target ${c.id} has no public IP for SCP upload`);let l=["set -euo pipefail",`mkdir -p ${yt(o)} /var/ts-cloud/staging`,`test -s ${yt(a)}`,`cp -- ${yt(a)} ${yt(s)}`].join(`
278
278
  `);try{this.sshExec(c.publicIp,l);continue}catch{}let u=`${o}/.${i}-${Is()}.tmp`;try{this.scpToHost(c.publicIp,e.localPath,u),this.sshExec(c.publicIp,Lt(u,a,s))}catch(d){try{this.sshExec(c.publicIp,Ht(u))}catch{}throw d}}return{artifactRef:s}}async findComputeTargets(e){let t=e.role||"app",r=(i)=>({id:String(i.id),name:i.name,publicIp:i.public_net.ipv4?.ip,publicIpv6:ue(i.public_net.ipv6?.ip),privateIp:i.private_net?.[0]?.ip,status:i.status});if(t==="app"||t==="lb"||t==="services"){let i=await pe(e.stackName??`${e.slug}-${e.environment}`),o=[...new Set(t==="app"?[i?.serverId,...i?.appServerIds??[]]:t==="lb"?[i?.lbServerId]:[i?.servicesServerId])].filter((l)=>typeof l==="number");if(this.stateOnly){if(o.length>0&&i?.publicIp)return o.map((l)=>({id:String(l),name:l===i.serverId?i.serverName:void 0,publicIp:i.publicIp,publicIpv6:i.publicIpv6,status:"running"}));if(t!=="app")return[];throw Error(`Hetzner API token required because '${e.stackName??`${e.slug}-${e.environment}`}' has no complete local compute state pin.`)}let a=await this.client.listServers();if(o.length>0){let l=[];for(let u of o){let d=a.find((m)=>m.id===u)??await this.tryGetServer(u);if(u===i?.serverId&&i.serverName&&d?.name!==i.serverName)continue;if(d&&d.status!=="off")l.push(d)}if(l.length>0)return l.map(r)}let c=a.filter((l)=>te(l.labels,e.slug,e.environment,t));if(c.length>0)return c.map(r);if(t==="app"){let l=a.filter((u)=>u.status!=="off"&&u.labels?.[`${K}/managed-by`]==="ts-cloud"&&u.labels?.[`${K}/environment`]===e.environment&&u.labels?.[`${K}/role`]==="app");if(l.length===1)return l.map(r)}return[]}if(this.stateOnly)throw Error(`Hetzner API token required to discover '${t}' compute targets.`);let s=(await this.client.listServers()).filter((i)=>te(i.labels,e.slug,e.environment,t));if(s.length>0)return s.map(r);return[]}async attachToComputeInfrastructure(e,t,r){let n=await this.client.listServers(),s=(m)=>n.filter((f)=>f.status!=="off"&&te(f.labels,e,r,m)),i=s("app");if(i.length===0)throw Error(`Cannot attach '${t.project.slug}' to '${e}': no running Hetzner app server is labeled for ${e}/${r}. Deploy the owner project first.`);let o=s("lb")[0],a=s("services")[0],c=i[0],l=o??c,u=T(t,r),d={provider:"hetzner",stackName:u,serverId:c.id,serverName:c.name,appServerIds:i.map((m)=>m.id),lbServerId:o?.id,servicesServerId:a?.id,servicesPrivateIp:a?.private_net?.[0]?.ip,publicIp:l.public_net.ipv4?.ip,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await ut(u,d),this.outputsFromState(d)}async listReachableResources(){return(await this.client.listServers()).map((t)=>({name:t.name,labels:t.labels}))}async runRemoteDeploy(e){if(e.targets.length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets provided"};let t=e.commands.join(`
279
- `),r=[];for(let s of e.targets){if(!s.publicIp){r.push({instanceId:s.id,status:"Failed",error:"Missing public IP"});continue}try{let i=this.sshExec(s.publicIp,t);Le(i),r.push({instanceId:s.id,status:"Success",output:i})}catch(i){r.push({instanceId:s.id,status:"Failed",error:i.message})}}let n=r.every((s)=>s.status==="Success");return{success:n,instanceCount:e.targets.length,perInstance:r,error:n?void 0:xe(r,"One or more SSH deploy commands failed")}}async ensureSshKey(e,t,r){if(!rc(this.sshPublicKeyPath))throw Error(`SSH public key not found at ${this.sshPublicKeyPath}. ts-cloud deploys to Hetzner over SSH and needs a public key to authorize on the server. Generate one (\`ssh-keygen -t ed25519\`) or set hetzner.sshPrivateKeyPath / HCLOUD_SSH_PUBLIC_KEY.`);let n=nc(this.sshPublicKeyPath,"utf8").trim(),s=ht(n),o=(await this.client.listSshKeys()).find((c)=>ht(c.public_key)===s);if(o)return o.id;return(await this.client.createSshKey({name:`${e}-${t}-deploy`,publicKey:n,labels:r})).id}async tryGetServer(e){try{return await this.client.getServer(e)}catch{return null}}refreshLbRoutes(e,t,r,n,s){let i=e.public_net.ipv4?.ip;if(!i){console.warn(`[ts-cloud] LB server '${e.name}' has no public IP — skipping the rpx route refresh; its routes may be stale.`);return}let o=r.filter((c)=>c.privateIp||c.publicIp);if(o.length===0){console.warn(`[ts-cloud] No routable app boxes found for LB '${e.name}' — leaving its current rpx routes untouched.`);return}let a=Me(t,o,{proxy:n,slug:s});this.sshExec(i,qe({config:a,slug:s}).join(`
279
+ `),r=[];for(let s of e.targets){if(!s.publicIp){r.push({instanceId:s.id,status:"Failed",error:"Missing public IP"});continue}try{let i=this.sshExec(s.publicIp,t);Le(i),r.push({instanceId:s.id,status:"Success",output:i})}catch(i){r.push({instanceId:s.id,status:"Failed",error:i.message})}}let n=r.every((s)=>s.status==="Success");return{success:n,instanceCount:e.targets.length,perInstance:r,error:n?void 0:xe(r,"One or more SSH deploy commands failed")}}async ensureSshKey(e,t,r){if(!rc(this.sshPublicKeyPath))throw Error(`SSH public key not found at ${this.sshPublicKeyPath}. ts-cloud deploys to Hetzner over SSH and needs a public key to authorize on the server. Generate one (\`ssh-keygen -t ed25519\`) or set hetzner.sshPrivateKeyPath / HCLOUD_SSH_PUBLIC_KEY.`);let n=nc(this.sshPublicKeyPath,"utf8").trim(),s=ht(n),o=(await this.client.listSshKeys()).find((c)=>ht(c.public_key)===s);if(o)return o.id;return(await this.client.createSshKey({name:`${e}-${t}-deploy`,publicKey:n,labels:r})).id}async tryGetServer(e){try{return await this.client.getServer(e)}catch{return null}}refreshLbRoutes(e,t,r,n,s){let i=e.public_net.ipv4?.ip;if(!i){console.warn(`[ts-cloud] LB server '${e.name}' has no public IP — skipping the rpx route refresh; its routes may be stale.`);return}let o=r.filter((c)=>c.privateIp||c.publicIp);if(o.length===0){console.warn(`[ts-cloud] No routable app boxes found for LB '${e.name}' — leaving its current rpx routes untouched.`);return}let a=Me(t,o,{proxy:n,slug:s});this.sshExec(i,Ge({config:a,slug:s}).join(`
280
280
  `))}async findExistingServer(e,t,r){let n=await this.client.listServers(),s=n.find((o)=>te(o.labels,e,t,"app")||o.name===r);if(s)return s;let i=n.filter((o)=>o.status!=="off"&&o.labels?.[`${K}/managed-by`]==="ts-cloud"&&o.labels?.[`${K}/environment`]===t&&o.labels?.[`${K}/role`]==="app");if(i.length===1){let o=i[0],a=o.labels?.[`${K}/project`]??"unknown";return console.warn(`[ts-cloud] No server named '${r}' found; adopting existing ts-cloud app server '${o.name}' (project label '${a}') for project '${e}' — `+"updating it in place instead of provisioning a new server."),o}return}async ensureFirewall(e,t,r){let s=(await this.client.listFirewalls()).find((o)=>o.name===e);if(s)return await this.client.setFirewallRules(s.id,r),{firewall:s};let{firewall:i}=await this.client.createFirewall({name:e,labels:t,rules:r});return{firewall:i}}collectUpstreamPorts(e){let t=new Set;for(let r of Object.values(e))if(typeof r.port==="number")t.add(r.port);return[...t].filter((r)=>![80,443].includes(r))}async sleep(e){await new Promise((t)=>setTimeout(t,e))}async waitForSshReady(e){let{sshIntervalMs:t,sshTimeoutMs:r}=this.bootWait,n=Date.now(),s;while(Date.now()-n<r)try{Ds(`ssh ${this.sshBaseArgs(e,["-o","ConnectTimeout=5"]).map(yt).join(" ")} true`,{stdio:"pipe",maxBuffer:Wr});return}catch(i){s=i,await this.sleep(t)}throw Error(`Timed out waiting for SSH on ${e} after ${r}ms: ${s?.message??"unknown error"}`)}async waitForCloudInit(e){let{cloudInitIntervalMs:t,cloudInitTimeoutMs:r}=this.bootWait,n=Date.now();while(Date.now()-n<r){try{let s=this.sshExec(e,"if command -v cloud-init >/dev/null 2>&1; then cloud-init status --long 2>/dev/null || true; else echo 'status: done'; fi");if(/status:\s*error/.test(s))throw Error(`cloud-init reported an error on ${e}:
281
281
  ${s}`);if(/status:\s*(?:done|degraded)/.test(s))return}catch(s){if(s instanceof Error&&/cloud-init reported an error/.test(s.message))throw s}await this.sleep(t)}throw Error(`Timed out waiting for cloud-init to finish on ${e} after ${r}ms`)}outputsFromState(e,t){return{deployStoragePath:e.deployStoragePath||"/var/ts-cloud/staging",appInstanceId:e.serverId?String(e.serverId):void 0,appPublicIp:t?.public_net.ipv4?.ip||e.publicIp,appPublicIpv6:ue(t?.public_net.ipv6?.ip)||e.publicIpv6,sshUser:e.sshUser||this.sshUser,servicesPrivateIp:e.servicesPrivateIp}}static SSH_HOST_KEY_OPTS=["-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR"];static SSH_KEEPALIVE_OPTS=["-o","ConnectTimeout=30","-o","ServerAliveInterval=15","-o","ServerAliveCountMax=4"];sshBaseArgs(e,t=[]){return["-i",this.sshPrivateKeyPath,..._e.SSH_HOST_KEY_OPTS,..._e.SSH_KEEPALIVE_OPTS,"-o","BatchMode=yes",...t,`${this.sshUser}@${e}`]}scpToHost(e,t,r){let n=["scp","-i",this.sshPrivateKeyPath,..._e.SSH_HOST_KEY_OPTS,..._e.SSH_KEEPALIVE_OPTS,"-o","BatchMode=yes",t,`${this.sshUser}@${e}:${r}`].map((i)=>`"${i.replace(/"/g,"\\\"")}"`).join(" "),s=3;for(let i=1;i<=3;i++)try{Ds(n,{stdio:"pipe",maxBuffer:Wr});return}catch(o){if(i===3)throw Error(Pe(o))}}sshExec(e,t){try{return Za("ssh",[...this.sshBaseArgs(e),$r],{encoding:"utf8",input:t,stdio:["pipe","pipe","pipe"],maxBuffer:Wr})}catch(r){throw Error(`${Pe(r)}${st(r,t)}`)}}}class Mt{name="ssh";usesCloudFormation=!1;async getComputeOutputs(){return{appPublicIp:"127.0.0.1",sshUser:"root"}}async uploadRelease(e){return{artifactRef:e.localPath}}async findComputeTargets(e){if((e.role||"app")!=="app")return[];return[{id:"localhost",name:"localhost",publicIp:"127.0.0.1",status:"running"}]}async runRemoteDeploy(e){let t=e.commands.join(`
282
282
  `);try{let r=Bun.spawn(["bash","-c",t],{stdout:"pipe",stderr:"pipe",env:process.env}),[n,s,i]=await Promise.all([new Response(r.stdout).text(),new Response(r.stderr).text(),r.exited]);return{success:i===0,instanceCount:1,perInstance:[{instanceId:"localhost",status:i===0?"Success":"Failed",output:n,error:s}]}}catch(r){return{success:!1,instanceCount:1,perInstance:[{instanceId:"localhost",status:"Failed",error:r?.message??String(r)}],error:r?.message??String(r)}}}}function Gr(){let e=process.env.TS_CLOUD_DASHBOARD_BOX;return e!=null&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}import{createHash as wc,randomUUID as fi}from"node:crypto";import{createReadStream as Tc}from"node:fs";import{isIP as $c}from"node:net";import{createHash as ic}from"node:crypto";import{appendFile as oc,mkdir as ac,readFile as cc}from"node:fs/promises";import{dirname as lc}from"node:path";var As=268435456,Ls=async(e,t)=>{let r=Bun.spawn(e,{stdin:t===void 0?"ignore":Buffer.from(t),stdout:"pipe",stderr:"pipe"}),[n,s,i]=await Promise.all([r.exited,new Response(r.stdout).text(),new Response(r.stderr).text()]);return{code:n,signal:r.signalCode,stdout:s.slice(-As),stderr:i.slice(-As)}},Hs=["-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR"],Ns=["-o","ConnectTimeout=30","-o","ServerAliveInterval=15","-o","ServerAliveCountMax=4"];function Us(e){if(e.hostKey==="insecure")return[...Hs];return["-o",`StrictHostKeyChecking=${e.hostKey.policy==="pin"?"yes":"accept-new"}`,"-o",`UserKnownHostsFile=${e.hostKey.knownHostsFile}`,"-o","LogLevel=ERROR"]}function ks(e){let t=[...Ns];if(e.connectTimeoutSec!==void 0)t[1]=`ConnectTimeout=${e.connectTimeoutSec}`;return t}function Vr(e,t,r=[]){return["-i",e.identityFile,"-p",String(e.port??22),...Us(e),...ks(e),"-o","BatchMode=yes",...r,`${e.user}@${t}`]}function Ms(e,t,r,n){return["-i",e.identityFile,"-P",String(e.port??22),...Us(e),...ks(e),"-o","BatchMode=yes",r,`${e.user}@${t}:${n}`]}function ur(e){return`SHA256:${ic("sha256").update(Buffer.from(e,"base64")).digest("base64").replace(/=+$/,"")}`}async function Yi(e,t=22,r=Ls){let n=await r(["ssh-keyscan","-T","10","-p",String(t),"-t","ed25519",e]),s=n.stdout.split(`
@@ -313,7 +313,7 @@ systemctl restart systemd-journald
313
313
  # The deploy user uploads releases as itself (scp), while the scripts run as
314
314
  # root through sudo. setgid group-writable directories let both write.
315
315
  install -d -m 2775 -g "$(id -gn ${Ae(e)})" /var/ts-cloud/artifacts /var/ts-cloud/staging
316
- `}function bc(e){let t=Ae(e),r=`/home/${e}`;return[`chown -R ${t}:"$(id -gn ${t})" ${Ae(`${r}/.ssh`)}`,`chmod 700 ${Ae(`${r}/.ssh`)}`]}function pr(e){let{config:t,environment:r,profile:n,sudoUser:s}=e;zt(t,n,e.facts?.arch);let i=t.infrastructure?.compute??{},o=t.sites??{},a=t.project.slug,c=e.lan?{...e.lan.hostname?{hostname:e.lan.hostname}:{},tls:e.lan.tls??"local-ca",...js(e)?{ip:js(e)}:{}}:void 0,l=i.proxy?.engine==="rpx"?Se(o,{proxy:i.proxy,slug:a,lan:c}):void 0,u=i.proxy?.engine==="rpx"&&l?le({proxy:i.proxy,config:l,slug:a,profile:n,bunBin:i.runtime==="node"||i.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,d=i.proxy?.engine==="rpx"&&l?qe({config:l,slug:a}):void 0,m=s?`/home/${s}/.ssh/authorized_keys`:void 0,f=Re(t,{environment:r,authorizedKeysPath:m}),h=s?[...f.servicesProvision??[],...bc(s)]:f.servicesProvision,x=[...new Set([...i.systemPackages??[],"psmisc","ca-certificates"])],_=i.swapGb??(n==="raspberry-pi"?Vs:void 0),y=ee({runtime:f.runtime,runtimeVersion:f.runtimeVersion,systemPackages:x,database:t.infrastructure?.database,phpProvision:f.phpProvision,servicesProvision:h,rpxProvision:u,swapGb:_}).replace(/^#!\/bin\/bash\nset -euo pipefail\n/,""),S=Gs(),R=l?.localCa?` lan=${l.localCa.hosts.join(",")} tls=local-ca`:c?` lan=${c.hostname??`${a}.local`} tls=${c.tls??"local-ca"}`:"",b=`#!/bin/bash
316
+ `}function bc(e){let t=Ae(e),r=`/home/${e}`;return[`chown -R ${t}:"$(id -gn ${t})" ${Ae(`${r}/.ssh`)}`,`chmod 700 ${Ae(`${r}/.ssh`)}`]}function pr(e){let{config:t,environment:r,profile:n,sudoUser:s}=e;zt(t,n,e.facts?.arch);let i=t.infrastructure?.compute??{},o=t.sites??{},a=t.project.slug,c=e.lan?{...e.lan.hostname?{hostname:e.lan.hostname}:{},tls:e.lan.tls??"local-ca",...js(e)?{ip:js(e)}:{}}:void 0,l=i.proxy?.engine==="rpx"?Se(o,{proxy:i.proxy,slug:a,lan:c}):void 0,u=i.proxy?.engine==="rpx"&&l?le({proxy:i.proxy,config:l,slug:a,profile:n,bunBin:i.runtime==="node"||i.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,d=i.proxy?.engine==="rpx"&&l?Ge({config:l,slug:a}):void 0,m=s?`/home/${s}/.ssh/authorized_keys`:void 0,f=Re(t,{environment:r,authorizedKeysPath:m}),h=s?[...f.servicesProvision??[],...bc(s)]:f.servicesProvision,x=[...new Set([...i.systemPackages??[],"psmisc","ca-certificates"])],_=i.swapGb??(n==="raspberry-pi"?Vs:void 0),y=ee({runtime:f.runtime,runtimeVersion:f.runtimeVersion,systemPackages:x,database:t.infrastructure?.database,phpProvision:f.phpProvision,servicesProvision:h,rpxProvision:u,swapGb:_}).replace(/^#!\/bin\/bash\nset -euo pipefail\n/,""),S=Gs(),R=l?.localCa?` lan=${l.localCa.hosts.join(",")} tls=local-ca`:c?` lan=${c.hostname??`${a}.local`} tls=${c.tls??"local-ca"}`:"",b=`#!/bin/bash
317
317
  set -euo pipefail
318
318
  # ts-cloud ssh bootstrap v${we} profile=${n}${R}
319
319
 
@@ -486,7 +486,7 @@ case "$root_fs" in
486
486
  xfs) xfs_growfs / ;;
487
487
  *) echo "Unsupported root filesystem: $root_fs" >&2; exit 1 ;;
488
488
  esac`,e)}async function Wc(e,t){let r=Buffer.from(t.join(`
489
- `)).toString("base64");await ke(e.host,`printf %s ${r} | base64 -d | while read -r unit; do [ -z "$unit" ] || systemctl is-active --quiet "$unit" || systemctl start "$unit"; done`,e)}async function os(e,t,r,n={recovered:!1}){if(await Tr(e.host,{...e,timeoutMs:e.sshTimeoutMs??600000}),!n.recovered)await jc(e);if(r)await Wc(e,r.runningServices);let s=await en(e),i=[],o=r?tt(r.runningServices,s.runningServices):[],a=r?tt(r.releaseLinks,s.releaseLinks):[],c=r?tt(r.routeFragments,s.routeFragments):[],l=r?tt(r.routeIds,s.routeIds):[],u=r?.persistentData.map((b)=>b.split("=")[0])??[],d=s.persistentData.map((b)=>b.split("=")[0]),m=tt(u,d),f=r?tt(r.dataCatalog,s.dataCatalog):[],h=s.routeProbes.filter((b)=>!b.ok),x=n.recovered&&r?r.cpuCores:t.cores??0,_=n.recovered&&r?r.memoryBytes:Kc(t),y=s.cpuCores>=x,S=s.memoryBytes>=_*0.9,R=n.recovered||s.rootDiskBytes>=(t.disk??0)*1e9*0.95;if(s.failedUnits.length>0)i.push(`Failed services: ${s.failedUnits.join(", ")}`);if(o.length>0)i.push(`Services did not return: ${o.join(", ")}`);if(a.length>0)i.push(`Release links changed: ${a.join(", ")}`);if(c.length>0)i.push(`Route manifests changed: ${c.join(", ")}`);if(l.length>0)i.push(`Routes disappeared: ${l.join(", ")}`);if(m.length>0)i.push(`Persistent data paths disappeared: ${m.join(", ")}`);if(f.length>0)i.push(`Databases or volumes disappeared: ${f.join(", ")}`);if(h.length>0)i.push(`Unhealthy routes: ${h.map((b)=>b.domain).join(", ")}`);if(!y)i.push(`Expected at least ${x} CPU cores, found ${s.cpuCores}`);if(!S)i.push(`Expected at least ${_} bytes of RAM`);if(!R)i.push(`Expected approximately ${t.disk??0} GB root disk`);return{ok:i.length===0,checks:{cpuCores:s.cpuCores,memoryBytes:s.memoryBytes,rootDiskBytes:s.rootDiskBytes,rootFilesystemBytes:s.rootFilesystemBytes,runningServices:s.runningServices.length,releaseLinks:s.releaseLinks.length,routeFragments:s.routeFragments.length,routes:s.routeIds.length,healthyRoutes:s.routeProbes.filter((b)=>b.ok).length,persistentDataPaths:s.persistentData.length,databasesAndVolumes:s.dataCatalog.length,failedUnits:s.failedUnits.length},failures:i}}function Kt(e){return e.split("=",1)[0]??e}function bi(e){return e.replace(/@[^.]+(?=\.service$)/,"")}function pc(e,t){let r=new Set(t.runningServices.map(bi)),n=new Set(t.routeFragments.map(Kt)),s=new Set(t.releaseLinks.map(Kt)),i=new Set(t.routeIds),o=new Set(t.dataCatalog);return{stoppedServices:e.runningServices.filter((a)=>!r.has(bi(a))),changedRouteFragments:e.routeFragments.filter((a)=>!n.has(Kt(a))),missingRouteIds:e.routeIds.filter((a)=>!i.has(a)),changedReleaseLinks:e.releaseLinks.filter((a)=>!s.has(Kt(a))),missingData:e.dataCatalog.filter((a)=>!o.has(a))}}function _i(e){return e.infrastructure?.compute??{}}function to(e){let t=_i(e),r=t.monitoring;return{firewallPorts:[...new Set([22,80,443,...t.firewall?.allowedPorts??[]])].filter((s)=>Number.isInteger(s)&&s>=1&&s<=65535).sort((s,i)=>s-i),monitoring:r!==!1&&(typeof r!=="object"||r.enabled!==!1),autoUpdates:t.autoUpdates!==!1,swapGb:Math.max(0,Math.floor(t.swapGb??2)),sshPasswordAuthentication:!1,sshMaxStartups:"100:30:200",journalMaxUse:"256M",journalRetention:"14day"}}function Vc(e){return["install -d -m 0755 /etc/ssh/sshd_config.d /etc/systemd/journald.conf.d /etc/sysctl.d /etc/fail2ban/jail.d","cat > /etc/ssh/sshd_config.d/99-ts-cloud-hardening.conf <<'TS_CLOUD_SSH_EOF'","# Managed by ts-cloud host optimization.","PasswordAuthentication no","KbdInteractiveAuthentication no","PermitRootLogin prohibit-password","MaxAuthTries 4","LoginGraceTime 30",`MaxStartups ${e.sshMaxStartups}`,"TS_CLOUD_SSH_EOF","sshd -t","systemctl reload ssh","cat > /etc/systemd/journald.conf.d/99-ts-cloud-retention.conf <<'TS_CLOUD_JOURNAL_EOF'","[Journal]",`SystemMaxUse=${e.journalMaxUse}`,`MaxRetentionSec=${e.journalRetention}`,"Compress=yes","TS_CLOUD_JOURNAL_EOF","systemctl restart systemd-journald","journalctl --vacuum-size=256M --vacuum-time=14d >/dev/null","cat > /etc/sysctl.d/99-ts-cloud-production.conf <<'TS_CLOUD_SYSCTL_EOF'","# Managed by ts-cloud host optimization.","vm.swappiness=10","vm.dirty_background_ratio=5","vm.dirty_ratio=15","net.core.somaxconn=4096","net.ipv4.tcp_max_syn_backlog=4096","net.ipv4.tcp_fin_timeout=30","net.ipv4.tcp_keepalive_time=300","net.ipv4.tcp_keepalive_intvl=30","net.ipv4.tcp_keepalive_probes=5","fs.inotify.max_user_watches=524288","TS_CLOUD_SYSCTL_EOF","sysctl --system >/dev/null","export DEBIAN_FRONTEND=noninteractive","command -v fail2ban-client >/dev/null 2>&1 || apt-get install -y fail2ban","cat > /etc/fail2ban/jail.d/99-ts-cloud-sshd.conf <<'TS_CLOUD_FAIL2BAN_EOF'","[sshd]","enabled = true","backend = systemd","bantime = 1h","findtime = 10m","maxretry = 5","TS_CLOUD_FAIL2BAN_EOF","systemctl enable --now fail2ban","systemctl restart fail2ban"]}function qc(e){if(e===0)return[];return["if ! swapon --show=NAME --noheadings 2>/dev/null | grep -qx '/swapfile'; then",` if [ ! -f /swapfile ]; then fallocate -l ${e}G /swapfile || dd if=/dev/zero of=/swapfile bs=1M count=${e*1024} status=none; fi`," chmod 600 /swapfile"," mkswap /swapfile >/dev/null"," swapon /swapfile","fi","grep -qE '^/swapfile\\s' /etc/fstab || echo '/swapfile none swap sw 0 0' >> /etc/fstab"]}function Ti(e){let t=_i(e),r=to(e),n=t.monitoring??!0,s=t.firewall??{enabled:!0};return["set -euo pipefail",...Z(t)?["systemctl disable --now nginx.service bun-gateway.service ts-cloud-nginx.service 2>/dev/null || true","systemctl reset-failed nginx.service bun-gateway.service ts-cloud-nginx.service 2>/dev/null || true"]:[],...qc(r.swapGb),...he(r.autoUpdates),...ye(n),...Vc(r),...xt(s),"systemctl daemon-reload","systemctl reset-failed"]}var Xc=String.raw`
489
+ `)).toString("base64");await ke(e.host,`printf %s ${r} | base64 -d | while read -r unit; do [ -z "$unit" ] || systemctl is-active --quiet "$unit" || systemctl start "$unit"; done`,e)}async function os(e,t,r,n={recovered:!1}){if(await Tr(e.host,{...e,timeoutMs:e.sshTimeoutMs??600000}),!n.recovered)await jc(e);if(r)await Wc(e,r.runningServices);let s=await en(e),i=[],o=r?tt(r.runningServices,s.runningServices):[],a=r?tt(r.releaseLinks,s.releaseLinks):[],c=r?tt(r.routeFragments,s.routeFragments):[],l=r?tt(r.routeIds,s.routeIds):[],u=r?.persistentData.map((b)=>b.split("=")[0])??[],d=s.persistentData.map((b)=>b.split("=")[0]),m=tt(u,d),f=r?tt(r.dataCatalog,s.dataCatalog):[],h=s.routeProbes.filter((b)=>!b.ok),x=n.recovered&&r?r.cpuCores:t.cores??0,_=n.recovered&&r?r.memoryBytes:Kc(t),y=s.cpuCores>=x,S=s.memoryBytes>=_*0.9,R=n.recovered||s.rootDiskBytes>=(t.disk??0)*1e9*0.95;if(s.failedUnits.length>0)i.push(`Failed services: ${s.failedUnits.join(", ")}`);if(o.length>0)i.push(`Services did not return: ${o.join(", ")}`);if(a.length>0)i.push(`Release links changed: ${a.join(", ")}`);if(c.length>0)i.push(`Route manifests changed: ${c.join(", ")}`);if(l.length>0)i.push(`Routes disappeared: ${l.join(", ")}`);if(m.length>0)i.push(`Persistent data paths disappeared: ${m.join(", ")}`);if(f.length>0)i.push(`Databases or volumes disappeared: ${f.join(", ")}`);if(h.length>0)i.push(`Unhealthy routes: ${h.map((b)=>b.domain).join(", ")}`);if(!y)i.push(`Expected at least ${x} CPU cores, found ${s.cpuCores}`);if(!S)i.push(`Expected at least ${_} bytes of RAM`);if(!R)i.push(`Expected approximately ${t.disk??0} GB root disk`);return{ok:i.length===0,checks:{cpuCores:s.cpuCores,memoryBytes:s.memoryBytes,rootDiskBytes:s.rootDiskBytes,rootFilesystemBytes:s.rootFilesystemBytes,runningServices:s.runningServices.length,releaseLinks:s.releaseLinks.length,routeFragments:s.routeFragments.length,routes:s.routeIds.length,healthyRoutes:s.routeProbes.filter((b)=>b.ok).length,persistentDataPaths:s.persistentData.length,databasesAndVolumes:s.dataCatalog.length,failedUnits:s.failedUnits.length},failures:i}}function Kt(e){return e.split("=",1)[0]??e}function bi(e){return e.replace(/@[^.]+(?=\.service$)/,"")}function pc(e,t){let r=new Set(t.runningServices.map(bi)),n=new Set(t.routeFragments.map(Kt)),s=new Set(t.releaseLinks.map(Kt)),i=new Set(t.routeIds),o=new Set(t.dataCatalog);return{stoppedServices:e.runningServices.filter((a)=>!r.has(bi(a))),changedRouteFragments:e.routeFragments.filter((a)=>!n.has(Kt(a))),missingRouteIds:e.routeIds.filter((a)=>!i.has(a)),changedReleaseLinks:e.releaseLinks.filter((a)=>!s.has(Kt(a))),missingData:e.dataCatalog.filter((a)=>!o.has(a))}}function _i(e){return e.infrastructure?.compute??{}}function to(e){let t=_i(e),r=t.monitoring;return{firewallPorts:[...new Set([22,80,443,...t.firewall?.allowedPorts??[]])].filter((s)=>Number.isInteger(s)&&s>=1&&s<=65535).sort((s,i)=>s-i),monitoring:r!==!1&&(typeof r!=="object"||r.enabled!==!1),autoUpdates:t.autoUpdates!==!1,swapGb:Math.max(0,Math.floor(t.swapGb??2)),sshPasswordAuthentication:!1,sshMaxStartups:"100:30:200",journalMaxUse:"256M",journalRetention:"14day"}}function Gc(e){return["install -d -m 0755 /etc/ssh/sshd_config.d /etc/systemd/journald.conf.d /etc/sysctl.d /etc/fail2ban/jail.d","cat > /etc/ssh/sshd_config.d/99-ts-cloud-hardening.conf <<'TS_CLOUD_SSH_EOF'","# Managed by ts-cloud host optimization.","PasswordAuthentication no","KbdInteractiveAuthentication no","PermitRootLogin prohibit-password","MaxAuthTries 4","LoginGraceTime 30",`MaxStartups ${e.sshMaxStartups}`,"TS_CLOUD_SSH_EOF","sshd -t","systemctl reload ssh","cat > /etc/systemd/journald.conf.d/99-ts-cloud-retention.conf <<'TS_CLOUD_JOURNAL_EOF'","[Journal]",`SystemMaxUse=${e.journalMaxUse}`,`MaxRetentionSec=${e.journalRetention}`,"Compress=yes","TS_CLOUD_JOURNAL_EOF","systemctl restart systemd-journald","journalctl --vacuum-size=256M --vacuum-time=14d >/dev/null","cat > /etc/sysctl.d/99-ts-cloud-production.conf <<'TS_CLOUD_SYSCTL_EOF'","# Managed by ts-cloud host optimization.","vm.swappiness=10","vm.dirty_background_ratio=5","vm.dirty_ratio=15","net.core.somaxconn=4096","net.ipv4.tcp_max_syn_backlog=4096","net.ipv4.tcp_fin_timeout=30","net.ipv4.tcp_keepalive_time=300","net.ipv4.tcp_keepalive_intvl=30","net.ipv4.tcp_keepalive_probes=5","fs.inotify.max_user_watches=524288","TS_CLOUD_SYSCTL_EOF","sysctl --system >/dev/null","export DEBIAN_FRONTEND=noninteractive","command -v fail2ban-client >/dev/null 2>&1 || apt-get install -y fail2ban","cat > /etc/fail2ban/jail.d/99-ts-cloud-sshd.conf <<'TS_CLOUD_FAIL2BAN_EOF'","[sshd]","enabled = true","backend = systemd","bantime = 1h","findtime = 10m","maxretry = 5","TS_CLOUD_FAIL2BAN_EOF","systemctl enable --now fail2ban","systemctl restart fail2ban"]}function Vc(e){if(e===0)return[];return["if ! swapon --show=NAME --noheadings 2>/dev/null | grep -qx '/swapfile'; then",` if [ ! -f /swapfile ]; then fallocate -l ${e}G /swapfile || dd if=/dev/zero of=/swapfile bs=1M count=${e*1024} status=none; fi`," chmod 600 /swapfile"," mkswap /swapfile >/dev/null"," swapon /swapfile","fi","grep -qE '^/swapfile\\s' /etc/fstab || echo '/swapfile none swap sw 0 0' >> /etc/fstab"]}function Ti(e){let t=_i(e),r=to(e),n=t.monitoring??!0,s=t.firewall??{enabled:!0};return["set -euo pipefail",...Z(t)?["systemctl disable --now nginx.service bun-gateway.service ts-cloud-nginx.service 2>/dev/null || true","systemctl reset-failed nginx.service bun-gateway.service ts-cloud-nginx.service 2>/dev/null || true"]:[],...Vc(r.swapGb),...he(r.autoUpdates),...ye(n),...Gc(r),...xt(s),"systemctl daemon-reload","systemctl reset-failed"]}var Xc=String.raw`
490
490
  const text = (command) => {
491
491
  const result = Bun.spawnSync(['bash', '-lc', command], { stdout: 'pipe', stderr: 'pipe' })
492
492
  return result.stdout.toString().trim()
@@ -554,7 +554,7 @@ console.log(JSON.stringify({
554
554
  changed = true
555
555
  }
556
556
  if (changed) writeFileSync('/run/ts-cloud-dashboard-routes-changed', '')
557
- `)}`,"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=${Qt(s)}`,`TS_CLOUD_DASHBOARD_SERVER_OWNER=${r?"1":"0"}`,`TS_CLOUD_DASHBOARD_DESIRED=${Qt(` ${i.join(" ")} `)}`,"for TS_CLOUD_UNIT_FILE in /etc/systemd/system/*.service; do",' [ -e "$TS_CLOUD_UNIT_FILE" ] || continue',' TS_CLOUD_UNIT=$(basename "$TS_CLOUD_UNIT_FILE")',' case "$TS_CLOUD_UNIT" in'," *-dashboard-*.service)",' if [ "$TS_CLOUD_DASHBOARD_SERVER_OWNER" != 1 ]; then',' case "$TS_CLOUD_UNIT" in "$TS_CLOUD_DASHBOARD_PREFIX"*.service) ;; *) continue ;; esac'," fi",' case "$TS_CLOUD_DASHBOARD_DESIRED" in',' *" $TS_CLOUD_UNIT "*) ;;'," *)",' systemctl disable --now "$TS_CLOUD_UNIT" 2>/dev/null || true',' rm -f "$TS_CLOUD_UNIT_FILE"'," ;;"," esac"," ;;"," esac","done","systemctl daemon-reload","systemctl reset-failed",...o]}async function Al(e,t,r,n){let{config:s,environment:i}=t,o=s.project.slug,a=T(s,i),c=await e.findComputeTargets({slug:o,environment:i,role:"app",stackName:a});if(c.length===0)return!0;let l=await e.runRemoteDeploy({targets:c,commands:Il(o,r,!s.cloud?.attachTo,r.map((u)=>s.sites?.[u]?.domain).filter((u)=>typeof u==="string")),comment:`ts-cloud reconcile management dashboard ${o}`,tags:{Project:o,Environment:i,Role:"app"}});if(!l.success)return n.error(`Management dashboard reconciliation failed: ${l.error||"unknown error"}`),!1;return!0}async function Ll(e,t,r){let{config:n}=t,s=n.cloud?.attachTo;if(!s||!e.listReachableResources)return;let i;try{i=await e.listReachableResources()}catch(c){r.warn(`Could not determine this credential's reach: ${c instanceof Error?c.message:String(c)}`);return}let o=Ri(i,{ownerSlug:s,selfSlug:n.project.slug}),a=dn(o)>0;for(let c of Oi(o,{ownerSlug:s,selfSlug:n.project.slug}))if(a)r.warn(c);else r.info(c)}async function Hl(e,t,r){let{config:n,environment:s}=t,i=n.cloud?.attachTo;if(!i)return!0;let o=so(n.infrastructure?.compute?.managedServices);if(o.length===0)return!0;let a=n.project.slug,c=T(n,s),l=await e.findComputeTargets({slug:a,environment:s,role:"app",stackName:c});if(l.length===0)return!0;let u=await e.runRemoteDeploy({targets:l,commands:io(o),comment:`ts-cloud preflight managed services ${a}`,tags:{Project:a,Environment:s,Role:"app"}});if(!u.success)return r.warn(`Could not check '${i}' for the declared services: ${u.error||"unknown error"}`),!0;let d=new Set;for(let m of u.perInstance)for(let f of oo(m.output,o))d.add(f);if(d.size===0)return!0;return r.error(ao([...d],i,l[0]?.publicIp)),!1}async function Nl(e,t,r){let{config:n,environment:s}=t;if(!n.cloud?.attachTo)return!0;let i=n.infrastructure?.compute,o=w(n),a=vt(o,i?.managedServices??{});if(a.length===0)return!0;let c=n.project.slug,l=T(n,s),u=await e.findComputeTargets({slug:c,environment:s,role:"app",stackName:l});if(u.length===0)return!0;r.step(`Ensuring database '${o?.name}' + role exist on the shared box...`);let d=await e.runRemoteDeploy({targets:u,commands:a,comment:`ts-cloud ensure database ${c}/${o?.name}`,tags:{Project:c,Environment:s,Role:"app"}});if(!d.success)return r.error(`Ensuring database '${o?.name}' failed: ${d.error||"unknown error"}`),!1;return r.success(`Database '${o?.name}' is ready on ${d.instanceCount} target(s)`),!0}async function ro(e){let{config:t,environment:r,driver:n,sha:s,runtime:i,tarballForSite:o,logger:a=Zt}=e,c=t.project.slug,l=e.cwd??process.cwd(),u=e.managementDashboard!==!1,d=Wt(t);if(u)Ao(t,{cwd:l,logger:{info:a.info,warn:a.warn}});let m=!u||d?[]:Ro(t);if(u&&e.rpxConfig&&e.rpxConfig!==t&&!Wt(e.rpxConfig))Ao(e.rpxConfig,{cwd:l,logger:{info:()=>{},warn:()=>{}}});if(u&&!await Al(n,e,Ro(t),a))return!1;let f=null,h=new Map;if(m.length>0)if(f=xs(t.sites?.[m[0]],{cwd:l,slug:c,sha:s,siteName:m[0],logger:{info:a.info,warn:a.warn}}),!f){a.warn("Management dashboard: no artifact available — skipping dashboard site(s) for this deploy.");for(let R of m)if(t.sites)delete t.sites[R]}else for(let R of m){if(R===m[0]){h.set(R,f);continue}try{let b=Ol(El(),`${c}-${R}-${s}.tar.gz`);Rl(f,b),h.set(R,b)}catch{h.set(R,f)}}let x=t.sites||{},_=Object.entries(x).filter(([R,b])=>{if(!b)return!1;let I=P(b);if(I==="bucket")return a.warn(`Site '${R}' targets a bucket — skipping (handled by the static-site path, not compute).`),!1;if(I==="redirect")return!1;if(I==="proxy")return!1;return!0});if(_.length===0)return _n(e);if(await Ll(n,e,a),!await Hl(n,e,a))return!1;if(!await Nl(n,e,a))return!1;let y=(R)=>h.get(R)??o(R);for(let[R,b]of _){a.step(`Deploying site: ${R}`);let I=Ei(b)?void 0:y(R),C=await mo(n,{config:t,environment:r,siteName:R,site:b,slug:c,sha:s,runtime:i,localTarballPath:I},a);if(!C.success){if(a.error(`Deploy of '${R}' failed: ${C.error||"unknown error"}`),C.perInstance)for(let E of C.perInstance)a.error(` ${E.instanceId}: ${E.status}${E.error?` — ${E.error}`:""}`);return!1}if(a.success(`Deployed ${c}/${R}@${s} to ${C.instanceCount} target(s)`),C.perInstance)for(let E of C.perInstance)a.info(` ✓ ${E.instanceId}: ${E.status}`)}if(!await _n(e))return!1;return!0}async function Ul(e,t,r){let n=Qi(e);if(!n||n.tls==="off")return n;let s=await Ie(t,r),i=s?.provider==="ssh"?s.lanIp:void 0;return i?{...n,ip:i}:n}async function _n(e){let{config:t,environment:r,driver:n,logger:s=Zt}=e,i=e.rpxConfig??t,o=i.infrastructure?.compute?.proxy??t.infrastructure?.compute?.proxy;if(o?.engine!=="rpx")return!0;let a=i.sites||{},c=t.project.slug,l=T(t,r),u=await n.findComputeTargets({slug:c,environment:r,role:"lb",stackName:l});if(u.length>0){let S=(await n.findComputeTargets({slug:c,environment:r,role:"app",stackName:l})).map((I)=>({privateIp:I.privateIp,publicIp:I.publicIp})),R=Me(a,S,{proxy:o,slug:c});if(R.proxies.length===0)return s.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;s.step(`Reloading the load balancer's rpx gateway with ${R.proxies.length} route(s)...`);let b=await n.runRemoteDeploy({targets:u,commands:qe({config:R,slug:c,preserveManagementDashboardRoutes:e.managementDashboard===!1}),comment:`ts-cloud rpx gateway reload ${c}`,tags:{Project:c,Environment:r,Role:"lb"}});if(!b.success)return s.error(`rpx gateway reload failed: ${b.error||"unknown error"}`),!1;return s.success(`rpx gateway reloaded on ${b.instanceCount} load balancer(s)`),!0}let d=await Ul(t,l,e.cwd),m=Se(a,{proxy:o,slug:c,lan:d});if(m.proxies.length===0)return s.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;let f=await n.findComputeTargets({slug:c,environment:r,role:"app",stackName:l});if(f.length===0)return s.warn("rpx gateway: no compute targets found — skipping gateway reload."),!0;let h=Boolean(t.cloud?.attachTo);if(h&&(o.version||o.tlsxVersion))s.warn(`rpx gateway: ignoring proxy.version/tlsxVersion — this project attaches to '${t.cloud?.attachTo}' and the gateway belongs to that box's owner.`);s.step(`Reloading rpx gateway with ${m.proxies.length} route(s)...`);let x=le({proxy:o,config:m,slug:c,tenant:h,profile:Nn(t),preserveManagementDashboardRoutes:e.managementDashboard===!1}),_=await n.runRemoteDeploy({targets:f,commands:x,comment:`ts-cloud rpx gateway reload ${c}`,tags:{Project:c,Environment:r,Role:"app"}});if(!_.success)return s.error(`rpx gateway reload failed: ${_.error||"unknown error"}`),!1;return s.success(`rpx gateway reloaded on ${_.instanceCount} target(s)`),!0}async function no(e){let{config:t,environment:r,driver:n,logger:s=Zt}=e,i=e.rpxConfig??t,o=i.infrastructure?.compute?.proxy??t.infrastructure?.compute?.proxy;if(o?.engine!=="rpx"||!o.onDemandTls)return!0;let a=Se(i.sites||{},{proxy:o,slug:t.project.slug});if(a.proxies.length===0)return!0;let c=br(a);if(c.length===0)return!0;let l=t.project.slug,u=T(t,r),d="lb",m=await n.findComputeTargets({slug:l,environment:r,role:d,stackName:u});if(m.length===0)d="app",m=await n.findComputeTargets({slug:l,environment:r,role:d,stackName:u});if(m.length===0)return s.warn("rpx TLS: no gateway targets found - skipping certificate issuance."),!0;s.step("Issuing rpx TLS certificates after DNS reconciliation...");let f=c.map((x)=>`test -s ${Dl(`${a.productionCerts.certsDir}/${x}.crt`)}`).join(" && "),h=await n.runRemoteDeploy({targets:m,commands:[`systemctl start ${vr(l)}`,f],comment:`ts-cloud rpx TLS issuance ${l}`,tags:{Project:l,Environment:r,Role:d}});if(!h.success)return s.error(`rpx TLS issuance failed: ${h.error||"unknown error"}`),!1;return s.success(`rpx TLS certificates reconciled on ${h.instanceCount} gateway target(s)`),!0}import{createHash as kl}from"node:crypto";function mc(e){let t=wn(e.name),r=Tn(e.publicKey),n=Fl([...e.existingKeys??[],{name:t,publicKey:r}]);return go(e.configText,n)}function gc(e){let t=wn(e.name),r=(e.existingKeys??[]).filter((n)=>n.name!==t);if((e.existingKeys??[]).length===r.length)throw Error(`SSH key '${t}' does not exist in compute.sshKeys`);return go(e.configText,r)}function _t(e=[]){return e.map((t)=>({name:t.name,publicKey:t.publicKey,type:zl(t.publicKey),fingerprint:Bl(t.publicKey),added:"configured"}))}function go(e,t){let r=Kl(e,"compute"),n=Ml(t),s=jl(e,r.start,r.end,"sshKeys");if(s){let c=s.propertyStart;while(c>0&&e[c-1]!==`
557
+ `)}`,"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=${Qt(s)}`,`TS_CLOUD_DASHBOARD_SERVER_OWNER=${r?"1":"0"}`,`TS_CLOUD_DASHBOARD_DESIRED=${Qt(` ${i.join(" ")} `)}`,"for TS_CLOUD_UNIT_FILE in /etc/systemd/system/*.service; do",' [ -e "$TS_CLOUD_UNIT_FILE" ] || continue',' TS_CLOUD_UNIT=$(basename "$TS_CLOUD_UNIT_FILE")',' case "$TS_CLOUD_UNIT" in'," *-dashboard-*.service)",' if [ "$TS_CLOUD_DASHBOARD_SERVER_OWNER" != 1 ]; then',' case "$TS_CLOUD_UNIT" in "$TS_CLOUD_DASHBOARD_PREFIX"*.service) ;; *) continue ;; esac'," fi",' case "$TS_CLOUD_DASHBOARD_DESIRED" in',' *" $TS_CLOUD_UNIT "*) ;;'," *)",' systemctl disable --now "$TS_CLOUD_UNIT" 2>/dev/null || true',' rm -f "$TS_CLOUD_UNIT_FILE"'," ;;"," esac"," ;;"," esac","done","systemctl daemon-reload","systemctl reset-failed",...o]}async function Al(e,t,r,n){let{config:s,environment:i}=t,o=s.project.slug,a=T(s,i),c=await e.findComputeTargets({slug:o,environment:i,role:"app",stackName:a});if(c.length===0)return!0;let l=await e.runRemoteDeploy({targets:c,commands:Il(o,r,!s.cloud?.attachTo,r.map((u)=>s.sites?.[u]?.domain).filter((u)=>typeof u==="string")),comment:`ts-cloud reconcile management dashboard ${o}`,tags:{Project:o,Environment:i,Role:"app"}});if(!l.success)return n.error(`Management dashboard reconciliation failed: ${l.error||"unknown error"}`),!1;return!0}async function Ll(e,t,r){let{config:n}=t,s=n.cloud?.attachTo;if(!s||!e.listReachableResources)return;let i;try{i=await e.listReachableResources()}catch(c){r.warn(`Could not determine this credential's reach: ${c instanceof Error?c.message:String(c)}`);return}let o=Ri(i,{ownerSlug:s,selfSlug:n.project.slug}),a=dn(o)>0;for(let c of Oi(o,{ownerSlug:s,selfSlug:n.project.slug}))if(a)r.warn(c);else r.info(c)}async function Hl(e,t,r){let{config:n,environment:s}=t,i=n.cloud?.attachTo;if(!i)return!0;let o=so(n.infrastructure?.compute?.managedServices);if(o.length===0)return!0;let a=n.project.slug,c=T(n,s),l=await e.findComputeTargets({slug:a,environment:s,role:"app",stackName:c});if(l.length===0)return!0;let u=await e.runRemoteDeploy({targets:l,commands:io(o),comment:`ts-cloud preflight managed services ${a}`,tags:{Project:a,Environment:s,Role:"app"}});if(!u.success)return r.warn(`Could not check '${i}' for the declared services: ${u.error||"unknown error"}`),!0;let d=new Set;for(let m of u.perInstance)for(let f of oo(m.output,o))d.add(f);if(d.size===0)return!0;return r.error(ao([...d],i,l[0]?.publicIp)),!1}async function Nl(e,t,r){let{config:n,environment:s}=t;if(!n.cloud?.attachTo)return!0;let i=n.infrastructure?.compute,o=w(n),a=vt(o,i?.managedServices??{});if(a.length===0)return!0;let c=n.project.slug,l=T(n,s),u=await e.findComputeTargets({slug:c,environment:s,role:"app",stackName:l});if(u.length===0)return!0;r.step(`Ensuring database '${o?.name}' + role exist on the shared box...`);let d=await e.runRemoteDeploy({targets:u,commands:a,comment:`ts-cloud ensure database ${c}/${o?.name}`,tags:{Project:c,Environment:s,Role:"app"}});if(!d.success)return r.error(`Ensuring database '${o?.name}' failed: ${d.error||"unknown error"}`),!1;return r.success(`Database '${o?.name}' is ready on ${d.instanceCount} target(s)`),!0}async function ro(e){let{config:t,environment:r,driver:n,sha:s,runtime:i,tarballForSite:o,logger:a=Zt}=e,c=t.project.slug,l=e.cwd??process.cwd(),u=e.managementDashboard!==!1,d=Wt(t);if(u)Ao(t,{cwd:l,logger:{info:a.info,warn:a.warn}});let m=!u||d?[]:Ro(t);if(u&&e.rpxConfig&&e.rpxConfig!==t&&!Wt(e.rpxConfig))Ao(e.rpxConfig,{cwd:l,logger:{info:()=>{},warn:()=>{}}});if(u&&!await Al(n,e,Ro(t),a))return!1;let f=null,h=new Map;if(m.length>0)if(f=xs(t.sites?.[m[0]],{cwd:l,slug:c,sha:s,siteName:m[0],logger:{info:a.info,warn:a.warn}}),!f){a.warn("Management dashboard: no artifact available — skipping dashboard site(s) for this deploy.");for(let R of m)if(t.sites)delete t.sites[R]}else for(let R of m){if(R===m[0]){h.set(R,f);continue}try{let b=Ol(El(),`${c}-${R}-${s}.tar.gz`);Rl(f,b),h.set(R,b)}catch{h.set(R,f)}}let x=t.sites||{},_=Object.entries(x).filter(([R,b])=>{if(!b)return!1;let I=P(b);if(I==="bucket")return a.warn(`Site '${R}' targets a bucket — skipping (handled by the static-site path, not compute).`),!1;if(I==="redirect")return!1;if(I==="proxy")return!1;return!0});if(_.length===0)return _n(e);if(await Ll(n,e,a),!await Hl(n,e,a))return!1;if(!await Nl(n,e,a))return!1;let y=(R)=>h.get(R)??o(R);for(let[R,b]of _){a.step(`Deploying site: ${R}`);let I=Ei(b)?void 0:y(R),C=await mo(n,{config:t,environment:r,siteName:R,site:b,slug:c,sha:s,runtime:i,localTarballPath:I},a);if(!C.success){if(a.error(`Deploy of '${R}' failed: ${C.error||"unknown error"}`),C.perInstance)for(let E of C.perInstance)a.error(` ${E.instanceId}: ${E.status}${E.error?` — ${E.error}`:""}`);return!1}if(a.success(`Deployed ${c}/${R}@${s} to ${C.instanceCount} target(s)`),C.perInstance)for(let E of C.perInstance)a.info(` ✓ ${E.instanceId}: ${E.status}`)}if(!await _n(e))return!1;return!0}async function Ul(e,t,r){let n=Qi(e);if(!n||n.tls==="off")return n;let s=await Ie(t,r),i=s?.provider==="ssh"?s.lanIp:void 0;return i?{...n,ip:i}:n}async function _n(e){let{config:t,environment:r,driver:n,logger:s=Zt}=e,i=e.rpxConfig??t,o=i.infrastructure?.compute?.proxy??t.infrastructure?.compute?.proxy;if(o?.engine!=="rpx")return!0;let a=i.sites||{},c=t.project.slug,l=T(t,r),u=await n.findComputeTargets({slug:c,environment:r,role:"lb",stackName:l});if(u.length>0){let S=(await n.findComputeTargets({slug:c,environment:r,role:"app",stackName:l})).map((I)=>({privateIp:I.privateIp,publicIp:I.publicIp})),R=Me(a,S,{proxy:o,slug:c});if(R.proxies.length===0)return s.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;s.step(`Reloading the load balancer's rpx gateway with ${R.proxies.length} route(s)...`);let b=await n.runRemoteDeploy({targets:u,commands:Ge({config:R,slug:c,preserveManagementDashboardRoutes:e.managementDashboard===!1}),comment:`ts-cloud rpx gateway reload ${c}`,tags:{Project:c,Environment:r,Role:"lb"}});if(!b.success)return s.error(`rpx gateway reload failed: ${b.error||"unknown error"}`),!1;return s.success(`rpx gateway reloaded on ${b.instanceCount} load balancer(s)`),!0}let d=await Ul(t,l,e.cwd),m=Se(a,{proxy:o,slug:c,lan:d});if(m.proxies.length===0)return s.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;let f=await n.findComputeTargets({slug:c,environment:r,role:"app",stackName:l});if(f.length===0)return s.warn("rpx gateway: no compute targets found — skipping gateway reload."),!0;let h=Boolean(t.cloud?.attachTo);if(h&&(o.version||o.tlsxVersion))s.warn(`rpx gateway: ignoring proxy.version/tlsxVersion — this project attaches to '${t.cloud?.attachTo}' and the gateway belongs to that box's owner.`);s.step(`Reloading rpx gateway with ${m.proxies.length} route(s)...`);let x=le({proxy:o,config:m,slug:c,tenant:h,profile:Nn(t),preserveManagementDashboardRoutes:e.managementDashboard===!1}),_=await n.runRemoteDeploy({targets:f,commands:x,comment:`ts-cloud rpx gateway reload ${c}`,tags:{Project:c,Environment:r,Role:"app"}});if(!_.success)return s.error(`rpx gateway reload failed: ${_.error||"unknown error"}`),!1;return s.success(`rpx gateway reloaded on ${_.instanceCount} target(s)`),!0}async function no(e){let{config:t,environment:r,driver:n,logger:s=Zt}=e,i=e.rpxConfig??t,o=i.infrastructure?.compute?.proxy??t.infrastructure?.compute?.proxy;if(o?.engine!=="rpx"||!o.onDemandTls)return!0;let a=Se(i.sites||{},{proxy:o,slug:t.project.slug});if(a.proxies.length===0)return!0;let c=br(a);if(c.length===0)return!0;let l=t.project.slug,u=T(t,r),d="lb",m=await n.findComputeTargets({slug:l,environment:r,role:d,stackName:u});if(m.length===0)d="app",m=await n.findComputeTargets({slug:l,environment:r,role:d,stackName:u});if(m.length===0)return s.warn("rpx TLS: no gateway targets found - skipping certificate issuance."),!0;s.step("Issuing rpx TLS certificates after DNS reconciliation...");let f=c.map((x)=>`test -s ${Dl(`${a.productionCerts.certsDir}/${x}.crt`)}`).join(" && "),h=await n.runRemoteDeploy({targets:m,commands:[`systemctl start ${vr(l)}`,f],comment:`ts-cloud rpx TLS issuance ${l}`,tags:{Project:l,Environment:r,Role:d}});if(!h.success)return s.error(`rpx TLS issuance failed: ${h.error||"unknown error"}`),!1;return s.success(`rpx TLS certificates reconciled on ${h.instanceCount} gateway target(s)`),!0}import{createHash as kl}from"node:crypto";function mc(e){let t=wn(e.name),r=Tn(e.publicKey),n=Fl([...e.existingKeys??[],{name:t,publicKey:r}]);return go(e.configText,n)}function gc(e){let t=wn(e.name),r=(e.existingKeys??[]).filter((n)=>n.name!==t);if((e.existingKeys??[]).length===r.length)throw Error(`SSH key '${t}' does not exist in compute.sshKeys`);return go(e.configText,r)}function _t(e=[]){return e.map((t)=>({name:t.name,publicKey:t.publicKey,type:zl(t.publicKey),fingerprint:Bl(t.publicKey),added:"configured"}))}function go(e,t){let r=Kl(e,"compute"),n=Ml(t),s=jl(e,r.start,r.end,"sshKeys");if(s){let c=s.propertyStart;while(c>0&&e[c-1]!==`
558
558
  `&&/\s/.test(e[c-1]))c--;return`${e.slice(0,c)}${n}${e.slice(s.end+1)}`}let i=e.slice(0,r.end).trimEnd(),o=e.slice(r.end),a=i.endsWith(",")||i.endsWith("{")?"":",";return`${i}${a}
559
559
  ${n},
560
560
  ${o}`}function Ml(e){if(e.length===0)return" sshKeys: []";return` sshKeys: [
@@ -721,4 +721,4 @@ EOF`,'echo "DISKPCT=${DISKPCT:-0}"','echo "DISKUSEDG=${DISKUSEDG:-0}"','echo "DI
721
721
  `)){let n=r.trim();if(!n.startsWith("LOG="))continue;let s=n.indexOf("\t");if(s<0)continue;let i=n.slice(4,s),o=n.slice(s+1),a=/^(\d{4}-\d{2}-\d{2}T[^\s]+)\s+(\S+)\s+(.*)$/.exec(o),c=a?.[1]??"",l=a?.[2]??"",u=(a?.[3]??o).trim();if(!u)continue;t.push({source:i,timestamp:c,when:c?Cn(c):V,host:l,message:u,level:To(u)})}return t.sort((r,n)=>String(n.timestamp).localeCompare(String(r.timestamp))).slice(0,600)}function Co(e){if(/^(?:127\.|localhost:|\[?::1\]?)/.test(e))return"loopback";if(/^(?:10\.|192\.168\.|172\.(?:1[6-9]|2\d|3[01])\.|169\.254\.|\[?f[cd][0-9a-f:])/i.test(e))return"private";return"public"}function du(e){if(Co(e)!=="public")return"ok";if(/:(?:22|80|443)$/.test(e)||/^\*:(?:22|80|443)$/.test(e))return"ok";return"warn"}function mu(e){if(e==null)return"warn";if(e<8)return"bad";if(e<30)return"warn";return"ok"}function fu(e){let t=[],r=[],n=[],s=[];for(let a of e.split(`
722
722
  `)){let c=a.trim();if(c.startsWith("PORT=")){let[l="",u="",d=""]=c.slice(5).split("\t");if(l&&u)t.push({proto:l,listen:u,processName:d||V,exposure:Co(u),tone:du(u)})}else if(c.startsWith("FIREWALL=")){let l=c.slice(9).trim();if(l)r.push(l)}else if(c.startsWith("AUTH=")){let l=c.slice(5),u=/^(\d{4}-\d{2}-\d{2}T[^\s]+)\s+(\S+)\s+(.*)$/.exec(l),d=(u?.[3]??l).trim();if(d)n.push({timestamp:u?.[1]??"",when:u?.[1]?Cn(u[1]):V,host:u?.[2]??"",message:d,level:To(d)})}else if(c.startsWith("CERT=")){let[l="",u=""]=c.slice(5).split("\t");if(!l)continue;let d=new Date(u),m=Number.isNaN(d.getTime())?null:Math.ceil((d.getTime()-Date.now())/86400000);s.push({domain:l,expires:Number.isNaN(d.getTime())?u||V:d.toISOString().slice(0,10),daysRemaining:m,status:mu(m)})}}let i=r.some((a)=>/Status:\s*active/i.test(a)),o=r.some((a)=>/unavailable/i.test(a));return{ports:t.slice(0,80),firewall:{status:i?"active":o?"unavailable":"inactive",summary:i?"ufw active":o?"ufw unavailable":"ufw inactive or not configured",rules:r.filter((a)=>a&&!/^Status:/i.test(a)).slice(0,60)},tlsCertificates:s,authEvents:n.sort((a,c)=>String(c.timestamp).localeCompare(String(a.timestamp))).slice(0,30)}}function Pn(e){let r=e.infrastructure?.compute?.firewall??{},n=[...new Set([22,80,443,...r.allowedPorts??[]])],s=wo(e);return{ports:n.map((i)=>({proto:"tcp",listen:`0.0.0.0:${i}`,processName:"configured firewall",exposure:"public",tone:[22,80,443].includes(Number(i))?"ok":"warn"})),firewall:{status:r.enabled===!1?"disabled":"configured",summary:r.enabled===!1?"host firewall disabled in config":"host firewall configured declaratively",rules:n.map((i)=>`ALLOW ${i}/tcp`)},tlsCertificates:s.map((i)=>({domain:i,expires:V,daysRemaining:null,status:"warn"})),authEvents:[]}}function Po(e,t){let r=t.security??Pn(e),n=!!t._serverReachable&&!t.metricsUnavailable,s=t.sites??[],i=s.filter((l)=>l.status==="shadowed"),o=(t.services??[]).filter((l)=>["failed","stopped"].includes(l.status)),a=(r.tlsCertificates??[]).filter((l)=>l.status!=="ok"),c=t.sshKeys??[];return[{name:"Live server probe",status:n?"pass":"warn",detail:n?"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:o.length?"fail":"pass",detail:o.length?`${o.length} service(s) need attention.`:`${(t.services??[]).length} service(s) reported healthy or configured.`},{name:"Route conflicts",status:i.length?"warn":"pass",detail:i.length?`${i.map((l)=>l.name).join(", ")} is shadowed by an earlier route.`:`${s.length} site route(s) are unshadowed.`},{name:"SSH access",status:c.length?"pass":"warn",detail:c.length?`${c.length} declarative authorized key(s) configured.`:"No declarative SSH keys are configured."},{name:"Firewall",status:["active","configured"].includes(r.firewall?.status)?"pass":"warn",detail:r.firewall?.summary??"Firewall status unavailable."},{name:"TLS certificates",status:a.length?"warn":"pass",detail:a.length?`${a.length} certificate(s) need renewal visibility.`:`${(r.tlsCertificates??[]).length} certificate(s) look healthy.`}]}function xo(e){let t=[];for(let r of e.serverDeploymentsDetail??e.serverDeployments??[])t.push({type:"deploy",tone:r.status==="failed"?"bad":"ok",title:`${r.site} deployed ${r.sha}`,detail:`${r.branch} · ${r.status}`,when:r.when,timestamp:r.timestamp});for(let r of e.serverLogs??[])if(r.level==="error"||r.level==="warn")t.push({type:"log",tone:r.level==="error"?"bad":"warn",title:`${r.source} ${r.level}`,detail:r.message,when:r.when,timestamp:r.timestamp});for(let r of e.sshKeys??[])t.push({type:"ssh",tone:"ok",title:`${r.name} authorized`,detail:r.fingerprint,when:r.added??V,timestamp:""});return t.sort((r,n)=>String(n.timestamp).localeCompare(String(r.timestamp))).slice(0,80)}function gu(e,t={}){let r=[];for(let n of e.split(`
723
723
  `)){let s=n.trim();if(!s.startsWith("DEPLOY="))continue;let i=s.split("\t"),o=i[0]?.replace(/^DEPLOY=/,"")??"",[a,c,l,u,d]=i.slice(1);if(!o||!a||!c)continue;let m=t[o]??{},f=P(m),h=(l||c).slice(0,7);r.push({sha:h,release:c,commit:l||c,site:o,branch:m.branch??(f==="server-static"?"build artifact":"main"),status:u||"unknown",when:Cn(a),timestamp:a,took:"-",by:"ts-cloud",rc:d?.replace(/^rc=/,"")??"",steps:f==="server-static"?["upload artifact","publish static files"]:["upload artifact","restart service"]})}return r.sort((n,s)=>String(s.timestamp).localeCompare(String(n.timestamp)))}function hu(e,t){let r=eu(e,t),n=So(e),s=iu(e),i=Math.max(1,Number(e.infrastructure?.compute?.disk?.size??1)),o={server:{name:r?.serverName??`${e.project.slug}-${t}-app`,provider:r?.provider??yo(e),region:Ql(e),ip:r?.publicIp??V,os:"Linux",uptime:V,probeStatus:"unavailable"},systemMetrics:{load:0,load5:0,load15:0,cpuUsedPct:0,cpus:Math.max(1,Number(e.infrastructure?.compute?.instances??1)),memUsedMb:0,memTotalMb:0,memAvailableMb:0,memCacheMb:0,swapUsedMb:0,swapTotalMb:0,diskUsedPct:0,diskUsedGb:0,diskTotalGb:i,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:Zl(e),services:n,servicesDetail:n.map((a)=>({...a,since:V,memMb:0,auto:!0})),backup:Jl(e),backupHistory:[],workers:tu(e),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:Pn(e),securityEmptyReason:"Live security checks are unavailable until the dashboard can reach the compute box.",sites:s,sitesDetail:s.map((a)=>{let c=e.sites?.[a.name]??{},l=P(c);return{...a,root:l==="server-static"?J(e.project.slug,a.name):`${J(e.project.slug,a.name)}/current`,branch:l==="server-static"?"build artifact":"main",build:c.build,php:c.php??c.phpVersion,aliases:Array.isArray(c.aliases)?c.aliases:[],redirects:c.redirects&&typeof c.redirects==="object"?c.redirects:{},envKeys:Object.keys(c.env??c.environment??{})}}),siteHealth:[],sshKeys:_t(e.infrastructure?.compute?.sshKeys??[]),_serverReachable:!1,_metricsStatus:"unavailable"};return o.diagnostics=Po(e,o),o.activity=xo(o),o.topology=rn(o,{project:e.project.name,environment:t}),o}async function di(e,t,r={}){if(!e.infrastructure?.compute)return null;let n=null;try{n=O({config:e})}catch{n=null}let s=null,i=0,o=[];if(n)try{if(o=await n.findComputeTargets({slug:e.project.slug,environment:t,role:"app"}),i=o.length,o.length){let d=(await n.runRemoteDeploy({targets:[o[0]],commands:Xl({includeServices:!r.telemetryOnly,includeSites:r.includeSiteHealth!==!1,projectFilter:e.cloud?.attachTo?e.project.slug:void 0}),comment:`ts-cloud dashboard:build ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output;if(d)s=Yl(d)}}catch{}let a=hu(e,t),c=(u,d=0)=>{let m=Number(u);return Number.isFinite(m)?m:d};if(a.server.os=s?.OS||a.server.os,a.server.uptime=s?.UPTIME||a.server.uptime,s){if(a.server.probeStatus="live",a.metricsUnavailable=!1,a._metricsStatus="live",a.systemMetrics={load:c(s.LOAD),load5:c(s.LOAD5),load15:c(s.LOAD15),cpuUsedPct:c(s.CPUUSED),cpus:c(s.CPUS,1),memUsedMb:c(s.MEMUSED),memTotalMb:c(s.MEMTOTAL,1),memAvailableMb:c(s.MEMAVAILABLE),memCacheMb:c(s.MEMCACHE),swapUsedMb:c(s.SWAPUSED),swapTotalMb:c(s.SWAPTOTAL),diskUsedPct:c(s.DISKPCT),diskUsedGb:c(s.DISKUSEDG),diskTotalGb:c(s.DISKTOTG,1),inodeUsedPct:c(s.INODEPCT),networkRxBytes:c(s.NETRX),networkTxBytes:c(s.NETTX),networkRxBytesPerSec:c(s.NETRXRATE),networkTxBytesPerSec:c(s.NETTXRATE),networkRxBytesToday:c(s.NETRXTODAY),networkTxBytesToday:c(s.NETTXTODAY),networkRxBytesMonth:c(s.NETRXMONTH),networkTxBytesMonth:c(s.NETTXMONTH),networkMonthKey:s.NETMONTHKEY||"",processes:c(s.PROCESSES),uptimeSeconds:c(s.UPTIME_SECONDS)},s.services.length){let u=[...new Map(s.services.map((d)=>[d.name,d])).values()];a.services=u.map((d)=>({name:d.name,status:d.status==="active"?"running":d.status})),a.servicesDetail=u.map((d)=>({name:d.name,status:d.status==="active"?"running":d.status,since:d.since&&d.since!==V?d.since:a.server.uptime,memMb:Math.max(0,Math.round(Number(d.memBytes??0)/1024/1024)),auto:d.enabled?!["disabled","static","masked"].includes(d.enabled):!0}))}if(s.discoveredSites.length)a.sitesDetail=ou(a.sitesDetail,s.discoveredSites,e.project.slug),a.sites=a.sitesDetail.map((u)=>({name:u.name,project:u.project,managedBy:u.managedBy,route:u.route,href:u.href,domain:u.domain,path:u.path,kind:u.kind,type:u.type,runtime:u.runtime,deploy:u.deploy,tls:u.tls,status:u.status,httpStatus:u.httpStatus,responseMs:u.responseMs,tlsDaysRemaining:u.tlsDaysRemaining,checkedAt:u.checkedAt})),a.siteHealth=a.sitesDetail.map((u)=>({name:u.name,project:u.project,route:u.route,status:u.status,httpStatus:u.httpStatus,responseMs:u.responseMs,tlsDaysRemaining:u.tlsDaysRemaining,checkedAt:u.checkedAt}))}if(n&&o.length&&!r.telemetryOnly)await Promise.all([(async()=>{try{let u=Object.keys(e.sites??{}),m=(await n.runRemoteDeploy({targets:[o[0]],commands:au(u,e.project.slug),comment:`ts-cloud dashboard:deploy-history ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",f=gu(m,e.sites);a.serverDeployments=f.slice(0,5),a.serverDeploymentsDetail=f.slice(0,50),a.deploymentsEmptyReason=f.length?void 0:"No deployment history was found on the server yet. Deploy again to populate this timeline."}catch{a.deploymentsEmptyReason="Deployment history could not be read from the server."}})(),(async()=>{try{let d=(await n.runRemoteDeploy({targets:[o[0]],commands:uu(e),comment:`ts-cloud dashboard:server-logs ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",m=pu(d);a.serverLogs=m,a.serverLogsEmptyReason=m.length?void 0:"No recent journal entries were found for the managed server units."}catch{a.serverLogsEmptyReason="Server logs could not be read from the box."}})(),(async()=>{try{let d=(await n.runRemoteDeploy({targets:[o[0]],commands:cu(e),comment:`ts-cloud dashboard:security ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",m=fu(d),f=Pn(e);if(!m.ports.length)m.ports=f.ports;if(!m.tlsCertificates.length)m.tlsCertificates=f.tlsCertificates;a.security=m,a.securityEmptyReason=void 0}catch{a.securityEmptyReason="Server security checks could not be read from the box."}})()]);else if(n&&i===0)a.deploymentsEmptyReason="No app server target was found for this environment.";let l=e.infrastructure?.compute?.sshKeys??e.infrastructure?.ssh?.keys??e.infrastructure?.sshKeys;if(Array.isArray(l)&&l.length)a.sshKeys=_t(l);return a._serverReachable=i>0&&!!s,a.diagnostics=Po(e,a),a.activity=xo(a),a.topology=rn(a,{project:e.project.name,environment:t}),a}
724
- export{Ge,rs,ue,Wi,ai,Ki,Ji,Xr,Xi,Qi,Se,Z,qe,ke,Qr,lr,We,dr,Yr,dt,pe,ut,ur,Yi,pr,mr,gr,Zr,fr,O,Zi,eo,ci,ns,en,is,os,pc,to,ss,as,cs,ls,pt,ds,tn,ro,no,mc,gc,_t,li,di};
724
+ export{qe,rs,ue,Wi,ai,Ki,Ji,Xr,Xi,Qi,Se,Z,Ge,ke,Qr,lr,We,dr,Yr,dt,pe,ut,ur,Yi,pr,mr,gr,Zr,fr,O,Zi,eo,ci,ns,en,is,os,pc,to,ss,as,cs,ls,pt,ds,tn,ro,no,mc,gc,_t,li,di};