@stacksjs/ts-cloud 0.16.5 → 0.16.7

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 (107) hide show
  1. package/dist/aws/index.js +1 -1
  2. package/dist/bin/{chunk-k9pb99tr.js → chunk-2tdt4xsv.js} +1 -1
  3. package/dist/bin/{chunk-ryhfvrsd.js → chunk-4v6y0dzc.js} +4 -4
  4. package/dist/bin/{chunk-x9ab1xz8.js → chunk-71ah0fk2.js} +1 -1
  5. package/dist/bin/chunk-czzczndx.js +2 -0
  6. package/dist/bin/{chunk-b48j6k55.js → chunk-deb7ws59.js} +1 -1
  7. package/dist/bin/{chunk-e1cxh9rj.js → chunk-gky64tr9.js} +2 -2
  8. package/dist/bin/{chunk-tkzz82s5.js → chunk-ph1n2es7.js} +7 -7
  9. package/dist/bin/{chunk-p197a99s.js → chunk-rs2d8nj2.js} +2 -2
  10. package/dist/bin/{chunk-xvn07b0e.js → chunk-v6mysz8x.js} +1 -1
  11. package/dist/bin/chunk-v8y0g7r7.js +1 -0
  12. package/dist/bin/{chunk-x4gsw45d.js → chunk-vfmad47g.js} +4 -4
  13. package/dist/bin/chunk-xe48f17b.js +1 -0
  14. package/dist/bin/{chunk-8dzsrbs1.js → chunk-zzwrhtmp.js} +13 -13
  15. package/dist/bin/cli.js +251 -251
  16. package/dist/bin/dashboard-server.js +1 -1
  17. package/dist/{chunk-sxtgx8fj.js → chunk-30504159.js} +15 -15
  18. package/dist/{chunk-srh0ctd4.js → chunk-3nccgrzf.js} +2 -2
  19. package/dist/{chunk-yqfkq6q7.js → chunk-7rygewtr.js} +1 -1
  20. package/dist/{chunk-6w827jkt.js → chunk-910yrha7.js} +143 -143
  21. package/dist/{chunk-q4bk0htq.js → chunk-9rkyxwex.js} +3 -3
  22. package/dist/{chunk-c3pvfcme.js → chunk-dbzveymg.js} +65 -65
  23. package/dist/{chunk-trsaqsgv.js → chunk-f5mqecfk.js} +2 -2
  24. package/dist/{chunk-nnfdz28e.js → chunk-fjqx22m1.js} +1 -1
  25. package/dist/chunk-my2adp07.js +2 -0
  26. package/dist/{chunk-t054j0zn.js → chunk-ndm0r1vb.js} +2 -2
  27. package/dist/{chunk-phr1cqgf.js → chunk-pnjajqyw.js} +1 -1
  28. package/dist/{chunk-bqtyqcj4.js → chunk-r7x7y3ha.js} +35 -35
  29. package/dist/{chunk-f0t7y458.js → chunk-rr1hqfyy.js} +4 -4
  30. package/dist/chunk-smmss8qy.js +1 -0
  31. package/dist/{chunk-f27a8et2.js → chunk-v99q99bs.js} +1 -1
  32. package/dist/{chunk-bvspqd2m.js → chunk-w41zkaey.js} +1 -1
  33. package/dist/{chunk-fgww8ya2.js → chunk-wkbk6pdg.js} +18 -18
  34. package/dist/{chunk-hhy358y8.js → chunk-wp6pg5sx.js} +3 -3
  35. package/dist/chunk-y2s8wcdg.js +1 -0
  36. package/dist/deploy/index.js +1 -1
  37. package/dist/dns/delegation.d.ts +17 -1
  38. package/dist/dns/index.js +1 -1
  39. package/dist/dns/route53-adapter.d.ts +14 -0
  40. package/dist/drivers/index.js +1 -1
  41. package/dist/index.js +32 -23
  42. package/dist/operations/index.js +1 -1
  43. package/dist/protection/index.js +1 -1
  44. package/dist/spend/index.js +1 -1
  45. package/dist/ssl/dns01-challenge.test.d.ts +1 -0
  46. package/dist/ssl/letsencrypt.d.ts +17 -1
  47. package/dist/ui/404.html +1 -1
  48. package/dist/ui/accept-invitation.html +1 -1
  49. package/dist/ui/access-denied.html +1 -1
  50. package/dist/ui/account/automation.html +6 -6
  51. package/dist/ui/account/security.html +2 -2
  52. package/dist/ui/applications/compose.html +6 -6
  53. package/dist/ui/applications/new.html +2 -2
  54. package/dist/ui/data/backups.html +6 -6
  55. package/dist/ui/data/services.html +6 -6
  56. package/dist/ui/data/volumes.html +6 -6
  57. package/dist/ui/index.html +5 -5
  58. package/dist/ui/infrastructure/topology.html +5 -5
  59. package/dist/ui/integrations.html +1 -1
  60. package/dist/ui/operations/alerts.html +6 -6
  61. package/dist/ui/operations/configuration.html +6 -6
  62. package/dist/ui/operations/jobs.html +6 -6
  63. package/dist/ui/operations/maintenance.html +6 -6
  64. package/dist/ui/operations/observability.html +6 -6
  65. package/dist/ui/operations/previews.html +6 -6
  66. package/dist/ui/operations/queue.html +6 -6
  67. package/dist/ui/operations/regions.html +6 -6
  68. package/dist/ui/operations/releases.html +6 -6
  69. package/dist/ui/operations/spend.html +6 -6
  70. package/dist/ui/operations/workloads.html +6 -6
  71. package/dist/ui/security.html +2 -2
  72. package/dist/ui/server/actions.html +6 -6
  73. package/dist/ui/server/activity.html +2 -2
  74. package/dist/ui/server/capacity.html +6 -6
  75. package/dist/ui/server/database.html +6 -6
  76. package/dist/ui/server/deployments.html +5 -5
  77. package/dist/ui/server/diagnostics.html +2 -2
  78. package/dist/ui/server/firewall.html +6 -6
  79. package/dist/ui/server/fleet.html +6 -6
  80. package/dist/ui/server/logs.html +6 -6
  81. package/dist/ui/server/metrics.html +5 -5
  82. package/dist/ui/server/security.html +2 -2
  83. package/dist/ui/server/services.html +2 -2
  84. package/dist/ui/server/sites.html +6 -6
  85. package/dist/ui/server/ssh-keys.html +6 -6
  86. package/dist/ui/server/team.html +6 -6
  87. package/dist/ui/server/terminal.html +2 -2
  88. package/dist/ui/serverless/alarms.html +6 -6
  89. package/dist/ui/serverless/assets.html +1 -1
  90. package/dist/ui/serverless/cost.html +2 -2
  91. package/dist/ui/serverless/data.html +6 -6
  92. package/dist/ui/serverless/deployments.html +2 -2
  93. package/dist/ui/serverless/firewall.html +1 -1
  94. package/dist/ui/serverless/functions.html +5 -5
  95. package/dist/ui/serverless/logs.html +6 -6
  96. package/dist/ui/serverless/metrics.html +2 -2
  97. package/dist/ui/serverless/queues.html +5 -5
  98. package/dist/ui/serverless/secrets.html +6 -6
  99. package/dist/ui/serverless/traces.html +6 -6
  100. package/dist/ui/serverless.html +6 -6
  101. package/package.json +3 -3
  102. package/dist/bin/chunk-2synp9gh.js +0 -1
  103. package/dist/bin/chunk-8dt5ehyk.js +0 -1
  104. package/dist/bin/chunk-p9em7chg.js +0 -2
  105. package/dist/chunk-11s59686.js +0 -2
  106. package/dist/chunk-gk5ehe62.js +0 -1
  107. package/dist/chunk-scy8mzqk.js +0 -1
@@ -1,4 +1,4 @@
1
- import{xs,A,C,pi,$s,Os,U,E,jt,Cr}from"./chunk-gxwsq3k0.js";import{u}from"./chunk-pdw0qjq1.js";import{v}from"./chunk-pd8v6bpd.js";import{K}from"./chunk-9jmnmhpy.js";import{f}from"./chunk-k3er0h4j.js";import{W,ni,gs,P,M,gr,ft,Xe,ao,ii,lo,ht,Ba,uo,po,ai,Lt,Ss,Fa,ci,bs,vs,Ts,Es,mo,Jr,Xr,ws,go}from"./chunk-x4gsw45d.js";import{io,oo,ms}from"./chunk-fbycbnvj.js";import{ps}from"./chunk-edaq5jef.js";import{mr}from"./chunk-f35pte64.js";import{Qr}from"./chunk-a929za72.js";import{existsSync as fl,readFileSync as gl}from"node:fs";import{readFileSync as on}from"node:fs";import{join as ta}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 Gt(e){return e.replace(/\.$/,"").toLowerCase()}function so(e,t,r){let s=Gt(e.name),n=Gt(t),i=Gt(r),o=i===n?"@":i.endsWith(`.${n}`)?i.slice(0,-(n.length+1)):i;return s===i||s===o||o==="@"&&(s===""||s===n)}async function no(e,t,r,s,n="A"){let i=await e.listRecords(t);if(!i.success)return[`could not list ${n} records: ${i.message||"unknown provider error"}`];let o=i.records.filter((l)=>l.type===n&&so(l,t,r)),a=o.findIndex((l)=>l.content===s);if(o.length<=1||a===-1)return[];let c=[];for(let[l,p]of o.entries()){if(l===a)continue;let d=await e.deleteRecord(t,p);if(!d.success)c.push(`could not remove stale ${p.name} ${n} ${p.content}: ${d.message||"unknown provider error"}`)}return c}function de(e){if(!e)return;let t=e.trim();if(!t)return;if(!t.includes("/"))return t;let[r]=t.split("/");if(!r.endsWith("::"))return r||void 0;return`${r}1`}var co=new Set(["mail","smtp","imap","mx"]);function qi(e){return!co.has(e.split(".")[0]??"")}async function Yn(e){let{provider:t,zone:r,fqdn:s,ipv4:n,ipv6:i,ttl:o=600}=e,a={published:[],warnings:[]},c=[{type:"A",content:n}];if(i&&qi(s))c.push({type:"AAAA",content:i});for(let{type:l,content:p}of c){let d=await t.upsertRecord(r,{name:s,type:l,content:p,ttl:o});if(d?.success===!1){a.warnings.push(`${s} → ${p} failed: ${d.error||d.message||"unknown error"}`);continue}if(a.warnings.push(...(await no(t,r,s,p,l)).map((m)=>`${s} cleanup: ${m}`)),await Hi(t,r,s,p,l))a.published.push({fqdn:s,type:l,content:p});else a.warnings.push(`${s} → ${p} reported success at ${t.name} but no matching ${l} record exists — create it manually: ${l} ${s} → ${p}`)}return a}async function Hi(e,t,r,s,n){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===n&&a===r&&o?.content===s})}catch{return!0}}function Wt(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 tt(e,t){let r=Wt(e?.stderr),s=/line (\d+): syntax error/.exec(r);if(!s)return"";let n=Number(s[1]),i=t.split(`
1
+ import{xs,A,C,pi,$s,Os,U,E,jt,Cr}from"./chunk-gxwsq3k0.js";import{u}from"./chunk-pdw0qjq1.js";import{v}from"./chunk-pd8v6bpd.js";import{K}from"./chunk-9jmnmhpy.js";import{f}from"./chunk-k3er0h4j.js";import{W,ni,gs,P,L,gr,ft,Xe,ao,ii,lo,ht,Ba,uo,po,ai,Lt,Ss,Fa,ci,bs,vs,Ts,Es,mo,Jr,Xr,ws,go}from"./chunk-vfmad47g.js";import{io,oo,ms}from"./chunk-fbycbnvj.js";import{ps}from"./chunk-edaq5jef.js";import{mr}from"./chunk-f35pte64.js";import{Qr}from"./chunk-a929za72.js";import{existsSync as fl,readFileSync as gl}from"node:fs";import{readFileSync as on}from"node:fs";import{join as ta}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 Gt(e){return e.replace(/\.$/,"").toLowerCase()}function so(e,t,r){let s=Gt(e.name),n=Gt(t),i=Gt(r),o=i===n?"@":i.endsWith(`.${n}`)?i.slice(0,-(n.length+1)):i;return s===i||s===o||o==="@"&&(s===""||s===n)}async function no(e,t,r,s,n="A"){let i=await e.listRecords(t);if(!i.success)return[`could not list ${n} records: ${i.message||"unknown provider error"}`];let o=i.records.filter((l)=>l.type===n&&so(l,t,r)),a=o.findIndex((l)=>l.content===s);if(o.length<=1||a===-1)return[];let c=[];for(let[l,p]of o.entries()){if(l===a)continue;let d=await e.deleteRecord(t,p);if(!d.success)c.push(`could not remove stale ${p.name} ${n} ${p.content}: ${d.message||"unknown provider error"}`)}return c}function de(e){if(!e)return;let t=e.trim();if(!t)return;if(!t.includes("/"))return t;let[r]=t.split("/");if(!r.endsWith("::"))return r||void 0;return`${r}1`}var co=new Set(["mail","smtp","imap","mx"]);function qi(e){return!co.has(e.split(".")[0]??"")}async function Yn(e){let{provider:t,zone:r,fqdn:s,ipv4:n,ipv6:i,ttl:o=600}=e,a={published:[],warnings:[]},c=[{type:"A",content:n}];if(i&&qi(s))c.push({type:"AAAA",content:i});for(let{type:l,content:p}of c){let d=await t.upsertRecord(r,{name:s,type:l,content:p,ttl:o});if(d?.success===!1){a.warnings.push(`${s} → ${p} failed: ${d.error||d.message||"unknown error"}`);continue}if(a.warnings.push(...(await no(t,r,s,p,l)).map((m)=>`${s} cleanup: ${m}`)),await Hi(t,r,s,p,l))a.published.push({fqdn:s,type:l,content:p});else a.warnings.push(`${s} → ${p} reported success at ${t.name} but no matching ${l} record exists — create it manually: ${l} ${s} → ${p}`)}return a}async function Hi(e,t,r,s,n){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===n&&a===r&&o?.content===s})}catch{return!0}}function Wt(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 tt(e,t){let r=Wt(e?.stderr),s=/line (\d+): syntax error/.exec(r);if(!s)return"";let n=Number(s[1]),i=t.split(`
2
2
  `),o=Math.max(1,n-12),a=Math.min(i.length,n+2),c=i.slice(o-1,a).map((l,p)=>{let d=o+p,m=/^[A-Z_][A-Z0-9_]*=/.test(l)?l.replace(/=.*/,"=<redacted>"):l;return` ${String(d).padStart(4)}${d===n?" >":" "} ${m}`});return["",`The deploy script bash rejected is ${i.length} lines; it stopped at ${n}.`,...c].join(`
3
3
  `)}function Ee(e){let t=e,r=typeof t?.status==="number"?` (exit ${t.status})`:"",s=t?.signal?` (signal ${t.signal})`:"",n=[Wt(t?.stderr),Wt(t?.stdout)].filter(Boolean).join(`
4
4
  `);return`Remote SSH command failed${r}${s}${n?`
@@ -8,11 +8,11 @@ ${e.slice(-As)}`:e}function Ie(e,t){let r=e.filter((o)=>o.status!=="Success");if
8
8
  ${ho(a)}`:c}),n=r.length-s.length,i=n>0?[`(+${n} more instance${n===1?"":"s"} failed)`]:[];return[t,...s,...i].join(`
9
9
  `)}class We{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new u}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((s)=>this.parseParameter(s)),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((s)=>this.parseParameter(s)),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((s)=>this.parseParameter(s)),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((s)=>({Name:s.Name,Type:s.Type,KeyId:s.KeyId,LastModifiedDate:s.LastModifiedDate,LastModifiedUser:s.LastModifiedUser,Description:s.Description,Value:s.Value,Version:s.Version,Labels:s.Labels,Tier:s.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=[],s;do{let n=await this.getParametersByPath({Path:e,Recursive:t,WithDecryption:!0,NextToken:s});if(n.Parameters)r.push(...n.Parameters);s=n.NextToken}while(s);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 s=await this.sendCommand({InstanceIds:[e],DocumentName:"AWS-RunShellScript",Parameters:{commands:t},TimeoutSeconds:r?.timeoutSeconds||600});if(!s.CommandId)return{success:!1,error:"Failed to send command"};if(r?.waitForCompletion===!1)return{success:!0,status:"Pending"};let n=r?.pollIntervalMs||2000,i=r?.maxWaitMs||300000,o=Date.now();while(Date.now()-o<i){await new Promise((a)=>setTimeout(a,n));try{let a=await this.getCommandInvocation({CommandId:s.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((n)=>({InstanceId:n.InstanceId,Status:n.Status,StatusDetails:n.StatusDetails,StandardOutputContent:n.CommandPlugins?.[0]?.Output,StandardErrorContent:n.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 s=e.pollIntervalMs||3000,n=e.maxWaitMs||600000,i=Date.now(),o=new Set(["Success","Failed","Cancelled","TimedOut"]),a=[];while(Date.now()-i<n){await new Promise((c)=>setTimeout(c,s));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})),p=a.every((d)=>d.Status==="Success");return{success:p,instanceCount:a.length,perInstance:l,error:p?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 yo(e){return`/etc/ts-cloud/${e}-upgrade.env`}function So(e){return`${e}-upgrade`}function Wi(e){if(!e||e.length===0)return[];let t=["mkdir -p /etc/ts-cloud"],r=[];for(let s of e){if(s.enabled===!1)continue;if(!s.service||!s.binary)continue;let{service:n,binary:i,command:o="upgrade",channel:a="stable",schedule:c="daily",randomizedDelay:l="4h",args:p=[]}=s,d=So(n),m=yo(n),g=[`--path ${i}`,`--service ${n}`,...a==="canary"?["--canary"]:[],...p].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 ${n} 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} ${g} $ARGS'`,"TS_CLOUD_APPUPD_SVC_EOF",`cat > /etc/systemd/system/${d}.timer <<'TS_CLOUD_APPUPD_TMR_EOF'`,"[Unit]",`Description=Scheduled ${n} 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 be(e=!0){if(!e)return[];return["export DEBIAN_FRONTEND=noninteractive","dpkg-query -W -f='${Status}' unattended-upgrades 2>/dev/null | grep -q 'ok installed' || apt-get install -y unattended-upgrades","cat > /etc/apt/apt.conf.d/20auto-upgrades <<'TS_CLOUD_AUTOUPD_EOF'",'APT::Periodic::Update-Package-Lists "1";','APT::Periodic::Unattended-Upgrade "1";','APT::Periodic::Download-Upgradeable-Packages "1";','APT::Periodic::AutocleanInterval "7";',"TS_CLOUD_AUTOUPD_EOF","systemctl enable --now unattended-upgrades 2>/dev/null || true"]}var Ns=[["nginx",80],["https",443],["phpFpm",9074],["mysql",3306],["postgres",5432],["redis",6379],["meilisearch",7700],["typesense",8108],["smtp",25]];function vo(e=!0){let t=typeof e==="object"?e:{},r=typeof e==="boolean"?e:e.enabled!==!1,s=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(s)&&s>0?s:0,bandwidthPercent:t.alerts?.bandwidthPercent??80}}function we(e=!0){let{enabled:t,cpuLoadPerCore:r,memPercent:s,diskPercent:n,bandwidthTb:i,bandwidthPercent:o}=vo(e);if(!t)return[];let a=Math.round(i*1000000000000),c=Ns.map(([p,d])=>`SVC_${p.toUpperCase()}=$(probe ${d})`),l=Ns.map(([p])=>`"${p}":"$SVC_${p.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
- 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 ${s} ]; then ALERTS="$ALERTS mem=\${MEM_PCT}%"; fi`,`if [ "\${DISK_PCT:-0}" -ge ${n} ]; 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 bo={"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"},wo="127.0.0.1:9074";function ks(e){return wo}function $o(e={}){let t=e.versions?.length?e.versions:["8.3"];return e.default&&t.includes(e.default)?e.default:t[0]}function _o(e={}){return{...e.optimizeForProduction===!1?{}:{...bo},...e.ini||{}}}function To(e={}){let t=_o(e),r=Object.keys(t);if(r.length===0)return[];let s=r.map((i)=>`${i}=${t[i]}`),n="ts-cloud-managed";return[ft(),"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'`,`; ${n} — production PHP tuning`,...s,"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 '/; ${n} BEGIN/,/; ${n} END/d' "$TS_CLOUD_LOADED_INI"`,` cat >> "$TS_CLOUD_LOADED_INI" <<'TS_CLOUD_PHPINI_EOF'`,`; ${n} BEGIN`,...s,`; ${n} END`,"TS_CLOUD_PHPINI_EOF","fi",`(cd ${M} && pantry restart php-fpm) 2>/dev/null || true`]}function yt(e={}){let t=$o(e),r=e.installNginx!==!1,s=e.installComposer!==!1,n=[`php.net@${t}`];if(s)n.push("getcomposer.org");if(r)n.push("nginx.org");return[...Xe(n),...ao(["php-fpm"]),...To(e)]}function Vt(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 Po(e){if(!e)return"";let t=typeof e==="object"?e:{},s=[`max-age=${t.maxAge??31536000}`];if(t.includeSubDomains??!0)s.push("includeSubDomains");if(t.preload)s.push("preload");return` add_header Strict-Transport-Security "${s.join("; ")}" always;`}function xo(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 Hs(e){return`/etc/nginx/.htpasswd-${e}`}var Co=new Set(["laravel","php","statamic","wordpress"]);function Ro(e){return Co.has(e)}function Eo(e){return e==="laravel"||e==="statamic"?"public":""}function Io(e,t){let r=e.replace(/\/+$/,""),s=t.replace(/^\/+|\/+$/g,"");return s?`${r}/${s}`:r}function Oo(e){let t=e.type??"laravel",r=e.webDirectory??Eo(t),s=Io(e.appDir,r),n=Ro(t),i=e.phpVersion??"8.3",o=[` root ${s};`,"",' add_header X-Frame-Options "SAMEORIGIN";',' add_header X-Content-Type-Options "nosniff";'],a=Po(e.hsts);if(a)o.push(a);for(let c of xo(e.security))o.push(c);if(o.push("",` index ${n?"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 ${Hs(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(n){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??ks(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 Do(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(" "),s=Oo(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(" ")};`]:[],"",...s,"}"];return`${[...i,"",...o].join(`
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 ${s} ]; then ALERTS="$ALERTS mem=\${MEM_PCT}%"; fi`,`if [ "\${DISK_PCT:-0}" -ge ${n} ]; 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 bo={"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"},wo="127.0.0.1:9074";function ks(e){return wo}function $o(e={}){let t=e.versions?.length?e.versions:["8.3"];return e.default&&t.includes(e.default)?e.default:t[0]}function _o(e={}){return{...e.optimizeForProduction===!1?{}:{...bo},...e.ini||{}}}function To(e={}){let t=_o(e),r=Object.keys(t);if(r.length===0)return[];let s=r.map((i)=>`${i}=${t[i]}`),n="ts-cloud-managed";return[ft(),"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'`,`; ${n} — production PHP tuning`,...s,"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 '/; ${n} BEGIN/,/; ${n} END/d' "$TS_CLOUD_LOADED_INI"`,` cat >> "$TS_CLOUD_LOADED_INI" <<'TS_CLOUD_PHPINI_EOF'`,`; ${n} BEGIN`,...s,`; ${n} END`,"TS_CLOUD_PHPINI_EOF","fi",`(cd ${L} && pantry restart php-fpm) 2>/dev/null || true`]}function yt(e={}){let t=$o(e),r=e.installNginx!==!1,s=e.installComposer!==!1,n=[`php.net@${t}`];if(s)n.push("getcomposer.org");if(r)n.push("nginx.org");return[...Xe(n),...ao(["php-fpm"]),...To(e)]}function Vt(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 Po(e){if(!e)return"";let t=typeof e==="object"?e:{},s=[`max-age=${t.maxAge??31536000}`];if(t.includeSubDomains??!0)s.push("includeSubDomains");if(t.preload)s.push("preload");return` add_header Strict-Transport-Security "${s.join("; ")}" always;`}function xo(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 Hs(e){return`/etc/nginx/.htpasswd-${e}`}var Co=new Set(["laravel","php","statamic","wordpress"]);function Ro(e){return Co.has(e)}function Eo(e){return e==="laravel"||e==="statamic"?"public":""}function Io(e,t){let r=e.replace(/\/+$/,""),s=t.replace(/^\/+|\/+$/g,"");return s?`${r}/${s}`:r}function Oo(e){let t=e.type??"laravel",r=e.webDirectory??Eo(t),s=Io(e.appDir,r),n=Ro(t),i=e.phpVersion??"8.3",o=[` root ${s};`,"",' add_header X-Frame-Options "SAMEORIGIN";',' add_header X-Content-Type-Options "nosniff";'],a=Po(e.hsts);if(a)o.push(a);for(let c of xo(e.security))o.push(c);if(o.push("",` index ${n?"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 ${Hs(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(n){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??ks(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 Do(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(" "),s=Oo(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(" ")};`]:[],"",...s,"}"];return`${[...i,"",...o].join(`
12
12
  `)}
13
13
  `}return`${["server {"," listen 80;"," listen [::]:80;",` server_name ${r};`,...s,"}"].join(`
14
14
  `)}
15
- `}function qt(e){let t=`/etc/nginx/sites-available/${e.siteName}`,r=`/etc/nginx/sites-enabled/${e.siteName}`,s=Do(e),n=[...Xt()];if(e.auth){let i=Hs(e.siteName),o=(l)=>l.split("'").join("'\\''"),a=o(e.auth.password),c=o(e.auth.username);n.push(`TS_CLOUD_HTPASS=$(openssl passwd -apr1 '${a}')`,`printf '%s:%s\\n' '${c}' "$TS_CLOUD_HTPASS" > ${i}`,`chmod 640 ${i}`,`chown root:www-data ${i} 2>/dev/null || true`)}return n.push(`cat > ${t} <<'TS_CLOUD_NGINX_EOF'`,s.replace(/\n$/,""),"TS_CLOUD_NGINX_EOF",`ln -sf ${t} ${r}`,"rm -f /etc/nginx/sites-enabled/default",`${$e} -t`,"systemctl reload ts-cloud-nginx 2>/dev/null || systemctl restart ts-cloud-nginx 2>/dev/null || true"),n}var $e="/usr/local/bin/ts-cloud-nginx";function Xt(e="/opt/pantry"){return[...gr(),...Xe(["nginx.org"]),"mkdir -p /etc/nginx/sites-available /etc/nginx/sites-enabled /var/log/nginx /var/lib/nginx/body /var/lib/nginx/proxy /var/lib/nginx/fastcgi /var/lib/nginx/uwsgi /var/lib/nginx/scgi","getent passwd www-data >/dev/null || useradd --system --no-create-home --shell /usr/sbin/nologin www-data","chown -R www-data:www-data /var/lib/nginx /var/log/nginx",`cat > ${$e} <<'TS_CLOUD_NGINXBIN_EOF'`,"#!/bin/sh",`eval "$(cd ${e} && pantry env 2>/dev/null)"`,"NGINX_BIN=/opt/pantry/pantry/.bin/nginx",'if [ ! -x "$NGINX_BIN" ]; then NGINX_BIN=$(command -v nginx || true); fi','if [ -z "$NGINX_BIN" ]; then echo "nginx binary not found; run pantry install nginx.org or install nginx explicitly" >&2; exit 1; fi','exec "$NGINX_BIN" -c /etc/nginx/nginx.conf "$@"',"TS_CLOUD_NGINXBIN_EOF",`chmod +x ${$e}`,"cat > /etc/nginx/fastcgi_params <<'TS_CLOUD_FCGI_EOF'","fastcgi_param QUERY_STRING $query_string;","fastcgi_param REQUEST_METHOD $request_method;","fastcgi_param CONTENT_TYPE $content_type;","fastcgi_param CONTENT_LENGTH $content_length;","fastcgi_param SCRIPT_NAME $fastcgi_script_name;","fastcgi_param REQUEST_URI $request_uri;","fastcgi_param DOCUMENT_URI $document_uri;","fastcgi_param DOCUMENT_ROOT $document_root;","fastcgi_param SERVER_PROTOCOL $server_protocol;","fastcgi_param REQUEST_SCHEME $scheme;","fastcgi_param HTTPS $https if_not_empty;","fastcgi_param GATEWAY_INTERFACE CGI/1.1;","fastcgi_param SERVER_SOFTWARE nginx/$nginx_version;","fastcgi_param REMOTE_ADDR $remote_addr;","fastcgi_param REMOTE_PORT $remote_port;","fastcgi_param SERVER_ADDR $server_addr;","fastcgi_param SERVER_PORT $server_port;","fastcgi_param SERVER_NAME $server_name;","fastcgi_param REDIRECT_STATUS 200;","TS_CLOUD_FCGI_EOF","cat > /etc/nginx/nginx.conf <<'TS_CLOUD_NGINXCONF_EOF'","user www-data;","worker_processes auto;","pid /run/nginx.pid;","error_log /var/log/nginx/error.log;","events { worker_connections 1024; }","http {"," default_type application/octet-stream;"," types {"," text/html html htm;"," text/css css;"," application/javascript js;"," application/json json;"," image/svg+xml svg;"," image/png png;"," image/jpeg jpg jpeg;"," image/gif gif;"," image/x-icon ico;"," image/webp webp;"," font/woff2 woff2;"," font/woff woff;"," text/plain txt;"," }"," access_log /var/log/nginx/access.log;"," sendfile on;"," tcp_nopush on;"," keepalive_timeout 65;"," server_tokens off;"," client_max_body_size 100m;"," client_body_temp_path /var/lib/nginx/body;"," proxy_temp_path /var/lib/nginx/proxy;"," fastcgi_temp_path /var/lib/nginx/fastcgi;"," uwsgi_temp_path /var/lib/nginx/uwsgi;"," scgi_temp_path /var/lib/nginx/scgi;"," server {"," listen 80 default_server;"," listen [::]:80 default_server;"," server_name _;"," return 444;"," }"," include /etc/nginx/sites-enabled/*;","}","TS_CLOUD_NGINXCONF_EOF","cat > /etc/systemd/system/ts-cloud-nginx.service <<'TS_CLOUD_NGINXUNIT_EOF'","[Unit]","Description=ts-cloud nginx (pantry)","After=network.target","","[Service]","Type=simple",`ExecStartPre=${$e} -t`,`ExecStart=${$e} -g 'daemon off;'`,`ExecReload=${$e} -s reload`,"Restart=always","RestartSec=3","","[Install]","WantedBy=multi-user.target","TS_CLOUD_NGINXUNIT_EOF","systemctl daemon-reload","systemctl enable ts-cloud-nginx","ls /etc/nginx/sites-enabled/* >/dev/null 2>&1 && systemctl restart ts-cloud-nginx || true"]}function rt(e,t){return!e.events||e.events.includes(t)}async function Yt(e,t,r,s={}){if(!e)return[];let n=s.fetchImpl??globalThis.fetch,i=[],o=[],a=(c,l)=>n(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)}).catch(()=>{return});if(e.slack?.webhookUrl&&rt(e,t))i.push("slack"),o.push(a(e.slack.webhookUrl,{text:r}));if(e.discord?.webhookUrl&&rt(e,t))i.push("discord"),o.push(a(e.discord.webhookUrl,{content:r}));if(e.telegram?.botToken&&e.telegram.chatId&&rt(e,t)){i.push("telegram");let c=`https://api.telegram.org/bot${e.telegram.botToken}/sendMessage`;o.push(a(c,{chat_id:e.telegram.chatId,text:r}))}if(e.webhook?.url&&rt(e,t))if(i.push("webhook"),(e.webhook.method||"POST")==="GET"){let c=e.webhook.url.includes("?")?"&":"?",l=`${e.webhook.url}${c}event=${encodeURIComponent(t)}&message=${encodeURIComponent(r)}`;o.push(n(l,{method:"GET"}).catch(()=>{return}))}else o.push(a(e.webhook.url,{event:t,message:r}));if(e.email?.to&&rt(e,t))i.push("email"),o.push(Ao(e.email,t,r));return await Promise.all(o),i}async function Ao(e,t,r){try{let s=await import("./chunk-xvn07b0e.js");await s.email.send({to:e.to,from:e.from,subject:`[ts-cloud] ${t}`,text:r})}catch{}}function Ls(e,t){return t??e}function ke(e){if(!e)return[];let t=[];if(e.slack?.webhookUrl)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"text\\":\\"$MSG\\"}" ${e.slack.webhookUrl} || true`);if(e.discord?.webhookUrl)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"content\\":\\"$MSG\\"}" ${e.discord.webhookUrl} || true`);if(e.telegram?.botToken&&e.telegram.chatId)t.push(`curl -fsS -X POST "https://api.telegram.org/bot${e.telegram.botToken}/sendMessage" --data-urlencode "chat_id=${e.telegram.chatId}" --data-urlencode "text=$MSG" || true`);if(e.webhook?.url)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"message\\":\\"$MSG\\"}" ${e.webhook.url} || true`);if(t.length===0)return[];return["cat > /usr/local/bin/ts-cloud-notify <<'TS_CLOUD_NOTIFY_EOF'","#!/bin/bash",'MSG="$1"',...t,"TS_CLOUD_NOTIFY_EOF","chmod +x /usr/local/bin/ts-cloud-notify"]}import{isIP as Us}from"node:net";var Vr="/etc/rpx/certs",zs="/etc/rpx/local-ca",No="rpx-root-ca.crt";function St(e=zs){return`${e.replace(/\/+$/,"")}/${No}`}function er(e){if(e.toLowerCase().endsWith(".local"))return!1;return e.split(".").length===2}function Gi(e,t={}){let r=new Set;for(let s of Object.values(e)){if(!s?.domain)continue;if(P(s)==="bucket")continue;r.add(s.domain)}if(t.autoWww!==!1)for(let s of[...r]){if(!er(s))continue;r.add(`www.${s}`)}return[...r]}var ko=["1.1.1.1","8.8.8.8"],Ho="/var/www/acme-challenge";function Lo(e){if(typeof e==="string")return{to:e};let t={to:e.to};if(e.status!=null)t.status=e.status;if(e.preservePath!=null)t.preservePath=e.preservePath;return t}function Mo(e){let t=e.auth;if(!t||t.enabled===!1||!t.password)return;return{username:t.username||"admin",password:t.password,...t.realm?{realm:t.realm}:{}}}function tr(e){if(!e)return;return e.tls??"local-ca"}function Ki(e,t){if(e.cloud?.provider!=="ssh")return;let r=e.ssh?.lan;if(!r)return;return{...r.hostname?{hostname:r.hostname}:{},tls:r.tls??"local-ca",...t?{ip:t}:{}}}function Fs(e){if(e.cloud?.provider!=="ssh")return;return e.ssh?.profile}function Uo(e){let t=e.trim().toLowerCase();if(!t||t.startsWith("*")||t.includes(":")||t.includes("/")||t.includes(" "))return!1;if(Us(t)!==0)return!1;return t.endsWith(".local")||!t.includes(".")}function zo(e,t,r){let s=[],n=new Set,i=(l,p)=>{let d=l.trim().toLowerCase();if(!d||n.has(d))return;n.add(d),s.push({host:d,source:p})},o=t.hostname?.trim(),a=(o||`${r}.local`).toLowerCase();if(i(a,o?"ssh.lan.hostname":`the ssh provider's default LAN name for project "${r}"`),Object.entries(e).some(([l,p])=>!!p&&Cr(l)))i(`dashboard.${a}`,"the management dashboard site");for(let[l,p]of Object.entries(e)){if(!p?.domain)continue;if(P(p)==="bucket")continue;if(!Uo(p.domain))continue;i(p.domain,`site "${l}"`)}return s}function Fo(e,t){if(!t?.length)return;return t.find((r)=>{let s=(r.startsWith(".")?r.slice(1):r).toLowerCase();return e===s||e.endsWith(`.${s}`)})}function Bo(e,t){if(!t?.enabled)return;for(let{host:r,source:s}of e){let n=Fo(r,t.allowedSuffixes);if(!n)continue;throw Error(`The LAN certificate authority and public on-demand TLS both claim "${r}". LAN source: ${s}. Public source: the on-demand TLS allowed suffix "${n}", which is derived from the site domains. A host is either LAN-only, with a certificate signed by the box's own CA, or public, with one issued by Let's Encrypt, never both. Give the LAN a name no site domain covers (ssh.lan.hostname), or take that domain out of the sites this deploy routes.`)}}function Bs(e){if(!e||e==="/")return;let t=`/${e}`.replace(/\/+/g,"/").replace(/\/+$/,"");if(!t.startsWith("/"))t=`/${t}`;return t===""||t==="/"?void 0:t}function Jt(e,t){let s=(t?`${e}${t}`:e).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return s.length>0?s:"rpx"}function Ko(e,t){if(!t||t.length===0)return`localhost:${e}`;return t.map((r)=>`${r.privateIp??r.publicIp}:${e}`)}function Ks(e,t,r){let s=(t.wwwRoot??"/var/www").replace(/\/+$/,""),n=t.slug??"app",i=t.proxy.certsDir??Vr,o=t.proxy.loadBalancer,a=[],c=new Set;for(let[m,g]of Object.entries(e)){if(!g||!g.domain)continue;let h=P(g);if(h==="bucket")continue;let _=Bs(g.path),w=Jt(g.domain,_),b=Mo(g);if(h==="redirect"){a.push({to:g.domain,path:_,redirect:Lo(g.redirect),id:w,...b?{auth:b}:{}}),c.add(g.domain);continue}if(h==="proxy"){let y=gs(g);if(y.length===0)continue;let T=y.length===1?y[0]:y;a.push({to:g.domain,path:_,from:T,id:w,...b?{auth:b}:{},...Array.isArray(T)&&o?{loadBalancer:o}:{}}),c.add(g.domain);continue}if(h==="server-app"){if(typeof g.port!=="number")continue;let y=Ko(g.port,r);a.push({to:g.domain,path:_,from:y,id:w,...b?{auth:b}:{},...Array.isArray(y)&&o?{loadBalancer:o}:{}})}else a.push({to:g.domain,path:_,static:{dir:`${s}/${n}-${m}/current`,spa:g.spa??!1,pathRewriteStyle:g.pathRewriteStyle??"directory"},cleanUrls:g.pathRewriteStyle!=="flat",...b?{auth:b}:{},id:w});c.add(g.domain)}if(t.proxy.autoWww!==!1)for(let m of[...c]){if(!er(m))continue;let g=`www.${m}`;if(c.has(g))continue;a.push({to:g,redirect:{to:`https://${m}`},id:Jt(g)}),c.add(g)}a.sort((m,g)=>{if(m.to!==g.to)return m.to.localeCompare(g.to);return(g.path?.length??0)-(m.path?.length??0)});let l={proxies:a,productionCerts:{certsDir:i,certsDirServerNames:[...c]},https:!0,hostsManagement:!1,cleanup:{hosts:!1,certs:!1}};if(t.proxy.onDemandTls&&c.size>0)l.onDemandTls={enabled:!0,allowedSuffixes:[...c],email:t.proxy.onDemandTlsEmail,certsDir:i,staging:t.proxy.onDemandTlsStaging??!1};if(t.proxy.onDemandTls)l.acmeChallengeWebroot=t.proxy.acmeWebroot??Ho;let p=t.proxy.cdn,d=p?.frontedHosts?.length?p.frontedHosts:[...c];if(p?.secret&&d.length>0)l.originGuard={header:p.secretHeader??"X-Origin-Verify",value:p.secret,hosts:d};if(t.lan)if(tr(t.lan)==="off")l.https=!1;else{let m=zo(e,t.lan,n);Bo(m,l.onDemandTls);let g=t.lan.ip&&Us(t.lan.ip)!==0?[t.lan.ip]:[];l.localCa={dir:zs,hosts:m.map((h)=>h.host),...g.length>0?{ips:g}:{},installTrust:!0}}return l}function fe(e,t){return Ks(e,t)}function Me(e,t,r){return Ks(e,r,t)}function Q(e){return e?.webServer==="rpx"||e?.proxy?.engine==="rpx"}var st="/etc/rpx",J="/opt/rpx-gateway",Qt="/etc/rpx/gateway.ts",He="/etc/rpx/gateway",me="rpx-gateway.service",te="/etc/rpx/sites.d";function jo(e=te,t=Vr){return`// Generated by ts-cloud — rpx gateway assembler.
15
+ `}function qt(e){let t=`/etc/nginx/sites-available/${e.siteName}`,r=`/etc/nginx/sites-enabled/${e.siteName}`,s=Do(e),n=[...Xt()];if(e.auth){let i=Hs(e.siteName),o=(l)=>l.split("'").join("'\\''"),a=o(e.auth.password),c=o(e.auth.username);n.push(`TS_CLOUD_HTPASS=$(openssl passwd -apr1 '${a}')`,`printf '%s:%s\\n' '${c}' "$TS_CLOUD_HTPASS" > ${i}`,`chmod 640 ${i}`,`chown root:www-data ${i} 2>/dev/null || true`)}return n.push(`cat > ${t} <<'TS_CLOUD_NGINX_EOF'`,s.replace(/\n$/,""),"TS_CLOUD_NGINX_EOF",`ln -sf ${t} ${r}`,"rm -f /etc/nginx/sites-enabled/default",`${$e} -t`,"systemctl reload ts-cloud-nginx 2>/dev/null || systemctl restart ts-cloud-nginx 2>/dev/null || true"),n}var $e="/usr/local/bin/ts-cloud-nginx";function Xt(e="/opt/pantry"){return[...gr(),...Xe(["nginx.org"]),"mkdir -p /etc/nginx/sites-available /etc/nginx/sites-enabled /var/log/nginx /var/lib/nginx/body /var/lib/nginx/proxy /var/lib/nginx/fastcgi /var/lib/nginx/uwsgi /var/lib/nginx/scgi","getent passwd www-data >/dev/null || useradd --system --no-create-home --shell /usr/sbin/nologin www-data","chown -R www-data:www-data /var/lib/nginx /var/log/nginx",`cat > ${$e} <<'TS_CLOUD_NGINXBIN_EOF'`,"#!/bin/sh",`eval "$(cd ${e} && pantry env 2>/dev/null)"`,"NGINX_BIN=/opt/pantry/pantry/.bin/nginx",'if [ ! -x "$NGINX_BIN" ]; then NGINX_BIN=$(command -v nginx || true); fi','if [ -z "$NGINX_BIN" ]; then echo "nginx binary not found; run pantry install nginx.org or install nginx explicitly" >&2; exit 1; fi','exec "$NGINX_BIN" -c /etc/nginx/nginx.conf "$@"',"TS_CLOUD_NGINXBIN_EOF",`chmod +x ${$e}`,"cat > /etc/nginx/fastcgi_params <<'TS_CLOUD_FCGI_EOF'","fastcgi_param QUERY_STRING $query_string;","fastcgi_param REQUEST_METHOD $request_method;","fastcgi_param CONTENT_TYPE $content_type;","fastcgi_param CONTENT_LENGTH $content_length;","fastcgi_param SCRIPT_NAME $fastcgi_script_name;","fastcgi_param REQUEST_URI $request_uri;","fastcgi_param DOCUMENT_URI $document_uri;","fastcgi_param DOCUMENT_ROOT $document_root;","fastcgi_param SERVER_PROTOCOL $server_protocol;","fastcgi_param REQUEST_SCHEME $scheme;","fastcgi_param HTTPS $https if_not_empty;","fastcgi_param GATEWAY_INTERFACE CGI/1.1;","fastcgi_param SERVER_SOFTWARE nginx/$nginx_version;","fastcgi_param REMOTE_ADDR $remote_addr;","fastcgi_param REMOTE_PORT $remote_port;","fastcgi_param SERVER_ADDR $server_addr;","fastcgi_param SERVER_PORT $server_port;","fastcgi_param SERVER_NAME $server_name;","fastcgi_param REDIRECT_STATUS 200;","TS_CLOUD_FCGI_EOF","cat > /etc/nginx/nginx.conf <<'TS_CLOUD_NGINXCONF_EOF'","user www-data;","worker_processes auto;","pid /run/nginx.pid;","error_log /var/log/nginx/error.log;","events { worker_connections 1024; }","http {"," default_type application/octet-stream;"," types {"," text/html html htm;"," text/css css;"," application/javascript js;"," application/json json;"," image/svg+xml svg;"," image/png png;"," image/jpeg jpg jpeg;"," image/gif gif;"," image/x-icon ico;"," image/webp webp;"," font/woff2 woff2;"," font/woff woff;"," text/plain txt;"," }"," access_log /var/log/nginx/access.log;"," sendfile on;"," tcp_nopush on;"," keepalive_timeout 65;"," server_tokens off;"," client_max_body_size 100m;"," client_body_temp_path /var/lib/nginx/body;"," proxy_temp_path /var/lib/nginx/proxy;"," fastcgi_temp_path /var/lib/nginx/fastcgi;"," uwsgi_temp_path /var/lib/nginx/uwsgi;"," scgi_temp_path /var/lib/nginx/scgi;"," server {"," listen 80 default_server;"," listen [::]:80 default_server;"," server_name _;"," return 444;"," }"," include /etc/nginx/sites-enabled/*;","}","TS_CLOUD_NGINXCONF_EOF","cat > /etc/systemd/system/ts-cloud-nginx.service <<'TS_CLOUD_NGINXUNIT_EOF'","[Unit]","Description=ts-cloud nginx (pantry)","After=network.target","","[Service]","Type=simple",`ExecStartPre=${$e} -t`,`ExecStart=${$e} -g 'daemon off;'`,`ExecReload=${$e} -s reload`,"Restart=always","RestartSec=3","","[Install]","WantedBy=multi-user.target","TS_CLOUD_NGINXUNIT_EOF","systemctl daemon-reload","systemctl enable ts-cloud-nginx","ls /etc/nginx/sites-enabled/* >/dev/null 2>&1 && systemctl restart ts-cloud-nginx || true"]}function rt(e,t){return!e.events||e.events.includes(t)}async function Yt(e,t,r,s={}){if(!e)return[];let n=s.fetchImpl??globalThis.fetch,i=[],o=[],a=(c,l)=>n(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)}).catch(()=>{return});if(e.slack?.webhookUrl&&rt(e,t))i.push("slack"),o.push(a(e.slack.webhookUrl,{text:r}));if(e.discord?.webhookUrl&&rt(e,t))i.push("discord"),o.push(a(e.discord.webhookUrl,{content:r}));if(e.telegram?.botToken&&e.telegram.chatId&&rt(e,t)){i.push("telegram");let c=`https://api.telegram.org/bot${e.telegram.botToken}/sendMessage`;o.push(a(c,{chat_id:e.telegram.chatId,text:r}))}if(e.webhook?.url&&rt(e,t))if(i.push("webhook"),(e.webhook.method||"POST")==="GET"){let c=e.webhook.url.includes("?")?"&":"?",l=`${e.webhook.url}${c}event=${encodeURIComponent(t)}&message=${encodeURIComponent(r)}`;o.push(n(l,{method:"GET"}).catch(()=>{return}))}else o.push(a(e.webhook.url,{event:t,message:r}));if(e.email?.to&&rt(e,t))i.push("email"),o.push(Ao(e.email,t,r));return await Promise.all(o),i}async function Ao(e,t,r){try{let s=await import("./chunk-v6mysz8x.js");await s.email.send({to:e.to,from:e.from,subject:`[ts-cloud] ${t}`,text:r})}catch{}}function Ls(e,t){return t??e}function ke(e){if(!e)return[];let t=[];if(e.slack?.webhookUrl)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"text\\":\\"$MSG\\"}" ${e.slack.webhookUrl} || true`);if(e.discord?.webhookUrl)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"content\\":\\"$MSG\\"}" ${e.discord.webhookUrl} || true`);if(e.telegram?.botToken&&e.telegram.chatId)t.push(`curl -fsS -X POST "https://api.telegram.org/bot${e.telegram.botToken}/sendMessage" --data-urlencode "chat_id=${e.telegram.chatId}" --data-urlencode "text=$MSG" || true`);if(e.webhook?.url)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"message\\":\\"$MSG\\"}" ${e.webhook.url} || true`);if(t.length===0)return[];return["cat > /usr/local/bin/ts-cloud-notify <<'TS_CLOUD_NOTIFY_EOF'","#!/bin/bash",'MSG="$1"',...t,"TS_CLOUD_NOTIFY_EOF","chmod +x /usr/local/bin/ts-cloud-notify"]}import{isIP as Us}from"node:net";var Vr="/etc/rpx/certs",zs="/etc/rpx/local-ca",No="rpx-root-ca.crt";function St(e=zs){return`${e.replace(/\/+$/,"")}/${No}`}function er(e){if(e.toLowerCase().endsWith(".local"))return!1;return e.split(".").length===2}function Gi(e,t={}){let r=new Set;for(let s of Object.values(e)){if(!s?.domain)continue;if(P(s)==="bucket")continue;r.add(s.domain)}if(t.autoWww!==!1)for(let s of[...r]){if(!er(s))continue;r.add(`www.${s}`)}return[...r]}var ko=["1.1.1.1","8.8.8.8"],Ho="/var/www/acme-challenge";function Lo(e){if(typeof e==="string")return{to:e};let t={to:e.to};if(e.status!=null)t.status=e.status;if(e.preservePath!=null)t.preservePath=e.preservePath;return t}function Mo(e){let t=e.auth;if(!t||t.enabled===!1||!t.password)return;return{username:t.username||"admin",password:t.password,...t.realm?{realm:t.realm}:{}}}function tr(e){if(!e)return;return e.tls??"local-ca"}function Ki(e,t){if(e.cloud?.provider!=="ssh")return;let r=e.ssh?.lan;if(!r)return;return{...r.hostname?{hostname:r.hostname}:{},tls:r.tls??"local-ca",...t?{ip:t}:{}}}function Fs(e){if(e.cloud?.provider!=="ssh")return;return e.ssh?.profile}function Uo(e){let t=e.trim().toLowerCase();if(!t||t.startsWith("*")||t.includes(":")||t.includes("/")||t.includes(" "))return!1;if(Us(t)!==0)return!1;return t.endsWith(".local")||!t.includes(".")}function zo(e,t,r){let s=[],n=new Set,i=(l,p)=>{let d=l.trim().toLowerCase();if(!d||n.has(d))return;n.add(d),s.push({host:d,source:p})},o=t.hostname?.trim(),a=(o||`${r}.local`).toLowerCase();if(i(a,o?"ssh.lan.hostname":`the ssh provider's default LAN name for project "${r}"`),Object.entries(e).some(([l,p])=>!!p&&Cr(l)))i(`dashboard.${a}`,"the management dashboard site");for(let[l,p]of Object.entries(e)){if(!p?.domain)continue;if(P(p)==="bucket")continue;if(!Uo(p.domain))continue;i(p.domain,`site "${l}"`)}return s}function Fo(e,t){if(!t?.length)return;return t.find((r)=>{let s=(r.startsWith(".")?r.slice(1):r).toLowerCase();return e===s||e.endsWith(`.${s}`)})}function Bo(e,t){if(!t?.enabled)return;for(let{host:r,source:s}of e){let n=Fo(r,t.allowedSuffixes);if(!n)continue;throw Error(`The LAN certificate authority and public on-demand TLS both claim "${r}". LAN source: ${s}. Public source: the on-demand TLS allowed suffix "${n}", which is derived from the site domains. A host is either LAN-only, with a certificate signed by the box's own CA, or public, with one issued by Let's Encrypt, never both. Give the LAN a name no site domain covers (ssh.lan.hostname), or take that domain out of the sites this deploy routes.`)}}function Bs(e){if(!e||e==="/")return;let t=`/${e}`.replace(/\/+/g,"/").replace(/\/+$/,"");if(!t.startsWith("/"))t=`/${t}`;return t===""||t==="/"?void 0:t}function Jt(e,t){let s=(t?`${e}${t}`:e).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return s.length>0?s:"rpx"}function Ko(e,t){if(!t||t.length===0)return`localhost:${e}`;return t.map((r)=>`${r.privateIp??r.publicIp}:${e}`)}function Ks(e,t,r){let s=(t.wwwRoot??"/var/www").replace(/\/+$/,""),n=t.slug??"app",i=t.proxy.certsDir??Vr,o=t.proxy.loadBalancer,a=[],c=new Set;for(let[m,g]of Object.entries(e)){if(!g||!g.domain)continue;let h=P(g);if(h==="bucket")continue;let _=Bs(g.path),w=Jt(g.domain,_),b=Mo(g);if(h==="redirect"){a.push({to:g.domain,path:_,redirect:Lo(g.redirect),id:w,...b?{auth:b}:{}}),c.add(g.domain);continue}if(h==="proxy"){let y=gs(g);if(y.length===0)continue;let T=y.length===1?y[0]:y;a.push({to:g.domain,path:_,from:T,id:w,...b?{auth:b}:{},...Array.isArray(T)&&o?{loadBalancer:o}:{}}),c.add(g.domain);continue}if(h==="server-app"){if(typeof g.port!=="number")continue;let y=Ko(g.port,r);a.push({to:g.domain,path:_,from:y,id:w,...b?{auth:b}:{},...Array.isArray(y)&&o?{loadBalancer:o}:{}})}else a.push({to:g.domain,path:_,static:{dir:`${s}/${n}-${m}/current`,spa:g.spa??!1,pathRewriteStyle:g.pathRewriteStyle??"directory"},cleanUrls:g.pathRewriteStyle!=="flat",...b?{auth:b}:{},id:w});c.add(g.domain)}if(t.proxy.autoWww!==!1)for(let m of[...c]){if(!er(m))continue;let g=`www.${m}`;if(c.has(g))continue;a.push({to:g,redirect:{to:`https://${m}`},id:Jt(g)}),c.add(g)}a.sort((m,g)=>{if(m.to!==g.to)return m.to.localeCompare(g.to);return(g.path?.length??0)-(m.path?.length??0)});let l={proxies:a,productionCerts:{certsDir:i,certsDirServerNames:[...c]},https:!0,hostsManagement:!1,cleanup:{hosts:!1,certs:!1}};if(t.proxy.onDemandTls&&c.size>0)l.onDemandTls={enabled:!0,allowedSuffixes:[...c],email:t.proxy.onDemandTlsEmail,certsDir:i,staging:t.proxy.onDemandTlsStaging??!1};if(t.proxy.onDemandTls)l.acmeChallengeWebroot=t.proxy.acmeWebroot??Ho;let p=t.proxy.cdn,d=p?.frontedHosts?.length?p.frontedHosts:[...c];if(p?.secret&&d.length>0)l.originGuard={header:p.secretHeader??"X-Origin-Verify",value:p.secret,hosts:d};if(t.lan)if(tr(t.lan)==="off")l.https=!1;else{let m=zo(e,t.lan,n);Bo(m,l.onDemandTls);let g=t.lan.ip&&Us(t.lan.ip)!==0?[t.lan.ip]:[];l.localCa={dir:zs,hosts:m.map((h)=>h.host),...g.length>0?{ips:g}:{},installTrust:!0}}return l}function fe(e,t){return Ks(e,t)}function Me(e,t,r){return Ks(e,r,t)}function Q(e){return e?.webServer==="rpx"||e?.proxy?.engine==="rpx"}var st="/etc/rpx",J="/opt/rpx-gateway",Qt="/etc/rpx/gateway.ts",He="/etc/rpx/gateway",me="rpx-gateway.service",te="/etc/rpx/sites.d";function jo(e=te,t=Vr){return`// Generated by ts-cloud — rpx gateway assembler.
16
16
  // Merges every app's fragment in ${e} so independent deploys compose
17
17
  // without clobbering each other. Each deploy writes only its own <slug>.json.
18
18
  import { startProxies } from '@stacksjs/rpx'
@@ -267,7 +267,7 @@ ${n}
267
267
  runcmd:
268
268
  - [ bash, ${r} ]
269
269
  ${pn(t.after)}`}function qr(e){let t=new Set([80,443,...e.sitePorts,...e.allowedPorts??[]]);if(e.allowSsh)t.add(22);return[...t].map((r)=>({direction:"in",protocol:"tcp",port:String(r),source_ips:["0.0.0.0/0","::/0"],description:`ts-cloud port ${r}`}))}var vr={micro:"cpx11",small:"cx23",medium:"cx33",large:"cx43",xlarge:"cx53","2xlarge":"ccx33"};function pt(e){if(!e)return vr.micro;if(e in vr)return vr[e];return e}var B="ts-cloud";function j(e,t,r="app"){return{[`${B}/project`]:e,[`${B}/environment`]:t,[`${B}/role`]:r,[`${B}/managed-by`]:"ts-cloud"}}function se(e,t,r,s="app"){return br(e,t,r)&&e[`${B}/role`]===s}function br(e,t,r){if(!e)return!1;return e[`${B}/project`]===t&&e[`${B}/environment`]===r}import{mkdir as ca,readFile as la,rename as ua,writeFile as pa}from"node:fs/promises";import{join as dn}from"node:path";var wr="storage/cloud/state";function _e(e=process.cwd()){return xs()?A(e,"state"):dn(e,wr)}function je(e,t=process.cwd()){return dn(_e(t),`${e}.json`)}async function De(e,t=process.cwd()){try{let r=await la(je(e,t),"utf8");return JSON.parse(r)}catch{return null}}async function Ve(e,t,r=process.cwd()){let s=je(e,r);await ca(_e(r),{recursive:!0});let n=`${s}.${process.pid}.tmp`;await pa(n,`${JSON.stringify(t,null,2)}
270
- `,"utf8"),await ua(n,s)}async function ue(e){return De(e)}async function mt(e,t){await Ve(e,t)}var $r=268435456;function ce(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function ya(e){let t=ma("sha256");for await(let r of fa(e))t.update(r);return t.digest("hex")}class Te{name="hetzner";usesCloudFormation=!1;client;sshPrivateKeyPath;sshPublicKeyPath;sshUser;location;stateOnly;waitForBoot;bootWait;constructor(e={}){let t=it(e.apiToken);if(this.stateOnly=!e.client&&!t&&e.allowStateOnly===!0,!e.client&&!t&&!this.stateOnly)throw Error("Hetzner API token required. Set hetzner.apiToken in cloud.config.ts or HCLOUD_TOKEN / HETZNER_API_TOKEN.");this.client=e.client??new Ke({apiToken:t??""});let r=sr(void 0,{sshPrivateKeyPath:e.sshPrivateKeyPath,sshPublicKeyPath:e.sshPublicKeyPath,sshUser:e.sshUser,location:e.location});this.sshPrivateKeyPath=r.sshPrivateKeyPath,this.sshPublicKeyPath=r.sshPublicKeyPath,this.sshUser=r.sshUser,this.location=r.location,this.waitForBoot=e.waitForBoot??!0,this.bootWait={sshIntervalMs:e.bootWait?.sshIntervalMs??5000,sshTimeoutMs:e.bootWait?.sshTimeoutMs??300000,cloudInitIntervalMs:e.bootWait?.cloudInitIntervalMs??5000,cloudInitTimeoutMs:e.bootWait?.cloudInitTimeoutMs??600000}}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e,s=t.project.slug,n=t.infrastructure?.compute;if(!n)throw Error("infrastructure.compute is required to provision Hetzner compute");if(t.cloud?.attachTo)return this.attachToComputeInfrastructure(t.cloud.attachTo,t,r);let i=E(t,r),o=`${s}-${r}-app`,a=n.runtime==="php"||!!n.php,c=cn(n);if(c.dedicatedServices||c.appServers>1)return a?this.provisionFleet(e,c):this.provisionBunFleet(e,c);let l=j(s,r,"app"),p=t.sites||{},d=Q(n)?[]:this.collectUpstreamPorts(p),m=`${s}-${r}-app-fw`,{firewall:g}=await this.ensureFirewall(m,l,qr({allowSsh:n.allowSsh!==!1,sitePorts:d,allowedPorts:[...n.firewall?.allowedPorts??[],...Qs(t.infrastructure?.sftp)]})),h=await this.ensureSshKey(s,r,l),_=await ue(i);if(_?.serverId){let F=await this.tryGetServer(_.serverId);if(F&&F.status!=="off")return this.outputsFromState(_,F)}let w=await this.findExistingServer(s,r,o);if(w&&w.status!=="off"){let F={provider:"hetzner",stackName:i,serverId:w.id,serverName:w.name,publicIp:w.public_net.ipv4?.ip,publicIpv6:de(w.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await mt(i,F),this.outputsFromState(F,w)}let b=n.proxy?.engine==="rpx"?ge({proxy:n.proxy,config:fe(p,{proxy:n.proxy,slug:t.project.slug}),slug:t.project.slug,bunBin:n.runtime==="node"||n.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,y=Oe(t,{environment:r}),T=n.bakedImage===!0,S=re({runtime:y.runtime,runtimeVersion:y.runtimeVersion,systemPackages:n.systemPackages,database:t.infrastructure?.database,phpProvision:y.phpProvision,servicesProvision:y.servicesProvision,rpxProvision:b,baked:T,swapGb:n.swapGb}),D=he(S),O=pt(n.size),R=ot(t),{server:H,action:ne}=await this.client.createServer({name:o,serverType:O,image:R,location:t.hetzner?.location||this.location,userData:D,labels:l,sshKeys:h?[h]:void 0,firewalls:[{firewall:g.id}]});await this.client.waitForAction(ne.id);let z=await this.client.waitForServerRunning(H.id),X={provider:"hetzner",stackName:i,serverId:z.id,serverName:z.name,firewallId:g.id,publicIp:z.public_net.ipv4?.ip,publicIpv6:de(z.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};await mt(i,X);let Y=z.public_net.ipv4?.ip;if(Y&&this.waitForBoot)await this.waitForSshReady(Y),await this.waitForCloudInit(Y);return this.outputsFromState(X,z)}async provisionFleet(e,t){let{config:r,environment:s}=e,n=r.project.slug,i=r.infrastructure.compute,o=E(r,s),a=pt(i.size),c=ot(r),l=r.hetzner?.location||this.location,p=i.bakedImage===!0,d=await ue(o);if(d?.loadBalancerId){let V=(await this.client.listLoadBalancers().catch(()=>[])).find((I)=>I.id===d.loadBalancerId);if(V)return{appPublicIp:V.public_net?.ipv4?.ip,loadBalancerIp:V.public_net?.ipv4?.ip,servicesPrivateIp:d.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}let m=await this.ensureSshKey(n,s,j(n,s,"app")),g=`${n}-${s}-net`,_=(await this.client.listNetworks().catch(()=>[])).find((N)=>N.name===g)??await this.client.createNetwork({name:g,labels:j(n,s,"app")}),{firewall:w}=await this.ensureFirewall(`${n}-${s}-app-fw`,j(n,s,"app"),qr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),{firewall:b}=await this.ensureFirewall(`${n}-${s}-services-fw`,j(n,s,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[_.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[_.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[_.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[_.ip_range]}]),y=yr(r),T=he(re({runtime:"php",servicesProvision:y,baked:p,swapGb:i.swapGb})),S=await this.client.listServers().catch(()=>[]),D=[],O=S.find((N)=>se(N.labels,n,s,"services"));if(!O){let{server:N,action:V}=await this.client.createServer({name:`${n}-${s}-services`,serverType:pt(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:c,location:l,userData:T,labels:j(n,s,"services"),sshKeys:m?[m]:void 0,firewalls:[{firewall:b.id}],networks:[_.id]});await this.client.waitForAction(V.id),O=await this.client.waitForServerRunning(N.id),D.push(N.id)}let R=O.id,H=O.private_net?.[0]?.ip??(await this.client.getServer(R)).private_net?.[0]?.ip,ne=[...be(!0),...we(!0),...Ue(i.sshKeys),...ke(r.notifications)],z=yt({versions:i.php?.versions,default:i.php?.default,extensions:i.php?.extensions,installNginx:!Q(i),optimizeForProduction:i.php?.optimizeForProduction,ini:i.php?.ini}),X=he(re({runtime:"php",phpProvision:z,servicesProvision:ne,baked:p,swapGb:i.swapGb})),Y=S.filter((N)=>se(N.labels,n,s,"app")),F=Y.map((N)=>N.id);if(Y.length>t.appServers)for(let N of Y.slice(t.appServers))await this.client.deleteServer(N.id).catch(()=>{}),F.splice(F.indexOf(N.id),1);for(let N=Y.length;N<t.appServers;N++){let{server:V,action:I}=await this.client.createServer({name:`${n}-${s}-app-${N+1}`,serverType:a,image:c,location:l,userData:X,labels:j(n,s,"app"),sshKeys:m?[m]:void 0,firewalls:[{firewall:w.id}],networks:[_.id]});await this.client.waitForAction(I.id),F.push(V.id),D.push(V.id)}if(this.waitForBoot&&D.length>0)await Promise.all(D.map(async(N)=>{let I=(await this.client.waitForServerRunning(N)).public_net.ipv4?.ip;if(I)await this.waitForSshReady(I),await this.waitForCloudInit(I)}));let ee=`${n}-${s}-lb`,k,ye;if(t.loadBalancer){let V=(await this.client.listLoadBalancers().catch(()=>[])).find((I)=>I.name===ee)??await this.client.createLoadBalancer({name:ee,location:l,network:_.id,labels:j(n,s,"lb"),labelSelector:`ts-cloud/project=${n},ts-cloud/environment=${s},ts-cloud/role=app`,services:[{listenPort:80,destinationPort:80},{listenPort:443,destinationPort:443}]});ye=V.id,k=V.public_net?.ipv4?.ip}let G=k??(await this.client.getServer(F[0]).catch(()=>{return}))?.public_net.ipv4?.ip,pe={provider:"hetzner",stackName:o,networkId:_.id,loadBalancerId:ye,servicesServerId:R,servicesPrivateIp:H,publicIp:G,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await mt(o,pe),{appPublicIp:G,loadBalancerIp:k,servicesPrivateIp:H,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async provisionBunFleet(e,t){let{config:r,environment:s}=e,n=r.project.slug,i=r.infrastructure.compute,o=E(r,s),a=pt(i.size),c=ot(r),l=r.hetzner?.location||this.location,p=i.bakedImage===!0,d=r.sites||{},m=await ue(o);if(m?.lbServerId){let I=await this.tryGetServer(m.lbServerId);if(I&&I.status!=="off"){let L=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"},q=await this.findComputeTargets({slug:n,environment:s,role:"app",stackName:o});return this.refreshLbRoutes(I,d,q.map((ae)=>({privateIp:ae.privateIp,publicIp:ae.publicIp})),L,n),{appPublicIp:I.public_net.ipv4?.ip??m.publicIp,loadBalancerIp:I.public_net.ipv4?.ip??m.publicIp,servicesPrivateIp:m.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}}let g=await this.ensureSshKey(n,s,j(n,s,"app")),h=`${n}-${s}-net`,w=(await this.client.listNetworks().catch(()=>[])).find((I)=>I.name===h)??await this.client.createNetwork({name:h,labels:j(n,s,"app")}),b=this.collectUpstreamPorts(d),{firewall:y}=await this.ensureFirewall(`${n}-${s}-app-fw`,j(n,s,"app"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},...b.map((I)=>({direction:"in",protocol:"tcp",port:String(I),source_ips:[w.ip_range],description:`ts-cloud port ${I} (private, LB-only)`}))]),{firewall:T}=await this.ensureFirewall(`${n}-${s}-lb-fw`,j(n,s,"lb"),qr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),S=await this.client.listServers().catch(()=>[]),D=[],O,R,H=!!i.servicesServer||!!i.managedServices,ne=t.dedicatedServices&&H;if(ne){let{firewall:I}=await this.ensureFirewall(`${n}-${s}-services-fw`,j(n,s,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[w.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[w.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[w.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[w.ip_range]}]),L=yr(r),q=he(re({runtime:"bun",servicesProvision:L,baked:p,swapGb:i.swapGb})),ae=S.find((ve)=>se(ve.labels,n,s,"services"));if(!ae){let{server:ve,action:Ze}=await this.client.createServer({name:`${n}-${s}-services`,serverType:pt(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:c,location:l,userData:q,labels:j(n,s,"services"),sshKeys:g?[g]:void 0,firewalls:[{firewall:I.id}],networks:[w.id]});await this.client.waitForAction(Ze.id),ae=await this.client.waitForServerRunning(ve.id),D.push(ve.id)}O=ae.id,R=ae.private_net?.[0]?.ip??(await this.client.getServer(O)).private_net?.[0]?.ip}let z=ne?{...i,managedServices:void 0,backups:void 0}:i,X=Oe({...r,infrastructure:{...r.infrastructure,compute:z}},{environment:s}),Y=he(re({runtime:X.runtime,runtimeVersion:X.runtimeVersion,systemPackages:i.systemPackages,database:r.infrastructure?.database,servicesProvision:X.servicesProvision,baked:p,swapGb:i.swapGb})),F=S.filter((I)=>se(I.labels,n,s,"app")),ee=F.map((I)=>I.id);if(F.length>t.appServers)for(let I of F.slice(t.appServers))await this.client.deleteServer(I.id).catch(()=>{}),ee.splice(ee.indexOf(I.id),1);for(let I=F.length;I<t.appServers;I++){let{server:L,action:q}=await this.client.createServer({name:`${n}-${s}-app-${I+1}`,serverType:a,image:c,location:l,userData:Y,labels:j(n,s,"app"),sshKeys:g?[g]:void 0,firewalls:[{firewall:y.id}],networks:[w.id]});await this.client.waitForAction(q.id),ee.push(L.id),D.push(L.id)}if(this.waitForBoot&&D.length>0)await Promise.all(D.map(async(I)=>{let q=(await this.client.waitForServerRunning(I)).public_net.ipv4?.ip;if(q)await this.waitForSshReady(q),await this.waitForCloudInit(q)}));let k=[];for(let I of ee){let L=S.find((q)=>q.id===I);if(!L||!L.private_net?.[0]?.ip)L=await this.client.getServer(I).catch(()=>L);k.push({privateIp:L?.private_net?.[0]?.ip,publicIp:L?.public_net.ipv4?.ip})}let ye=`${n}-${s}-lb`,G,pe;if(t.loadBalancer){let I=S.find((q)=>se(q.labels,n,s,"lb")),L=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"};if(!I){let q=ge({proxy:L,config:Me(d,k,{proxy:L,slug:n}),slug:n,bunBin:X.runtime==="node"||X.runtime==="deno"?void 0:"/usr/local/bin/bun"}),ae=he(re({runtime:"bun",rpxProvision:q,baked:!1})),ve=typeof i.loadBalancer==="object"?i.loadBalancer.size:void 0,{server:Ze,action:Kt}=await this.client.createServer({name:ye,serverType:pt(ve??"micro"),image:c,location:l,userData:ae,labels:j(n,s,"lb"),sshKeys:g?[g]:void 0,firewalls:[{firewall:T.id}],networks:[w.id]});if(await this.client.waitForAction(Kt.id),I=await this.client.waitForServerRunning(Ze.id),this.waitForBoot){let et=I.public_net.ipv4?.ip;if(et)await this.waitForSshReady(et),await this.waitForCloudInit(et)}}else this.refreshLbRoutes(I,d,k,L,n);G=I.id,pe=I.public_net.ipv4?.ip}let N=pe??(await this.client.getServer(ee[0]).catch(()=>{return}))?.public_net.ipv4?.ip,V={provider:"hetzner",stackName:o,networkId:w.id,lbServerId:G,appServerIds:ee,servicesServerId:O,servicesPrivateIp:R,publicIp:N,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await mt(o,V),{appPublicIp:N,loadBalancerIp:pe,servicesPrivateIp:R,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async destroyCompute(e){let{config:t,environment:r}=e,s=t.project.slug,n=E(t,r),i=await ue(n),o=[],a=`${s}-${r}-lb`,l=(await this.client.listLoadBalancers().catch(()=>[])).find((y)=>y.name===a);if(l)try{await this.client.deleteLoadBalancer(l.id),o.push(`load balancer ${a}`)}catch{}let p=await this.client.listServers().catch(()=>[]),d=new Set;for(let y of p)if(se(y.labels,s,r,"app")||se(y.labels,s,r,"services")||se(y.labels,s,r,"lb"))d.add(y.id);if(i?.serverId)d.add(i.serverId);if(i?.servicesServerId)d.add(i.servicesServerId);if(i?.lbServerId)d.add(i.lbServerId);for(let y of i?.appServerIds??[])d.add(y);for(let y of d)try{await this.client.deleteServer(y),o.push(`server ${y}`)}catch{}let m=await this.client.listFirewalls().catch(()=>[]);for(let y of[`${s}-${r}-app-fw`,`${s}-${r}-services-fw`,`${s}-${r}-lb-fw`]){let T=m.find((S)=>S.name===y);if(!T)continue;for(let S=0;S<12;S++)try{await this.client.deleteFirewall(T.id),o.push(`firewall ${y}`);break}catch{await this.sleep(3000)}}let g=`${s}-${r}-net`,_=(await this.client.listNetworks().catch(()=>[])).find((y)=>y.name===g);if(_)for(let y=0;y<12;y++)try{await this.client.deleteNetwork(_.id),o.push(`network ${g}`);break}catch{await this.sleep(3000)}let b=(await this.client.listSshKeys().catch(()=>[])).filter((y)=>br(y.labels,s,r));for(let y of b)try{await this.client.deleteSshKey(y.id),o.push(`ssh key ${y.name}`)}catch{}return await mt(n,{provider:"hetzner",stackName:n}).catch(()=>{}),{destroyed:o}}async getComputeOutputs(e){let t=E(e.config,e.environment),r=await ue(t);if(r?.serverId){let i=await this.tryGetServer(r.serverId);if(i)return this.outputsFromState(r,i)}if(r?.lbServerId){let o=(await this.tryGetServer(r.lbServerId))?.public_net.ipv4?.ip??r.publicIp;return{...this.outputsFromState(r),appPublicIp:o,loadBalancerIp:o}}if(r?.loadBalancerId||r?.servicesPrivateIp)return this.outputsFromState(r);let n=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:E(e.config,e.environment)}))[0];return{deployStoragePath:"/var/ts-cloud/staging",appInstanceId:n?.id,appPublicIp:n?.publicIp,sshUser:this.sshUser}}async uploadRelease(e){let t=e.targets?.length?e.targets:await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:E(e.config,e.environment)});if(t.length===0)throw Error("No Hetzner compute targets found for release upload");let n=`/var/ts-cloud/staging/${`${e.remoteKey.replace(/^releases\//,"").replace(/\.tar\.gz$/,"").replace(/\//g,"-")}-${fn()}.tar.gz`}`,i=await ya(e.localPath),o="/var/ts-cloud/artifacts",a=`${o}/${i}.tar.gz`;for(let c of t){if(!c.publicIp)throw Error(`Target ${c.id} has no public IP for SCP upload`);let l=["set -euo pipefail",`mkdir -p ${ce(o)} /var/ts-cloud/staging`,`test -s ${ce(a)}`,`cp -- ${ce(a)} ${ce(n)}`].join(`
270
+ `,"utf8"),await ua(n,s)}async function ue(e){return De(e)}async function mt(e,t){await Ve(e,t)}var $r=268435456;function ce(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function ya(e){let t=ma("sha256");for await(let r of fa(e))t.update(r);return t.digest("hex")}class Te{name="hetzner";usesCloudFormation=!1;client;sshPrivateKeyPath;sshPublicKeyPath;sshUser;location;stateOnly;waitForBoot;bootWait;constructor(e={}){let t=it(e.apiToken);if(this.stateOnly=!e.client&&!t&&e.allowStateOnly===!0,!e.client&&!t&&!this.stateOnly)throw Error("Hetzner API token required. Set hetzner.apiToken in cloud.config.ts or HCLOUD_TOKEN / HETZNER_API_TOKEN.");this.client=e.client??new Ke({apiToken:t??""});let r=sr(void 0,{sshPrivateKeyPath:e.sshPrivateKeyPath,sshPublicKeyPath:e.sshPublicKeyPath,sshUser:e.sshUser,location:e.location});this.sshPrivateKeyPath=r.sshPrivateKeyPath,this.sshPublicKeyPath=r.sshPublicKeyPath,this.sshUser=r.sshUser,this.location=r.location,this.waitForBoot=e.waitForBoot??!0,this.bootWait={sshIntervalMs:e.bootWait?.sshIntervalMs??5000,sshTimeoutMs:e.bootWait?.sshTimeoutMs??300000,cloudInitIntervalMs:e.bootWait?.cloudInitIntervalMs??5000,cloudInitTimeoutMs:e.bootWait?.cloudInitTimeoutMs??600000}}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e,s=t.project.slug,n=t.infrastructure?.compute;if(!n)throw Error("infrastructure.compute is required to provision Hetzner compute");if(t.cloud?.attachTo)return this.attachToComputeInfrastructure(t.cloud.attachTo,t,r);let i=E(t,r),o=`${s}-${r}-app`,a=n.runtime==="php"||!!n.php,c=cn(n);if(c.dedicatedServices||c.appServers>1)return a?this.provisionFleet(e,c):this.provisionBunFleet(e,c);let l=j(s,r,"app"),p=t.sites||{},d=Q(n)?[]:this.collectUpstreamPorts(p),m=`${s}-${r}-app-fw`,{firewall:g}=await this.ensureFirewall(m,l,qr({allowSsh:n.allowSsh!==!1,sitePorts:d,allowedPorts:[...n.firewall?.allowedPorts??[],...Qs(t.infrastructure?.sftp)]})),h=await this.ensureSshKey(s,r,l),_=await ue(i);if(_?.serverId){let F=await this.tryGetServer(_.serverId);if(F&&F.status!=="off")return this.outputsFromState(_,F)}let w=await this.findExistingServer(s,r,o);if(w&&w.status!=="off"){let F={provider:"hetzner",stackName:i,serverId:w.id,serverName:w.name,publicIp:w.public_net.ipv4?.ip,publicIpv6:de(w.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await mt(i,F),this.outputsFromState(F,w)}let b=n.proxy?.engine==="rpx"?ge({proxy:n.proxy,config:fe(p,{proxy:n.proxy,slug:t.project.slug}),slug:t.project.slug,bunBin:n.runtime==="node"||n.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,y=Oe(t,{environment:r}),T=n.bakedImage===!0,S=re({runtime:y.runtime,runtimeVersion:y.runtimeVersion,systemPackages:n.systemPackages,database:t.infrastructure?.database,phpProvision:y.phpProvision,servicesProvision:y.servicesProvision,rpxProvision:b,baked:T,swapGb:n.swapGb}),D=he(S),O=pt(n.size),R=ot(t),{server:H,action:ne}=await this.client.createServer({name:o,serverType:O,image:R,location:t.hetzner?.location||this.location,userData:D,labels:l,sshKeys:h?[h]:void 0,firewalls:[{firewall:g.id}]});await this.client.waitForAction(ne.id);let z=await this.client.waitForServerRunning(H.id),X={provider:"hetzner",stackName:i,serverId:z.id,serverName:z.name,firewallId:g.id,publicIp:z.public_net.ipv4?.ip,publicIpv6:de(z.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};await mt(i,X);let Y=z.public_net.ipv4?.ip;if(Y&&this.waitForBoot)await this.waitForSshReady(Y),await this.waitForCloudInit(Y);return this.outputsFromState(X,z)}async provisionFleet(e,t){let{config:r,environment:s}=e,n=r.project.slug,i=r.infrastructure.compute,o=E(r,s),a=pt(i.size),c=ot(r),l=r.hetzner?.location||this.location,p=i.bakedImage===!0,d=await ue(o);if(d?.loadBalancerId){let V=(await this.client.listLoadBalancers().catch(()=>[])).find((I)=>I.id===d.loadBalancerId);if(V)return{appPublicIp:V.public_net?.ipv4?.ip,loadBalancerIp:V.public_net?.ipv4?.ip,servicesPrivateIp:d.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}let m=await this.ensureSshKey(n,s,j(n,s,"app")),g=`${n}-${s}-net`,_=(await this.client.listNetworks().catch(()=>[])).find((N)=>N.name===g)??await this.client.createNetwork({name:g,labels:j(n,s,"app")}),{firewall:w}=await this.ensureFirewall(`${n}-${s}-app-fw`,j(n,s,"app"),qr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),{firewall:b}=await this.ensureFirewall(`${n}-${s}-services-fw`,j(n,s,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[_.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[_.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[_.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[_.ip_range]}]),y=yr(r),T=he(re({runtime:"php",servicesProvision:y,baked:p,swapGb:i.swapGb})),S=await this.client.listServers().catch(()=>[]),D=[],O=S.find((N)=>se(N.labels,n,s,"services"));if(!O){let{server:N,action:V}=await this.client.createServer({name:`${n}-${s}-services`,serverType:pt(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:c,location:l,userData:T,labels:j(n,s,"services"),sshKeys:m?[m]:void 0,firewalls:[{firewall:b.id}],networks:[_.id]});await this.client.waitForAction(V.id),O=await this.client.waitForServerRunning(N.id),D.push(N.id)}let R=O.id,H=O.private_net?.[0]?.ip??(await this.client.getServer(R)).private_net?.[0]?.ip,ne=[...be(!0),...we(!0),...Ue(i.sshKeys),...ke(r.notifications)],z=yt({versions:i.php?.versions,default:i.php?.default,extensions:i.php?.extensions,installNginx:!Q(i),optimizeForProduction:i.php?.optimizeForProduction,ini:i.php?.ini}),X=he(re({runtime:"php",phpProvision:z,servicesProvision:ne,baked:p,swapGb:i.swapGb})),Y=S.filter((N)=>se(N.labels,n,s,"app")),F=Y.map((N)=>N.id);if(Y.length>t.appServers)for(let N of Y.slice(t.appServers))await this.client.deleteServer(N.id).catch(()=>{}),F.splice(F.indexOf(N.id),1);for(let N=Y.length;N<t.appServers;N++){let{server:V,action:I}=await this.client.createServer({name:`${n}-${s}-app-${N+1}`,serverType:a,image:c,location:l,userData:X,labels:j(n,s,"app"),sshKeys:m?[m]:void 0,firewalls:[{firewall:w.id}],networks:[_.id]});await this.client.waitForAction(I.id),F.push(V.id),D.push(V.id)}if(this.waitForBoot&&D.length>0)await Promise.all(D.map(async(N)=>{let I=(await this.client.waitForServerRunning(N)).public_net.ipv4?.ip;if(I)await this.waitForSshReady(I),await this.waitForCloudInit(I)}));let ee=`${n}-${s}-lb`,k,ye;if(t.loadBalancer){let V=(await this.client.listLoadBalancers().catch(()=>[])).find((I)=>I.name===ee)??await this.client.createLoadBalancer({name:ee,location:l,network:_.id,labels:j(n,s,"lb"),labelSelector:`ts-cloud/project=${n},ts-cloud/environment=${s},ts-cloud/role=app`,services:[{listenPort:80,destinationPort:80},{listenPort:443,destinationPort:443}]});ye=V.id,k=V.public_net?.ipv4?.ip}let G=k??(await this.client.getServer(F[0]).catch(()=>{return}))?.public_net.ipv4?.ip,pe={provider:"hetzner",stackName:o,networkId:_.id,loadBalancerId:ye,servicesServerId:R,servicesPrivateIp:H,publicIp:G,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await mt(o,pe),{appPublicIp:G,loadBalancerIp:k,servicesPrivateIp:H,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async provisionBunFleet(e,t){let{config:r,environment:s}=e,n=r.project.slug,i=r.infrastructure.compute,o=E(r,s),a=pt(i.size),c=ot(r),l=r.hetzner?.location||this.location,p=i.bakedImage===!0,d=r.sites||{},m=await ue(o);if(m?.lbServerId){let I=await this.tryGetServer(m.lbServerId);if(I&&I.status!=="off"){let M=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"},q=await this.findComputeTargets({slug:n,environment:s,role:"app",stackName:o});return this.refreshLbRoutes(I,d,q.map((ae)=>({privateIp:ae.privateIp,publicIp:ae.publicIp})),M,n),{appPublicIp:I.public_net.ipv4?.ip??m.publicIp,loadBalancerIp:I.public_net.ipv4?.ip??m.publicIp,servicesPrivateIp:m.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}}let g=await this.ensureSshKey(n,s,j(n,s,"app")),h=`${n}-${s}-net`,w=(await this.client.listNetworks().catch(()=>[])).find((I)=>I.name===h)??await this.client.createNetwork({name:h,labels:j(n,s,"app")}),b=this.collectUpstreamPorts(d),{firewall:y}=await this.ensureFirewall(`${n}-${s}-app-fw`,j(n,s,"app"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},...b.map((I)=>({direction:"in",protocol:"tcp",port:String(I),source_ips:[w.ip_range],description:`ts-cloud port ${I} (private, LB-only)`}))]),{firewall:T}=await this.ensureFirewall(`${n}-${s}-lb-fw`,j(n,s,"lb"),qr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),S=await this.client.listServers().catch(()=>[]),D=[],O,R,H=!!i.servicesServer||!!i.managedServices,ne=t.dedicatedServices&&H;if(ne){let{firewall:I}=await this.ensureFirewall(`${n}-${s}-services-fw`,j(n,s,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[w.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[w.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[w.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[w.ip_range]}]),M=yr(r),q=he(re({runtime:"bun",servicesProvision:M,baked:p,swapGb:i.swapGb})),ae=S.find((ve)=>se(ve.labels,n,s,"services"));if(!ae){let{server:ve,action:Ze}=await this.client.createServer({name:`${n}-${s}-services`,serverType:pt(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:c,location:l,userData:q,labels:j(n,s,"services"),sshKeys:g?[g]:void 0,firewalls:[{firewall:I.id}],networks:[w.id]});await this.client.waitForAction(Ze.id),ae=await this.client.waitForServerRunning(ve.id),D.push(ve.id)}O=ae.id,R=ae.private_net?.[0]?.ip??(await this.client.getServer(O)).private_net?.[0]?.ip}let z=ne?{...i,managedServices:void 0,backups:void 0}:i,X=Oe({...r,infrastructure:{...r.infrastructure,compute:z}},{environment:s}),Y=he(re({runtime:X.runtime,runtimeVersion:X.runtimeVersion,systemPackages:i.systemPackages,database:r.infrastructure?.database,servicesProvision:X.servicesProvision,baked:p,swapGb:i.swapGb})),F=S.filter((I)=>se(I.labels,n,s,"app")),ee=F.map((I)=>I.id);if(F.length>t.appServers)for(let I of F.slice(t.appServers))await this.client.deleteServer(I.id).catch(()=>{}),ee.splice(ee.indexOf(I.id),1);for(let I=F.length;I<t.appServers;I++){let{server:M,action:q}=await this.client.createServer({name:`${n}-${s}-app-${I+1}`,serverType:a,image:c,location:l,userData:Y,labels:j(n,s,"app"),sshKeys:g?[g]:void 0,firewalls:[{firewall:y.id}],networks:[w.id]});await this.client.waitForAction(q.id),ee.push(M.id),D.push(M.id)}if(this.waitForBoot&&D.length>0)await Promise.all(D.map(async(I)=>{let q=(await this.client.waitForServerRunning(I)).public_net.ipv4?.ip;if(q)await this.waitForSshReady(q),await this.waitForCloudInit(q)}));let k=[];for(let I of ee){let M=S.find((q)=>q.id===I);if(!M||!M.private_net?.[0]?.ip)M=await this.client.getServer(I).catch(()=>M);k.push({privateIp:M?.private_net?.[0]?.ip,publicIp:M?.public_net.ipv4?.ip})}let ye=`${n}-${s}-lb`,G,pe;if(t.loadBalancer){let I=S.find((q)=>se(q.labels,n,s,"lb")),M=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"};if(!I){let q=ge({proxy:M,config:Me(d,k,{proxy:M,slug:n}),slug:n,bunBin:X.runtime==="node"||X.runtime==="deno"?void 0:"/usr/local/bin/bun"}),ae=he(re({runtime:"bun",rpxProvision:q,baked:!1})),ve=typeof i.loadBalancer==="object"?i.loadBalancer.size:void 0,{server:Ze,action:Kt}=await this.client.createServer({name:ye,serverType:pt(ve??"micro"),image:c,location:l,userData:ae,labels:j(n,s,"lb"),sshKeys:g?[g]:void 0,firewalls:[{firewall:T.id}],networks:[w.id]});if(await this.client.waitForAction(Kt.id),I=await this.client.waitForServerRunning(Ze.id),this.waitForBoot){let et=I.public_net.ipv4?.ip;if(et)await this.waitForSshReady(et),await this.waitForCloudInit(et)}}else this.refreshLbRoutes(I,d,k,M,n);G=I.id,pe=I.public_net.ipv4?.ip}let N=pe??(await this.client.getServer(ee[0]).catch(()=>{return}))?.public_net.ipv4?.ip,V={provider:"hetzner",stackName:o,networkId:w.id,lbServerId:G,appServerIds:ee,servicesServerId:O,servicesPrivateIp:R,publicIp:N,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await mt(o,V),{appPublicIp:N,loadBalancerIp:pe,servicesPrivateIp:R,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async destroyCompute(e){let{config:t,environment:r}=e,s=t.project.slug,n=E(t,r),i=await ue(n),o=[],a=`${s}-${r}-lb`,l=(await this.client.listLoadBalancers().catch(()=>[])).find((y)=>y.name===a);if(l)try{await this.client.deleteLoadBalancer(l.id),o.push(`load balancer ${a}`)}catch{}let p=await this.client.listServers().catch(()=>[]),d=new Set;for(let y of p)if(se(y.labels,s,r,"app")||se(y.labels,s,r,"services")||se(y.labels,s,r,"lb"))d.add(y.id);if(i?.serverId)d.add(i.serverId);if(i?.servicesServerId)d.add(i.servicesServerId);if(i?.lbServerId)d.add(i.lbServerId);for(let y of i?.appServerIds??[])d.add(y);for(let y of d)try{await this.client.deleteServer(y),o.push(`server ${y}`)}catch{}let m=await this.client.listFirewalls().catch(()=>[]);for(let y of[`${s}-${r}-app-fw`,`${s}-${r}-services-fw`,`${s}-${r}-lb-fw`]){let T=m.find((S)=>S.name===y);if(!T)continue;for(let S=0;S<12;S++)try{await this.client.deleteFirewall(T.id),o.push(`firewall ${y}`);break}catch{await this.sleep(3000)}}let g=`${s}-${r}-net`,_=(await this.client.listNetworks().catch(()=>[])).find((y)=>y.name===g);if(_)for(let y=0;y<12;y++)try{await this.client.deleteNetwork(_.id),o.push(`network ${g}`);break}catch{await this.sleep(3000)}let b=(await this.client.listSshKeys().catch(()=>[])).filter((y)=>br(y.labels,s,r));for(let y of b)try{await this.client.deleteSshKey(y.id),o.push(`ssh key ${y.name}`)}catch{}return await mt(n,{provider:"hetzner",stackName:n}).catch(()=>{}),{destroyed:o}}async getComputeOutputs(e){let t=E(e.config,e.environment),r=await ue(t);if(r?.serverId){let i=await this.tryGetServer(r.serverId);if(i)return this.outputsFromState(r,i)}if(r?.lbServerId){let o=(await this.tryGetServer(r.lbServerId))?.public_net.ipv4?.ip??r.publicIp;return{...this.outputsFromState(r),appPublicIp:o,loadBalancerIp:o}}if(r?.loadBalancerId||r?.servicesPrivateIp)return this.outputsFromState(r);let n=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:E(e.config,e.environment)}))[0];return{deployStoragePath:"/var/ts-cloud/staging",appInstanceId:n?.id,appPublicIp:n?.publicIp,sshUser:this.sshUser}}async uploadRelease(e){let t=e.targets?.length?e.targets:await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:E(e.config,e.environment)});if(t.length===0)throw Error("No Hetzner compute targets found for release upload");let n=`/var/ts-cloud/staging/${`${e.remoteKey.replace(/^releases\//,"").replace(/\.tar\.gz$/,"").replace(/\//g,"-")}-${fn()}.tar.gz`}`,i=await ya(e.localPath),o="/var/ts-cloud/artifacts",a=`${o}/${i}.tar.gz`;for(let c of t){if(!c.publicIp)throw Error(`Target ${c.id} has no public IP for SCP upload`);let l=["set -euo pipefail",`mkdir -p ${ce(o)} /var/ts-cloud/staging`,`test -s ${ce(a)}`,`cp -- ${ce(a)} ${ce(n)}`].join(`
271
271
  `);try{this.sshExec(c.publicIp,l);continue}catch{}let p=`${o}/.${i}-${fn()}.tmp`;this.scpToHost(c.publicIp,e.localPath,p),this.sshExec(c.publicIp,["set -euo pipefail",`chmod 600 ${ce(p)}`,`mv -f -- ${ce(p)} ${ce(a)}`,`cp -- ${ce(a)} ${ce(n)}`,`find ${ce(o)} -type f -name '*.tar.gz' -mtime +7 -delete 2>/dev/null || true`].join(`
272
272
  `))}return{artifactRef:n}}async findComputeTargets(e){let t=e.role||"app",r=(i)=>({id:String(i.id),name:i.name,publicIp:i.public_net.ipv4?.ip,publicIpv6:de(i.public_net.ipv6?.ip),privateIp:i.private_net?.[0]?.ip,status:i.status});if(t==="app"||t==="lb"||t==="services"){let i=await ue(e.stackName??`${e.slug}-${e.environment}`),o=[...new Set(t==="app"?[i?.serverId,...i?.appServerIds??[]]:t==="lb"?[i?.lbServerId]:[i?.servicesServerId])].filter((l)=>typeof l==="number");if(this.stateOnly){if(o.length>0&&i?.publicIp)return o.map((l)=>({id:String(l),name:l===i.serverId?i.serverName:void 0,publicIp:i.publicIp,publicIpv6:i.publicIpv6,status:"running"}));if(t!=="app")return[];throw Error(`Hetzner API token required because '${e.stackName??`${e.slug}-${e.environment}`}' has no complete local compute state pin.`)}let a=await this.client.listServers();if(o.length>0){let l=[];for(let p of o){let d=a.find((m)=>m.id===p)??await this.tryGetServer(p);if(p===i?.serverId&&i.serverName&&d?.name!==i.serverName)continue;if(d&&d.status!=="off")l.push(d)}if(l.length>0)return l.map(r)}let c=a.filter((l)=>se(l.labels,e.slug,e.environment,t));if(c.length>0)return c.map(r);if(t==="app"){let l=a.filter((p)=>p.status!=="off"&&p.labels?.[`${B}/managed-by`]==="ts-cloud"&&p.labels?.[`${B}/environment`]===e.environment&&p.labels?.[`${B}/role`]==="app");if(l.length===1)return l.map(r)}return[]}if(this.stateOnly)throw Error(`Hetzner API token required to discover '${t}' compute targets.`);let n=(await this.client.listServers()).filter((i)=>se(i.labels,e.slug,e.environment,t));if(n.length>0)return n.map(r);return[]}async attachToComputeInfrastructure(e,t,r){let s=await this.client.listServers(),n=(m)=>s.filter((g)=>g.status!=="off"&&se(g.labels,e,r,m)),i=n("app");if(i.length===0)throw Error(`Cannot attach '${t.project.slug}' to '${e}': no running Hetzner app server is labeled for ${e}/${r}. Deploy the owner project first.`);let o=n("lb")[0],a=n("services")[0],c=i[0],l=o??c,p=E(t,r),d={provider:"hetzner",stackName:p,serverId:c.id,serverName:c.name,appServerIds:i.map((m)=>m.id),lbServerId:o?.id,servicesServerId:a?.id,servicesPrivateIp:a?.private_net?.[0]?.ip,publicIp:l.public_net.ipv4?.ip,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await mt(p,d),this.outputsFromState(d)}async listReachableResources(){return(await this.client.listServers()).map((t)=>({name:t.name,labels:t.labels}))}async runRemoteDeploy(e){if(e.targets.length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets provided"};let t=e.commands.join(`
273
273
  `),r=[];for(let n of e.targets){if(!n.publicIp){r.push({instanceId:n.id,status:"Failed",error:"Missing public IP"});continue}try{let i=this.sshExec(n.publicIp,t);Ne(i),r.push({instanceId:n.id,status:"Success",output:i})}catch(i){r.push({instanceId:n.id,status:"Failed",error:i.message})}}let s=r.every((n)=>n.status==="Success");return{success:s,instanceCount:e.targets.length,perInstance:r,error:s?void 0:Ie(r,"One or more SSH deploy commands failed")}}async ensureSshKey(e,t,r){if(!ga(this.sshPublicKeyPath))throw Error(`SSH public key not found at ${this.sshPublicKeyPath}. ts-cloud deploys to Hetzner over SSH and needs a public key to authorize on the server. Generate one (\`ssh-keygen -t ed25519\`) or set hetzner.sshPrivateKeyPath / HCLOUD_SSH_PUBLIC_KEY.`);let s=ha(this.sshPublicKeyPath,"utf8").trim(),n=at(s),o=(await this.client.listSshKeys()).find((c)=>at(c.public_key)===n);if(o)return o.id;return(await this.client.createSshKey({name:`${e}-${t}-deploy`,publicKey:s,labels:r})).id}async tryGetServer(e){try{return await this.client.getServer(e)}catch{return null}}refreshLbRoutes(e,t,r,s,n){let i=e.public_net.ipv4?.ip;if(!i){console.warn(`[ts-cloud] LB server '${e.name}' has no public IP — skipping the rpx route refresh; its routes may be stale.`);return}let o=r.filter((c)=>c.privateIp||c.publicIp);if(o.length===0){console.warn(`[ts-cloud] No routable app boxes found for LB '${e.name}' — leaving its current rpx routes untouched.`);return}let a=Me(t,o,{proxy:s,slug:n});this.sshExec(i,Ge({config:a,slug:n}).join(`
@@ -521,13 +521,13 @@ console.log(JSON.stringify({
521
521
  [Service]
522
522
  MemoryAccounting=true
523
523
  MemoryHigh=%sM
524
- ' "$TS_CLOUD_MEM_MB" "$TS_CLOUD_HIGH_MB" > /etc/systemd/system/${e}.d/50-ts-cloud-memory.conf`,"systemctl daemon-reload",'echo "[ts-cloud] memoryHigh=auto resolved to ${TS_CLOUD_HIGH_MB}M (one eighth of ${TS_CLOUD_MEM_MB}M)"',...kr()]}function kr(){return[`TS_CLOUD_COMMIT=$(for f in /sys/fs/cgroup/system.slice/*.service/memory.high /sys/fs/cgroup/system.slice/*.slice/*.service/memory.high; do [ -f "$f" ] || continue; v=$(cat "$f" 2>/dev/null); [ "$v" = "max" ] && continue; echo "$v"; done | awk '{s+=$1} END {print int(s/1048576)}')`,"TS_CLOUD_RAM=$(awk '/^MemTotal:/{print int($2/1024)}' /proc/meminfo)",'if [ -n "$TS_CLOUD_COMMIT" ] && [ "$TS_CLOUD_COMMIT" -gt 0 ] && [ "$TS_CLOUD_RAM" -gt 0 ]; then TS_CLOUD_PCT=$((TS_CLOUD_COMMIT * 100 / TS_CLOUD_RAM)); if [ "$TS_CLOUD_PCT" -gt 300 ]; then echo "[ts-cloud] WARNING: services on this box declare ${TS_CLOUD_COMMIT}M of MemoryHigh against ${TS_CLOUD_RAM}M of RAM (${TS_CLOUD_PCT}% committed). Soft ceilings, so this is not fatal - but no ceiling can protect the box once enough of them are drawn on at once."; else echo "[ts-cloud] memory commitment: ${TS_CLOUD_COMMIT}M declared against ${TS_CLOUD_RAM}M RAM (${TS_CLOUD_PCT}%)"; fi; fi']}function Tc(e){return[`TS_CLOUD_SLICE=$(systemctl show ${e} -p Slice --value 2>/dev/null || true)`,'if [ -n "$TS_CLOUD_SLICE" ] && [ "$TS_CLOUD_SLICE" != "system.slice" ]; then systemctl set-property --runtime "$TS_CLOUD_SLICE" MemoryHigh=infinity MemoryMax=infinity 2>/dev/null || true; systemctl set-property "$TS_CLOUD_SLICE" MemoryHigh=infinity MemoryMax=infinity 2>/dev/null || true; fi']}function Qn(e){let{unitBase:t,unitPattern:r,port:s}=e,n=e.path&&e.path.startsWith("/")?e.path:"/",i=Math.max(10,e.intervalSeconds??60),o=Math.max(1,e.failuresBeforeRestart??3),a=`/usr/local/sbin/${t}-liveness`,l=r.includes("@*")?`TS_CLOUD_UNIT=$(systemctl list-units --plain --no-legend --type=service '${r}' 2>/dev/null | awk '{print $1}' | head -1)`:`TS_CLOUD_UNIT=${r}`;return[`cat > ${a} <<'TS_CLOUD_LIVENESS_EOF'`,"#!/bin/sh","set -eu",`exec 9>/run/${t}-liveness.lock`,"flock -n 9 || exit 0",l,'[ -n "$TS_CLOUD_UNIT" ] || exit 0','systemctl is-active --quiet "$TS_CLOUD_UNIT" || exit 0',`if curl -s -o /dev/null --max-time 5 "http://127.0.0.1:${s}${n}"; then`,` rm -f /run/${t}-liveness.fail`," exit 0","fi",`TS_CLOUD_FAILS=$(cat /run/${t}-liveness.fail 2>/dev/null || echo 0)`,"TS_CLOUD_FAILS=$((TS_CLOUD_FAILS + 1))",`echo "$TS_CLOUD_FAILS" > /run/${t}-liveness.fail`,`[ "$TS_CLOUD_FAILS" -ge ${o} ] || exit 0`,`logger -t ${t}-liveness "no HTTP response on 127.0.0.1:${s}${n} after $TS_CLOUD_FAILS checks; restarting $TS_CLOUD_UNIT"`,'systemctl restart "$TS_CLOUD_UNIT"',`rm -f /run/${t}-liveness.fail`,"TS_CLOUD_LIVENESS_EOF",`chmod +x ${a}`,`cat > /etc/systemd/system/${t}-liveness.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=Liveness check for ${t} (managed by ts-cloud)`,"","[Service]","Type=oneshot",`ExecStart=${a}`,"TS_CLOUD_UNIT_EOF",`cat > /etc/systemd/system/${t}-liveness.timer <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=Run the ${t} liveness check every ${i}s`,"","[Timer]",`OnUnitActiveSec=${i}s`,`OnBootSec=${i}s`,"Persistent=true","","[Install]","WantedBy=timers.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",`systemctl enable --now ${t}-liveness.timer >/dev/null 2>&1 || true`]}var Pc=20,ri=3,xc=5,Cc=60;function Mr(e){let{siteName:t,slug:r,artifactFetch:s,releaseId:n,execStart:i,envEntries:o,port:a,keepReleases:c=ai,preStartCommands:l=[],healthCheckPath:p,healthGateSeconds:d=5,liveness:m,memoryHigh:g="auto",memoryMax:h,cpuWeight:_,ioWeight:w,tasksMax:b,stopTimeout:y}=e,T=[..._!=null?[`CPUWeight=${_}`]:[],...w!=null?[`IOWeight=${w}`]:[],...b!=null?[`TasksMax=${b}`]:[],...y?[`TimeoutStopSec=${y}`]:[]],S=e.zeroDowntime??a!=null,D=e.appDir??`/var/www/${t}`,O=Lt(D,n),R=`${r}-${t}`,H=`${R}.service`,ne=ut(r,t,n),z=e.sharedPaths??[],X=Fa([".env",...z,...kt(o,z)]),Y=Nt(o),F=l.length>0?[`cd ${O.release}`,...l]:[],ee=["set -euo pipefail",...bs(O),Ts(O),...s,...ci(O,X),...vs(O),`tar xzf ${ne} -C "$TS_CLOUD_STAGED"`,`rm -f ${ne}`,`cat > ${O.shared}/.env <<'TS_CLOUD_ENV_EOF'`,Y,"TS_CLOUD_ENV_EOF",`chmod 600 ${O.shared}/.env`,...Es(O),`find ${O.release} -maxdepth 1 \\( -type f -o -type l \\) -name '.env*' ! -name '.env.example' ! -name '*.example' -delete`,`sed -i -E '/^[[:space:]]*(PORT|PORT_BACKEND|PORT_ADMIN|PORT_FRONTEND)[[:space:]]*=/d' ${O.shared}/.env 2>/dev/null || true`,...mo(O,X),...F];if(S&&a!=null){let k=`${R}@${n}.service`,ye=p?p.startsWith("/")?p:`/${p}`:null,G=`{ echo "[ts-cloud] release ${n} failed its health gate — previous release keeps serving" >&2; journalctl -u ${k} -n 50 --no-pager >&2 || true; systemctl stop ${k} 2>/dev/null || true; exit 1; }`;return[...ee,`cat > /etc/systemd/system/${R}@.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} release %i (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${O.releases}/%i`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...g&&g!=="auto"?[`MemoryHigh=${g}`]:[],...h?[`MemoryMax=${h}`]:[],...T,`EnvironmentFile=${O.releases}/%i/.env`,`Environment=PORT=${a}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...g==="auto"?Jn(`${R}@.service`):kr(),...Tc(k),`TS_CLOUD_OLD_UNITS=$(systemctl list-units --plain --no-legend --type=service "${R}@*.service" 2>/dev/null | awk '{print $1}' | grep -v "^${k}$" || true)`,`if [ -f /etc/systemd/system/${H} ] && systemctl is-active --quiet ${H}; then echo "[ts-cloud] retiring pre-zero-downtime unit ${H} (one-time restart cutover)"; systemctl stop ${H}; fi`,`systemctl restart ${k}`,`TS_CLOUD_GATE_OK=1; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do sleep 1; systemctl is-active --quiet ${k} || { TS_CLOUD_GATE_OK=0; break; }; done`,`if [ "$TS_CLOUD_GATE_OK" -ne 1 ]; then echo "[ts-cloud] release ${n} could not overlap the previous release (no SO_REUSEPORT?) — retiring old instances and retrying" >&2; for TS_CLOUD_RU in \${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_RU" 2>/dev/null || true; done; systemctl restart ${k}; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do sleep 1; systemctl is-active --quiet ${k} || ${G}; done; fi`,`if ss -ltnpH "sport = :${a}" >/dev/null 2>&1; then`," TS_CLOUD_BOUND=0",` for TS_CLOUD_I in $(seq 1 ${Cc}); do`,` TS_CLOUD_NEW_PID="$(systemctl show -p MainPID --value ${k} 2>/dev/null || true)"`,` if [ -n "$TS_CLOUD_NEW_PID" ] && [ "$TS_CLOUD_NEW_PID" != "0" ] && ss -ltnpH "sport = :${a}" 2>/dev/null | grep -q "pid=$TS_CLOUD_NEW_PID,"; then TS_CLOUD_BOUND=1; break; fi`,` sleep ${ri}`," done",` if [ "$TS_CLOUD_BOUND" -ne 1 ]; then echo "[ts-cloud] release ${n} never joined ${a} alongside the previous release" >&2; ${G}; fi`,"else",' echo "[ts-cloud] cannot read listener PIDs on this host — the response gate runs without the bind check" >&2',"fi",...ye?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${Pc}); do if curl -sf -o /dev/null --max-time ${xc} "http://127.0.0.1:${a}${ye}"; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${ri}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${G}`]:[],...Jr(O),`systemctl enable ${k} 2>/dev/null || true`,'for TS_CLOUD_U in ${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done',`TS_CLOUD_LISTENING=0; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do if ss -ltnH "sport = :${a}" 2>/dev/null | grep -q .; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done`,`if [ "$TS_CLOUD_LISTENING" -ne 1 ]; then echo "[ts-cloud] nothing is listening on ${a} after retiring the previous release — restarting ${k} on the now-free port" >&2; systemctl restart ${k}; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do if ss -ltnH "sport = :${a}" 2>/dev/null | grep -q .; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done; fi`,`if [ "$TS_CLOUD_LISTENING" -ne 1 ]; then echo "[ts-cloud] ${k} is active but never bound ${a}" >&2; journalctl -u ${k} -n 50 --no-pager >&2 || true; exit 1; fi`,`systemctl list-unit-files --plain --no-legend "${R}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v -e "^${k}$" -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/${H} ]; then systemctl disable ${H} 2>/dev/null || true; rm -f /etc/systemd/system/${H}; systemctl daemon-reload; fi`,...Xr(O,c),...m===!1?[]:Qn({unitBase:R,unitPattern:`${R}@*.service`,port:a,path:m?.path??p,intervalSeconds:m?.intervalSeconds,failuresBeforeRestart:m?.failuresBeforeRestart})]}return[...ee,`cat > /etc/systemd/system/${H} <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${O.current}`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...g&&g!=="auto"?[`MemoryHigh=${g}`]:[],...h?[`MemoryMax=${h}`]:[],...T,`EnvironmentFile=${O.current}/.env`,...a?[`Environment=PORT=${a}`]:[],"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...g==="auto"?Jn(H):kr(),`systemctl enable ${H}`,...Jr(O),`systemctl restart ${H}`,`systemctl is-active ${H}`,...Xr(O,c),...m===!1||!a?[]:Qn({unitBase:R,unitPattern:H,port:a,path:m?.path??p,intervalSeconds:m?.intervalSeconds,failuresBeforeRestart:m?.failuresBeforeRestart})]}function Ur(e){let{siteName:t,artifactFetch:r,releaseId:s,keepReleases:n=ai,preStartCommands:i=[]}=e,o=e.appDir??`/var/www/${t}`,a=Lt(o,s),c=ut(e.slug,t,s),l=i.length>0?[`cd ${a.release}`,...i]:[];return["set -euo pipefail",...bs(a),Ts(a),...r,...ci(a,[]),...vs(a),`tar xzf ${c} -C "$TS_CLOUD_STAGED"`,...Es(a),`rm -f ${c}`,...l,...Jr(a),...Xr(a,n)]}function ut(e,t,r){return`/tmp/${[e,t,r].filter(Boolean).join("-")}-release.tar.gz`}function Fr(e,t,r,s){return[`aws s3 cp "s3://${e}/${t}" ${s} --region ${r}`]}function Br(e,t){return[`mv "${e}" ${t}`]}function Kr(){return['echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',"find /var/ts-cloud/staging -xdev -maxdepth 1 -type f -mmin +60 -delete 2>/dev/null || true",'find /tmp -xdev -maxdepth 1 -type f -name "*-release.tar.gz" -mmin +60 -delete 2>/dev/null || true',"find /root/.bun/install/cache -xdev -type f -mtime +7 -delete 2>/dev/null || true","find /root/.bun/install/cache -xdev -depth -type d -empty -delete 2>/dev/null || true","journalctl --vacuum-time=14d --vacuum-size=512M >/dev/null 2>&1 || true",'if command -v docker >/dev/null 2>&1; then docker image prune --all --force --filter "until=168h" >/dev/null 2>&1 || true; fi','if command -v podman >/dev/null 2>&1; then podman image prune --all --force --filter "until=168h" >/dev/null 2>&1 || true; fi',"if command -v apt-get >/dev/null 2>&1; then apt-get clean >/dev/null 2>&1 || true; fi",'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"']}import{copyFileSync as Jc}from"node:fs";import{tmpdir as Qc}from"node:os";import{join as Zc}from"node:path";var Rc=`${B}/project`;function si(e,t){let r=t.ownerSlug.trim(),s=t.selfSlug?.trim(),n={total:e.length,owner:[],self:[],others:new Map,unmanaged:[]};for(let i of e){let o=i.labels?.[Rc]?.trim();if(!o){n.unmanaged.push(i.name);continue}if(o===r){n.owner.push(i.name);continue}if(s&&o===s){n.self.push(i.name);continue}let a=n.others.get(o);if(a)a.push(i.name);else n.others.set(o,[i.name])}return n}function jr(e){let t=e.unmanaged.length;for(let r of e.others.values())t+=r.length;return t}function oi(e,t){let r=jr(e),s=[];if(s.push(`Attaching to '${t.ownerSlug}' shares one provider project, so this deploy's credential can write to all ${e.total} server(s) it can see.`),r===0)return s.push("Nothing outside the two projects being joined is reachable with it."),s;s.push(`${r} of them belong to neither project:`);for(let n of[...e.others.keys()].sort())s.push(` ${n}: ${[...e.others.get(n)].sort().join(", ")}`);if(e.unmanaged.length>0)s.push(` not managed by ts-cloud: ${[...e.unmanaged].sort().join(", ")}`);return s.push("A compromised CI run or a mistargeted teardown in this project now reaches those. Keep the app in its own provider project instead if that is not acceptable, which rules out attaching."),s}var Ec=new Set(["laravel","php","statamic","wordpress"]);function Gr(e){if(e.framework)return e.framework;if(e.type&&Ec.has(e.type))return"laravel";return"stacks"}var li=`eval "$(cd ${M} && pantry env 2>/dev/null)"`,ui="/usr/local/bin/bun",Ic="storage/framework/core/buddy/src/cli.ts",Oc="node_modules/@stacksjs/ts-cloud/dist/bin/stacks-scheduler.js",di={id:"stacks",wrapExec:(e)=>e,execEnv:{PATH:"/usr/local/bin:/usr/bin:/bin",BUN_INSTALL:"/root/.bun",APP_ENV:"production",NODE_ENV:"production"},schedulerMode:"daemon",schedulerCommand:()=>`${ui} ${Oc}`,queueWorkerCommand:(e,{current:t})=>{let r=[`--queue=${e.queue||"default"}`,`--sleep=${e.sleep??3}`,`--tries=${e.tries??3}`,`--timeout=${e.timeout??60}`];return`${ui} ${t}/${Ic} queue:work ${r.join(" ")}`}},Dc={id:"laravel",wrapExec:(e)=>`/bin/sh -lc '${li}; exec ${e}'`,schedulerMode:"cron",schedulerCommand:({current:e})=>`cd ${e} && ${li} && php artisan schedule:run`,queueWorkerCommand:(e,{current:t})=>{let r=`${t}/artisan`;if(e.horizon)return`php ${r} horizon`;let s=[e.connection||"default",`--queue=${e.queue||"default"}`,`--sleep=${e.sleep??3}`,`--tries=${e.tries??3}`,`--timeout=${e.timeout??60}`,`--memory=${e.memory??128}`];if(e.maxJobs)s.push(`--max-jobs=${e.maxJobs}`);if(e.maxTime)s.push(`--max-time=${e.maxTime}`);return`php ${r} queue:work ${s.join(" ")}`}},Ac={stacks:di,laravel:Dc};function mi(e){return Ac[e]??di}function fi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Nc(e){return`'${e.split("'").join("'\\''")}'`}function gi(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"unnamed"}function kc(e,t,r){return`${e}-${t}-queue-${r}`}function Hc(e,t,r,s){return`${e}-${t}-daemon-${r.name?gi(r.name):gi(r.command).slice(0,32)||String(s)}`}function Yr(e){let t=["[Unit]",`Description=${e.description}`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${e.workingDir}`,...Object.entries(e.environment??{}).map(([r,s])=>`Environment="${r}=${s}"`),`ExecStart=${e.execStart}`,`Restart=${e.restart||"always"}`,"RestartSec=5","MemoryAccounting=true",`MemoryHigh=${e.memoryHigh??"2G"}`,...e.memoryMax?[`MemoryMax=${e.memoryMax}`]:[]];if(e.user)t.push(`User=${e.user}`);if(typeof e.stopWaitSecs==="number")t.push(`TimeoutStopSec=${e.stopWaitSecs}`);return t.push("","[Install]","WantedBy=multi-user.target"),`${t.join(`
524
+ ' "$TS_CLOUD_MEM_MB" "$TS_CLOUD_HIGH_MB" > /etc/systemd/system/${e}.d/50-ts-cloud-memory.conf`,"systemctl daemon-reload",'echo "[ts-cloud] memoryHigh=auto resolved to ${TS_CLOUD_HIGH_MB}M (one eighth of ${TS_CLOUD_MEM_MB}M)"',...kr()]}function kr(){return[`TS_CLOUD_COMMIT=$(for f in /sys/fs/cgroup/system.slice/*.service/memory.high /sys/fs/cgroup/system.slice/*.slice/*.service/memory.high; do [ -f "$f" ] || continue; v=$(cat "$f" 2>/dev/null); [ "$v" = "max" ] && continue; echo "$v"; done | awk '{s+=$1} END {print int(s/1048576)}')`,"TS_CLOUD_RAM=$(awk '/^MemTotal:/{print int($2/1024)}' /proc/meminfo)",'if [ -n "$TS_CLOUD_COMMIT" ] && [ "$TS_CLOUD_COMMIT" -gt 0 ] && [ "$TS_CLOUD_RAM" -gt 0 ]; then TS_CLOUD_PCT=$((TS_CLOUD_COMMIT * 100 / TS_CLOUD_RAM)); if [ "$TS_CLOUD_PCT" -gt 300 ]; then echo "[ts-cloud] WARNING: services on this box declare ${TS_CLOUD_COMMIT}M of MemoryHigh against ${TS_CLOUD_RAM}M of RAM (${TS_CLOUD_PCT}% committed). Soft ceilings, so this is not fatal - but no ceiling can protect the box once enough of them are drawn on at once."; else echo "[ts-cloud] memory commitment: ${TS_CLOUD_COMMIT}M declared against ${TS_CLOUD_RAM}M RAM (${TS_CLOUD_PCT}%)"; fi; fi']}function Tc(e){return[`TS_CLOUD_SLICE=$(systemctl show ${e} -p Slice --value 2>/dev/null || true)`,'if [ -n "$TS_CLOUD_SLICE" ] && [ "$TS_CLOUD_SLICE" != "system.slice" ]; then systemctl set-property --runtime "$TS_CLOUD_SLICE" MemoryHigh=infinity MemoryMax=infinity 2>/dev/null || true; systemctl set-property "$TS_CLOUD_SLICE" MemoryHigh=infinity MemoryMax=infinity 2>/dev/null || true; fi']}function Qn(e){let{unitBase:t,unitPattern:r,port:s}=e,n=e.path&&e.path.startsWith("/")?e.path:"/",i=Math.max(10,e.intervalSeconds??60),o=Math.max(1,e.failuresBeforeRestart??3),a=`/usr/local/sbin/${t}-liveness`,l=r.includes("@*")?`TS_CLOUD_UNIT=$(systemctl list-units --plain --no-legend --type=service '${r}' 2>/dev/null | awk '{print $1}' | head -1)`:`TS_CLOUD_UNIT=${r}`;return[`cat > ${a} <<'TS_CLOUD_LIVENESS_EOF'`,"#!/bin/sh","set -eu",`exec 9>/run/${t}-liveness.lock`,"flock -n 9 || exit 0",l,'[ -n "$TS_CLOUD_UNIT" ] || exit 0','systemctl is-active --quiet "$TS_CLOUD_UNIT" || exit 0',`if curl -s -o /dev/null --max-time 5 "http://127.0.0.1:${s}${n}"; then`,` rm -f /run/${t}-liveness.fail`," exit 0","fi",`TS_CLOUD_FAILS=$(cat /run/${t}-liveness.fail 2>/dev/null || echo 0)`,"TS_CLOUD_FAILS=$((TS_CLOUD_FAILS + 1))",`echo "$TS_CLOUD_FAILS" > /run/${t}-liveness.fail`,`[ "$TS_CLOUD_FAILS" -ge ${o} ] || exit 0`,`logger -t ${t}-liveness "no HTTP response on 127.0.0.1:${s}${n} after $TS_CLOUD_FAILS checks; restarting $TS_CLOUD_UNIT"`,'systemctl restart "$TS_CLOUD_UNIT"',`rm -f /run/${t}-liveness.fail`,"TS_CLOUD_LIVENESS_EOF",`chmod +x ${a}`,`cat > /etc/systemd/system/${t}-liveness.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=Liveness check for ${t} (managed by ts-cloud)`,"","[Service]","Type=oneshot",`ExecStart=${a}`,"TS_CLOUD_UNIT_EOF",`cat > /etc/systemd/system/${t}-liveness.timer <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=Run the ${t} liveness check every ${i}s`,"","[Timer]",`OnUnitActiveSec=${i}s`,`OnBootSec=${i}s`,"Persistent=true","","[Install]","WantedBy=timers.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",`systemctl enable --now ${t}-liveness.timer >/dev/null 2>&1 || true`]}var Pc=20,ri=3,xc=5,Cc=60;function Mr(e){let{siteName:t,slug:r,artifactFetch:s,releaseId:n,execStart:i,envEntries:o,port:a,keepReleases:c=ai,preStartCommands:l=[],healthCheckPath:p,healthGateSeconds:d=5,liveness:m,memoryHigh:g="auto",memoryMax:h,cpuWeight:_,ioWeight:w,tasksMax:b,stopTimeout:y}=e,T=[..._!=null?[`CPUWeight=${_}`]:[],...w!=null?[`IOWeight=${w}`]:[],...b!=null?[`TasksMax=${b}`]:[],...y?[`TimeoutStopSec=${y}`]:[]],S=e.zeroDowntime??a!=null,D=e.appDir??`/var/www/${t}`,O=Lt(D,n),R=`${r}-${t}`,H=`${R}.service`,ne=ut(r,t,n),z=e.sharedPaths??[],X=Fa([".env",...z,...kt(o,z)]),Y=Nt(o),F=l.length>0?[`cd ${O.release}`,...l]:[],ee=["set -euo pipefail",...bs(O),Ts(O),...s,...ci(O,X),...vs(O),`tar xzf ${ne} -C "$TS_CLOUD_STAGED"`,`rm -f ${ne}`,`cat > ${O.shared}/.env <<'TS_CLOUD_ENV_EOF'`,Y,"TS_CLOUD_ENV_EOF",`chmod 600 ${O.shared}/.env`,...Es(O),`find ${O.release} -maxdepth 1 \\( -type f -o -type l \\) -name '.env*' ! -name '.env.example' ! -name '*.example' -delete`,`sed -i -E '/^[[:space:]]*(PORT|PORT_BACKEND|PORT_ADMIN|PORT_FRONTEND)[[:space:]]*=/d' ${O.shared}/.env 2>/dev/null || true`,...mo(O,X),...F];if(S&&a!=null){let k=`${R}@${n}.service`,ye=p?p.startsWith("/")?p:`/${p}`:null,G=`{ echo "[ts-cloud] release ${n} failed its health gate — previous release keeps serving" >&2; journalctl -u ${k} -n 50 --no-pager >&2 || true; systemctl stop ${k} 2>/dev/null || true; exit 1; }`;return[...ee,`cat > /etc/systemd/system/${R}@.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} release %i (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${O.releases}/%i`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...g&&g!=="auto"?[`MemoryHigh=${g}`]:[],...h?[`MemoryMax=${h}`]:[],...T,`EnvironmentFile=${O.releases}/%i/.env`,`Environment=PORT=${a}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...g==="auto"?Jn(`${R}@.service`):kr(),...Tc(k),`TS_CLOUD_OLD_UNITS=$(systemctl list-units --plain --no-legend --type=service "${R}@*.service" 2>/dev/null | awk '{print $1}' | grep -v "^${k}$" || true)`,`if [ -f /etc/systemd/system/${H} ] && systemctl is-active --quiet ${H}; then echo "[ts-cloud] retiring pre-zero-downtime unit ${H} (one-time restart cutover)"; systemctl stop ${H}; fi`,`systemctl restart ${k}`,`TS_CLOUD_GATE_OK=1; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do sleep 1; systemctl is-active --quiet ${k} || { TS_CLOUD_GATE_OK=0; break; }; done`,`if [ "$TS_CLOUD_GATE_OK" -ne 1 ]; then echo "[ts-cloud] release ${n} could not overlap the previous release (no SO_REUSEPORT?) — retiring old instances and retrying" >&2; for TS_CLOUD_RU in \${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_RU" 2>/dev/null || true; done; systemctl restart ${k}; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do sleep 1; systemctl is-active --quiet ${k} || ${G}; done; fi`,`if ss -ltnpH "sport = :${a}" >/dev/null 2>&1; then`," TS_CLOUD_BOUND=0",` for TS_CLOUD_I in $(seq 1 ${Cc}); do`,` TS_CLOUD_NEW_PID="$(systemctl show -p MainPID --value ${k} 2>/dev/null || true)"`,` if [ -n "$TS_CLOUD_NEW_PID" ] && [ "$TS_CLOUD_NEW_PID" != "0" ] && ss -ltnpH "sport = :${a}" 2>/dev/null | grep -q "pid=$TS_CLOUD_NEW_PID,"; then TS_CLOUD_BOUND=1; break; fi`,` sleep ${ri}`," done",` if [ "$TS_CLOUD_BOUND" -ne 1 ]; then echo "[ts-cloud] release ${n} never joined ${a} alongside the previous release" >&2; ${G}; fi`,"else",' echo "[ts-cloud] cannot read listener PIDs on this host — the response gate runs without the bind check" >&2',"fi",...ye?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${Pc}); do if curl -sf -o /dev/null --max-time ${xc} "http://127.0.0.1:${a}${ye}"; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${ri}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${G}`]:[],...Jr(O),`systemctl enable ${k} 2>/dev/null || true`,'for TS_CLOUD_U in ${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done',`TS_CLOUD_LISTENING=0; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do if ss -ltnH "sport = :${a}" 2>/dev/null | grep -q .; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done`,`if [ "$TS_CLOUD_LISTENING" -ne 1 ]; then echo "[ts-cloud] nothing is listening on ${a} after retiring the previous release — restarting ${k} on the now-free port" >&2; systemctl restart ${k}; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do if ss -ltnH "sport = :${a}" 2>/dev/null | grep -q .; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done; fi`,`if [ "$TS_CLOUD_LISTENING" -ne 1 ]; then echo "[ts-cloud] ${k} is active but never bound ${a}" >&2; journalctl -u ${k} -n 50 --no-pager >&2 || true; exit 1; fi`,`systemctl list-unit-files --plain --no-legend "${R}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v -e "^${k}$" -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/${H} ]; then systemctl disable ${H} 2>/dev/null || true; rm -f /etc/systemd/system/${H}; systemctl daemon-reload; fi`,...Xr(O,c),...m===!1?[]:Qn({unitBase:R,unitPattern:`${R}@*.service`,port:a,path:m?.path??p,intervalSeconds:m?.intervalSeconds,failuresBeforeRestart:m?.failuresBeforeRestart})]}return[...ee,`cat > /etc/systemd/system/${H} <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${O.current}`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...g&&g!=="auto"?[`MemoryHigh=${g}`]:[],...h?[`MemoryMax=${h}`]:[],...T,`EnvironmentFile=${O.current}/.env`,...a?[`Environment=PORT=${a}`]:[],"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...g==="auto"?Jn(H):kr(),`systemctl enable ${H}`,...Jr(O),`systemctl restart ${H}`,`systemctl is-active ${H}`,...Xr(O,c),...m===!1||!a?[]:Qn({unitBase:R,unitPattern:H,port:a,path:m?.path??p,intervalSeconds:m?.intervalSeconds,failuresBeforeRestart:m?.failuresBeforeRestart})]}function Ur(e){let{siteName:t,artifactFetch:r,releaseId:s,keepReleases:n=ai,preStartCommands:i=[]}=e,o=e.appDir??`/var/www/${t}`,a=Lt(o,s),c=ut(e.slug,t,s),l=i.length>0?[`cd ${a.release}`,...i]:[];return["set -euo pipefail",...bs(a),Ts(a),...r,...ci(a,[]),...vs(a),`tar xzf ${c} -C "$TS_CLOUD_STAGED"`,...Es(a),`rm -f ${c}`,...l,...Jr(a),...Xr(a,n)]}function ut(e,t,r){return`/tmp/${[e,t,r].filter(Boolean).join("-")}-release.tar.gz`}function Fr(e,t,r,s){return[`aws s3 cp "s3://${e}/${t}" ${s} --region ${r}`]}function Br(e,t){return[`mv "${e}" ${t}`]}function Kr(){return['echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',"find /var/ts-cloud/staging -xdev -maxdepth 1 -type f -mmin +60 -delete 2>/dev/null || true",'find /tmp -xdev -maxdepth 1 -type f -name "*-release.tar.gz" -mmin +60 -delete 2>/dev/null || true',"find /root/.bun/install/cache -xdev -type f -mtime +7 -delete 2>/dev/null || true","find /root/.bun/install/cache -xdev -depth -type d -empty -delete 2>/dev/null || true","journalctl --vacuum-time=14d --vacuum-size=512M >/dev/null 2>&1 || true",'if command -v docker >/dev/null 2>&1; then docker image prune --all --force --filter "until=168h" >/dev/null 2>&1 || true; fi','if command -v podman >/dev/null 2>&1; then podman image prune --all --force --filter "until=168h" >/dev/null 2>&1 || true; fi',"if command -v apt-get >/dev/null 2>&1; then apt-get clean >/dev/null 2>&1 || true; fi",'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"']}import{copyFileSync as Jc}from"node:fs";import{tmpdir as Qc}from"node:os";import{join as Zc}from"node:path";var Rc=`${B}/project`;function si(e,t){let r=t.ownerSlug.trim(),s=t.selfSlug?.trim(),n={total:e.length,owner:[],self:[],others:new Map,unmanaged:[]};for(let i of e){let o=i.labels?.[Rc]?.trim();if(!o){n.unmanaged.push(i.name);continue}if(o===r){n.owner.push(i.name);continue}if(s&&o===s){n.self.push(i.name);continue}let a=n.others.get(o);if(a)a.push(i.name);else n.others.set(o,[i.name])}return n}function jr(e){let t=e.unmanaged.length;for(let r of e.others.values())t+=r.length;return t}function oi(e,t){let r=jr(e),s=[];if(s.push(`Attaching to '${t.ownerSlug}' shares one provider project, so this deploy's credential can write to all ${e.total} server(s) it can see.`),r===0)return s.push("Nothing outside the two projects being joined is reachable with it."),s;s.push(`${r} of them belong to neither project:`);for(let n of[...e.others.keys()].sort())s.push(` ${n}: ${[...e.others.get(n)].sort().join(", ")}`);if(e.unmanaged.length>0)s.push(` not managed by ts-cloud: ${[...e.unmanaged].sort().join(", ")}`);return s.push("A compromised CI run or a mistargeted teardown in this project now reaches those. Keep the app in its own provider project instead if that is not acceptable, which rules out attaching."),s}var Ec=new Set(["laravel","php","statamic","wordpress"]);function Gr(e){if(e.framework)return e.framework;if(e.type&&Ec.has(e.type))return"laravel";return"stacks"}var li=`eval "$(cd ${L} && pantry env 2>/dev/null)"`,ui="/usr/local/bin/bun",Ic="storage/framework/core/buddy/src/cli.ts",Oc="node_modules/@stacksjs/ts-cloud/dist/bin/stacks-scheduler.js",di={id:"stacks",wrapExec:(e)=>e,execEnv:{PATH:"/usr/local/bin:/usr/bin:/bin",BUN_INSTALL:"/root/.bun",APP_ENV:"production",NODE_ENV:"production"},schedulerMode:"daemon",schedulerCommand:()=>`${ui} ${Oc}`,queueWorkerCommand:(e,{current:t})=>{let r=[`--queue=${e.queue||"default"}`,`--sleep=${e.sleep??3}`,`--tries=${e.tries??3}`,`--timeout=${e.timeout??60}`];return`${ui} ${t}/${Ic} queue:work ${r.join(" ")}`}},Dc={id:"laravel",wrapExec:(e)=>`/bin/sh -lc '${li}; exec ${e}'`,schedulerMode:"cron",schedulerCommand:({current:e})=>`cd ${e} && ${li} && php artisan schedule:run`,queueWorkerCommand:(e,{current:t})=>{let r=`${t}/artisan`;if(e.horizon)return`php ${r} horizon`;let s=[e.connection||"default",`--queue=${e.queue||"default"}`,`--sleep=${e.sleep??3}`,`--tries=${e.tries??3}`,`--timeout=${e.timeout??60}`,`--memory=${e.memory??128}`];if(e.maxJobs)s.push(`--max-jobs=${e.maxJobs}`);if(e.maxTime)s.push(`--max-time=${e.maxTime}`);return`php ${r} queue:work ${s.join(" ")}`}},Ac={stacks:di,laravel:Dc};function mi(e){return Ac[e]??di}function fi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Nc(e){return`'${e.split("'").join("'\\''")}'`}function gi(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"unnamed"}function kc(e,t,r){return`${e}-${t}-queue-${r}`}function Hc(e,t,r,s){return`${e}-${t}-daemon-${r.name?gi(r.name):gi(r.command).slice(0,32)||String(s)}`}function Yr(e){let t=["[Unit]",`Description=${e.description}`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${e.workingDir}`,...Object.entries(e.environment??{}).map(([r,s])=>`Environment="${r}=${s}"`),`ExecStart=${e.execStart}`,`Restart=${e.restart||"always"}`,"RestartSec=5","MemoryAccounting=true",`MemoryHigh=${e.memoryHigh??"2G"}`,...e.memoryMax?[`MemoryMax=${e.memoryMax}`]:[]];if(e.user)t.push(`User=${e.user}`);if(typeof e.stopWaitSecs==="number")t.push(`TimeoutStopSec=${e.stopWaitSecs}`);return t.push("","[Install]","WantedBy=multi-user.target"),`${t.join(`
525
525
  `)}
526
526
  `}function Zr(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_UNIT_EOF'`,t.replace(/\n$/,""),"TS_CLOUD_UNIT_EOF"]}function Lc(e,t){return`/etc/cron.d/${e}-${t}-scheduler`}function es(e){let{slug:t,siteName:r,site:s}=e,i=`${e.appBase??`/var/www/${r}`}/current`,o=mi(Gr(s)),a={current:i},c=[],l=[];(s.queues||[]).forEach((b,y)=>{let T=Math.max(1,b.processes??1);for(let S=0;S<T;S++){let D=kc(t,r,l.length);l.push(D),c.push(...Zr(D,Yr({description:`${r} queue worker ${y}.${S} (managed by ts-cloud)`,workingDir:i,execStart:o.wrapExec(o.queueWorkerCommand(b,a)),environment:o.execEnv,stopWaitSecs:b.stopWaitSecs??90})))}}),(s.daemons||[]).forEach((b,y)=>{let T=Math.max(1,b.processes??1);for(let S=0;S<T;S++){let D=`${Hc(t,r,b,y)}-${S}`;l.push(D),c.push(...Zr(D,Yr({description:`${r} daemon ${b.name||b.command} (managed by ts-cloud)`,workingDir:b.directory||i,execStart:o.wrapExec(b.command),environment:o.execEnv,restart:b.restart,user:b.user})))}});let m=s.scheduler,g=m===!0||typeof m==="object"&&m!==null,h=`${t}-${r}-scheduler`;if(g&&o.schedulerMode==="daemon")l.push(h),c.push(...Zr(h,Yr({description:`${r} scheduler (managed by ts-cloud)`,workingDir:i,execStart:o.wrapExec(o.schedulerCommand(a)),environment:o.execEnv})));let _=l.map((b)=>`${b}.service`).join(" ");c.push("systemctl daemon-reload",`TS_CLOUD_DESIRED="${_}"`,`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E '^${fi(t)}-${fi(r)}-((queue|daemon)-.*|scheduler)\\.service$' || true); do`,' case " $TS_CLOUD_DESIRED " in',' *" $unit "*) ;;',' *) systemctl stop "$unit" 2>/dev/null || true; systemctl disable "$unit" 2>/dev/null || true; rm -f "/etc/systemd/system/$unit" ;;'," esac","done","systemctl daemon-reload");for(let b of l)c.push(`systemctl enable ${b}.service`,`systemctl restart ${b}.service`);let w=Lc(t,r);if(g&&o.schedulerMode==="cron"){let b=typeof m==="object"&&m!==null?m:void 0,y=`${o.schedulerCommand(a)} >> /dev/null 2>&1`;if(b?.heartbeatUrl){let S=b.heartbeatMethod||"GET",D=S==="GET"?"":`-X ${S} `;y+=` && curl -fsS -m 10 ${D}${Nc(b.heartbeatUrl)} >/dev/null 2>&1`}let T=`* * * * * root ${y}
527
527
  `.replace(/%/g,"\\%");c.push(`cat > ${w} <<'TS_CLOUD_CRON_EOF'`,T.replace(/\n$/,""),"TS_CLOUD_CRON_EOF",`chmod 644 ${w}`)}else c.push(`rm -f ${w}`);return c}function ts(e){return!!(e.queues?.length||e.daemons?.length||e.scheduler)}function us(e){if(e.ssl?.provider)return e.ssl.provider;return e.domain?"letsencrypt":"none"}var hi={cloudflare:{pkg:"python3-certbot-dns-cloudflare",plugin:"dns-cloudflare"},route53:{pkg:"python3-certbot-dns-route53",plugin:"dns-route53"},digitalocean:{pkg:"python3-certbot-dns-digitalocean",plugin:"dns-digitalocean"},google:{pkg:"python3-certbot-dns-google",plugin:"dns-google"}};function yi(e){return`/etc/letsencrypt/ts-cloud-${e}.ini`}function Mc(e){let t=e?hi[e.provider]:void 0,r=["certbot","python3-certbot-nginx",...t?[t.pkg]:[]].join(" ");return["export DEBIAN_FRONTEND=noninteractive",t?`apt-get update -y && apt-get install -y ${r}`:`command -v certbot >/dev/null 2>&1 || { apt-get update -y && apt-get install -y ${r}; }`,"mkdir -p /etc/letsencrypt/renewal-hooks/deploy","cat > /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh <<'TS_CLOUD_HOOK_EOF'","#!/bin/sh","systemctl reload ts-cloud-nginx 2>/dev/null || systemctl reload nginx 2>/dev/null || true","TS_CLOUD_HOOK_EOF","chmod +x /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh","systemctl enable certbot.timer 2>/dev/null || true","systemctl start certbot.timer 2>/dev/null || true"]}function Uc(e){if(!e.credentials||Object.keys(e.credentials).length===0)return[];let t=yi(e.provider),r=Object.entries(e.credentials).map(([s,n])=>`${s} = ${n}`).join(`
528
- `);return[`cat > ${t} <<'TS_CLOUD_DNSCREDS_EOF'`,r,"TS_CLOUD_DNSCREDS_EOF",`chmod 600 ${t}`]}function zc(e){let t=e.dns,r=e.wildcard?[`*.${e.domain}`,e.domain]:[e.domain,...e.aliases||[]].filter(Boolean),s=["certbot","--non-interactive","--agree-tos","--keep-until-expiring"];if(t){let n=hi[t.provider].plugin;if(s.push(`--${n}`),t.provider!=="route53"&&t.credentials)s.push(`--${n}-credentials ${yi(t.provider)}`);if(typeof t.propagationSeconds==="number"&&t.provider!=="route53")s.push(`--${n}-propagation-seconds ${t.propagationSeconds}`);s.push("certonly")}else s.push("--nginx",`--nginx-ctl ${$e}`,e.redirect===!1?"--no-redirect":"--redirect");if(e.email)s.push(`-m ${e.email}`);else s.push("--register-unsafely-without-email");for(let n of r)s.push(`-d ${n}`);return[s.join(" ")]}function fs(e){if(us(e)!=="letsencrypt"||!e.domain)return[];let t=e.ssl,r=t?.dns,s=t?.wildcard===!0;if(s&&!r)return[];return[...Mc(r),...r?Uc(r):[],...zc({domain:e.domain,aliases:e.aliases,email:t?.email,wildcard:s,dns:r})]}function Si(e){let{repository:t,releaseDir:r,commit:s}=e,n=t.branch||"main",i=t.url,o=[`rm -rf ${r}`,`mkdir -p ${r}`];if(t.strategy==="tag")if(t.tag)o.push(`git clone -q --depth 1 --branch ${oe(t.tag)} ${oe(i)} ${r}`),o.push(`printf '%s' ${oe(t.tag)} > ${r}/.ts-cloud-tag`);else{let a=t.tagPattern||"v*";o.push(`TS_CLOUD_TAG="$(git ls-remote --tags --refs --sort=-v:refname ${oe(i)} ${oe(`refs/tags/${a}`)} | head -n1 | sed 's#.*refs/tags/##')"`,`test -n "$TS_CLOUD_TAG" || { echo "no tags matching" ${oe(a)} "found in" ${oe(i)} >&2; exit 1; }`,`git clone -q --depth 1 --branch "$TS_CLOUD_TAG" ${oe(i)} ${r}`,`printf '%s' "$TS_CLOUD_TAG" > ${r}/.ts-cloud-tag`)}else if(s)o.push(`git -C ${r} init -q`,`git -C ${r} remote add origin ${oe(i)}`,`git -C ${r} fetch -q --depth 1 origin ${oe(s)}`,`git -C ${r} checkout -q FETCH_HEAD`);else o.push(`git clone -q --depth 1 --branch ${oe(n)} ${oe(i)} ${r}`);return o.push(`git -C ${r} rev-parse HEAD > ${r}/.ts-cloud-sha`),o}function oe(e){return`'${e.split("'").join("'\\''")}'`}var Ht="$CREATE_RELEASE",Mt="$ACTIVATE_RELEASE",wi="$RESTART_QUEUES",vi="composer install --no-interaction --prefer-dist --optimize-autoloader --no-dev",Fc=["php artisan migrate --force","php artisan config:cache","php artisan route:cache","php artisan view:cache","php artisan event:cache","php artisan storage:link"];function Bc(e){switch(e){case"laravel":case"statamic":return[Ht,vi,...Fc,Mt,wi];case"php":case"wordpress":return[Ht,`${vi} || true`,Mt];case"static":case"spa":return[Ht,Mt]}}function Kc(e,t){return e.replace(/^php\s+/,`${t} `).replace(/(\s)php\s+artisan\s+/g,`$1${t} artisan `)}function jc(e,t){let r=Nt(t);return[`cat > ${e} <<'TS_CLOUD_ENV_EOF'`,r,"TS_CLOUD_ENV_EOF",`chmod 600 ${e}`]}function bi(e,t,r){return[`cat > ${e} <<'${r}'`,t.replace(/\n$/,""),r,`chmod 600 ${e}`]}function Gc(e,t){if(!t)return[];let r=[];if(t.composerAuth){let s=typeof t.composerAuth==="string"?t.composerAuth:JSON.stringify(t.composerAuth,null,2);r.push(...bi(`${e}/auth.json`,s,"TS_CLOUD_AUTHJSON_EOF"))}if(t.npmrc)r.push(...bi(`${e}/.npmrc`,t.npmrc,"TS_CLOUD_NPMRC_EOF"));return r}function $i(e){let t=e.healthCheck?.path;if(!t||!e.domain)return[];let s=`http://127.0.0.1${t.startsWith("/")?t:`/${t}`}`;return[`echo "[ts-cloud] health check ${s} (Host: ${e.domain})"`,"TS_CLOUD_HC_OK=0",`for i in $(seq 1 10); do TS_CLOUD_HC=$(curl -s -o /dev/null -w "%{http_code}" -H "Host: ${e.domain}" -m 10 "${s}" 2>/dev/null || echo 000); case "$TS_CLOUD_HC" in 2*|3*) TS_CLOUD_HC_OK=1; break ;; esac; sleep 3; done`,'[ "$TS_CLOUD_HC_OK" = 1 ] && echo "health check passed ($TS_CLOUD_HC)" || { echo "health check FAILED (last=$TS_CLOUD_HC)" >&2; exit 1; }']}function _i(e){let{siteName:t,site:r,releaseId:s,commit:n}=e;if(!r.repository?.url)throw Error(`Site '${t}' is a PHP/git site but has no repository.url to clone`);let i=e.appBase??`/var/www/${t}`,o="php",a=Lt(i,s),c=r.sharedPaths??po,l=[...c,...kt(r.env,c)],p=r.keepReleases??ai,d=r.deployScript?.length?r.deployScript:Bc(r.type??"laravel"),m=["set -euo pipefail",'export HOME="${HOME:-/root}"','export COMPOSER_HOME="${COMPOSER_HOME:-/root/.composer}"',"export COMPOSER_ALLOW_SUPERUSER=1",ft()];if(m.push(...go(i,{releaseId:s,commit:n,branch:r.repository.branch,keepLogs:p})),m.push(...ci(a,l)),r.env&&Object.keys(r.env).length>0)m.push(...jc(`${a.shared}/.env`,r.env));for(let g of d){let h=g.trim();if(h===Ht)m.push(...Si({repository:r.repository,releaseDir:a.release,commit:n})),m.push(...mo(a,l)),m.push(`cd ${a.release}`),m.push(...Gc(a.release,r.credentials)),m.push(`chown -R www-data:www-data ${a.shared}/storage 2>/dev/null || true`,`[ -d ${a.release}/bootstrap/cache ] && chown -R www-data:www-data ${a.release}/bootstrap/cache 2>/dev/null || true`,`chmod -R ug+rwX ${a.shared}/storage 2>/dev/null || true`);else if(h===Mt)m.push(...Jr(a)),m.push(...Xr(a,p)),m.push(`(cd ${M} && pantry restart php-fpm) 2>/dev/null || true`);else if(h===wi)m.push(`${o} artisan queue:restart || true`);else m.push(Kc(g,o))}return m}var Ut={mysql:{port:3306,binaries:["mysqld","mysql"]},mariadb:{port:3306,binaries:["mariadbd","mariadb","mysqld"]},postgres:{port:5432,binaries:["postgres","psql"]},redis:{port:6379,binaries:["redis-server","redis-cli"]},memcached:{port:11211,binaries:["memcached"]},meilisearch:{port:7700,binaries:["meilisearch"]},vitess:{port:15306,binaries:["vtgate"]}},dt="ts-cloud-service:";function Wc(e){return e===!0||typeof e==="object"&&e!=null}function Ti(e){if(!e)return[];return Object.keys(Ut).filter((t)=>Wc(e[t]))}function Pi(e){if(e.length===0)return[];return[ft(),"ts_cloud_port_open() {",' if command -v ss >/dev/null 2>&1; then ss -ltn 2>/dev/null | grep -qE "[:.]$1[[:space:]]" && return 0; fi',' if command -v netstat >/dev/null 2>&1; then netstat -ltn 2>/dev/null | grep -qE "[:.]$1[[:space:]]" && return 0; fi'," (exec 3<>/dev/tcp/127.0.0.1/$1) 2>/dev/null && { exec 3<&- 3>&-; return 0; }"," return 1","}","ts_cloud_probe() {",' TS_CLOUD_SVC="$1"; TS_CLOUD_PORT="$2"; shift 2',' for TS_CLOUD_BIN in "$@"; do',` if command -v "$TS_CLOUD_BIN" >/dev/null 2>&1; then echo "${dt}$TS_CLOUD_SVC:present"; return 0; fi`," done",` if ts_cloud_port_open "$TS_CLOUD_PORT"; then echo "${dt}$TS_CLOUD_SVC:present"; return 0; fi`,` echo "${dt}$TS_CLOUD_SVC:missing"`," return 0","}",...e.filter((t)=>Ut[t]).map((t)=>`ts_cloud_probe ${t} ${Ut[t].port} ${Ut[t].binaries.join(" ")}`),"exit 0"]}function xi(e,t){if(!e)return[];let r=new Map;for(let s of e.split(`
528
+ `);return[`cat > ${t} <<'TS_CLOUD_DNSCREDS_EOF'`,r,"TS_CLOUD_DNSCREDS_EOF",`chmod 600 ${t}`]}function zc(e){let t=e.dns,r=e.wildcard?[`*.${e.domain}`,e.domain]:[e.domain,...e.aliases||[]].filter(Boolean),s=["certbot","--non-interactive","--agree-tos","--keep-until-expiring"];if(t){let n=hi[t.provider].plugin;if(s.push(`--${n}`),t.provider!=="route53"&&t.credentials)s.push(`--${n}-credentials ${yi(t.provider)}`);if(typeof t.propagationSeconds==="number"&&t.provider!=="route53")s.push(`--${n}-propagation-seconds ${t.propagationSeconds}`);s.push("certonly")}else s.push("--nginx",`--nginx-ctl ${$e}`,e.redirect===!1?"--no-redirect":"--redirect");if(e.email)s.push(`-m ${e.email}`);else s.push("--register-unsafely-without-email");for(let n of r)s.push(`-d ${n}`);return[s.join(" ")]}function fs(e){if(us(e)!=="letsencrypt"||!e.domain)return[];let t=e.ssl,r=t?.dns,s=t?.wildcard===!0;if(s&&!r)return[];return[...Mc(r),...r?Uc(r):[],...zc({domain:e.domain,aliases:e.aliases,email:t?.email,wildcard:s,dns:r})]}function Si(e){let{repository:t,releaseDir:r,commit:s}=e,n=t.branch||"main",i=t.url,o=[`rm -rf ${r}`,`mkdir -p ${r}`];if(t.strategy==="tag")if(t.tag)o.push(`git clone -q --depth 1 --branch ${oe(t.tag)} ${oe(i)} ${r}`),o.push(`printf '%s' ${oe(t.tag)} > ${r}/.ts-cloud-tag`);else{let a=t.tagPattern||"v*";o.push(`TS_CLOUD_TAG="$(git ls-remote --tags --refs --sort=-v:refname ${oe(i)} ${oe(`refs/tags/${a}`)} | head -n1 | sed 's#.*refs/tags/##')"`,`test -n "$TS_CLOUD_TAG" || { echo "no tags matching" ${oe(a)} "found in" ${oe(i)} >&2; exit 1; }`,`git clone -q --depth 1 --branch "$TS_CLOUD_TAG" ${oe(i)} ${r}`,`printf '%s' "$TS_CLOUD_TAG" > ${r}/.ts-cloud-tag`)}else if(s)o.push(`git -C ${r} init -q`,`git -C ${r} remote add origin ${oe(i)}`,`git -C ${r} fetch -q --depth 1 origin ${oe(s)}`,`git -C ${r} checkout -q FETCH_HEAD`);else o.push(`git clone -q --depth 1 --branch ${oe(n)} ${oe(i)} ${r}`);return o.push(`git -C ${r} rev-parse HEAD > ${r}/.ts-cloud-sha`),o}function oe(e){return`'${e.split("'").join("'\\''")}'`}var Ht="$CREATE_RELEASE",Mt="$ACTIVATE_RELEASE",wi="$RESTART_QUEUES",vi="composer install --no-interaction --prefer-dist --optimize-autoloader --no-dev",Fc=["php artisan migrate --force","php artisan config:cache","php artisan route:cache","php artisan view:cache","php artisan event:cache","php artisan storage:link"];function Bc(e){switch(e){case"laravel":case"statamic":return[Ht,vi,...Fc,Mt,wi];case"php":case"wordpress":return[Ht,`${vi} || true`,Mt];case"static":case"spa":return[Ht,Mt]}}function Kc(e,t){return e.replace(/^php\s+/,`${t} `).replace(/(\s)php\s+artisan\s+/g,`$1${t} artisan `)}function jc(e,t){let r=Nt(t);return[`cat > ${e} <<'TS_CLOUD_ENV_EOF'`,r,"TS_CLOUD_ENV_EOF",`chmod 600 ${e}`]}function bi(e,t,r){return[`cat > ${e} <<'${r}'`,t.replace(/\n$/,""),r,`chmod 600 ${e}`]}function Gc(e,t){if(!t)return[];let r=[];if(t.composerAuth){let s=typeof t.composerAuth==="string"?t.composerAuth:JSON.stringify(t.composerAuth,null,2);r.push(...bi(`${e}/auth.json`,s,"TS_CLOUD_AUTHJSON_EOF"))}if(t.npmrc)r.push(...bi(`${e}/.npmrc`,t.npmrc,"TS_CLOUD_NPMRC_EOF"));return r}function $i(e){let t=e.healthCheck?.path;if(!t||!e.domain)return[];let s=`http://127.0.0.1${t.startsWith("/")?t:`/${t}`}`;return[`echo "[ts-cloud] health check ${s} (Host: ${e.domain})"`,"TS_CLOUD_HC_OK=0",`for i in $(seq 1 10); do TS_CLOUD_HC=$(curl -s -o /dev/null -w "%{http_code}" -H "Host: ${e.domain}" -m 10 "${s}" 2>/dev/null || echo 000); case "$TS_CLOUD_HC" in 2*|3*) TS_CLOUD_HC_OK=1; break ;; esac; sleep 3; done`,'[ "$TS_CLOUD_HC_OK" = 1 ] && echo "health check passed ($TS_CLOUD_HC)" || { echo "health check FAILED (last=$TS_CLOUD_HC)" >&2; exit 1; }']}function _i(e){let{siteName:t,site:r,releaseId:s,commit:n}=e;if(!r.repository?.url)throw Error(`Site '${t}' is a PHP/git site but has no repository.url to clone`);let i=e.appBase??`/var/www/${t}`,o="php",a=Lt(i,s),c=r.sharedPaths??po,l=[...c,...kt(r.env,c)],p=r.keepReleases??ai,d=r.deployScript?.length?r.deployScript:Bc(r.type??"laravel"),m=["set -euo pipefail",'export HOME="${HOME:-/root}"','export COMPOSER_HOME="${COMPOSER_HOME:-/root/.composer}"',"export COMPOSER_ALLOW_SUPERUSER=1",ft()];if(m.push(...go(i,{releaseId:s,commit:n,branch:r.repository.branch,keepLogs:p})),m.push(...ci(a,l)),r.env&&Object.keys(r.env).length>0)m.push(...jc(`${a.shared}/.env`,r.env));for(let g of d){let h=g.trim();if(h===Ht)m.push(...Si({repository:r.repository,releaseDir:a.release,commit:n})),m.push(...mo(a,l)),m.push(`cd ${a.release}`),m.push(...Gc(a.release,r.credentials)),m.push(`chown -R www-data:www-data ${a.shared}/storage 2>/dev/null || true`,`[ -d ${a.release}/bootstrap/cache ] && chown -R www-data:www-data ${a.release}/bootstrap/cache 2>/dev/null || true`,`chmod -R ug+rwX ${a.shared}/storage 2>/dev/null || true`);else if(h===Mt)m.push(...Jr(a)),m.push(...Xr(a,p)),m.push(`(cd ${L} && pantry restart php-fpm) 2>/dev/null || true`);else if(h===wi)m.push(`${o} artisan queue:restart || true`);else m.push(Kc(g,o))}return m}var Ut={mysql:{port:3306,binaries:["mysqld","mysql"]},mariadb:{port:3306,binaries:["mariadbd","mariadb","mysqld"]},postgres:{port:5432,binaries:["postgres","psql"]},redis:{port:6379,binaries:["redis-server","redis-cli"]},memcached:{port:11211,binaries:["memcached"]},meilisearch:{port:7700,binaries:["meilisearch"]},vitess:{port:15306,binaries:["vtgate"]}},dt="ts-cloud-service:";function Wc(e){return e===!0||typeof e==="object"&&e!=null}function Ti(e){if(!e)return[];return Object.keys(Ut).filter((t)=>Wc(e[t]))}function Pi(e){if(e.length===0)return[];return[ft(),"ts_cloud_port_open() {",' if command -v ss >/dev/null 2>&1; then ss -ltn 2>/dev/null | grep -qE "[:.]$1[[:space:]]" && return 0; fi',' if command -v netstat >/dev/null 2>&1; then netstat -ltn 2>/dev/null | grep -qE "[:.]$1[[:space:]]" && return 0; fi'," (exec 3<>/dev/tcp/127.0.0.1/$1) 2>/dev/null && { exec 3<&- 3>&-; return 0; }"," return 1","}","ts_cloud_probe() {",' TS_CLOUD_SVC="$1"; TS_CLOUD_PORT="$2"; shift 2',' for TS_CLOUD_BIN in "$@"; do',` if command -v "$TS_CLOUD_BIN" >/dev/null 2>&1; then echo "${dt}$TS_CLOUD_SVC:present"; return 0; fi`," done",` if ts_cloud_port_open "$TS_CLOUD_PORT"; then echo "${dt}$TS_CLOUD_SVC:present"; return 0; fi`,` echo "${dt}$TS_CLOUD_SVC:missing"`," return 0","}",...e.filter((t)=>Ut[t]).map((t)=>`ts_cloud_probe ${t} ${Ut[t].port} ${Ut[t].binaries.join(" ")}`),"exit 0"]}function xi(e,t){if(!e)return[];let r=new Map;for(let s of e.split(`
529
529
  `)){let n=s.indexOf(dt);if(n===-1)continue;let[i,o]=s.slice(n+dt.length).trim().split(":");if(i)r.set(i,o)}return t.filter((s)=>r.get(s)==="missing")}function Ci(e,t,r){let s=r?` on ${r}`:"",n=e.map((o)=>`managedServices.${o}`).join(", "),i=e.length===1?`no ${e[0]}`:`none of ${e.join(", ")}`;return`This project declares ${n}, but '${t}' has ${i}${s}. Attach mode does not provision services on the owner's box, so nothing will install ${e.length===1?"it":"them"}. Point the app at an external service, or ask the owner of '${t}' to add ${e.length===1?"it":"them"} to their own config and re-provision.`}var Ri="/var/lib/pantry/php-fpm/pool.d",Vc=9100,qc=400;function zt(e){return(e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"site").slice(0,28)}function Ei(e){return`web_${zt(e)}`}function Xc(e){let t=zt(e),r=0;for(let s=0;s<t.length;s++)r=r*31+t.charCodeAt(s)>>>0;return Vc+r%qc}function hs(e){return`127.0.0.1:${Xc(e)}`}function Yc(e){let t=zt(e.siteName),r=Ei(e.siteName),s=e.maxChildren??10;return[`; ts-cloud-managed pool for ${e.siteName} (site isolation)`,`[${t}]`,`user = ${r}`,`group = ${r}`,`listen = ${hs(e.siteName)}`,"pm = dynamic",`pm.max_children = ${s}`,"pm.start_servers = 2","pm.min_spare_servers = 1","pm.max_spare_servers = 3","pm.max_requests = 500","catch_workers_output = yes",`php_admin_value[open_basedir] = ${e.appBase}:/tmp`,""].join(`
530
- `)}function Ii(e){let t=Ei(e.siteName),r=zt(e.siteName),s=`${Ri}/${r}.conf`;return[`getent group ${t} >/dev/null || groupadd --system ${t}`,`id -u ${t} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin -g ${t} ${t}`,`usermod -aG ${t} www-data 2>/dev/null || true`,`chown -R ${t}:${t} ${e.appBase} || true`,`chmod -R g+rX ${e.appBase} || true`,`chmod 600 ${e.appBase}/shared/.env 2>/dev/null || true`,`mkdir -p ${Ri}`,`cat > ${s} <<'TS_CLOUD_FPMPOOL_EOF'`,Yc(e).replace(/\n$/,""),"TS_CLOUD_FPMPOOL_EOF",`(cd ${M} && pantry restart php-fpm) 2>/dev/null || true`]}var Bt={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};function el(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function Oi(e,t,r=Bt){let{config:s,environment:n,siteName:i,site:o,slug:a,sha:c,runtime:l,localTarballPath:p}=t,d=`releases/${i}/${c}.tar.gz`,m=E(s,n),g=await e.getComputeOutputs({config:s,environment:n}),h=await e.findComputeTargets({slug:a,environment:n,role:"app",stackName:m});if(h.length===0)return{success:!1,error:e.name==="aws"?`Stack '${m}' has no EC2 instances tagged Project=${a} Environment=${n} Role=app, and storage/cloud/state/${m}.json pins no live instance. For a shared box, record its instanceId there.`:`No Hetzner servers labeled ts-cloud/project=${a} ts-cloud/environment=${n} ts-cloud/role=app, and storage/cloud/state/${m}.json pins no live server. For a shared box, record its serverId there.`};let _=g.servicesPrivateIp?ln(g.servicesPrivateIp,C(s)):Ba(C(s)),w=Os(pi(s,{environment:n})),b=s.infrastructure?.compute,y=Q(b)?{HOST:"127.0.0.1"}:{},T=n==="production"?{APP_ENV:"production",NODE_ENV:"production"}:{},S={..._,...w,...y,...o.env||{},...T},D=Nr(S,o.sharedPaths??[]);if(D.warning)r.warn(`Site '${i}': ${D.warning}`);else if(D.path)r.info(`Site '${i}': sharing '${D.path}' so the SQLite database survives deploys.`);if(ni(o)){let pe=o.phpVersion??b?.php?.default??b?.php?.versions?.[0],N=W(a,i),V=Object.keys(_).length>0?{...o,env:S}:o,I=_i({siteName:i,site:V,releaseId:c,appBase:N,defaultPhpVersion:pe}),L=!Q(b),ae=us(o)==="custom"&&o.ssl?.certPath&&o.ssl?.keyPath?{certPath:o.ssl.certPath,keyPath:o.ssl.keyPath}:void 0,ve=o.isolation?Ii({siteName:i,appBase:N}):[],Ze=L?qt({siteName:i,domain:o.domain||i,aliases:o.aliases,type:o.type,appDir:`${N}/current`,webDirectory:o.webDirectory,phpVersion:pe,fastcgiPass:o.isolation?hs(i):void 0,redirects:o.redirects,ssl:ae,auth:o.auth&&o.auth.enabled!==!1&&o.auth.password?{username:o.auth.username||"admin",password:o.auth.password,realm:o.auth.realm}:void 0,serverSnippet:Vt(o.nginx,b?.nginxTemplates),clientMaxBodySize:o.nginx?.clientMaxBodySize,hsts:o.ssl?.hsts,tlsProtocols:o.ssl?.tlsProtocols,security:o.security}):[],Kt=L?fs(o):[],et=ts(o)?es({slug:a,siteName:i,site:o,phpVersion:pe,appBase:N}):[],to=L?$i(o):[];r.step(`Deploying PHP site '${i}' to ${h.length} target(s)...`);let Ce=await e.runRemoteDeploy({targets:h,commands:[...ws(N,a),...I,...ve,...Ze,...Kt,...et,...to],comment:`ts-cloud deploy ${a}/${i}@${c}`,tags:{Project:a,Environment:n,Role:"app"}}),Ds=Ls(s.notifications,o.notifications);if(!Ce.success)return await Yt(Ds,"deploy-failed",`❌ Deploy of ${a}/${i}@${c} failed: ${Ce.error||"unknown error"}`),{success:!1,error:Ce.error||"Remote PHP deploy failed",instanceCount:Ce.instanceCount,perInstance:Ce.perInstance};let ro=o.domain?` → https://${o.domain}`:"";return await Yt(Ds,"deploy",`✅ Deployed ${a}/${i}@${c}${ro}`),{success:!0,instanceCount:Ce.instanceCount,perInstance:Ce.perInstance}}if(!p)return{success:!1,error:`Site '${i}' requires a release tarball but none was provided`};let O=await e.uploadRelease({config:s,environment:n,localPath:p,remoteKey:d,targets:h}),R=ut(a,i,c),H=e.name==="aws"?Fr(g.deployBucketName,d,s.project.region||"us-east-1",R):Br(O.artifactRef,R),ne=P(o),z=W(a,i),X=ne==="server-static"?Ur({siteName:i,slug:a,appDir:z,artifactFetch:H,releaseId:c,preStartCommands:o.preStart}):Mr({siteName:i,slug:a,appDir:z,artifactFetch:H,releaseId:c,execStart:Lr(o.start,l,`${z.replace(/\/+$/,"")}/releases/%i`),envEntries:S,port:o.port,preStartCommands:o.preStart,sharedPaths:o.sharedPaths,zeroDowntime:o.zeroDowntime!==!1,healthCheckPath:o.healthCheck?.path,memoryHigh:o.memoryHigh,memoryMax:o.memoryMax,cpuWeight:o.cpuWeight,ioWeight:o.ioWeight,tasksMax:o.tasksMax,stopTimeout:o.stopTimeout}),Y=ne==="server-static"&&!Q(b)&&!!o.domain,F=Y?qt({siteName:i,domain:o.domain,aliases:o.aliases,type:o.type==="spa"?"spa":"static",appDir:`${z}/current`,webDirectory:"",redirects:o.redirects,auth:o.auth&&o.auth.enabled!==!1&&o.auth.password?{username:o.auth.username||"admin",password:o.auth.password,realm:o.auth.realm}:void 0,serverSnippet:Vt(o.nginx,b?.nginxTemplates),clientMaxBodySize:o.nginx?.clientMaxBodySize,hsts:o.ssl?.hsts,tlsProtocols:o.ssl?.tlsProtocols,security:o.security}):[],ee=Y?fs(o):[],k=ts(o)?es({slug:a,siteName:i,site:o,appBase:z}):[],ye=[...go(z,{releaseId:c,commit:c,branch:o.repository?.branch??"main"}),...ws(z,a),...X,...F,...ee,...k,...Kr()];r.step(`Deploying to ${h.length} target(s)...`);let G=await e.runRemoteDeploy({targets:h,commands:ye,comment:`ts-cloud deploy ${a}/${i}@${c}`,tags:{Project:a,Environment:n,Role:"app"}});if(!G.success)return{success:!1,error:G.error||"Remote deploy failed",instanceCount:G.instanceCount,perInstance:G.perInstance};return{success:!0,instanceCount:G.instanceCount,perInstance:G.perInstance}}function Ft(e){return`'${e.replaceAll("'","'\\''")}'`}function tl(e,t,r=!1,s=[]){let n=`${e}-dashboard-`,i=t.map((a)=>`${e}-${a}.service`),o=r?[`export TS_CLOUD_DASHBOARD_KEEP_DOMAINS=${Ft(JSON.stringify(s))}`,"rm -f /run/ts-cloud-dashboard-routes-changed",`/usr/local/bin/bun --bun -e ${Ft(`
530
+ `)}function Ii(e){let t=Ei(e.siteName),r=zt(e.siteName),s=`${Ri}/${r}.conf`;return[`getent group ${t} >/dev/null || groupadd --system ${t}`,`id -u ${t} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin -g ${t} ${t}`,`usermod -aG ${t} www-data 2>/dev/null || true`,`chown -R ${t}:${t} ${e.appBase} || true`,`chmod -R g+rX ${e.appBase} || true`,`chmod 600 ${e.appBase}/shared/.env 2>/dev/null || true`,`mkdir -p ${Ri}`,`cat > ${s} <<'TS_CLOUD_FPMPOOL_EOF'`,Yc(e).replace(/\n$/,""),"TS_CLOUD_FPMPOOL_EOF",`(cd ${L} && pantry restart php-fpm) 2>/dev/null || true`]}var Bt={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};function el(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function Oi(e,t,r=Bt){let{config:s,environment:n,siteName:i,site:o,slug:a,sha:c,runtime:l,localTarballPath:p}=t,d=`releases/${i}/${c}.tar.gz`,m=E(s,n),g=await e.getComputeOutputs({config:s,environment:n}),h=await e.findComputeTargets({slug:a,environment:n,role:"app",stackName:m});if(h.length===0)return{success:!1,error:e.name==="aws"?`Stack '${m}' has no EC2 instances tagged Project=${a} Environment=${n} Role=app, and storage/cloud/state/${m}.json pins no live instance. For a shared box, record its instanceId there.`:`No Hetzner servers labeled ts-cloud/project=${a} ts-cloud/environment=${n} ts-cloud/role=app, and storage/cloud/state/${m}.json pins no live server. For a shared box, record its serverId there.`};let _=g.servicesPrivateIp?ln(g.servicesPrivateIp,C(s)):Ba(C(s)),w=Os(pi(s,{environment:n})),b=s.infrastructure?.compute,y=Q(b)?{HOST:"127.0.0.1"}:{},T=n==="production"?{APP_ENV:"production",NODE_ENV:"production"}:{},S={..._,...w,...y,...o.env||{},...T},D=Nr(S,o.sharedPaths??[]);if(D.warning)r.warn(`Site '${i}': ${D.warning}`);else if(D.path)r.info(`Site '${i}': sharing '${D.path}' so the SQLite database survives deploys.`);if(ni(o)){let pe=o.phpVersion??b?.php?.default??b?.php?.versions?.[0],N=W(a,i),V=Object.keys(_).length>0?{...o,env:S}:o,I=_i({siteName:i,site:V,releaseId:c,appBase:N,defaultPhpVersion:pe}),M=!Q(b),ae=us(o)==="custom"&&o.ssl?.certPath&&o.ssl?.keyPath?{certPath:o.ssl.certPath,keyPath:o.ssl.keyPath}:void 0,ve=o.isolation?Ii({siteName:i,appBase:N}):[],Ze=M?qt({siteName:i,domain:o.domain||i,aliases:o.aliases,type:o.type,appDir:`${N}/current`,webDirectory:o.webDirectory,phpVersion:pe,fastcgiPass:o.isolation?hs(i):void 0,redirects:o.redirects,ssl:ae,auth:o.auth&&o.auth.enabled!==!1&&o.auth.password?{username:o.auth.username||"admin",password:o.auth.password,realm:o.auth.realm}:void 0,serverSnippet:Vt(o.nginx,b?.nginxTemplates),clientMaxBodySize:o.nginx?.clientMaxBodySize,hsts:o.ssl?.hsts,tlsProtocols:o.ssl?.tlsProtocols,security:o.security}):[],Kt=M?fs(o):[],et=ts(o)?es({slug:a,siteName:i,site:o,phpVersion:pe,appBase:N}):[],to=M?$i(o):[];r.step(`Deploying PHP site '${i}' to ${h.length} target(s)...`);let Ce=await e.runRemoteDeploy({targets:h,commands:[...ws(N,a),...I,...ve,...Ze,...Kt,...et,...to],comment:`ts-cloud deploy ${a}/${i}@${c}`,tags:{Project:a,Environment:n,Role:"app"}}),Ds=Ls(s.notifications,o.notifications);if(!Ce.success)return await Yt(Ds,"deploy-failed",`❌ Deploy of ${a}/${i}@${c} failed: ${Ce.error||"unknown error"}`),{success:!1,error:Ce.error||"Remote PHP deploy failed",instanceCount:Ce.instanceCount,perInstance:Ce.perInstance};let ro=o.domain?` → https://${o.domain}`:"";return await Yt(Ds,"deploy",`✅ Deployed ${a}/${i}@${c}${ro}`),{success:!0,instanceCount:Ce.instanceCount,perInstance:Ce.perInstance}}if(!p)return{success:!1,error:`Site '${i}' requires a release tarball but none was provided`};let O=await e.uploadRelease({config:s,environment:n,localPath:p,remoteKey:d,targets:h}),R=ut(a,i,c),H=e.name==="aws"?Fr(g.deployBucketName,d,s.project.region||"us-east-1",R):Br(O.artifactRef,R),ne=P(o),z=W(a,i),X=ne==="server-static"?Ur({siteName:i,slug:a,appDir:z,artifactFetch:H,releaseId:c,preStartCommands:o.preStart}):Mr({siteName:i,slug:a,appDir:z,artifactFetch:H,releaseId:c,execStart:Lr(o.start,l,`${z.replace(/\/+$/,"")}/releases/%i`),envEntries:S,port:o.port,preStartCommands:o.preStart,sharedPaths:o.sharedPaths,zeroDowntime:o.zeroDowntime!==!1,healthCheckPath:o.healthCheck?.path,memoryHigh:o.memoryHigh,memoryMax:o.memoryMax,cpuWeight:o.cpuWeight,ioWeight:o.ioWeight,tasksMax:o.tasksMax,stopTimeout:o.stopTimeout}),Y=ne==="server-static"&&!Q(b)&&!!o.domain,F=Y?qt({siteName:i,domain:o.domain,aliases:o.aliases,type:o.type==="spa"?"spa":"static",appDir:`${z}/current`,webDirectory:"",redirects:o.redirects,auth:o.auth&&o.auth.enabled!==!1&&o.auth.password?{username:o.auth.username||"admin",password:o.auth.password,realm:o.auth.realm}:void 0,serverSnippet:Vt(o.nginx,b?.nginxTemplates),clientMaxBodySize:o.nginx?.clientMaxBodySize,hsts:o.ssl?.hsts,tlsProtocols:o.ssl?.tlsProtocols,security:o.security}):[],ee=Y?fs(o):[],k=ts(o)?es({slug:a,siteName:i,site:o,appBase:z}):[],ye=[...go(z,{releaseId:c,commit:c,branch:o.repository?.branch??"main"}),...ws(z,a),...X,...F,...ee,...k,...Kr()];r.step(`Deploying to ${h.length} target(s)...`);let G=await e.runRemoteDeploy({targets:h,commands:ye,comment:`ts-cloud deploy ${a}/${i}@${c}`,tags:{Project:a,Environment:n,Role:"app"}});if(!G.success)return{success:!1,error:G.error||"Remote deploy failed",instanceCount:G.instanceCount,perInstance:G.perInstance};return{success:!0,instanceCount:G.instanceCount,perInstance:G.perInstance}}function Ft(e){return`'${e.replaceAll("'","'\\''")}'`}function tl(e,t,r=!1,s=[]){let n=`${e}-dashboard-`,i=t.map((a)=>`${e}-${a}.service`),o=r?[`export TS_CLOUD_DASHBOARD_KEEP_DOMAINS=${Ft(JSON.stringify(s))}`,"rm -f /run/ts-cloud-dashboard-routes-changed",`/usr/local/bin/bun --bun -e ${Ft(`
531
531
  const { chmodSync, existsSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } = require('node:fs')
532
532
  const { basename, join } = require('node:path')
533
533
  const root = '/etc/rpx/sites.d'
@@ -1,4 +1,4 @@
1
- import{u}from"./chunk-pdw0qjq1.js";class O{client;region;constructor(e="us-east-1"){this.region=e,this.client=new u}async createHostedZone(e){let t=e.CallerReference||`${Date.now()}-${Math.random().toString(36).slice(2)}`,o=`<?xml version="1.0" encoding="UTF-8"?>
1
+ import{u}from"./chunk-pdw0qjq1.js";class M{client;region;constructor(e="us-east-1"){this.region=e,this.client=new u}async createHostedZone(e){let t=e.CallerReference||`${Date.now()}-${Math.random().toString(36).slice(2)}`,o=`<?xml version="1.0" encoding="UTF-8"?>
2
2
  <CreateHostedZoneRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
3
3
  <Name>${e.Name}</Name>
4
4
  <CallerReference>${t}</CallerReference>`;if(e.HostedZoneConfig){if(o+=`
@@ -47,4 +47,4 @@ import{u}from"./chunk-pdw0qjq1.js";class O{client;region;constructor(e="us-east-
47
47
  </Changes>
48
48
  </ChangeBatch>
49
49
  </ChangeResourceRecordSetsRequest>`;let n=await this.client.request({service:"route53",region:this.region,method:"POST",path:`/2013-04-01/hostedzone/${t}/rrset`,headers:{"content-type":"application/xml"},body:o});return this.parseChangeResourceRecordSetsResponse(n)}escapeXml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}parseCreateHostedZoneResponse(e){let t=e.CreateHostedZoneResponse||e;return{HostedZone:this.parseHostedZone(t.HostedZone),ChangeInfo:{Id:t.ChangeInfo?.Id||"",Status:t.ChangeInfo?.Status||"",SubmittedAt:t.ChangeInfo?.SubmittedAt||""},DelegationSet:this.parseDelegationSet(t.DelegationSet),Location:t.Location||""}}parseListHostedZonesResponse(e){let t=e.ListHostedZonesResponse||e.ListHostedZonesByNameResponse||e,o=t.HostedZones?.HostedZone||t.HostedZones||[];if(!Array.isArray(o))o=o?[o]:[];return{HostedZones:o.map((n)=>this.parseHostedZone(n)),IsTruncated:t.IsTruncated==="true"||t.IsTruncated===!0,MaxItems:t.MaxItems||"100",Marker:t.Marker,NextMarker:t.NextMarker}}parseGetHostedZoneResponse(e){let t=e.GetHostedZoneResponse||e;return{HostedZone:this.parseHostedZone(t.HostedZone),DelegationSet:this.parseDelegationSet(t.DelegationSet),VPCs:t.VPCs?.VPC?Array.isArray(t.VPCs.VPC)?t.VPCs.VPC:[t.VPCs.VPC]:void 0}}parseListResourceRecordSetsResponse(e){let t=e.ListResourceRecordSetsResponse||e,o=t.ResourceRecordSets?.ResourceRecordSet||t.ResourceRecordSets||[];if(!Array.isArray(o))o=o?[o]:[];return{ResourceRecordSets:o.map((n)=>this.parseResourceRecordSet(n)),IsTruncated:t.IsTruncated==="true"||t.IsTruncated===!0,MaxItems:t.MaxItems||"100",NextRecordName:t.NextRecordName,NextRecordType:t.NextRecordType,NextRecordIdentifier:t.NextRecordIdentifier}}parseChangeResourceRecordSetsResponse(e){let t=e.ChangeResourceRecordSetsResponse||e;return{ChangeInfo:{Id:t.ChangeInfo?.Id||"",Status:t.ChangeInfo?.Status||"",SubmittedAt:t.ChangeInfo?.SubmittedAt||"",Comment:t.ChangeInfo?.Comment}}}parseHostedZone(e){if(!e)return{Id:"",Name:""};return{Id:e.Id||"",Name:e.Name||"",CallerReference:e.CallerReference,Config:e.Config?{Comment:e.Config.Comment,PrivateZone:e.Config.PrivateZone==="true"||e.Config.PrivateZone===!0}:void 0,ResourceRecordSetCount:e.ResourceRecordSetCount?Number(e.ResourceRecordSetCount):void 0}}parseDelegationSet(e){if(!e)return{NameServers:[]};let t=e.NameServers?.NameServer||e.NameServers||[];if(!Array.isArray(t))t=t?[t]:[];return{Id:e.Id,CallerReference:e.CallerReference,NameServers:t}}parseResourceRecordSet(e){if(!e)return{Name:"",Type:""};let t=e.ResourceRecords?.ResourceRecord||e.ResourceRecords||[];if(!Array.isArray(t))t=t?[t]:[];return{Name:e.Name||"",Type:e.Type||"",TTL:e.TTL?Number(e.TTL):void 0,ResourceRecords:t.map((o)=>({Value:o.Value||o})),AliasTarget:e.AliasTarget?{HostedZoneId:e.AliasTarget.HostedZoneId,DNSName:e.AliasTarget.DNSName,EvaluateTargetHealth:e.AliasTarget.EvaluateTargetHealth==="true"||e.AliasTarget.EvaluateTargetHealth===!0}:void 0,SetIdentifier:e.SetIdentifier,Weight:e.Weight?Number(e.Weight):void 0,Region:e.Region,GeoLocation:e.GeoLocation,Failover:e.Failover,HealthCheckId:e.HealthCheckId}}async findHostedZoneByName(e){let t=e.endsWith(".")?e:`${e}.`;return(await this.listHostedZonesByName({DNSName:t})).HostedZones.find((s)=>s.Name===t)||null}async createARecord(e){let t=Array.isArray(e.Value)?e.Value:[e.Value];return this.changeResourceRecordSets({HostedZoneId:e.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:e.Name,Type:"A",TTL:e.TTL||300,ResourceRecords:t.map((o)=>({Value:o}))}}]}})}async createCnameRecord(e){return this.changeResourceRecordSets({HostedZoneId:e.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:e.Name,Type:"CNAME",TTL:e.TTL||300,ResourceRecords:[{Value:e.Value}]}}]}})}async createAliasRecord(e){return this.changeResourceRecordSets({HostedZoneId:e.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:e.Name,Type:e.Type||"A",AliasTarget:{HostedZoneId:e.TargetHostedZoneId,DNSName:e.TargetDNSName,EvaluateTargetHealth:e.EvaluateTargetHealth??!1}}}]}})}async createTxtRecord(e){let o=(Array.isArray(e.Value)?e.Value:[e.Value]).map((n)=>{if(!n.startsWith('"'))return`"${n}"`;return n});return this.changeResourceRecordSets({HostedZoneId:e.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:e.Name,Type:"TXT",TTL:e.TTL||300,ResourceRecords:o.map((n)=>({Value:n}))}}]}})}async createMxRecord(e){return this.changeResourceRecordSets({HostedZoneId:e.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:e.Name,Type:"MX",TTL:e.TTL||300,ResourceRecords:e.Values.map((t)=>({Value:`${t.priority} ${t.mailServer}`}))}}]}})}async deleteRecord(e){return this.changeResourceRecordSets({HostedZoneId:e.HostedZoneId,ChangeBatch:{Changes:[{Action:"DELETE",ResourceRecordSet:e.RecordSet}]}})}async waitForChange(e,t=60,o=5000){let n=e.replace("/change/","");for(let s=0;s<t;s++){let r=await this.client.request({service:"route53",region:this.region,method:"GET",path:`/2013-04-01/change/${n}`});if((r.GetChangeResponse?.ChangeInfo?.Status||r.ChangeInfo?.Status)==="INSYNC")return!0;await new Promise((a)=>setTimeout(a,o))}return!1}async findOrCreateHostedZone(e){let t=e.domainName.endsWith(".")?e.domainName:`${e.domainName}.`,o=await this.findHostedZoneByName(t);if(o){let s=await this.getHostedZone({Id:o.Id});return{hostedZone:o,nameServers:s.DelegationSet.NameServers,isNew:!1}}let n=await this.createHostedZone({Name:t,HostedZoneConfig:{Comment:e.comment||`Hosted zone for ${e.domainName}`,PrivateZone:e.privateZone},VPC:e.vpc});return{hostedZone:n.HostedZone,nameServers:n.DelegationSet.NameServers,isNew:!0}}static getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length<=2)return e;return t.slice(-2).join(".")}async findHostedZoneForDomain(e){let o=e.replace(/\.$/,"").split(".");for(let n=0;n<o.length-1;n++){let s=o.slice(n).join("."),r=await this.findHostedZoneByName(s);if(r)return r}return null}async ensureHostedZone(e){let t=await this.findOrCreateHostedZone({domainName:e.domainName,comment:e.comment});return{hostedZoneId:t.hostedZone.Id.replace("/hostedzone/",""),nameServers:t.nameServers,isNew:t.isNew,action:t.isNew?"created":"found"}}async setupDomainDns(e){let{domain:t,createIfNotExists:o=!0}=e,n=await this.findHostedZoneByName(t);if(n){let r=await this.getHostedZone({Id:n.Id});return{success:!0,hostedZoneId:n.Id.replace("/hostedzone/",""),nameServers:r.DelegationSet.NameServers,isNew:!1,message:`Found existing hosted zone for ${t}`}}if(!o)return{success:!1,hostedZoneId:null,nameServers:[],isNew:!1,message:`No hosted zone found for ${t} and createIfNotExists is false`};let s=await this.createHostedZone({Name:t,HostedZoneConfig:{Comment:`Created automatically by ts-cloud for ${t}`}});return{success:!0,hostedZoneId:s.HostedZone.Id.replace("/hostedzone/",""),nameServers:s.DelegationSet.NameServers,isNew:!0,message:`Created new hosted zone for ${t}. Please update your domain registrar with these name servers: ${s.DelegationSet.NameServers.join(", ")}`}}static CloudFrontHostedZoneId="Z2FDTNDATAQYW2";static S3WebsiteHostedZoneIds={"us-east-1":"Z3AQBSTGFYJSTF","us-east-2":"Z2O1EMRO9K5GLX","us-west-1":"Z2F56UZL2M1ACD","us-west-2":"Z3BJ6K6RIION7M","ap-east-1":"ZNB98KWMFR0R6","ap-south-1":"Z11RGJOFQNVJUP","ap-northeast-1":"Z2M4EHUR26P7ZW","ap-northeast-2":"Z3W03O7B5YMIYP","ap-northeast-3":"Z2YQB5RD63NC85","ap-southeast-1":"Z3O0J2DXBE1FTB","ap-southeast-2":"Z1WCIGYICN2BYD","ca-central-1":"Z1QDHH18159H29","eu-central-1":"Z21DNDUVLTQW6Q","eu-west-1":"Z1BKCTXD74EZPE","eu-west-2":"Z3GKZC51ZF0DB4","eu-west-3":"Z3R1K369G5AVDG","eu-north-1":"Z3BAZG2TWCNX0D","sa-east-1":"Z7KQH4QJS55SO"};static ALBHostedZoneIds={"us-east-1":"Z35SXDOTRQ7X7K","us-east-2":"Z3AADJGX6KTTL2","us-west-1":"Z368ELLRRE2KJ0","us-west-2":"Z1H1FL5HABSF5","ap-east-1":"Z3DQVH9N71FHZ0","ap-south-1":"ZP97RAFLXTNZK","ap-northeast-1":"Z14GRHDCWA56QT","ap-northeast-2":"ZWKZPGTI48KDX","ap-northeast-3":"Z5LXEBD8Y73MNV","ap-southeast-1":"Z1LMS91P8CMLE5","ap-southeast-2":"Z1GM3OXH4ZPM65","ca-central-1":"ZQSVJUPU6J1EY","eu-central-1":"Z215JYRZR1TBD5","eu-west-1":"Z32O12XQLNTSW2","eu-west-2":"ZHURV8PSTC4K8","eu-west-3":"Z3Q77PNBQS71R4","eu-north-1":"Z23TAZ6LKFMNIO","sa-east-1":"Z2P70J7HTTTPLU"};static APIGatewayHostedZoneIds={"us-east-1":"Z1UJRXOUMOOFQ8","us-east-2":"ZOJJZC49E0EPZ","us-west-1":"Z2MUQ32089INYE","us-west-2":"Z2OJLYMUO9EFXC","ap-east-1":"Z3FD1VL90ND7K5","ap-south-1":"Z3VO1THU9YC4UR","ap-northeast-1":"Z1YSHQZHG15GKL","ap-northeast-2":"Z20JF4UZKIW1U8","ap-northeast-3":"Z2YQB5RD63NC85","ap-southeast-1":"ZL327KTPIQFUL","ap-southeast-2":"Z2RPCDW04V8134","ca-central-1":"Z19DQILCV0OWEC","eu-central-1":"Z1U9ULNL0V5AJ3","eu-west-1":"ZLY8HYME6SFDD","eu-west-2":"ZJ5UAJN8Y3Z2Q","eu-west-3":"Z3KY65QIEKYHQQ","eu-north-1":"Z3UWIKFBOOGXPP","sa-east-1":"ZCMLWB8V5SYIT"}}
50
- export{O};
50
+ export{M};
@@ -1 +1 @@
1
- import{za,Ou}from"./chunk-b48j6k55.js";import"./chunk-p197a99s.js";import"./chunk-k3er0h4j.js";import"./chunk-pdw0qjq1.js";export{za as EmailClient,Ou as email};
1
+ import{za,Ou}from"./chunk-deb7ws59.js";import"./chunk-rs2d8nj2.js";import"./chunk-k3er0h4j.js";import"./chunk-pdw0qjq1.js";export{za as EmailClient,Ou as email};
@@ -0,0 +1 @@
1
+ import{Xo,Iu,Ru,Qo}from"./chunk-gky64tr9.js";import"./chunk-vfmad47g.js";import"./chunk-gxwsq3k0.js";export{Iu as getComputeDeployHistory,Qo as restoreDatabaseBackup,Xo as rollbackComputeSite,Ru as runComputeRecipe};