@stacksjs/ts-cloud 0.16.57 → 0.16.58

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 (93) hide show
  1. package/dist/bin/{chunk-8nfrknq3.js → chunk-0vfw6xy0.js} +1 -1
  2. package/dist/bin/{chunk-1q6wqzh1.js → chunk-1gznb7bh.js} +3 -3
  3. package/dist/bin/chunk-32nkkq9k.js +1 -0
  4. package/dist/bin/chunk-37aphhk9.js +3 -0
  5. package/dist/bin/{chunk-6sfn8fjv.js → chunk-4fkmd2ce.js} +1 -1
  6. package/dist/bin/{chunk-tbp1gf1p.js → chunk-5mnfp9ae.js} +1 -1
  7. package/dist/bin/chunk-5wz1e4ne.js +1 -0
  8. package/dist/bin/chunk-71vhvzhv.js +1 -0
  9. package/dist/bin/{chunk-jxm62h8r.js → chunk-8t01yv89.js} +1 -1
  10. package/dist/bin/{chunk-s59x3psv.js → chunk-9292d4yb.js} +34 -34
  11. package/dist/bin/{chunk-sbate1ky.js → chunk-agakphd1.js} +1 -1
  12. package/dist/bin/{chunk-k1kk78qg.js → chunk-ebhfg18g.js} +4 -4
  13. package/dist/bin/{chunk-1cccv502.js → chunk-enmw6v4x.js} +1 -1
  14. package/dist/bin/{chunk-8fh0gv4q.js → chunk-gvv4hn0h.js} +1 -1
  15. package/dist/bin/{chunk-s98wngxx.js → chunk-nnrta1g9.js} +1 -1
  16. package/dist/bin/{chunk-mn3x457v.js → chunk-p1eqv66t.js} +73 -73
  17. package/dist/bin/{chunk-dg8ceycc.js → chunk-qvrfaeqq.js} +7 -7
  18. package/dist/bin/chunk-sgkyg842.js +1 -0
  19. package/dist/bin/{chunk-rqvrjp8g.js → chunk-t8qzx4ka.js} +21 -21
  20. package/dist/bin/{chunk-v9js2b1d.js → chunk-tdftrmyx.js} +1 -1
  21. package/dist/bin/{chunk-hkx5j0bn.js → chunk-vmrkqtch.js} +1 -1
  22. package/dist/bin/{chunk-bn2sn094.js → chunk-wg9zm31f.js} +1 -1
  23. package/dist/bin/{chunk-jyvr7eh5.js → chunk-wzpsq446.js} +1 -1
  24. package/dist/bin/{chunk-e3zsrpbj.js → chunk-yn3499yh.js} +1 -1
  25. package/dist/bin/{chunk-28124w0n.js → chunk-zp1cxtbh.js} +1 -1
  26. package/dist/bin/{chunk-ek27709c.js → chunk-zpjy26jk.js} +3 -3
  27. package/dist/bin/cli.js +211 -211
  28. package/dist/bin/dashboard-server.js +1 -1
  29. package/dist/{chunk-r3qpx6xp.js → chunk-4f0b21fp.js} +2 -2
  30. package/dist/deploy/index.js +1 -1
  31. package/dist/drivers/shared/compute-ops.d.ts +6 -3
  32. package/dist/index.js +1 -1
  33. package/dist/mail/index.js +2 -2
  34. package/dist/ui/404.html +1 -1
  35. package/dist/ui/accept-invitation.html +1 -1
  36. package/dist/ui/access-denied.html +1 -1
  37. package/dist/ui/account/automation.html +6 -6
  38. package/dist/ui/account/security.html +2 -2
  39. package/dist/ui/applications/compose.html +6 -6
  40. package/dist/ui/applications/new.html +2 -2
  41. package/dist/ui/data/backups.html +6 -6
  42. package/dist/ui/data/services.html +6 -6
  43. package/dist/ui/data/volumes.html +6 -6
  44. package/dist/ui/index.html +6 -6
  45. package/dist/ui/infrastructure/topology.html +6 -6
  46. package/dist/ui/integrations.html +2 -2
  47. package/dist/ui/operations/alerts.html +6 -6
  48. package/dist/ui/operations/configuration.html +6 -6
  49. package/dist/ui/operations/jobs.html +5 -5
  50. package/dist/ui/operations/maintenance.html +5 -5
  51. package/dist/ui/operations/observability.html +6 -6
  52. package/dist/ui/operations/previews.html +6 -6
  53. package/dist/ui/operations/queue.html +5 -5
  54. package/dist/ui/operations/regions.html +5 -5
  55. package/dist/ui/operations/releases.html +6 -6
  56. package/dist/ui/operations/spend.html +6 -6
  57. package/dist/ui/operations/workloads.html +6 -6
  58. package/dist/ui/security.html +2 -2
  59. package/dist/ui/server/actions.html +6 -6
  60. package/dist/ui/server/activity.html +2 -2
  61. package/dist/ui/server/capacity.html +6 -6
  62. package/dist/ui/server/database.html +5 -5
  63. package/dist/ui/server/deployments.html +5 -5
  64. package/dist/ui/server/diagnostics.html +1 -1
  65. package/dist/ui/server/firewall.html +5 -5
  66. package/dist/ui/server/fleet.html +6 -6
  67. package/dist/ui/server/logs.html +5 -5
  68. package/dist/ui/server/metrics.html +5 -5
  69. package/dist/ui/server/security.html +2 -2
  70. package/dist/ui/server/services.html +2 -2
  71. package/dist/ui/server/sites.html +6 -6
  72. package/dist/ui/server/ssh-keys.html +6 -6
  73. package/dist/ui/server/team.html +6 -6
  74. package/dist/ui/server/terminal.html +2 -2
  75. package/dist/ui/serverless/alarms.html +6 -6
  76. package/dist/ui/serverless/assets.html +2 -2
  77. package/dist/ui/serverless/cost.html +2 -2
  78. package/dist/ui/serverless/data.html +6 -6
  79. package/dist/ui/serverless/deployments.html +2 -2
  80. package/dist/ui/serverless/firewall.html +1 -1
  81. package/dist/ui/serverless/functions.html +5 -5
  82. package/dist/ui/serverless/logs.html +6 -6
  83. package/dist/ui/serverless/metrics.html +2 -2
  84. package/dist/ui/serverless/queues.html +5 -5
  85. package/dist/ui/serverless/secrets.html +6 -6
  86. package/dist/ui/serverless/traces.html +6 -6
  87. package/dist/ui/serverless.html +6 -6
  88. package/package.json +3 -3
  89. package/dist/bin/chunk-6tdt3ea9.js +0 -1
  90. package/dist/bin/chunk-cdseg15k.js +0 -3
  91. package/dist/bin/chunk-et6hzqpx.js +0 -1
  92. package/dist/bin/chunk-gx5wqrgh.js +0 -1
  93. package/dist/bin/chunk-pexjxc5g.js +0 -1
@@ -1,4 +1,4 @@
1
- import{p}from"./chunk-0xfy78nc.js";import{ca,A,w,ne,Fr,da,qo,le,B,T,Jt,Br}from"./chunk-rqvrjp8g.js";import{v}from"./chunk-rbyrd9we.js";import{Q}from"./chunk-9t78j764.js";import{g}from"./chunk-7cactd6c.js";import{J,Di,Gs,I,U,kr,Ct,nt,Lo,ki,Uo,Tt,Gc,Fo,Bo,_i,jo,Ht,Xs,Wc,Oi,Qs,Ys,Zs,ea,Vo,hn,ta,yn,ra,zo}from"./chunk-k1kk78qg.js";import{ko,No,$s}from"./chunk-1q6wqzh1.js";import{fs}from"./chunk-q0takzyx.js";import{an}from"./chunk-p6qa21fr.js";import{wr}from"./chunk-bzzwbkrx.js";class We{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new p}async putParameter(e){let t={Name:e.Name,Value:e.Value};if(e.Type)t.Type=e.Type;if(e.Description)t.Description=e.Description;if(e.KeyId)t.KeyId=e.KeyId;if(e.Overwrite!==void 0)t.Overwrite=e.Overwrite;if(e.AllowedPattern)t.AllowedPattern=e.AllowedPattern;if(e.Tags&&e.Tags.length>0)t.Tags=e.Tags;if(e.Tier)t.Tier=e.Tier;if(e.DataType)t.DataType=e.DataType;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.PutParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Version:r.Version,Tier:r.Tier}}async getParameter(e){let t={Name:e.Name};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameter:r.Parameter?this.parseParameter(r.Parameter):void 0}}async getParameters(e){let t={Names:e.Names};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:r.Parameters?.map((n)=>this.parseParameter(n)),InvalidParameters:r.InvalidParameters}}async getParametersByPath(e){let t={Path:e.Path};if(e.Recursive!==void 0)t.Recursive=e.Recursive;if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;if(e.MaxResults)t.MaxResults=e.MaxResults;if(e.NextToken)t.NextToken=e.NextToken;if(e.ParameterFilters&&e.ParameterFilters.length>0)t.ParameterFilters=e.ParameterFilters;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParametersByPath","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:r.Parameters?.map((n)=>this.parseParameter(n)),NextToken:r.NextToken}}async deleteParameter(e){let t={Name:e.Name};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DeleteParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async deleteParameters(e){let t={Names:e},r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DeleteParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{DeletedParameters:r.DeletedParameters,InvalidParameters:r.InvalidParameters}}async describeParameters(e){let t={};if(e?.Filters&&e.Filters.length>0)t.Filters=e.Filters;if(e?.ParameterFilters&&e.ParameterFilters.length>0)t.ParameterFilters=e.ParameterFilters;if(e?.MaxResults)t.MaxResults=e.MaxResults;if(e?.NextToken)t.NextToken=e.NextToken;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DescribeParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:r.Parameters?.map((n)=>this.parseParameter(n)),NextToken:r.NextToken}}async getParameterHistory(e){let t={Name:e.Name};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;if(e.MaxResults)t.MaxResults=e.MaxResults;if(e.NextToken)t.NextToken=e.NextToken;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameterHistory","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:r.Parameters?.map((n)=>({Name:n.Name,Type:n.Type,KeyId:n.KeyId,LastModifiedDate:n.LastModifiedDate,LastModifiedUser:n.LastModifiedUser,Description:n.Description,Value:n.Value,Version:n.Version,Labels:n.Labels,Tier:n.Tier})),NextToken:r.NextToken}}async labelParameterVersion(e){let t={Name:e.Name,Labels:e.Labels};if(e.ParameterVersion!==void 0)t.ParameterVersion=e.ParameterVersion;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.LabelParameterVersion","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{InvalidLabels:r.InvalidLabels,ParameterVersion:r.ParameterVersion}}async addTagsToResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId,Tags:e.Tags};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.AddTagsToResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async removeTagsFromResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId,TagKeys:e.TagKeys};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.RemoveTagsFromResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async listTagsForResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId};return{TagList:(await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.ListTagsForResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})).TagList}}async setString(e,t,r){return this.putParameter({Name:e,Value:t,Type:"String",Description:r?.description,Overwrite:r?.overwrite??!0,Tags:r?.tags})}async setSecureString(e,t,r){return this.putParameter({Name:e,Value:t,Type:"SecureString",Description:r?.description,Overwrite:r?.overwrite??!0,KeyId:r?.kmsKeyId,Tags:r?.tags})}async getValue(e){return(await this.getParameter({Name:e,WithDecryption:!0})).Parameter?.Value}async getAllByPath(e,t=!0){let r=[],n;do{let s=await this.getParametersByPath({Path:e,Recursive:t,WithDecryption:!0,NextToken:n});if(s.Parameters)r.push(...s.Parameters);n=s.NextToken}while(n);return r}parseParameter(e){return{Name:e.Name,Type:e.Type,Value:e.Value,Version:e.Version,LastModifiedDate:e.LastModifiedDate,ARN:e.ARN,DataType:e.DataType,Description:e.Description,AllowedPattern:e.AllowedPattern,KeyId:e.KeyId,Tier:e.Tier}}async sendCommand(e){if(!e.InstanceIds&&!e.Targets)throw Error("SendCommand requires either InstanceIds or Targets");let t={DocumentName:e.DocumentName};if(e.InstanceIds)t.InstanceIds=e.InstanceIds;if(e.Targets)t.Targets=e.Targets;if(e.Parameters)t.Parameters=e.Parameters;if(e.TimeoutSeconds)t.TimeoutSeconds=e.TimeoutSeconds;if(e.Comment)t.Comment=e.Comment;if(e.OutputS3BucketName)t.OutputS3BucketName=e.OutputS3BucketName;if(e.OutputS3KeyPrefix)t.OutputS3KeyPrefix=e.OutputS3KeyPrefix;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.SendCommand","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{CommandId:r.Command?.CommandId,Status:r.Command?.Status,StatusDetails:r.Command?.StatusDetails}}async getCommandInvocation(e){let t={CommandId:e.CommandId,InstanceId:e.InstanceId},r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetCommandInvocation","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Status:r.Status,StatusDetails:r.StatusDetails,StandardOutputContent:r.StandardOutputContent,StandardErrorContent:r.StandardErrorContent,ResponseCode:r.ResponseCode}}async runShellCommand(e,t,r){let n=await this.sendCommand({InstanceIds:[e],DocumentName:"AWS-RunShellScript",Parameters:{commands:t},TimeoutSeconds:r?.timeoutSeconds||600});if(!n.CommandId)return{success:!1,error:"Failed to send command"};if(r?.waitForCompletion===!1)return{success:!0,status:"Pending"};let s=r?.pollIntervalMs||2000,o=r?.maxWaitMs||300000,i=Date.now();while(Date.now()-i<o){await new Promise((a)=>setTimeout(a,s));try{let a=await this.getCommandInvocation({CommandId:n.CommandId,InstanceId:e});if(a.Status==="Success")return{success:!0,output:a.StandardOutputContent,error:a.StandardErrorContent,status:a.Status};if(a.Status==="Failed"||a.Status==="Cancelled"||a.Status==="TimedOut")return{success:!1,output:a.StandardOutputContent,error:a.StandardErrorContent||a.StatusDetails,status:a.Status}}catch(a){if(!a.message?.includes("InvocationDoesNotExist"))return{success:!1,error:a.message}}}return{success:!1,error:"Command timed out waiting for completion"}}async listCommandInvocations(e){let t={CommandId:e.CommandId};if(e.Details)t.Details=!0;return((await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.ListCommandInvocations","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})).CommandInvocations||[]).map((s)=>({InstanceId:s.InstanceId,Status:s.Status,StatusDetails:s.StatusDetails,StandardOutputContent:s.CommandPlugins?.[0]?.Output,StandardErrorContent:s.CommandPlugins?.[0]?.StandardErrorUrl}))}async sendCommandByTags(e){let t=Object.entries(e.tags).map(([c,l])=>({Key:`tag:${c}`,Values:[l]})),r=await this.sendCommand({Targets:t,DocumentName:"AWS-RunShellScript",Parameters:{commands:e.commands},TimeoutSeconds:e.timeoutSeconds||600,Comment:e.comment});if(!r.CommandId)return{success:!1,instanceCount:0,perInstance:[],error:"Failed to send command"};let n=e.pollIntervalMs||3000,s=e.maxWaitMs||600000,o=Date.now(),i=new Set(["Success","Failed","Cancelled","TimedOut"]),a=[];while(Date.now()-o<s){await new Promise((c)=>setTimeout(c,n));try{if(a=await this.listCommandInvocations({CommandId:r.CommandId,Details:!0}),a.length===0)continue;if(a.every((l)=>i.has(l.Status||""))){let l=a.map((d)=>({instanceId:d.InstanceId,status:d.Status||"Unknown",output:d.StandardOutputContent,error:d.StandardErrorContent||d.StatusDetails})),u=a.every((d)=>d.Status==="Success");return{success:u,instanceCount:a.length,perInstance:l,error:u?void 0:"One or more instances reported a non-success status"}}}catch(c){if(!c.message?.includes("InvocationDoesNotExist"))return{success:!1,instanceCount:0,perInstance:[],error:c.message}}}return{success:!1,instanceCount:a.length,perInstance:a.map((c)=>({instanceId:c.InstanceId,status:c.Status||"Unknown"})),error:"Command timed out waiting for all instances to complete"}}}function cs(e={}){let t=new Set;for(let r of Object.values(e)){if(!r.domain)continue;if(!(r.redirect||r.deploy==="server"||r.start))continue;t.add(r.domain);for(let n of r.aliases??[]){let s=String(n).trim().toLowerCase();if(s)t.add(s)}}return t}function dr(e){return e.replace(/\.$/,"").toLowerCase()}function Vi(e,t,r){let n=dr(e.name),s=dr(t),o=dr(r),i=o===s?"@":o.endsWith(`.${s}`)?o.slice(0,-(s.length+1)):o;return n===o||n===i||i==="@"&&(n===""||n===s)}async function qi(e,t,r,n,s="A"){let o=await e.listRecords(t);if(!o.success)return[`could not list ${s} records: ${o.message||"unknown provider error"}`];let i=o.records.filter((l)=>l.type===s&&Vi(l,t,r)),a=i.findIndex((l)=>l.content===n);if(i.length<=1||a===-1)return[];let c=[];for(let[l,u]of i.entries()){if(l===a)continue;let d=await e.deleteRecord(t,u);if(!d.success)c.push(`could not remove stale ${u.name} ${s} ${u.content}: ${d.message||"unknown provider error"}`)}return c}function me(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 Xi=new Set(["mail","smtp","imap","mx"]);function Yi(e){return!Xi.has(e.split(".")[0]??"")}async function ui(e){let{provider:t,zone:r,fqdn:n,ipv4:s,ipv6:o,ttl:i=600}=e,a={published:[],warnings:[]},c=[{type:"A",content:s}];if(o&&Yi(n))c.push({type:"AAAA",content:o});for(let{type:l,content:u}of c){let d=await t.upsertRecord(r,{name:n,type:l,content:u,ttl:i});if(d?.success===!1){a.warnings.push(`${n} → ${u} failed: ${d.error||d.message||"unknown error"}`);continue}if(a.warnings.push(...(await qi(t,r,n,u,l)).map((m)=>`${n} cleanup: ${m}`)),await Zi(t,r,n,u,l))a.published.push({fqdn:n,type:l,content:u});else a.warnings.push(`${n} → ${u} reported success at ${t.name} but no matching ${l} record exists — create it manually: ${l} ${n} → ${u}`)}return a}async function Zi(e,t,r,n,s){try{if(typeof e?.listRecords!=="function")return!0;let o=await e.listRecords(t);if(!o?.success||!Array.isArray(o.records))return!0;return o.records.some((i)=>{let a=typeof i?.name==="string"?i.name.replace(/\.$/,""):"";return i?.type===s&&a===r&&i?.content===n})}catch{return!0}}import{readFileSync as Cs}from"node:fs";import{join as Va}from"node:path";function Sr(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 ut(e,t){let r=Sr(e?.stderr),n=/line (\d+): syntax error/.exec(r);if(!n)return"";let s=Number(n[1]),o=t.split(`
1
+ import{p}from"./chunk-0xfy78nc.js";import{ca,R,A,ne,Fr,da,qo,le,B,T,Jt,Br}from"./chunk-t8qzx4ka.js";import{v}from"./chunk-rbyrd9we.js";import{Q}from"./chunk-9t78j764.js";import{g}from"./chunk-7cactd6c.js";import{J,Di,Gs,w,U,kr,Ct,nt,Lo,ki,Uo,Tt,Gc,Fo,Bo,_i,jo,Ht,Xs,Wc,Oi,Qs,Ys,Zs,ea,Vo,hn,ta,yn,ra,zo}from"./chunk-ebhfg18g.js";import{ko,No,$s}from"./chunk-1gznb7bh.js";import{fs}from"./chunk-q0takzyx.js";import{an}from"./chunk-p6qa21fr.js";import{wr}from"./chunk-bzzwbkrx.js";class We{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new p}async putParameter(e){let t={Name:e.Name,Value:e.Value};if(e.Type)t.Type=e.Type;if(e.Description)t.Description=e.Description;if(e.KeyId)t.KeyId=e.KeyId;if(e.Overwrite!==void 0)t.Overwrite=e.Overwrite;if(e.AllowedPattern)t.AllowedPattern=e.AllowedPattern;if(e.Tags&&e.Tags.length>0)t.Tags=e.Tags;if(e.Tier)t.Tier=e.Tier;if(e.DataType)t.DataType=e.DataType;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.PutParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Version:r.Version,Tier:r.Tier}}async getParameter(e){let t={Name:e.Name};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameter:r.Parameter?this.parseParameter(r.Parameter):void 0}}async getParameters(e){let t={Names:e.Names};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:r.Parameters?.map((n)=>this.parseParameter(n)),InvalidParameters:r.InvalidParameters}}async getParametersByPath(e){let t={Path:e.Path};if(e.Recursive!==void 0)t.Recursive=e.Recursive;if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;if(e.MaxResults)t.MaxResults=e.MaxResults;if(e.NextToken)t.NextToken=e.NextToken;if(e.ParameterFilters&&e.ParameterFilters.length>0)t.ParameterFilters=e.ParameterFilters;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParametersByPath","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:r.Parameters?.map((n)=>this.parseParameter(n)),NextToken:r.NextToken}}async deleteParameter(e){let t={Name:e.Name};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DeleteParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async deleteParameters(e){let t={Names:e},r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DeleteParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{DeletedParameters:r.DeletedParameters,InvalidParameters:r.InvalidParameters}}async describeParameters(e){let t={};if(e?.Filters&&e.Filters.length>0)t.Filters=e.Filters;if(e?.ParameterFilters&&e.ParameterFilters.length>0)t.ParameterFilters=e.ParameterFilters;if(e?.MaxResults)t.MaxResults=e.MaxResults;if(e?.NextToken)t.NextToken=e.NextToken;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DescribeParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:r.Parameters?.map((n)=>this.parseParameter(n)),NextToken:r.NextToken}}async getParameterHistory(e){let t={Name:e.Name};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;if(e.MaxResults)t.MaxResults=e.MaxResults;if(e.NextToken)t.NextToken=e.NextToken;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameterHistory","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:r.Parameters?.map((n)=>({Name:n.Name,Type:n.Type,KeyId:n.KeyId,LastModifiedDate:n.LastModifiedDate,LastModifiedUser:n.LastModifiedUser,Description:n.Description,Value:n.Value,Version:n.Version,Labels:n.Labels,Tier:n.Tier})),NextToken:r.NextToken}}async labelParameterVersion(e){let t={Name:e.Name,Labels:e.Labels};if(e.ParameterVersion!==void 0)t.ParameterVersion=e.ParameterVersion;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.LabelParameterVersion","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{InvalidLabels:r.InvalidLabels,ParameterVersion:r.ParameterVersion}}async addTagsToResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId,Tags:e.Tags};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.AddTagsToResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async removeTagsFromResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId,TagKeys:e.TagKeys};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.RemoveTagsFromResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async listTagsForResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId};return{TagList:(await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.ListTagsForResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})).TagList}}async setString(e,t,r){return this.putParameter({Name:e,Value:t,Type:"String",Description:r?.description,Overwrite:r?.overwrite??!0,Tags:r?.tags})}async setSecureString(e,t,r){return this.putParameter({Name:e,Value:t,Type:"SecureString",Description:r?.description,Overwrite:r?.overwrite??!0,KeyId:r?.kmsKeyId,Tags:r?.tags})}async getValue(e){return(await this.getParameter({Name:e,WithDecryption:!0})).Parameter?.Value}async getAllByPath(e,t=!0){let r=[],n;do{let s=await this.getParametersByPath({Path:e,Recursive:t,WithDecryption:!0,NextToken:n});if(s.Parameters)r.push(...s.Parameters);n=s.NextToken}while(n);return r}parseParameter(e){return{Name:e.Name,Type:e.Type,Value:e.Value,Version:e.Version,LastModifiedDate:e.LastModifiedDate,ARN:e.ARN,DataType:e.DataType,Description:e.Description,AllowedPattern:e.AllowedPattern,KeyId:e.KeyId,Tier:e.Tier}}async sendCommand(e){if(!e.InstanceIds&&!e.Targets)throw Error("SendCommand requires either InstanceIds or Targets");let t={DocumentName:e.DocumentName};if(e.InstanceIds)t.InstanceIds=e.InstanceIds;if(e.Targets)t.Targets=e.Targets;if(e.Parameters)t.Parameters=e.Parameters;if(e.TimeoutSeconds)t.TimeoutSeconds=e.TimeoutSeconds;if(e.Comment)t.Comment=e.Comment;if(e.OutputS3BucketName)t.OutputS3BucketName=e.OutputS3BucketName;if(e.OutputS3KeyPrefix)t.OutputS3KeyPrefix=e.OutputS3KeyPrefix;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.SendCommand","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{CommandId:r.Command?.CommandId,Status:r.Command?.Status,StatusDetails:r.Command?.StatusDetails}}async getCommandInvocation(e){let t={CommandId:e.CommandId,InstanceId:e.InstanceId},r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetCommandInvocation","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Status:r.Status,StatusDetails:r.StatusDetails,StandardOutputContent:r.StandardOutputContent,StandardErrorContent:r.StandardErrorContent,ResponseCode:r.ResponseCode}}async runShellCommand(e,t,r){let n=await this.sendCommand({InstanceIds:[e],DocumentName:"AWS-RunShellScript",Parameters:{commands:t},TimeoutSeconds:r?.timeoutSeconds||600});if(!n.CommandId)return{success:!1,error:"Failed to send command"};if(r?.waitForCompletion===!1)return{success:!0,status:"Pending"};let s=r?.pollIntervalMs||2000,o=r?.maxWaitMs||300000,i=Date.now();while(Date.now()-i<o){await new Promise((a)=>setTimeout(a,s));try{let a=await this.getCommandInvocation({CommandId:n.CommandId,InstanceId:e});if(a.Status==="Success")return{success:!0,output:a.StandardOutputContent,error:a.StandardErrorContent,status:a.Status};if(a.Status==="Failed"||a.Status==="Cancelled"||a.Status==="TimedOut")return{success:!1,output:a.StandardOutputContent,error:a.StandardErrorContent||a.StatusDetails,status:a.Status}}catch(a){if(!a.message?.includes("InvocationDoesNotExist"))return{success:!1,error:a.message}}}return{success:!1,error:"Command timed out waiting for completion"}}async listCommandInvocations(e){let t={CommandId:e.CommandId};if(e.Details)t.Details=!0;return((await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.ListCommandInvocations","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})).CommandInvocations||[]).map((s)=>({InstanceId:s.InstanceId,Status:s.Status,StatusDetails:s.StatusDetails,StandardOutputContent:s.CommandPlugins?.[0]?.Output,StandardErrorContent:s.CommandPlugins?.[0]?.StandardErrorUrl}))}async sendCommandByTags(e){let t=Object.entries(e.tags).map(([c,l])=>({Key:`tag:${c}`,Values:[l]})),r=await this.sendCommand({Targets:t,DocumentName:"AWS-RunShellScript",Parameters:{commands:e.commands},TimeoutSeconds:e.timeoutSeconds||600,Comment:e.comment});if(!r.CommandId)return{success:!1,instanceCount:0,perInstance:[],error:"Failed to send command"};let n=e.pollIntervalMs||3000,s=e.maxWaitMs||600000,o=Date.now(),i=new Set(["Success","Failed","Cancelled","TimedOut"]),a=[];while(Date.now()-o<s){await new Promise((c)=>setTimeout(c,n));try{if(a=await this.listCommandInvocations({CommandId:r.CommandId,Details:!0}),a.length===0)continue;if(a.every((l)=>i.has(l.Status||""))){let l=a.map((d)=>({instanceId:d.InstanceId,status:d.Status||"Unknown",output:d.StandardOutputContent,error:d.StandardErrorContent||d.StatusDetails})),u=a.every((d)=>d.Status==="Success");return{success:u,instanceCount:a.length,perInstance:l,error:u?void 0:"One or more instances reported a non-success status"}}}catch(c){if(!c.message?.includes("InvocationDoesNotExist"))return{success:!1,instanceCount:0,perInstance:[],error:c.message}}}return{success:!1,instanceCount:a.length,perInstance:a.map((c)=>({instanceId:c.InstanceId,status:c.Status||"Unknown"})),error:"Command timed out waiting for all instances to complete"}}}function cs(e={}){let t=new Set;for(let r of Object.values(e)){if(!r.domain)continue;if(!(r.redirect||r.deploy==="server"||r.start))continue;t.add(r.domain);for(let n of r.aliases??[]){let s=String(n).trim().toLowerCase();if(s)t.add(s)}}return t}function dr(e){return e.replace(/\.$/,"").toLowerCase()}function Vi(e,t,r){let n=dr(e.name),s=dr(t),o=dr(r),i=o===s?"@":o.endsWith(`.${s}`)?o.slice(0,-(s.length+1)):o;return n===o||n===i||i==="@"&&(n===""||n===s)}async function qi(e,t,r,n,s="A"){let o=await e.listRecords(t);if(!o.success)return[`could not list ${s} records: ${o.message||"unknown provider error"}`];let i=o.records.filter((l)=>l.type===s&&Vi(l,t,r)),a=i.findIndex((l)=>l.content===n);if(i.length<=1||a===-1)return[];let c=[];for(let[l,u]of i.entries()){if(l===a)continue;let d=await e.deleteRecord(t,u);if(!d.success)c.push(`could not remove stale ${u.name} ${s} ${u.content}: ${d.message||"unknown provider error"}`)}return c}function me(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 Xi=new Set(["mail","smtp","imap","mx"]);function Yi(e){return!Xi.has(e.split(".")[0]??"")}async function ui(e){let{provider:t,zone:r,fqdn:n,ipv4:s,ipv6:o,ttl:i=600}=e,a={published:[],warnings:[]},c=[{type:"A",content:s}];if(o&&Yi(n))c.push({type:"AAAA",content:o});for(let{type:l,content:u}of c){let d=await t.upsertRecord(r,{name:n,type:l,content:u,ttl:i});if(d?.success===!1){a.warnings.push(`${n} → ${u} failed: ${d.error||d.message||"unknown error"}`);continue}if(a.warnings.push(...(await qi(t,r,n,u,l)).map((m)=>`${n} cleanup: ${m}`)),await Zi(t,r,n,u,l))a.published.push({fqdn:n,type:l,content:u});else a.warnings.push(`${n} → ${u} reported success at ${t.name} but no matching ${l} record exists — create it manually: ${l} ${n} → ${u}`)}return a}async function Zi(e,t,r,n,s){try{if(typeof e?.listRecords!=="function")return!0;let o=await e.listRecords(t);if(!o?.success||!Array.isArray(o.records))return!0;return o.records.some((i)=>{let a=typeof i?.name==="string"?i.name.replace(/\.$/,""):"";return i?.type===s&&a===r&&i?.content===n})}catch{return!0}}import{readFileSync as Cs}from"node:fs";import{join as Va}from"node:path";function Sr(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 ut(e,t){let r=Sr(e?.stderr),n=/line (\d+): syntax error/.exec(r);if(!n)return"";let s=Number(n[1]),o=t.split(`
2
2
  `),i=Math.max(1,s-12),a=Math.min(o.length,s+2),c=o.slice(i-1,a).map((l,u)=>{let d=i+u,m=/^[A-Z_][A-Z0-9_]*=/.test(l)?l.replace(/=.*/,"=<redacted>"):l;return` ${String(d).padStart(4)}${d===s?" >":" "} ${m}`});return["",`The deploy script bash rejected is ${o.length} lines; it stopped at ${s}.`,...c].join(`
3
3
  `)}function ke(e){let t=e,r=typeof t?.status==="number"?` (exit ${t.status})`:"",n=t?.signal?` (signal ${t.signal})`:"",s=[Sr(t?.stderr),Sr(t?.stdout)].filter(Boolean).join(`
4
4
  `);return`Remote SSH command failed${r}${n}${s?`
@@ -12,7 +12,7 @@ EOF`,'DISK_PCT=0; DISK_ALERTS=""; ALERT_KEY=""',...m,"UPTIME_SEC=$(cut -d' ' -f1
12
12
  `)}
13
13
  `}return`${["server {"," listen 80;"," listen [::]:80;",` server_name ${r};`,...n,"}"].join(`
14
14
  `)}
15
- `}function _r(e){let t=`/etc/nginx/sites-available/${e.siteName}`,r=`/etc/nginx/sites-enabled/${e.siteName}`,n=ba(e),s=[...$r()];if(e.auth){let o=Vn(e.siteName),i=(l)=>l.split("'").join("'\\''"),a=i(e.auth.password),c=i(e.auth.username);s.push(`TS_CLOUD_HTPASS=$(openssl passwd -apr1 '${a}')`,`printf '%s:%s\\n' '${c}' "$TS_CLOUD_HTPASS" > ${o}`,`chmod 640 ${o}`,`chown root:www-data ${o} 2>/dev/null || true`)}return s.push(`cat > ${t} <<'TS_CLOUD_NGINX_EOF'`,n.replace(/\n$/,""),"TS_CLOUD_NGINX_EOF",`ln -sf ${t} ${r}`,"rm -f /etc/nginx/sites-enabled/default",`${xe} -t`,"systemctl reload ts-cloud-nginx 2>/dev/null || systemctl restart ts-cloud-nginx 2>/dev/null || true"),s}var xe="/usr/local/bin/ts-cloud-nginx";function $r(e="/opt/pantry"){return[...kr(),...nt(["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 > ${xe} <<'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 ${xe}`,"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=${xe} -t`,`ExecStart=${xe} -g 'daemon off;'`,`ExecReload=${xe} -s reload`,"Restart=always","RestartSec=3","","[Install]","WantedBy=multi-user.target","TS_CLOUD_NGINXUNIT_EOF","systemctl daemon-reload","systemctl enable ts-cloud-nginx","ls /etc/nginx/sites-enabled/* >/dev/null 2>&1 && systemctl restart ts-cloud-nginx || true"]}import{readFileSync as wa}from"node:fs";function _a(e){if(typeof e==="string")return e;if(!/^\/[\w./-]+$/.test(e.envFile)||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e.variable))throw Error("Invalid notification env-file reference");let r=wa(e.envFile,"utf8").split(/\r?\n/).map((n)=>n.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/)).find((n)=>n?.[1]===e.variable)?.[2];if(!r)throw Error(`Notification variable ${e.variable} is missing`);return r.replace(/^(['"])(.*)\1$/,"$2")}function pt(e,t){return!e.events||e.events.includes(t)}async function Tr(e,t,r,n={}){if(!e)return[];let s=n.fetchImpl??globalThis.fetch,o=[],i=[],a=async(c,l)=>{try{return await s(_a(c),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)})}catch{return}};if(e.slack?.webhookUrl&&pt(e,t))o.push("slack"),i.push(a(e.slack.webhookUrl,{text:r}));if(e.discord?.webhookUrl&&pt(e,t))o.push("discord"),i.push(a(e.discord.webhookUrl,{content:r}));if(e.telegram?.botToken&&e.telegram.chatId&&pt(e,t)){o.push("telegram");let c=`https://api.telegram.org/bot${e.telegram.botToken}/sendMessage`;i.push(a(c,{chat_id:e.telegram.chatId,text:r}))}if(e.webhook?.url&&pt(e,t))if(o.push("webhook"),(e.webhook.method||"POST")==="GET"){let c=e.webhook.url.includes("?")?"&":"?",l=`${e.webhook.url}${c}event=${encodeURIComponent(t)}&message=${encodeURIComponent(r)}`;i.push(s(l,{method:"GET"}).catch(()=>{return}))}else i.push(a(e.webhook.url,{event:t,message:r}));if(e.email?.to&&pt(e,t))o.push("email"),i.push($a(e.email,t,r));return await Promise.all(i),o}async function $a(e,t,r){try{let n=await import("./chunk-kj1e4xvg.js");await n.email.send({to:e.to,from:e.from,subject:`[ts-cloud] ${t}`,text:r})}catch{}}function qn(e,t){return t??e}function He(e){if(!e)return[];let t=(s)=>"'"+s.replaceAll("'",`'"'"'`)+"'",r=(s)=>{if(typeof s==="string")return t(s);if(!/^\/[\w./-]+$/.test(s.envFile)||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(s.variable))throw Error("Invalid notification env-file reference");return'"$(read_env '+t(s.envFile)+" "+t(s.variable)+')"'},n=[];for(let[s,o]of[["slack","text"],["discord","content"]]){let i=e[s]?.webhookUrl;if(i)n.push("URL="+r(i),'post "$URL" '+t(o))}if(e.telegram?.botToken&&e.telegram.chatId)n.push("curl -fsS --max-time 30 -X POST "+t("https://api.telegram.org/bot"+e.telegram.botToken+"/sendMessage")+" --data-urlencode "+t("chat_id="+e.telegram.chatId)+' --data-urlencode "text=$MSG" >/dev/null || FAILED=1');if(e.webhook?.url)if(e.webhook.method==="GET")n.push("curl -fsS --max-time 30 -G "+t(e.webhook.url)+' --data-urlencode "message=$MSG" >/dev/null || FAILED=1');else n.push("post "+t(e.webhook.url)+" message");if(!n.length)return[];return["cat > /usr/local/bin/ts-cloud-notify.new <<'TS_CLOUD_NOTIFY_EOF'","#!/bin/bash","set -uo pipefail",'MSG="${1:-}"; FAILED=0',String.raw`read_env(){ awk -v key="$2" '$0 ~ "^[[:space:]]*(export[[:space:]]+)?" key "[[:space:]]*=" { sub("^[^=]*=[[:space:]]*", ""); sub(/[\r[:space:]]+$/, ""); if (($0 ~ /^".*"$/) || ($0 ~ /^\047.*\047$/)) $0=substr($0,2,length($0)-2); print; exit }' "$1"; }`,String.raw`ESCAPED=$(printf %s "$MSG" | LC_ALL=C awk 'BEGIN{ORS=""; for(i=1;i<32;i++) esc[sprintf("%c",i)]=sprintf("\\u%04x",i)} {if(NR>1) printf "\\n"; for(i=1;i<=length($0);i++){ c=substr($0,i,1); if(c=="\\") printf "\\\\"; else if(c=="\"") printf "\\\""; else if(c in esc) printf "%s",esc[c]; else printf "%s",c }}')`,String.raw`post(){ if [ -z "$1" ]; then FAILED=1; return; fi; curl -fsS --max-time 30 -X POST -H 'Content-Type: application/json' --data "{\"$2\":\"$ESCAPED\"}" "$1" >/dev/null || FAILED=1; }`,...n,'exit "$FAILED"',"TS_CLOUD_NOTIFY_EOF","chmod 0700 /usr/local/bin/ts-cloud-notify.new","mv -f /usr/local/bin/ts-cloud-notify.new /usr/local/bin/ts-cloud-notify"]}import{isIP as Yn}from"node:net";var en="/etc/rpx/certs",Jn="/etc/rpx/local-ca",Ta="rpx-root-ca.crt";function At(e=Jn){return`${e.replace(/\/+$/,"")}/${Ta}`}function xr(e){if(e.toLowerCase().endsWith(".local"))return!1;return e.split(".").length===2}function to(e,t={}){let r=new Set;for(let s of Object.values(e)){if(!s?.domain)continue;if(I(s)==="bucket")continue;r.add(s.domain)}let n=new Set;for(let s of Object.values(e)){if(!s?.domain||I(s)==="bucket")continue;for(let o of s.aliases??[]){let i=String(o).trim().toLowerCase();if(i&&i!==s.domain)n.add(i)}}if(t.autoWww!==!1)for(let s of[...r]){if(!xr(s))continue;r.add(`www.${s}`)}for(let s of n)r.add(s);return[...r]}var Ca=["1.1.1.1","8.8.8.8"],Pa="/var/www/acme-challenge";function xa(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 Ra(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 Rr(e){if(!e)return;return e.tls??"local-ca"}function ro(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 Qn(e){if(e.cloud?.provider!=="ssh")return;return e.ssh?.profile}function Ea(e){let t=e.trim().toLowerCase();if(!t||t.startsWith("*")||t.includes(":")||t.includes("/")||t.includes(" "))return!1;if(Yn(t)!==0)return!1;return t.endsWith(".local")||!t.includes(".")}function Oa(e,t,r){let n=[],s=new Set,o=(l,u)=>{let d=l.trim().toLowerCase();if(!d||s.has(d))return;s.add(d),n.push({host:d,source:u})},i=t.hostname?.trim(),a=(i||`${r}.local`).toLowerCase();if(o(a,i?"ssh.lan.hostname":`the ssh provider's default LAN name for project "${r}"`),Object.entries(e).some(([l,u])=>!!u&&Br(l)))o(`dashboard.${a}`,"the management dashboard site");for(let[l,u]of Object.entries(e)){if(!u?.domain)continue;if(I(u)==="bucket")continue;if(!Ea(u.domain))continue;o(u.domain,`site "${l}"`)}return n}function Da(e,t){if(!t?.length)return;return t.find((r)=>{let n=(r.startsWith(".")?r.slice(1):r).toLowerCase();return e===n||e.endsWith(`.${n}`)})}function Ia(e,t){if(!t?.enabled)return;for(let{host:r,source:n}of e){let s=Da(r,t.allowedSuffixes);if(!s)continue;throw Error(`The LAN certificate authority and public on-demand TLS both claim "${r}". LAN source: ${n}. Public source: the on-demand TLS allowed suffix "${s}", 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 Aa(e){let t=e.split(".");return t.length>=3&&t[0]==="*"&&t.slice(1).every((r)=>/^[a-z0-9-]+$/i.test(r))}function Zn(e,t={}){let{wildcardCerts:r,...n}=e;return JSON.stringify({...t,...n},null,2)}function es(e){if(!e||e==="/")return;let t=`/${e}`.replace(/\/+/g,"/").replace(/\/+$/,"");if(!t.startsWith("/"))t=`/${t}`;return t===""||t==="/"?void 0:t}function It(e,t){let n=(t?`${e}${t}`:e).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return n.length>0?n:"rpx"}function La(e,t){if(!t||t.length===0)return`localhost:${e}`;return t.map((r)=>`${r.privateIp??r.publicIp}:${e}`)}function ts(e,t,r){let n=(t.wwwRoot??"/var/www").replace(/\/+$/,""),s=t.slug??"app",o=t.proxy.certsDir??en,i=t.proxy.loadBalancer,a=[],c=new Set,l=new Map;for(let[h,f]of Object.entries(e)){if(!f||!f.domain)continue;let S=I(f);if(S==="bucket")continue;let k=a.length,E=[...new Set((f.aliases??[]).map((x)=>String(x).trim().toLowerCase()).filter((x)=>x&&x!==f.domain))],O=()=>{let x=a.slice(k).filter((H)=>H.to===f.domain);for(let H of E){for(let V of x)a.push({...V,to:H,id:It(H,V.path)});if(Aa(H)){if(!l.has(H))l.set(H,{domain:H,dnsEnvFile:`${n}/${s}-${h}/shared/.env`})}else c.add(H)}},D=es(f.path),R=It(f.domain,D),z=Ra(f);if(S==="redirect"){a.push({to:f.domain,path:D,redirect:xa(f.redirect),id:R,...z?{auth:z}:{}}),c.add(f.domain),O();continue}if(S==="proxy"){let x=Gs(f);if(x.length===0)continue;let H=x.length===1?x[0]:x;a.push({to:f.domain,path:D,from:H,id:R,...z?{auth:z}:{},...Array.isArray(H)&&i?{loadBalancer:i}:{}}),c.add(f.domain),O();continue}if(S==="server-app"){if(typeof f.port!=="number")continue;let x=La(f.port,r);a.push({to:f.domain,path:D,from:x,id:R,...z?{auth:z}:{},...Array.isArray(x)&&i?{loadBalancer:i}:{}})}else a.push({to:f.domain,path:D,static:{dir:`${n}/${s}-${h}/current`,spa:f.spa??!1,pathRewriteStyle:f.pathRewriteStyle??"directory"},cleanUrls:f.pathRewriteStyle!=="flat",...z?{auth:z}:{},id:R});c.add(f.domain),O()}if(t.proxy.autoWww!==!1)for(let h of[...c]){if(!xr(h))continue;let f=`www.${h}`;if(c.has(f))continue;a.push({to:f,redirect:{to:`https://${h}`},id:It(f)}),c.add(f)}a.sort((h,f)=>{if(h.to!==f.to)return h.to.localeCompare(f.to);return(f.path?.length??0)-(h.path?.length??0)});let u={proxies:a,productionCerts:{certsDir:o,certsDirServerNames:[...c,...l.keys()]},https:!0,hostsManagement:!1,cleanup:{hosts:!1,certs:!1},...l.size>0?{wildcardCerts:[...l.values()]}:{}};if(t.proxy.onDemandTls&&c.size>0)u.onDemandTls={enabled:!0,allowedSuffixes:[...c],email:t.proxy.onDemandTlsEmail,certsDir:o,staging:t.proxy.onDemandTlsStaging??!1};if(t.proxy.onDemandTls)u.acmeChallengeWebroot=t.proxy.acmeWebroot??Pa;let d=t.proxy.cdn,m=d?.frontedHosts?.length?d.frontedHosts:[...c];if(d?.secret&&m.length>0)u.originGuard={header:d.secretHeader??"X-Origin-Verify",value:d.secret,hosts:m};if(t.lan)if(Rr(t.lan)==="off")u.https=!1;else{let h=Oa(e,t.lan,s);Ia(h,u.onDemandTls);let f=t.lan.ip&&Yn(t.lan.ip)!==0?[t.lan.ip]:[];u.localCa={dir:Jn,hosts:h.map((S)=>S.host),...f.length>0?{ips:f}:{},installTrust:!0}}return u}function Te(e,t){return ts({...e,...t.mail?qo(t.mail):{}},t)}function qe(e,t,r){return ts({...e,...r.mail?qo(r.mail):{}},r,t)}function Z(e){return e?.webServer==="rpx"||e?.proxy?.engine==="rpx"}var dt="/etc/rpx",ie="/opt/rpx-gateway",Cr="/etc/rpx/gateway.ts",Ge="/etc/rpx/gateway",ye="rpx-gateway.service",pe="/etc/rpx/sites.d";function ka(e=pe,t=en){return`// Generated by ts-cloud — rpx gateway assembler.
15
+ `}function _r(e){let t=`/etc/nginx/sites-available/${e.siteName}`,r=`/etc/nginx/sites-enabled/${e.siteName}`,n=ba(e),s=[...$r()];if(e.auth){let o=Vn(e.siteName),i=(l)=>l.split("'").join("'\\''"),a=i(e.auth.password),c=i(e.auth.username);s.push(`TS_CLOUD_HTPASS=$(openssl passwd -apr1 '${a}')`,`printf '%s:%s\\n' '${c}' "$TS_CLOUD_HTPASS" > ${o}`,`chmod 640 ${o}`,`chown root:www-data ${o} 2>/dev/null || true`)}return s.push(`cat > ${t} <<'TS_CLOUD_NGINX_EOF'`,n.replace(/\n$/,""),"TS_CLOUD_NGINX_EOF",`ln -sf ${t} ${r}`,"rm -f /etc/nginx/sites-enabled/default",`${xe} -t`,"systemctl reload ts-cloud-nginx 2>/dev/null || systemctl restart ts-cloud-nginx 2>/dev/null || true"),s}var xe="/usr/local/bin/ts-cloud-nginx";function $r(e="/opt/pantry"){return[...kr(),...nt(["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 > ${xe} <<'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 ${xe}`,"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=${xe} -t`,`ExecStart=${xe} -g 'daemon off;'`,`ExecReload=${xe} -s reload`,"Restart=always","RestartSec=3","","[Install]","WantedBy=multi-user.target","TS_CLOUD_NGINXUNIT_EOF","systemctl daemon-reload","systemctl enable ts-cloud-nginx","ls /etc/nginx/sites-enabled/* >/dev/null 2>&1 && systemctl restart ts-cloud-nginx || true"]}import{readFileSync as wa}from"node:fs";function _a(e){if(typeof e==="string")return e;if(!/^\/[\w./-]+$/.test(e.envFile)||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e.variable))throw Error("Invalid notification env-file reference");let r=wa(e.envFile,"utf8").split(/\r?\n/).map((n)=>n.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/)).find((n)=>n?.[1]===e.variable)?.[2];if(!r)throw Error(`Notification variable ${e.variable} is missing`);return r.replace(/^(['"])(.*)\1$/,"$2")}function pt(e,t){return!e.events||e.events.includes(t)}async function Tr(e,t,r,n={}){if(!e)return[];let s=n.fetchImpl??globalThis.fetch,o=[],i=[],a=async(c,l)=>{try{return await s(_a(c),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)})}catch{return}};if(e.slack?.webhookUrl&&pt(e,t))o.push("slack"),i.push(a(e.slack.webhookUrl,{text:r}));if(e.discord?.webhookUrl&&pt(e,t))o.push("discord"),i.push(a(e.discord.webhookUrl,{content:r}));if(e.telegram?.botToken&&e.telegram.chatId&&pt(e,t)){o.push("telegram");let c=`https://api.telegram.org/bot${e.telegram.botToken}/sendMessage`;i.push(a(c,{chat_id:e.telegram.chatId,text:r}))}if(e.webhook?.url&&pt(e,t))if(o.push("webhook"),(e.webhook.method||"POST")==="GET"){let c=e.webhook.url.includes("?")?"&":"?",l=`${e.webhook.url}${c}event=${encodeURIComponent(t)}&message=${encodeURIComponent(r)}`;i.push(s(l,{method:"GET"}).catch(()=>{return}))}else i.push(a(e.webhook.url,{event:t,message:r}));if(e.email?.to&&pt(e,t))o.push("email"),i.push($a(e.email,t,r));return await Promise.all(i),o}async function $a(e,t,r){try{let n=await import("./chunk-kj1e4xvg.js");await n.email.send({to:e.to,from:e.from,subject:`[ts-cloud] ${t}`,text:r})}catch{}}function qn(e,t){return t??e}function He(e){if(!e)return[];let t=(s)=>"'"+s.replaceAll("'",`'"'"'`)+"'",r=(s)=>{if(typeof s==="string")return t(s);if(!/^\/[\w./-]+$/.test(s.envFile)||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(s.variable))throw Error("Invalid notification env-file reference");return'"$(read_env '+t(s.envFile)+" "+t(s.variable)+')"'},n=[];for(let[s,o]of[["slack","text"],["discord","content"]]){let i=e[s]?.webhookUrl;if(i)n.push("URL="+r(i),'post "$URL" '+t(o))}if(e.telegram?.botToken&&e.telegram.chatId)n.push("curl -fsS --max-time 30 -X POST "+t("https://api.telegram.org/bot"+e.telegram.botToken+"/sendMessage")+" --data-urlencode "+t("chat_id="+e.telegram.chatId)+' --data-urlencode "text=$MSG" >/dev/null || FAILED=1');if(e.webhook?.url)if(e.webhook.method==="GET")n.push("curl -fsS --max-time 30 -G "+t(e.webhook.url)+' --data-urlencode "message=$MSG" >/dev/null || FAILED=1');else n.push("post "+t(e.webhook.url)+" message");if(!n.length)return[];return["cat > /usr/local/bin/ts-cloud-notify.new <<'TS_CLOUD_NOTIFY_EOF'","#!/bin/bash","set -uo pipefail",'MSG="${1:-}"; FAILED=0',String.raw`read_env(){ awk -v key="$2" '$0 ~ "^[[:space:]]*(export[[:space:]]+)?" key "[[:space:]]*=" { sub("^[^=]*=[[:space:]]*", ""); sub(/[\r[:space:]]+$/, ""); if (($0 ~ /^".*"$/) || ($0 ~ /^\047.*\047$/)) $0=substr($0,2,length($0)-2); print; exit }' "$1"; }`,String.raw`ESCAPED=$(printf %s "$MSG" | LC_ALL=C awk 'BEGIN{ORS=""; for(i=1;i<32;i++) esc[sprintf("%c",i)]=sprintf("\\u%04x",i)} {if(NR>1) printf "\\n"; for(i=1;i<=length($0);i++){ c=substr($0,i,1); if(c=="\\") printf "\\\\"; else if(c=="\"") printf "\\\""; else if(c in esc) printf "%s",esc[c]; else printf "%s",c }}')`,String.raw`post(){ if [ -z "$1" ]; then FAILED=1; return; fi; curl -fsS --max-time 30 -X POST -H 'Content-Type: application/json' --data "{\"$2\":\"$ESCAPED\"}" "$1" >/dev/null || FAILED=1; }`,...n,'exit "$FAILED"',"TS_CLOUD_NOTIFY_EOF","chmod 0700 /usr/local/bin/ts-cloud-notify.new","mv -f /usr/local/bin/ts-cloud-notify.new /usr/local/bin/ts-cloud-notify"]}import{isIP as Yn}from"node:net";var en="/etc/rpx/certs",Jn="/etc/rpx/local-ca",Ta="rpx-root-ca.crt";function At(e=Jn){return`${e.replace(/\/+$/,"")}/${Ta}`}function xr(e){if(e.toLowerCase().endsWith(".local"))return!1;return e.split(".").length===2}function to(e,t={}){let r=new Set;for(let s of Object.values(e)){if(!s?.domain)continue;if(w(s)==="bucket")continue;r.add(s.domain)}let n=new Set;for(let s of Object.values(e)){if(!s?.domain||w(s)==="bucket")continue;for(let o of s.aliases??[]){let i=String(o).trim().toLowerCase();if(i&&i!==s.domain)n.add(i)}}if(t.autoWww!==!1)for(let s of[...r]){if(!xr(s))continue;r.add(`www.${s}`)}for(let s of n)r.add(s);return[...r]}var Ca=["1.1.1.1","8.8.8.8"],Pa="/var/www/acme-challenge";function xa(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 Ra(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 Rr(e){if(!e)return;return e.tls??"local-ca"}function ro(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 Qn(e){if(e.cloud?.provider!=="ssh")return;return e.ssh?.profile}function Ea(e){let t=e.trim().toLowerCase();if(!t||t.startsWith("*")||t.includes(":")||t.includes("/")||t.includes(" "))return!1;if(Yn(t)!==0)return!1;return t.endsWith(".local")||!t.includes(".")}function Oa(e,t,r){let n=[],s=new Set,o=(l,u)=>{let d=l.trim().toLowerCase();if(!d||s.has(d))return;s.add(d),n.push({host:d,source:u})},i=t.hostname?.trim(),a=(i||`${r}.local`).toLowerCase();if(o(a,i?"ssh.lan.hostname":`the ssh provider's default LAN name for project "${r}"`),Object.entries(e).some(([l,u])=>!!u&&Br(l)))o(`dashboard.${a}`,"the management dashboard site");for(let[l,u]of Object.entries(e)){if(!u?.domain)continue;if(w(u)==="bucket")continue;if(!Ea(u.domain))continue;o(u.domain,`site "${l}"`)}return n}function Da(e,t){if(!t?.length)return;return t.find((r)=>{let n=(r.startsWith(".")?r.slice(1):r).toLowerCase();return e===n||e.endsWith(`.${n}`)})}function Ia(e,t){if(!t?.enabled)return;for(let{host:r,source:n}of e){let s=Da(r,t.allowedSuffixes);if(!s)continue;throw Error(`The LAN certificate authority and public on-demand TLS both claim "${r}". LAN source: ${n}. Public source: the on-demand TLS allowed suffix "${s}", 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 Aa(e){let t=e.split(".");return t.length>=3&&t[0]==="*"&&t.slice(1).every((r)=>/^[a-z0-9-]+$/i.test(r))}function Zn(e,t={}){let{wildcardCerts:r,...n}=e;return JSON.stringify({...t,...n},null,2)}function es(e){if(!e||e==="/")return;let t=`/${e}`.replace(/\/+/g,"/").replace(/\/+$/,"");if(!t.startsWith("/"))t=`/${t}`;return t===""||t==="/"?void 0:t}function It(e,t){let n=(t?`${e}${t}`:e).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return n.length>0?n:"rpx"}function La(e,t){if(!t||t.length===0)return`localhost:${e}`;return t.map((r)=>`${r.privateIp??r.publicIp}:${e}`)}function ts(e,t,r){let n=(t.wwwRoot??"/var/www").replace(/\/+$/,""),s=t.slug??"app",o=t.proxy.certsDir??en,i=t.proxy.loadBalancer,a=[],c=new Set,l=new Map;for(let[h,f]of Object.entries(e)){if(!f||!f.domain)continue;let S=w(f);if(S==="bucket")continue;let k=a.length,O=[...new Set((f.aliases??[]).map((x)=>String(x).trim().toLowerCase()).filter((x)=>x&&x!==f.domain))],D=()=>{let x=a.slice(k).filter((H)=>H.to===f.domain);for(let H of O){for(let V of x)a.push({...V,to:H,id:It(H,V.path)});if(Aa(H)){if(!l.has(H))l.set(H,{domain:H,dnsEnvFile:`${n}/${s}-${h}/shared/.env`})}else c.add(H)}},I=es(f.path),E=It(f.domain,I),z=Ra(f);if(S==="redirect"){a.push({to:f.domain,path:I,redirect:xa(f.redirect),id:E,...z?{auth:z}:{}}),c.add(f.domain),D();continue}if(S==="proxy"){let x=Gs(f);if(x.length===0)continue;let H=x.length===1?x[0]:x;a.push({to:f.domain,path:I,from:H,id:E,...z?{auth:z}:{},...Array.isArray(H)&&i?{loadBalancer:i}:{}}),c.add(f.domain),D();continue}if(S==="server-app"){if(typeof f.port!=="number")continue;let x=La(f.port,r);a.push({to:f.domain,path:I,from:x,id:E,...z?{auth:z}:{},...Array.isArray(x)&&i?{loadBalancer:i}:{}})}else a.push({to:f.domain,path:I,static:{dir:`${n}/${s}-${h}/current`,spa:f.spa??!1,pathRewriteStyle:f.pathRewriteStyle??"directory"},cleanUrls:f.pathRewriteStyle!=="flat",...z?{auth:z}:{},id:E});c.add(f.domain),D()}if(t.proxy.autoWww!==!1)for(let h of[...c]){if(!xr(h))continue;let f=`www.${h}`;if(c.has(f))continue;a.push({to:f,redirect:{to:`https://${h}`},id:It(f)}),c.add(f)}a.sort((h,f)=>{if(h.to!==f.to)return h.to.localeCompare(f.to);return(f.path?.length??0)-(h.path?.length??0)});let u={proxies:a,productionCerts:{certsDir:o,certsDirServerNames:[...c,...l.keys()]},https:!0,hostsManagement:!1,cleanup:{hosts:!1,certs:!1},...l.size>0?{wildcardCerts:[...l.values()]}:{}};if(t.proxy.onDemandTls&&c.size>0)u.onDemandTls={enabled:!0,allowedSuffixes:[...c],email:t.proxy.onDemandTlsEmail,certsDir:o,staging:t.proxy.onDemandTlsStaging??!1};if(t.proxy.onDemandTls)u.acmeChallengeWebroot=t.proxy.acmeWebroot??Pa;let d=t.proxy.cdn,m=d?.frontedHosts?.length?d.frontedHosts:[...c];if(d?.secret&&m.length>0)u.originGuard={header:d.secretHeader??"X-Origin-Verify",value:d.secret,hosts:m};if(t.lan)if(Rr(t.lan)==="off")u.https=!1;else{let h=Oa(e,t.lan,s);Ia(h,u.onDemandTls);let f=t.lan.ip&&Yn(t.lan.ip)!==0?[t.lan.ip]:[];u.localCa={dir:Jn,hosts:h.map((S)=>S.host),...f.length>0?{ips:f}:{},installTrust:!0}}return u}function Te(e,t){return ts({...e,...t.mail?qo(t.mail):{}},t)}function qe(e,t,r){return ts({...e,...r.mail?qo(r.mail):{}},r,t)}function Z(e){return e?.webServer==="rpx"||e?.proxy?.engine==="rpx"}var dt="/etc/rpx",ie="/opt/rpx-gateway",Cr="/etc/rpx/gateway.ts",Ge="/etc/rpx/gateway",ye="rpx-gateway.service",pe="/etc/rpx/sites.d";function ka(e=pe,t=en){return`// Generated by ts-cloud — rpx gateway assembler.
16
16
  // Merges every app's fragment in ${e} so independent deploys compose
17
17
  // without clobbering each other. Each deploy writes only its own <slug>.json.
18
18
  import { startProxies } from '@stacksjs/rpx'
@@ -135,13 +135,13 @@ const retained = Array.isArray(current.proxies) ? current.proxies.filter(isDashb
135
135
  const next = Array.isArray(candidate.proxies) ? candidate.proxies.filter(route => !isDashboard(route)) : []
136
136
  candidate.proxies = [...next, ...retained]
137
137
  writeFileSync(candidatePath, JSON.stringify(candidate, null, 2) + '\\n', { mode: 0o600 })
138
- `.trim();return[`__tsc_fragment_candidate="$(mktemp "${e}.candidate.XXXXXX")"`,`cat > "$__tsc_fragment_candidate" <<'${r}'`,t,r,'chmod 0600 "$__tsc_fragment_candidate"',`if [ -f ${e} ]; then TS_CLOUD_RPX_CURRENT_FRAGMENT=${e} TS_CLOUD_RPX_CANDIDATE_FRAGMENT="$__tsc_fragment_candidate" ${n.bunBin} -e ${Na(s)}; fi`,`mv -f "$__tsc_fragment_candidate" ${e}`,`chmod 0600 ${e}`]}var Ha={high:"256M",max:"384M"},Ua={high:"512M",max:"768M"};function Er(e){return`rpx-cert-renew-${(e||"app").replace(/[^a-z0-9._-]+/gi,"-")}.service`}function Or(e){let t=new Set;for(let r of e.proxies){let n=r.to;if(!n||n.startsWith("*")||n.includes(":")||!n.includes("."))continue;t.add(n)}return[...t]}function Ma(e){if(e.length===0)return[];let t=["# Wildcards: dns-01 (Porkbun), keys read from the site's env file for tlsx alone.","dns_env() {",' [ -r "$1" ] || return 0',` sed -n "s/^$2=//p" "$1" | tail -n 1 | sed -e 's/^"\\(.*\\)"$/\\1/' -e "s/^'\\(.*\\)'$/\\1/"`,"}","wildcard() {",' apex="$1"',' envfile="$2"',' name="*.$apex"',' key=$(dns_env "$envfile" PORKBUN_API_KEY)',' secret=$(dns_env "$envfile" PORKBUN_SECRET_KEY)',' if [ -z "$key" ] || [ -z "$secret" ]; then',' echo "wildcard $name skipped: no PORKBUN_API_KEY / PORKBUN_SECRET_KEY in $envfile (non-fatal)"'," return 0"," fi",' if [ ! -s "$CERTS/_wildcard.$apex.crt" ]; then',' PORKBUN_API_KEY="$key" PORKBUN_SECRET_KEY="$secret" $TLSX acme:issue -d "$name" --method dns-01 --dns-provider porkbun --dir "$CERTS" --prod --email "$EMAIL" || echo "issue $name failed (non-fatal)"'," else",' PORKBUN_API_KEY="$key" PORKBUN_SECRET_KEY="$secret" $TLSX acme:renew --domains "$name" --method dns-01 --dir "$CERTS" --days 30 --prod --email "$EMAIL" || echo "renew $name failed (non-fatal)"'," fi","}"];for(let r of e){let n=r.domain.replace(/^\*\./,"");t.push(`wildcard '${n}' '${r.dnsEnvFile.replace(/'/g,"")}'`)}return t}function Xn(e){let{config:t,proxy:r}=e,n=t.acmeChallengeWebroot,s=Or(t);if(!r.onDemandTls||!n||s.length===0)return[];let o=e.bunBin??"/usr/local/bin/bun",i=r.tlsxVersion??"latest",a=t.productionCerts.certsDir,c=r.onDemandTlsEmail??`webmaster@${s[0]}`,l=`${o} ${ie}/node_modules/@stacksjs/tlsx/dist/bin/cli.js`,u=s.join(","),d=s.join(" "),m=(e.slug||"app").replace(/[^a-z0-9._-]+/gi,"-"),h=`${dt}/renew-certs-${m}.sh`,f=Er(m),S=`rpx-cert-renew-${m}.timer`,k=t.wildcardCerts??[],E=k.length>0?"tlsx http-01 + dns-01 wildcard":"tlsx http-01",O=["#!/bin/sh",`# Generated by ts-cloud — issue/renew rpx gateway TLS certs via ${E}.`,"# The running gateway serves the challenge from $WEBROOT on :80, so this needs","# no downtime and no DNS credentials. Reloads the gateway only if a cert changed.","set -u",`CERTS='${a}'`,`WEBROOT='${n}'`,`EMAIL='${c}'`,`TLSX="${l}"`,`BUN='${o}'`,`DOMAINS='${u}'`,"DNS_ATTEMPTS='24'","DNS_DELAY_SECONDS='5'",`DNS_RESOLVERS='${Ca.join(" ")}'`,"dns_resolves() {",' d="$1"'," for ns in $DNS_RESOLVERS; do",` if $BUN --eval "const{Resolver}=require('node:dns');const r=new Resolver();r.setServers([process.argv[1]]);r.resolve4(process.argv[2],e=>process.exit(e?1:0))" "$ns" "$d" >/dev/null 2>&1; then`," return 0"," fi"," done",' getent ahosts "$d" >/dev/null 2>&1',"}","wait_for_dns() {",' d="$1"'," attempt=1",' while ! dns_resolves "$d"; do',' if [ "$attempt" -ge "$DNS_ATTEMPTS" ]; then',' echo "DNS for $d did not become resolvable after $DNS_ATTEMPTS attempts" >&2'," return 1"," fi",' echo "Waiting for public DNS before ACME: $d (attempt $attempt/$DNS_ATTEMPTS)"',' sleep "$DNS_DELAY_SECONDS"'," attempt=$((attempt + 1))"," done","}",'before=$(cat "$CERTS"/*.crt 2>/dev/null | sha256sum)',`for d in ${d}; do`,' if [ ! -s "$CERTS/$d.crt" ]; then',' if wait_for_dns "$d"; then',' $TLSX acme:issue -d "$d" --method http-01 --webroot "$WEBROOT" --dir "$CERTS" --prod --email "$EMAIL" || echo "issue $d failed (non-fatal)"'," else",' echo "issue $d skipped until DNS resolves (non-fatal)"'," fi"," # rpx reloads its SNI set when a PEM appears. Complete that reload"," # before the next hostname starts http-01, or :80 can disappear in"," # the middle of the following challenge on a multi-domain deploy.",` [ -s "$CERTS/$d.crt" ] && systemctl restart ${ye}`," fi","done",'$TLSX acme:renew --domains "$DOMAINS" --method http-01 --webroot "$WEBROOT" --dir "$CERTS" --days 30 --prod --email "$EMAIL" || echo "renew: some domains failed (non-fatal)"',...Ma(k),'rm -f "$CERTS"/*.chain.crt','after=$(cat "$CERTS"/*.crt 2>/dev/null | sha256sum)',`[ "$before" = "$after" ] || systemctl restart ${ye}`].join(`
139
- `),D=["[Unit]",`Description=Issue/renew rpx gateway TLS certs for ${m} (${E})`,`After=network-online.target ${ye}`,"Wants=network-online.target","","[Service]","Type=oneshot",`ExecStart=${h}`].join(`
140
- `),R=["[Unit]",`Description=Daily rpx gateway TLS cert issuance/renewal for ${m}`,"","[Timer]","OnCalendar=*-*-* 03:30:00","RandomizedDelaySec=1h","Persistent=true","","[Install]","WantedBy=timers.target"].join(`
141
- `);return[`mkdir -p ${n}`,...e.tenant?[]:[`(cd ${ie} && ${o} add @stacksjs/tlsx@${i}) || true`],...Ve(h,O,"TS_CLOUD_RENEW_EOF"),`chmod +x ${h}`,...Ve(`/etc/systemd/system/${f}`,D,"TS_CLOUD_RENEW_SVC_EOF"),...Ve(`/etc/systemd/system/${S}`,R,"TS_CLOUD_RENEW_TIMER_EOF"),"systemctl daemon-reload",`systemctl enable --now ${S} || true`,`${h} || true`]}function ve(e){let{config:t,proxy:r}=e,n=e.bunBin??"/usr/local/bin/bun",s=r.version??"latest",o=t.productionCerts.certsDir,i=(e.slug||"app").replace(/[^a-z0-9._-]+/gi,"-"),a=Zn(t,{slug:i}),c=ka(pe,o);if(e.tenant)return["set -euo pipefail",`if [ ! -x ${Ge} ] || [ ! -d ${ie}/node_modules/@stacksjs/rpx ]; then`,` echo "ts-cloud: no rpx gateway on this box. This project attaches to another project's compute, so it does not provision one - deploy the owning project first." >&2`," exit 1","fi",`mkdir -p ${pe} ${o}`,`__tsc_rpx_before="$(sha256sum ${pe}/${i}.json 2>/dev/null | cut -d' ' -f1 || true)"`,...Pr(`${pe}/${i}.json`,a,"TS_CLOUD_RPX_FRAGMENT_EOF",{bunBin:n,preserveManagementDashboardRoutes:e.preserveManagementDashboardRoutes}),`__tsc_rpx_after="$(sha256sum ${pe}/${i}.json 2>/dev/null | cut -d' ' -f1 || true)"`,`if [ "$__tsc_rpx_before" != "$__tsc_rpx_after" ] || ! systemctl is-active --quiet ${ye}; then`,` systemctl restart ${ye}`,"else",` echo "[ts-cloud] rpx routes for ${i} unchanged - leaving the shared gateway alone"`,"fi",...Xn(e)];let u=[`Environment=RPX_UPSTREAM_TIMEOUT=${r.upstreamTimeout??60}`];if(typeof r.maxUpstreamConns==="number")u.push(`Environment=RPX_MAX_UPSTREAM_CONNS=${r.maxUpstreamConns}`);let d=e.profile==="raspberry-pi"?Ha:Ua,m=r.memoryHigh??d.high,h=r.memoryMax??d.max;return["set -euo pipefail",`mkdir -p ${dt} ${pe} ${o} ${ie}`,`rm -rf ${ie}.next ${ie}.prev`,`mkdir -p ${ie}.next`,`(cd ${ie}.next && ${n} add @stacksjs/rpx@${s})`,`mv ${ie} ${ie}.prev`,`mv ${ie}.next ${ie}`,`rm -rf ${ie}.prev`,`ln -sfn ${ie}/node_modules ${dt}/node_modules`,...Pr(`${pe}/${i}.json`,a,"TS_CLOUD_RPX_FRAGMENT_EOF",{bunBin:n,preserveManagementDashboardRoutes:e.preserveManagementDashboardRoutes}),...Ve(Cr,c,"TS_CLOUD_RPX_EOF"),`${n} build --production --compile --outfile ${Ge}.next ${Cr}`,`chmod 0755 ${Ge}.next`,`mv -f ${Ge}.next ${Ge}`,...Ve(`/etc/systemd/system/${ye}`,["[Unit]","Description=rpx reverse-proxy gateway (managed by ts-cloud)","After=network.target network-online.target","Wants=network-online.target","","[Service]","Type=simple",`ExecStart=${Ge}`,`WorkingDirectory=${ie}`,"Environment=BUN_INSTALL=/root/.bun","Environment=APP_ENV=production","Environment=NODE_ENV=production",...u,"MemoryAccounting=true",`MemoryHigh=${m}`,`MemoryMax=${h}`,"CPUWeight=500","IOWeight=500","OOMPolicy=stop","Restart=always","RestartSec=5","StartLimitIntervalSec=120","StartLimitBurst=5",`ExecStartPre=/bin/sh -c 'for p in 80 443; do fuser -k -n tcp "$p" 2>/dev/null || true; done; sleep 1'`,"LimitNOFILE=1048576","AmbientCapabilities=CAP_NET_BIND_SERVICE","","[Install]","WantedBy=multi-user.target"].join(`
138
+ `.trim();return[`__tsc_fragment_candidate="$(mktemp "${e}.candidate.XXXXXX")"`,`cat > "$__tsc_fragment_candidate" <<'${r}'`,t,r,'chmod 0600 "$__tsc_fragment_candidate"',`if [ -f ${e} ]; then TS_CLOUD_RPX_CURRENT_FRAGMENT=${e} TS_CLOUD_RPX_CANDIDATE_FRAGMENT="$__tsc_fragment_candidate" ${n.bunBin} -e ${Na(s)}; fi`,`mv -f "$__tsc_fragment_candidate" ${e}`,`chmod 0600 ${e}`]}var Ha={high:"256M",max:"384M"},Ua={high:"512M",max:"768M"};function Er(e){return`rpx-cert-renew-${(e||"app").replace(/[^a-z0-9._-]+/gi,"-")}.service`}function Or(e){let t=new Set;for(let r of e.proxies){let n=r.to;if(!n||n.startsWith("*")||n.includes(":")||!n.includes("."))continue;t.add(n)}return[...t]}function Ma(e){if(e.length===0)return[];let t=["# Wildcards: dns-01 (Porkbun), keys read from the site's env file for tlsx alone.","dns_env() {",' [ -r "$1" ] || return 0',` sed -n "s/^$2=//p" "$1" | tail -n 1 | sed -e 's/^"\\(.*\\)"$/\\1/' -e "s/^'\\(.*\\)'$/\\1/"`,"}","wildcard() {",' apex="$1"',' envfile="$2"',' name="*.$apex"',' key=$(dns_env "$envfile" PORKBUN_API_KEY)',' secret=$(dns_env "$envfile" PORKBUN_SECRET_KEY)',' if [ -z "$key" ] || [ -z "$secret" ]; then',' echo "wildcard $name skipped: no PORKBUN_API_KEY / PORKBUN_SECRET_KEY in $envfile (non-fatal)"'," return 0"," fi",' if [ ! -s "$CERTS/_wildcard.$apex.crt" ]; then',' PORKBUN_API_KEY="$key" PORKBUN_SECRET_KEY="$secret" $TLSX acme:issue -d "$name" --method dns-01 --dns-provider porkbun --dir "$CERTS" --prod --email "$EMAIL" || echo "issue $name failed (non-fatal)"'," else",' PORKBUN_API_KEY="$key" PORKBUN_SECRET_KEY="$secret" $TLSX acme:renew --domains "$name" --method dns-01 --dir "$CERTS" --days 30 --prod --email "$EMAIL" || echo "renew $name failed (non-fatal)"'," fi","}"];for(let r of e){let n=r.domain.replace(/^\*\./,"");t.push(`wildcard '${n}' '${r.dnsEnvFile.replace(/'/g,"")}'`)}return t}function Xn(e){let{config:t,proxy:r}=e,n=t.acmeChallengeWebroot,s=Or(t);if(!r.onDemandTls||!n||s.length===0)return[];let o=e.bunBin??"/usr/local/bin/bun",i=r.tlsxVersion??"latest",a=t.productionCerts.certsDir,c=r.onDemandTlsEmail??`webmaster@${s[0]}`,l=`${o} ${ie}/node_modules/@stacksjs/tlsx/dist/bin/cli.js`,u=s.join(","),d=s.join(" "),m=(e.slug||"app").replace(/[^a-z0-9._-]+/gi,"-"),h=`${dt}/renew-certs-${m}.sh`,f=Er(m),S=`rpx-cert-renew-${m}.timer`,k=t.wildcardCerts??[],O=k.length>0?"tlsx http-01 + dns-01 wildcard":"tlsx http-01",D=["#!/bin/sh",`# Generated by ts-cloud — issue/renew rpx gateway TLS certs via ${O}.`,"# The running gateway serves the challenge from $WEBROOT on :80, so this needs","# no downtime and no DNS credentials. Reloads the gateway only if a cert changed.","set -u",`CERTS='${a}'`,`WEBROOT='${n}'`,`EMAIL='${c}'`,`TLSX="${l}"`,`BUN='${o}'`,`DOMAINS='${u}'`,"DNS_ATTEMPTS='24'","DNS_DELAY_SECONDS='5'",`DNS_RESOLVERS='${Ca.join(" ")}'`,"dns_resolves() {",' d="$1"'," for ns in $DNS_RESOLVERS; do",` if $BUN --eval "const{Resolver}=require('node:dns');const r=new Resolver();r.setServers([process.argv[1]]);r.resolve4(process.argv[2],e=>process.exit(e?1:0))" "$ns" "$d" >/dev/null 2>&1; then`," return 0"," fi"," done",' getent ahosts "$d" >/dev/null 2>&1',"}","wait_for_dns() {",' d="$1"'," attempt=1",' while ! dns_resolves "$d"; do',' if [ "$attempt" -ge "$DNS_ATTEMPTS" ]; then',' echo "DNS for $d did not become resolvable after $DNS_ATTEMPTS attempts" >&2'," return 1"," fi",' echo "Waiting for public DNS before ACME: $d (attempt $attempt/$DNS_ATTEMPTS)"',' sleep "$DNS_DELAY_SECONDS"'," attempt=$((attempt + 1))"," done","}",'before=$(cat "$CERTS"/*.crt 2>/dev/null | sha256sum)',`for d in ${d}; do`,' if [ ! -s "$CERTS/$d.crt" ]; then',' if wait_for_dns "$d"; then',' $TLSX acme:issue -d "$d" --method http-01 --webroot "$WEBROOT" --dir "$CERTS" --prod --email "$EMAIL" || echo "issue $d failed (non-fatal)"'," else",' echo "issue $d skipped until DNS resolves (non-fatal)"'," fi"," # rpx reloads its SNI set when a PEM appears. Complete that reload"," # before the next hostname starts http-01, or :80 can disappear in"," # the middle of the following challenge on a multi-domain deploy.",` [ -s "$CERTS/$d.crt" ] && systemctl restart ${ye}`," fi","done",'$TLSX acme:renew --domains "$DOMAINS" --method http-01 --webroot "$WEBROOT" --dir "$CERTS" --days 30 --prod --email "$EMAIL" || echo "renew: some domains failed (non-fatal)"',...Ma(k),'rm -f "$CERTS"/*.chain.crt','after=$(cat "$CERTS"/*.crt 2>/dev/null | sha256sum)',`[ "$before" = "$after" ] || systemctl restart ${ye}`].join(`
139
+ `),I=["[Unit]",`Description=Issue/renew rpx gateway TLS certs for ${m} (${O})`,`After=network-online.target ${ye}`,"Wants=network-online.target","","[Service]","Type=oneshot",`ExecStart=${h}`].join(`
140
+ `),E=["[Unit]",`Description=Daily rpx gateway TLS cert issuance/renewal for ${m}`,"","[Timer]","OnCalendar=*-*-* 03:30:00","RandomizedDelaySec=1h","Persistent=true","","[Install]","WantedBy=timers.target"].join(`
141
+ `);return[`mkdir -p ${n}`,...e.tenant?[]:[`(cd ${ie} && ${o} add @stacksjs/tlsx@${i}) || true`],...Ve(h,D,"TS_CLOUD_RENEW_EOF"),`chmod +x ${h}`,...Ve(`/etc/systemd/system/${f}`,I,"TS_CLOUD_RENEW_SVC_EOF"),...Ve(`/etc/systemd/system/${S}`,E,"TS_CLOUD_RENEW_TIMER_EOF"),"systemctl daemon-reload",`systemctl enable --now ${S} || true`,`${h} || true`]}function ve(e){let{config:t,proxy:r}=e,n=e.bunBin??"/usr/local/bin/bun",s=r.version??"latest",o=t.productionCerts.certsDir,i=(e.slug||"app").replace(/[^a-z0-9._-]+/gi,"-"),a=Zn(t,{slug:i}),c=ka(pe,o);if(e.tenant)return["set -euo pipefail",`if [ ! -x ${Ge} ] || [ ! -d ${ie}/node_modules/@stacksjs/rpx ]; then`,` echo "ts-cloud: no rpx gateway on this box. This project attaches to another project's compute, so it does not provision one - deploy the owning project first." >&2`," exit 1","fi",`mkdir -p ${pe} ${o}`,`__tsc_rpx_before="$(sha256sum ${pe}/${i}.json 2>/dev/null | cut -d' ' -f1 || true)"`,...Pr(`${pe}/${i}.json`,a,"TS_CLOUD_RPX_FRAGMENT_EOF",{bunBin:n,preserveManagementDashboardRoutes:e.preserveManagementDashboardRoutes}),`__tsc_rpx_after="$(sha256sum ${pe}/${i}.json 2>/dev/null | cut -d' ' -f1 || true)"`,`if [ "$__tsc_rpx_before" != "$__tsc_rpx_after" ] || ! systemctl is-active --quiet ${ye}; then`,` systemctl restart ${ye}`,"else",` echo "[ts-cloud] rpx routes for ${i} unchanged - leaving the shared gateway alone"`,"fi",...Xn(e)];let u=[`Environment=RPX_UPSTREAM_TIMEOUT=${r.upstreamTimeout??60}`];if(typeof r.maxUpstreamConns==="number")u.push(`Environment=RPX_MAX_UPSTREAM_CONNS=${r.maxUpstreamConns}`);let d=e.profile==="raspberry-pi"?Ha:Ua,m=r.memoryHigh??d.high,h=r.memoryMax??d.max;return["set -euo pipefail",`mkdir -p ${dt} ${pe} ${o} ${ie}`,`rm -rf ${ie}.next ${ie}.prev`,`mkdir -p ${ie}.next`,`(cd ${ie}.next && ${n} add @stacksjs/rpx@${s})`,`mv ${ie} ${ie}.prev`,`mv ${ie}.next ${ie}`,`rm -rf ${ie}.prev`,`ln -sfn ${ie}/node_modules ${dt}/node_modules`,...Pr(`${pe}/${i}.json`,a,"TS_CLOUD_RPX_FRAGMENT_EOF",{bunBin:n,preserveManagementDashboardRoutes:e.preserveManagementDashboardRoutes}),...Ve(Cr,c,"TS_CLOUD_RPX_EOF"),`${n} build --production --compile --outfile ${Ge}.next ${Cr}`,`chmod 0755 ${Ge}.next`,`mv -f ${Ge}.next ${Ge}`,...Ve(`/etc/systemd/system/${ye}`,["[Unit]","Description=rpx reverse-proxy gateway (managed by ts-cloud)","After=network.target network-online.target","Wants=network-online.target","","[Service]","Type=simple",`ExecStart=${Ge}`,`WorkingDirectory=${ie}`,"Environment=BUN_INSTALL=/root/.bun","Environment=APP_ENV=production","Environment=NODE_ENV=production",...u,"MemoryAccounting=true",`MemoryHigh=${m}`,`MemoryMax=${h}`,"CPUWeight=500","IOWeight=500","OOMPolicy=stop","Restart=always","RestartSec=5","StartLimitIntervalSec=120","StartLimitBurst=5",`ExecStartPre=/bin/sh -c 'for p in 80 443; do fuser -k -n tcp "$p" 2>/dev/null || true; done; sleep 1'`,"LimitNOFILE=1048576","AmbientCapabilities=CAP_NET_BIND_SERVICE","","[Install]","WantedBy=multi-user.target"].join(`
142
142
  `),"TS_CLOUD_RPX_UNIT_EOF"),"systemctl daemon-reload","systemctl disable --now bun-gateway.service 2>/dev/null || true","systemctl disable --now bun-gateway-renew.timer bun-gateway-renew.service 2>/dev/null || true","rm -f /etc/systemd/system/bun-gateway-renew.timer /etc/systemd/system/bun-gateway-renew.service","systemctl disable --now ts-cloud-nginx.service 2>/dev/null || true",`for timer in /etc/systemd/system/rpx-cert-renew-*.timer; do [ -e "$timer" ] || continue; unit="$(basename "$timer")"; tenant="\${unit#rpx-cert-renew-}"; tenant="\${tenant%.timer}"; [ -f "${pe}/$tenant.json" ] && continue; systemctl disable --now "$unit" 2>/dev/null || true; rm -f "$timer" "/etc/systemd/system/rpx-cert-renew-$tenant.service" "${dt}/renew-certs-$tenant.sh"; done`,`systemctl enable ${ye}`,`systemctl restart ${ye}`,...Xn(e)]}function Ke(e){let t=(e.slug||"app").replace(/[^a-z0-9._-]+/gi,"-"),r=Zn(e.config,{slug:t});return["set -euo pipefail",`mkdir -p ${pe}`,...Pr(`${pe}/${t}.json`,r,"TS_CLOUD_RPX_FRAGMENT_EOF",{bunBin:"/usr/local/bin/bun",preserveManagementDashboardRoutes:e.preserveManagementDashboardRoutes}),`systemctl restart ${ye}`]}function Ye(e=[],t={}){let r=t.path??"/root/.ssh/authorized_keys",s=[`mkdir -p ${r.replace(/\/[^/]*$/,"")}`,`touch ${r}`,`sed -i '/^${rs("# >>> ts-cloud managed keys >>>")}$/,/^${rs("# <<< ts-cloud managed keys <<<")}$/d' ${r}`];if(e.length>0){let o=["# >>> ts-cloud managed keys >>>",...e.map((i)=>`${i.publicKey.trim()} ${i.name}`),"# <<< ts-cloud managed keys <<<"].join(`
143
143
  `);s.push(`cat >> ${r} <<'TS_CLOUD_KEYS_EOF'`,o,"TS_CLOUD_KEYS_EOF",`chmod 600 ${r}`)}return s}function rs(e){return e.replace(/[.*[\]\\/^$]/g,"\\$&")}function ss(e,t){let r=`/tmp/ts-cloud-${e}.sh`,n=`TS_CLOUD_${e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}_EOF`;return[`cat > ${r} <<'${n}'`,t.replace(/\n$/,""),n,`chmod +x ${r}`,`bash ${r} || echo "ts-cloud: ${e} setup did not complete; continuing" >&2`,`rm -f ${r}`]}function os(e,t){if(e===!1)return;if(e===!0||e===void 0)return t;return e}var ns={enabled:!0,ports:[80,443]},za={mode:"detection",paranoiaLevel:1};function Fa(e=!0,t=[]){let r=os(e,ns);if(!r||r.enabled===!1)return[];let n=[...new Set([...r.ports??ns.ports??[],...t])].sort((s,o)=>s-o);return ss("ddos",wr({...r,ports:n}))}function Ba(e=!0){let t=os(e,za);if(!t||t.mode==="off")return[];return ss("waf",fs(t))}function is(e={},t=[]){return[...Fa(e.ddos,t),...Ba(e.waf)]}function Ka(e){return`${e}-sftp`}function as(e){return e.port??2222}function ja(e){let t=e.sftp.storage;if(t?.type==="efs"&&t.path)return t.path;return`/var/sftp/${e.slug}`}function Qe(e){return`'${e.split("'").join("'\\''")}'`}function gs(e,t){if(t==="aws")return;let r=e.storage;if(r?.type==="s3"||!r&&!!e.bucket)throw Error(`sftp: bucket-backed storage is only available on the aws provider (Transfer Family). On ${t}, use storage: { type: 'efs' } to serve a directory on the server.`);for(let[s,o]of Object.entries(e.users))if(!o.sshPublicKeys?.length)throw Error(`sftp: user ${s} needs at least one SSH public key`)}function hs(e){let{slug:t,sftp:r}=e,n=Ka(t),s=ja(e),o=as(r),i="/etc/ts-sftp/host_key",a="/etc/ts-sftp/users",c=r.serviceUser??"ts-sftp",l=[`# --- ts-sftp (${n}) ---`,`id -u ${c} >/dev/null 2>&1 || useradd --system --home-dir ${Qe(s)} --shell /usr/sbin/nologin ${c}`,'export HOME="${HOME:-/root}"','command -v bun >/dev/null 2>&1 || (curl -fsSL https://bun.sh/install | bash && ln -sf "$HOME/.bun/bin/bun" /usr/local/bin/bun)',`mkdir -p ${Qe(s)} /etc/ts-sftp /etc/ts-sftp/users /opt/ts-sftp`,"chmod 750 /etc/ts-sftp",`cd /opt/ts-sftp && [ -f package.json ] || printf '{"name":"ts-sftp-host","private":true}' > package.json`,`cd /opt/ts-sftp && bun add ts-sftp@${r.version??"latest"} --no-save --production || bun add ts-sftp@${r.version??"latest"}`,`[ -f /etc/ts-sftp/host_key ] || bun /opt/ts-sftp/node_modules/ts-sftp/dist/bin/cli.js keygen --out /etc/ts-sftp/host_key --comment ${Qe(`${t}-sftp`)}`,"chmod 600 /etc/ts-sftp/host_key",'BUN_REAL=$(readlink -f "$(command -v bun)")','case "$BUN_REAL" in /root/*) install -m 0755 "$BUN_REAL" /usr/local/bin/ts-sftp-bun; BUN_BIN=/usr/local/bin/ts-sftp-bun;; *) BUN_BIN="$BUN_REAL";; esac'],u=[];for(let[d,m]of Object.entries(r.users)){let h=(m.homeDirectory??d).replace(/^\/+|\/+$/g,"");if(!h||h.split("/").includes(".."))throw Error(`sftp: invalid homeDirectory for user ${d}`);let f=`/etc/ts-sftp/users/${d}.pub`;l.push(`mkdir -p ${Qe(`${s}/${h}`)}`,`printf '%s\\n' ${Qe(m.sshPublicKeys.join(`
144
- `))} > ${f}`,`chmod 644 ${f}`),u.push(`--user ${d}:${f}`)}return l.push(`chown -R ${c}:${c} ${Qe(s)} /etc/ts-sftp`,`cat > /etc/systemd/system/${n}.service <<TSCLOUD_SFTP_UNIT`,"[Unit]","Description=ts-sftp file transfer server","After=network.target","","[Service]",`User=${c}`,`ExecStart=$BUN_BIN /opt/ts-sftp/node_modules/ts-sftp/dist/bin/cli.js serve --root ${s} --host-key /etc/ts-sftp/host_key --port ${o}${r.readOnly?" --read-only":""} ${u.join(" ")}`,"Restart=always","RestartSec=2","NoNewPrivileges=true","PrivateTmp=true","ProtectSystem=strict",`ReadWritePaths=${s}`,"","[Install]","WantedBy=multi-user.target","TSCLOUD_SFTP_UNIT","systemctl daemon-reload",`systemctl enable ${n}.service`,`systemctl restart ${n}.service`),l}function Ss(e){return e?[as(e)]:[]}var Wa=[80,443];function Lt(e={}){if(e.enabled===!1)return[];let t=[...new Set([...Wa,...e.allowedPorts||[]])].filter((n)=>Number.isInteger(n)&&n>=1&&n<=65535).sort((n,s)=>n-s),r=["export DEBIAN_FRONTEND=noninteractive","command -v ufw >/dev/null 2>&1 || apt-get install -y ufw","ufw --force reset","ufw default deny incoming","ufw default allow outgoing","ufw allow OpenSSH"];for(let n of t)r.push(`ufw allow ${n}/tcp`);return r.push("ufw --force enable"),r}function Ue(e,t){let r=e.infrastructure?.compute??{},n=r.runtime==="php"||!!r.php,s=ne(e,{environment:t?.environment}),o=n||!!r.managedServices,i=o?kr():[],a=!Z({...r,proxy:le(e,{environment:t?.environment})}),c=n?[...i,...Dt({versions:r.php?.versions,default:r.php?.default,extensions:r.php?.extensions,installNginx:a,optimizeForProduction:r.php?.optimizeForProduction,ini:r.php?.ini}),...a?$r():[]]:void 0,l=[],u=w(e);if(!n&&o)l.push(...i);if(l.push(...He(e.notifications)),r.managedServices)l.push(...Uo(r.managedServices,{mail:s.enabled?s:void 0}),...Tt(u,r.managedServices));let d=e.infrastructure?.sftp;if(d)gs(d,B(e)),l.push(...hs({slug:e.project.slug,sftp:d}));let m=r.firewall??(n?{enabled:!0}:{enabled:!1}),h=Fr(s);if(l.push(...Lt(h.length>0?{...m,allowedPorts:[...m.allowedPorts??[],...h]}:m)),l.push(...is({ddos:r.ddos,waf:r.waf},[...r.firewall?.allowedPorts??[],...h])),l.push(...Pe(r.autoUpdates??n)),l.push(...eo(r.appUpdates)),l.push(...we(r.monitoring??n)),l.push(...Ye(r.sshKeys,{path:t?.authorizedKeysPath})),r.backups?.enabled)l.push(...Fo({database:u,backups:r.backups}));return{runtime:r.runtime||"bun",runtimeVersion:r.runtimeVersion||"latest",phpBox:n,phpProvision:c,servicesProvision:l.length>0?l:void 0}}function de(e={}){let{runtime:t="bun",runtimeVersion:r="latest",systemPackages:n=[],database:s,phpProvision:o,servicesProvision:i,caddyfile:a,rpxProvision:c,baked:l=!1,swapGb:u=2}=e,d=new Set(n);if(s==="sqlite")d.add("sqlite3");else if(s==="mysql")d.add("mysql-client");else if(s==="postgres")d.add("postgresql-client");let m=`#!/bin/bash
144
+ `))} > ${f}`,`chmod 644 ${f}`),u.push(`--user ${d}:${f}`)}return l.push(`chown -R ${c}:${c} ${Qe(s)} /etc/ts-sftp`,`cat > /etc/systemd/system/${n}.service <<TSCLOUD_SFTP_UNIT`,"[Unit]","Description=ts-sftp file transfer server","After=network.target","","[Service]",`User=${c}`,`ExecStart=$BUN_BIN /opt/ts-sftp/node_modules/ts-sftp/dist/bin/cli.js serve --root ${s} --host-key /etc/ts-sftp/host_key --port ${o}${r.readOnly?" --read-only":""} ${u.join(" ")}`,"Restart=always","RestartSec=2","NoNewPrivileges=true","PrivateTmp=true","ProtectSystem=strict",`ReadWritePaths=${s}`,"","[Install]","WantedBy=multi-user.target","TSCLOUD_SFTP_UNIT","systemctl daemon-reload",`systemctl enable ${n}.service`,`systemctl restart ${n}.service`),l}function Ss(e){return e?[as(e)]:[]}var Wa=[80,443];function Lt(e={}){if(e.enabled===!1)return[];let t=[...new Set([...Wa,...e.allowedPorts||[]])].filter((n)=>Number.isInteger(n)&&n>=1&&n<=65535).sort((n,s)=>n-s),r=["export DEBIAN_FRONTEND=noninteractive","command -v ufw >/dev/null 2>&1 || apt-get install -y ufw","ufw --force reset","ufw default deny incoming","ufw default allow outgoing","ufw allow OpenSSH"];for(let n of t)r.push(`ufw allow ${n}/tcp`);return r.push("ufw --force enable"),r}function Ue(e,t){let r=e.infrastructure?.compute??{},n=r.runtime==="php"||!!r.php,s=ne(e,{environment:t?.environment}),o=n||!!r.managedServices,i=o?kr():[],a=!Z({...r,proxy:le(e,{environment:t?.environment})}),c=n?[...i,...Dt({versions:r.php?.versions,default:r.php?.default,extensions:r.php?.extensions,installNginx:a,optimizeForProduction:r.php?.optimizeForProduction,ini:r.php?.ini}),...a?$r():[]]:void 0,l=[],u=A(e);if(!n&&o)l.push(...i);if(l.push(...He(e.notifications)),r.managedServices)l.push(...Uo(r.managedServices,{mail:s.enabled?s:void 0}),...Tt(u,r.managedServices));let d=e.infrastructure?.sftp;if(d)gs(d,B(e)),l.push(...hs({slug:e.project.slug,sftp:d}));let m=r.firewall??(n?{enabled:!0}:{enabled:!1}),h=Fr(s);if(l.push(...Lt(h.length>0?{...m,allowedPorts:[...m.allowedPorts??[],...h]}:m)),l.push(...is({ddos:r.ddos,waf:r.waf},[...r.firewall?.allowedPorts??[],...h])),l.push(...Pe(r.autoUpdates??n)),l.push(...eo(r.appUpdates)),l.push(...we(r.monitoring??n)),l.push(...Ye(r.sshKeys,{path:t?.authorizedKeysPath})),r.backups?.enabled)l.push(...Fo({database:u,backups:r.backups}));return{runtime:r.runtime||"bun",runtimeVersion:r.runtimeVersion||"latest",phpBox:n,phpProvision:c,servicesProvision:l.length>0?l:void 0}}function de(e={}){let{runtime:t="bun",runtimeVersion:r="latest",systemPackages:n=[],database:s,phpProvision:o,servicesProvision:i,caddyfile:a,rpxProvision:c,baked:l=!1,swapGb:u=2}=e,d=new Set(n);if(s==="sqlite")d.add("sqlite3");else if(s==="mysql")d.add("mysql-client");else if(s==="postgres")d.add("postgresql-client");let m=`#!/bin/bash
145
145
  set -euo pipefail
146
146
  `,h=Math.floor(u);if(h>0)m+=`
147
147
  # Swap: a swapless box under memory pressure lets the kernel OOM killer choose
@@ -251,21 +251,21 @@ ${f.join(`
251
251
  `)}
252
252
  `}return m+=`
253
253
  echo "ts-cloud bootstrap complete — instance is ready for site deploys"
254
- `,m}var ys="/aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id";function vs(e,t){let r=[{port:22,protocol:"tcp",cidr:"0.0.0.0/0"},{port:80,protocol:"tcp",cidr:"0.0.0.0/0"},{port:443,protocol:"tcp",cidr:"0.0.0.0/0"}],n=new Set;for(let s of Object.values(e.sites||{}))if(s&&typeof s.port==="number"&&![22,80,443].includes(s.port))n.add(s.port);for(let s of Fr(ne(e,{environment:t})))n.add(s);for(let s of n)r.push({port:s,protocol:"tcp",cidr:"0.0.0.0/0"});return r}function bs(e,t){let r={...e.infrastructure?.compute,proxy:le(e,{environment:t})},n=Ue(e,{environment:t}),s=r.proxy?.engine==="rpx"?ve({proxy:r.proxy,config:Te(e.sites??{},{proxy:r.proxy,slug:e.project.slug,mail:ne(e,{environment:t})}),slug:e.project.slug,bunBin:r.runtime==="node"||r.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0;return de({runtime:n.runtime,runtimeVersion:n.runtimeVersion,systemPackages:r.systemPackages,database:e.infrastructure?.database,phpProvision:n.phpProvision,servicesProvision:n.servicesProvision,rpxProvision:s,baked:r.bakedImage===!0,swapGb:r.swapGb})}function ws(e){return Buffer.from(e,"utf8").toString("base64")}function _s(e){return e.infrastructure?.compute?.image??null}function kt(e,t){return`${e}-${t}-app-sg`}function Dr(e,t,r="app"){return[{Key:"Project",Value:e},{Key:"Environment",Value:t},{Key:"Role",Value:r},{Key:"ManagedBy",Value:"ts-cloud"}]}function Ga(e,t,r){if(!e?.length)return!1;let n=(s)=>e.find((o)=>o.Key===s)?.Value;return n("Project")===t&&n("Environment")===r}function Ts(e,t){let r=kt(t.slug,t.environment);return e.find((n)=>{if(n.GroupName!==r)return!1;if(t.vpcId&&n.VpcId&&n.VpcId!==t.vpcId)return!1;if(!!n.Tags?.some((o)=>o.Key==="Project"))return Ga(n.Tags,t.slug,t.environment);return!!t.vpcId&&n.VpcId===t.vpcId})}function qa(e){try{let t=Cs(Va(process.cwd(),"storage/cloud/state",`${e}.json`),"utf8"),r=JSON.parse(t);return typeof r.instanceId==="string"&&r.instanceId.length>0?r.instanceId:null}catch{return null}}class Nt{name="aws";usesCloudFormation=!0;region;ec2Client;cfnClient;constructor(e={}){this.region=e.region||"us-east-1",this.ec2Client=e.ec2Client??((t)=>new Q(t)),this.cfnClient=e.cfnClient??((t)=>new v(t))}resolveRegion(e){return e.project.region||this.region}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e,n=this.resolveRegion(t),s=t.project.slug,o=t.infrastructure?.compute;if(!o)throw Error("infrastructure.compute is required to provision AWS compute");let i=this.ec2Client(n),a=await this.findComputeTargets({slug:s,environment:r,role:"app",region:n});if(a.length>0){let H=a[0];return{appInstanceId:H.id,appPublicIp:H.publicIp,appPublicIpv6:H.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}let c=_s(t);if(!c){if(c=(await new We(n).getParameter({Name:ys})).Parameter?.Value??null,!c)throw Error("Could not resolve the Ubuntu 24.04 AMI from SSM")}let l=await i.describeVpcs(),u=(l.Vpcs||[]).find((H)=>H.IsDefault)||(l.Vpcs||[])[0];if(!u?.VpcId)throw Error("No VPC found to launch the instance into");let d=(await i.describeSubnets({Filters:[{Name:"vpc-id",Values:[u.VpcId]}]})).Subnets||[],m=d.find((H)=>H.MapPublicIpOnLaunch)||d[0],h=m?.SubnetId;if(!m?.MapPublicIpOnLaunch)console.warn("ts-cloud: no public subnet found; the instance may not get a public IP (deploys/SSL need one).");let f=kt(s,r),k=(await i.describeSecurityGroups({Filters:[{Name:"group-name",Values:[f]},{Name:"vpc-id",Values:[u.VpcId]}]})).SecurityGroups?.[0]?.GroupId;if(!k)k=(await i.createSecurityGroup({GroupName:f,Description:`ts-cloud ${s}/${r} app`,VpcId:u.VpcId,TagSpecifications:[{ResourceType:"security-group",Tags:Dr(s,r)}]})).GroupId;let E=vs(t,r);await i.authorizeSecurityGroupIngress({GroupId:k,IpPermissions:E.map((H)=>({IpProtocol:H.protocol,FromPort:H.port,ToPort:H.port,IpRanges:[{CidrIp:H.cidr}]}))}).catch((H)=>{if(!/InvalidPermission\.Duplicate/.test(H instanceof Error?H.message:""))throw H});let O=ws(bs(t,r)),D=o.server?.instanceType||"t3.small",z=(await i.runInstances({ImageId:c,InstanceType:D,MinCount:1,MaxCount:1,SecurityGroupIds:k?[k]:void 0,SubnetId:h,UserData:O,IamInstanceProfile:o.server?.iamInstanceProfile?{Name:o.server.iamInstanceProfile}:void 0,TagSpecifications:[{ResourceType:"instance",Tags:[{Key:"Name",Value:`${s}-${r}-app`},...Dr(s,r)]}]})).Instances?.[0]?.InstanceId;if(!z)throw Error("RunInstances did not return an instance id");let x=await i.waitForInstanceState(z,"running");if(!x)throw Error(`Instance ${z} did not reach 'running' before timeout`);return{appInstanceId:z,appPublicIp:x.PublicIpAddress,appPublicIpv6:me(x.Ipv6Address),sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}async destroyCompute(e){let{config:t,environment:r}=e,n=t.project.slug,s=this.resolveRegion(t),o=this.ec2Client(s),i=[],c=(await this.findComputeTargets({slug:n,environment:r,role:"app",region:s})).map((f)=>f.id),l;if(c.length>0)l=(await o.describeInstances({InstanceIds:c}).catch(()=>({Reservations:[]}))).Reservations?.flatMap((S)=>S.Instances??[]).find((S)=>S.VpcId)?.VpcId;if(c.length>0)await o.terminateInstances(c),i.push(...c.map((f)=>`instance ${f}`)),await Promise.all(c.map((f)=>o.waitForInstanceState(f,"terminated").catch(()=>{return})));let u=kt(n,r),d=[{Name:"group-name",Values:[u]}];if(l)d.push({Name:"vpc-id",Values:[l]});let m=await o.describeSecurityGroups({Filters:d}).catch(()=>({SecurityGroups:[]})),h=Ts(m.SecurityGroups??[],{slug:n,environment:r,vpcId:l});if(h?.GroupId)for(let f=0;f<10;f++)try{await o.deleteSecurityGroup(h.GroupId),i.push(`security group ${u}`);break}catch{await new Promise((S)=>setTimeout(S,3000))}return{destroyed:i}}async getComputeOutputs(e){let t=this.resolveRegion(e.config),r=T(e.config,e.environment),n=this.cfnClient(t);try{let s=await n.getStackOutputs(r);return{deployBucketName:s.deployBucketName,appInstanceId:s.appInstanceId,appPublicIp:s.appPublicIp,sshUser:"ec2-user"}}catch(s){if(!/does not exist|ValidationError/i.test(s instanceof Error?s.message:""))throw s;let i=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",region:t}))[0];return{appInstanceId:i?.id,appPublicIp:i?.publicIp,appPublicIpv6:i?.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}}async uploadRelease(e){let t=this.resolveRegion(e.config),n=(await this.getComputeOutputs({config:e.config,environment:e.environment})).deployBucketName;if(!n)throw Error("No deployBucketName in stack outputs. Re-deploy infrastructure to add the staging bucket.");return await new g(t).putObject({bucket:n,key:e.remoteKey,body:Cs(e.localPath),contentType:"application/gzip"}),{artifactRef:`s3://${n}/${e.remoteKey}`}}async findComputeTargets(e){let t=e.region??this.region,r=this.ec2Client(t),n=[{Name:"tag:Project",Values:[e.slug]},{Name:"tag:Environment",Values:[e.environment]},{Name:"tag:Role",Values:[e.role||"app"]},{Name:"instance-state-name",Values:["running","pending"]}],s=await r.describeInstances({Filters:n}),o=this.reservationsToTargets(s.Reservations);if(o.length>0||(e.role||"app")!=="app")return o;let i=e.stackName??`${e.slug}-${e.environment}`,a=qa(i);if(!a)try{a=(await this.cfnClient(t).getStackOutputs(i)).appInstanceId??null}catch{a=null}if(!a)return[];try{let c=await r.describeInstances({InstanceIds:[a],Filters:[{Name:"instance-state-name",Values:["running","pending"]}]});return this.reservationsToTargets(c.Reservations)}catch{return[]}}reservationsToTargets(e){let t=[];for(let r of e||[])for(let n of r.Instances||[]){if(!n.InstanceId)continue;let s=n.Tags?.find((o)=>o.Key==="Name")?.Value;t.push({id:n.InstanceId,name:s,publicIp:n.PublicIpAddress,publicIpv6:me(n.Ipv6Address),privateIp:n.PrivateIpAddress,status:n.State?.Name})}return t}bashWrap(e){return["bash <<'TS_CLOUD_BASH_EOF'",e.join(`
254
+ `,m}var ys="/aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id";function vs(e,t){let r=[{port:22,protocol:"tcp",cidr:"0.0.0.0/0"},{port:80,protocol:"tcp",cidr:"0.0.0.0/0"},{port:443,protocol:"tcp",cidr:"0.0.0.0/0"}],n=new Set;for(let s of Object.values(e.sites||{}))if(s&&typeof s.port==="number"&&![22,80,443].includes(s.port))n.add(s.port);for(let s of Fr(ne(e,{environment:t})))n.add(s);for(let s of n)r.push({port:s,protocol:"tcp",cidr:"0.0.0.0/0"});return r}function bs(e,t){let r={...e.infrastructure?.compute,proxy:le(e,{environment:t})},n=Ue(e,{environment:t}),s=r.proxy?.engine==="rpx"?ve({proxy:r.proxy,config:Te(e.sites??{},{proxy:r.proxy,slug:e.project.slug,mail:ne(e,{environment:t})}),slug:e.project.slug,bunBin:r.runtime==="node"||r.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0;return de({runtime:n.runtime,runtimeVersion:n.runtimeVersion,systemPackages:r.systemPackages,database:e.infrastructure?.database,phpProvision:n.phpProvision,servicesProvision:n.servicesProvision,rpxProvision:s,baked:r.bakedImage===!0,swapGb:r.swapGb})}function ws(e){return Buffer.from(e,"utf8").toString("base64")}function _s(e){return e.infrastructure?.compute?.image??null}function kt(e,t){return`${e}-${t}-app-sg`}function Dr(e,t,r="app"){return[{Key:"Project",Value:e},{Key:"Environment",Value:t},{Key:"Role",Value:r},{Key:"ManagedBy",Value:"ts-cloud"}]}function Ga(e,t,r){if(!e?.length)return!1;let n=(s)=>e.find((o)=>o.Key===s)?.Value;return n("Project")===t&&n("Environment")===r}function Ts(e,t){let r=kt(t.slug,t.environment);return e.find((n)=>{if(n.GroupName!==r)return!1;if(t.vpcId&&n.VpcId&&n.VpcId!==t.vpcId)return!1;if(!!n.Tags?.some((o)=>o.Key==="Project"))return Ga(n.Tags,t.slug,t.environment);return!!t.vpcId&&n.VpcId===t.vpcId})}function qa(e){try{let t=Cs(Va(process.cwd(),"storage/cloud/state",`${e}.json`),"utf8"),r=JSON.parse(t);return typeof r.instanceId==="string"&&r.instanceId.length>0?r.instanceId:null}catch{return null}}class Nt{name="aws";usesCloudFormation=!0;region;ec2Client;cfnClient;constructor(e={}){this.region=e.region||"us-east-1",this.ec2Client=e.ec2Client??((t)=>new Q(t)),this.cfnClient=e.cfnClient??((t)=>new v(t))}resolveRegion(e){return e.project.region||this.region}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e,n=this.resolveRegion(t),s=t.project.slug,o=t.infrastructure?.compute;if(!o)throw Error("infrastructure.compute is required to provision AWS compute");let i=this.ec2Client(n),a=await this.findComputeTargets({slug:s,environment:r,role:"app",region:n});if(a.length>0){let H=a[0];return{appInstanceId:H.id,appPublicIp:H.publicIp,appPublicIpv6:H.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}let c=_s(t);if(!c){if(c=(await new We(n).getParameter({Name:ys})).Parameter?.Value??null,!c)throw Error("Could not resolve the Ubuntu 24.04 AMI from SSM")}let l=await i.describeVpcs(),u=(l.Vpcs||[]).find((H)=>H.IsDefault)||(l.Vpcs||[])[0];if(!u?.VpcId)throw Error("No VPC found to launch the instance into");let d=(await i.describeSubnets({Filters:[{Name:"vpc-id",Values:[u.VpcId]}]})).Subnets||[],m=d.find((H)=>H.MapPublicIpOnLaunch)||d[0],h=m?.SubnetId;if(!m?.MapPublicIpOnLaunch)console.warn("ts-cloud: no public subnet found; the instance may not get a public IP (deploys/SSL need one).");let f=kt(s,r),k=(await i.describeSecurityGroups({Filters:[{Name:"group-name",Values:[f]},{Name:"vpc-id",Values:[u.VpcId]}]})).SecurityGroups?.[0]?.GroupId;if(!k)k=(await i.createSecurityGroup({GroupName:f,Description:`ts-cloud ${s}/${r} app`,VpcId:u.VpcId,TagSpecifications:[{ResourceType:"security-group",Tags:Dr(s,r)}]})).GroupId;let O=vs(t,r);await i.authorizeSecurityGroupIngress({GroupId:k,IpPermissions:O.map((H)=>({IpProtocol:H.protocol,FromPort:H.port,ToPort:H.port,IpRanges:[{CidrIp:H.cidr}]}))}).catch((H)=>{if(!/InvalidPermission\.Duplicate/.test(H instanceof Error?H.message:""))throw H});let D=ws(bs(t,r)),I=o.server?.instanceType||"t3.small",z=(await i.runInstances({ImageId:c,InstanceType:I,MinCount:1,MaxCount:1,SecurityGroupIds:k?[k]:void 0,SubnetId:h,UserData:D,IamInstanceProfile:o.server?.iamInstanceProfile?{Name:o.server.iamInstanceProfile}:void 0,TagSpecifications:[{ResourceType:"instance",Tags:[{Key:"Name",Value:`${s}-${r}-app`},...Dr(s,r)]}]})).Instances?.[0]?.InstanceId;if(!z)throw Error("RunInstances did not return an instance id");let x=await i.waitForInstanceState(z,"running");if(!x)throw Error(`Instance ${z} did not reach 'running' before timeout`);return{appInstanceId:z,appPublicIp:x.PublicIpAddress,appPublicIpv6:me(x.Ipv6Address),sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}async destroyCompute(e){let{config:t,environment:r}=e,n=t.project.slug,s=this.resolveRegion(t),o=this.ec2Client(s),i=[],c=(await this.findComputeTargets({slug:n,environment:r,role:"app",region:s})).map((f)=>f.id),l;if(c.length>0)l=(await o.describeInstances({InstanceIds:c}).catch(()=>({Reservations:[]}))).Reservations?.flatMap((S)=>S.Instances??[]).find((S)=>S.VpcId)?.VpcId;if(c.length>0)await o.terminateInstances(c),i.push(...c.map((f)=>`instance ${f}`)),await Promise.all(c.map((f)=>o.waitForInstanceState(f,"terminated").catch(()=>{return})));let u=kt(n,r),d=[{Name:"group-name",Values:[u]}];if(l)d.push({Name:"vpc-id",Values:[l]});let m=await o.describeSecurityGroups({Filters:d}).catch(()=>({SecurityGroups:[]})),h=Ts(m.SecurityGroups??[],{slug:n,environment:r,vpcId:l});if(h?.GroupId)for(let f=0;f<10;f++)try{await o.deleteSecurityGroup(h.GroupId),i.push(`security group ${u}`);break}catch{await new Promise((S)=>setTimeout(S,3000))}return{destroyed:i}}async getComputeOutputs(e){let t=this.resolveRegion(e.config),r=T(e.config,e.environment),n=this.cfnClient(t);try{let s=await n.getStackOutputs(r);return{deployBucketName:s.deployBucketName,appInstanceId:s.appInstanceId,appPublicIp:s.appPublicIp,sshUser:"ec2-user"}}catch(s){if(!/does not exist|ValidationError/i.test(s instanceof Error?s.message:""))throw s;let i=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",region:t}))[0];return{appInstanceId:i?.id,appPublicIp:i?.publicIp,appPublicIpv6:i?.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}}async uploadRelease(e){let t=this.resolveRegion(e.config),n=(await this.getComputeOutputs({config:e.config,environment:e.environment})).deployBucketName;if(!n)throw Error("No deployBucketName in stack outputs. Re-deploy infrastructure to add the staging bucket.");return await new g(t).putObject({bucket:n,key:e.remoteKey,body:Cs(e.localPath),contentType:"application/gzip"}),{artifactRef:`s3://${n}/${e.remoteKey}`}}async findComputeTargets(e){let t=e.region??this.region,r=this.ec2Client(t),n=[{Name:"tag:Project",Values:[e.slug]},{Name:"tag:Environment",Values:[e.environment]},{Name:"tag:Role",Values:[e.role||"app"]},{Name:"instance-state-name",Values:["running","pending"]}],s=await r.describeInstances({Filters:n}),o=this.reservationsToTargets(s.Reservations);if(o.length>0||(e.role||"app")!=="app")return o;let i=e.stackName??`${e.slug}-${e.environment}`,a=qa(i);if(!a)try{a=(await this.cfnClient(t).getStackOutputs(i)).appInstanceId??null}catch{a=null}if(!a)return[];try{let c=await r.describeInstances({InstanceIds:[a],Filters:[{Name:"instance-state-name",Values:["running","pending"]}]});return this.reservationsToTargets(c.Reservations)}catch{return[]}}reservationsToTargets(e){let t=[];for(let r of e||[])for(let n of r.Instances||[]){if(!n.InstanceId)continue;let s=n.Tags?.find((o)=>o.Key==="Name")?.Value;t.push({id:n.InstanceId,name:s,publicIp:n.PublicIpAddress,publicIpv6:me(n.Ipv6Address),privateIp:n.PrivateIpAddress,status:n.State?.Name})}return t}bashWrap(e){return["bash <<'TS_CLOUD_BASH_EOF'",e.join(`
255
255
  `),"TS_CLOUD_BASH_EOF"]}async runRemoteDeploy(e){let t=this.region,r=new We(t);if(e.targets.length>0){let s=await r.sendCommand({InstanceIds:e.targets.map((o)=>o.id),DocumentName:"AWS-RunShellScript",Parameters:{commands:this.bashWrap(e.commands)},TimeoutSeconds:e.timeoutSeconds||600,Comment:e.comment});if(!s.CommandId)return{success:!1,instanceCount:0,perInstance:[],error:"Failed to send SSM command"};return this.pollSsmCommand(r,s.CommandId,e.targets.length,((e.timeoutSeconds||600)+30)*1000)}if(!e.tags||Object.keys(e.tags).length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets or tags provided for AWS deploy"};let n=await r.sendCommandByTags({tags:e.tags,commands:this.bashWrap(e.commands),timeoutSeconds:e.timeoutSeconds||600,comment:e.comment});return{success:n.success,instanceCount:n.instanceCount,perInstance:n.perInstance.map((s)=>({instanceId:s.instanceId,status:s.status,output:s.output,error:s.error})),error:n.error}}async pollSsmCommand(e,t,r,n=600000){let o=Date.now(),i=new Set(["Success","Failed","Cancelled","TimedOut"]),a=[];while(Date.now()-o<n){await new Promise((u)=>setTimeout(u,3000));try{if(a=await e.listCommandInvocations({CommandId:t,Details:!0}),a.length>=r&&a.every((d)=>i.has(d.Status||"")))break}catch{}}let c=a.map((u)=>({instanceId:u.InstanceId,status:u.Status||"Unknown",output:u.StandardOutputContent,error:u.StandardErrorContent})),l=c.length>0&&c.every((u)=>u.status==="Success");return{success:l,instanceCount:c.length,perInstance:c,error:l?void 0:Ne(c,"One or more SSM command invocations failed")}}}import{execFileSync as Ec,execSync as Vs}from"node:child_process";import{createHash as Oc,randomUUID as qs}from"node:crypto";import{createReadStream as Dc,existsSync as Ic,readFileSync as Ac}from"node:fs";async function Ps(e,t){let r=await import("node:fs"),n=await import("node:path"),s=await import("node:child_process"),o="/etc/ts-cloud/compute-storage.json",i="/var/lib/ts-cloud/compute-storage-state.json",a="/run/ts-cloud-root-web",c=t[0]??"status";if(!["plan","status","check","apply","ensure-site","reclaim"].includes(c))throw Error(`Unknown compute storage command: ${c}`);let l=(y,P)=>{try{return JSON.parse(r.readFileSync(y,"utf8"))}catch(M){if(M.code==="ENOENT")return P;throw M}},u=(y,P)=>{r.mkdirSync(n.dirname(y),{recursive:!0});let M=`${y}.${process.pid}.tmp`;r.writeFileSync(M,`${JSON.stringify(P,null,2)}
256
- `,{mode:420}),r.renameSync(M,y)},d=(y,P)=>s.execFileSync(y,P,{encoding:"utf8",maxBuffer:16777216}),m=(y,P)=>{let M=s.spawnSync(y,P,{encoding:"utf8"});return M.status===0?M.stdout.trim():""},h=(y)=>!!m("findmnt",["-n","--mountpoint",y]),f=(y,P)=>{try{let M=r.statSync(y),C=r.statSync(P);return M.dev===C.dev&&M.ino===C.ino}catch{return!1}},S=l("/var/lib/ts-cloud/compute-storage-state.json",{entries:[]}),k=e.deploymentStorage,E=e.volumes.find((y)=>y.key===k?.volume),O=(y,P)=>{if(!E)return[];let M=[];for(let C of r.readdirSync(e.webRoot,{withFileTypes:!0})){if(!C.isDirectory()||C.isSymbolicLink())continue;let F=n.join(e.webRoot,C.name);if(y&&F!==y&&F!==n.join(e.webRoot,`${P}-shared`))continue;for(let N of["releases",...k?.includeBackups===!1?[]:["backups"]]){let K=n.join(F,N);if(!r.existsSync(K)||!r.lstatSync(K).isDirectory())continue;M.push({source:K,destination:n.join(E.mountPath,N,C.name)})}}return M},D=(y)=>{try{return h(y.mountPath)&&r.statSync(y.mountPath).dev===r.statSync(y.device).rdev}catch{return!1}},R=(y)=>{let P=r.statfsSync(y),M=(P.blocks-P.bfree)*P.bsize,C=P.bavail*P.bsize;return{path:y,sizeBytes:P.blocks*P.bsize,usedBytes:M,availableBytes:C,usedPercent:Math.ceil(100*M/(M+C))}},z=()=>{let y=[],P=[R("/")];for(let C of e.volumes)if(!D(C))y.push(`missing or incorrect volume mount: ${C.mountPath}`);else P.push(R(C.mountPath));for(let C of S.entries)if(!h(C.source)||!f(C.source,C.destination))y.push(`missing deployment mount: ${C.source}`);let M=new Set(S.entries.map((C)=>C.source));for(let C of O())if(!M.has(C.source))y.push(`deployment needs volume placement: ${C.source}`);return{timestamp:new Date().toISOString(),volumes:e.volumes.map((C)=>({key:C.key,name:C.name,id:C.id,size:C.size,mountPath:C.mountPath})),disks:P,mounts:S.entries.length,problems:y}};if(c==="plan")return console.log(JSON.stringify({volumes:e.volumes,entries:O(),state:S},null,2));if(c==="status"||c==="check"){let y=z();if(c==="check"){u("/var/lib/ts-cloud/compute-storage-status.json",y);let P="/var/lib/ts-cloud/compute-storage-alert.json",M=l(P,{problems:[]});if(JSON.stringify(M.problems)!==JSON.stringify(y.problems)){let C=y.problems.join("; ")||"all configured mounts are healthy",F=`${y.problems.length?"Storage alert":"Storage recovered"} on ${m("hostname",[])}: ${C}`;d("/usr/local/bin/ts-cloud-notify",[F.length>1800?`${F.slice(0,1600)}... Full report: /var/lib/ts-cloud/compute-storage-status.json`:F])}u(P,{problems:y.problems,timestamp:y.timestamp})}if(console.log(JSON.stringify(y)),y.problems.length)process.exitCode=1;return y}if(process.getuid?.()!==0)throw Error("Compute storage changes require root");let x=()=>{let C=r.readFileSync("/etc/fstab","utf8");if(!r.existsSync("/etc/fstab.before-ts-cloud-storage"))r.copyFileSync("/etc/fstab","/etc/fstab.before-ts-cloud-storage");let F=[];for(let j of e.volumes){let W=d("blkid",["-s","UUID","-o","value",j.device]).trim();if(!W)throw Error(`Volume ${j.name} has no filesystem UUID`);F.push(`UUID=${W} ${j.mountPath} ext4 defaults,noatime,nodev,nosuid,nofail,x-systemd.device-timeout=30s 0 2`)}for(let j of S.entries)F.push(`${j.destination} ${j.source} none bind,nofail,x-systemd.requires-mounts-for=${E.mountPath} 0 0`);let N=`# BEGIN ts-cloud compute storage
256
+ `,{mode:420}),r.renameSync(M,y)},d=(y,P)=>s.execFileSync(y,P,{encoding:"utf8",maxBuffer:16777216}),m=(y,P)=>{let M=s.spawnSync(y,P,{encoding:"utf8"});return M.status===0?M.stdout.trim():""},h=(y)=>!!m("findmnt",["-n","--mountpoint",y]),f=(y,P)=>{try{let M=r.statSync(y),C=r.statSync(P);return M.dev===C.dev&&M.ino===C.ino}catch{return!1}},S=l("/var/lib/ts-cloud/compute-storage-state.json",{entries:[]}),k=e.deploymentStorage,O=e.volumes.find((y)=>y.key===k?.volume),D=(y,P)=>{if(!O)return[];let M=[];for(let C of r.readdirSync(e.webRoot,{withFileTypes:!0})){if(!C.isDirectory()||C.isSymbolicLink())continue;let F=n.join(e.webRoot,C.name);if(y&&F!==y&&F!==n.join(e.webRoot,`${P}-shared`))continue;for(let N of["releases",...k?.includeBackups===!1?[]:["backups"]]){let K=n.join(F,N);if(!r.existsSync(K)||!r.lstatSync(K).isDirectory())continue;M.push({source:K,destination:n.join(O.mountPath,N,C.name)})}}return M},I=(y)=>{try{return h(y.mountPath)&&r.statSync(y.mountPath).dev===r.statSync(y.device).rdev}catch{return!1}},E=(y)=>{let P=r.statfsSync(y),M=(P.blocks-P.bfree)*P.bsize,C=P.bavail*P.bsize;return{path:y,sizeBytes:P.blocks*P.bsize,usedBytes:M,availableBytes:C,usedPercent:Math.ceil(100*M/(M+C))}},z=()=>{let y=[],P=[E("/")];for(let C of e.volumes)if(!I(C))y.push(`missing or incorrect volume mount: ${C.mountPath}`);else P.push(E(C.mountPath));for(let C of S.entries)if(!h(C.source)||!f(C.source,C.destination))y.push(`missing deployment mount: ${C.source}`);let M=new Set(S.entries.map((C)=>C.source));for(let C of D())if(!M.has(C.source))y.push(`deployment needs volume placement: ${C.source}`);return{timestamp:new Date().toISOString(),volumes:e.volumes.map((C)=>({key:C.key,name:C.name,id:C.id,size:C.size,mountPath:C.mountPath})),disks:P,mounts:S.entries.length,problems:y}};if(c==="plan")return console.log(JSON.stringify({volumes:e.volumes,entries:D(),state:S},null,2));if(c==="status"||c==="check"){let y=z();if(c==="check"){u("/var/lib/ts-cloud/compute-storage-status.json",y);let P="/var/lib/ts-cloud/compute-storage-alert.json",M=l(P,{problems:[]});if(JSON.stringify(M.problems)!==JSON.stringify(y.problems)){let C=y.problems.join("; ")||"all configured mounts are healthy",F=`${y.problems.length?"Storage alert":"Storage recovered"} on ${m("hostname",[])}: ${C}`;d("/usr/local/bin/ts-cloud-notify",[F.length>1800?`${F.slice(0,1600)}... Full report: /var/lib/ts-cloud/compute-storage-status.json`:F])}u(P,{problems:y.problems,timestamp:y.timestamp})}if(console.log(JSON.stringify(y)),y.problems.length)process.exitCode=1;return y}if(process.getuid?.()!==0)throw Error("Compute storage changes require root");let x=()=>{let C=r.readFileSync("/etc/fstab","utf8");if(!r.existsSync("/etc/fstab.before-ts-cloud-storage"))r.copyFileSync("/etc/fstab","/etc/fstab.before-ts-cloud-storage");let F=[];for(let j of e.volumes){let W=d("blkid",["-s","UUID","-o","value",j.device]).trim();if(!W)throw Error(`Volume ${j.name} has no filesystem UUID`);F.push(`UUID=${W} ${j.mountPath} ext4 defaults,noatime,nodev,nosuid,nofail,x-systemd.device-timeout=30s 0 2`)}for(let j of S.entries)F.push(`${j.destination} ${j.source} none bind,nofail,x-systemd.requires-mounts-for=${O.mountPath} 0 0`);let N=`# BEGIN ts-cloud compute storage
257
257
  ${F.join(`
258
258
  `)}
259
259
  # END ts-cloud compute storage`,K;if(C.includes("# BEGIN ts-cloud compute storage")){let j=C.indexOf("# BEGIN ts-cloud compute storage"),W=C.indexOf("# END ts-cloud compute storage",j);if(W<0)throw Error("Incomplete managed storage block in fstab");K=C.slice(0,j)+N+C.slice(W+30)}else K=`${C.trimEnd()}
260
260
  ${N}
261
- `;r.writeFileSync("/etc/fstab.ts-cloud-new",K),r.renameSync("/etc/fstab.ts-cloud-new","/etc/fstab")},H=()=>{for(let y of e.volumes){if(!r.existsSync(y.device)||!r.statSync(y.device).isBlockDevice())throw Error(`Volume device missing: ${y.device}`);let P=m("blkid",["-s","TYPE","-o","value",y.device]);if(!P){if(!y.allowFormat)throw Error(`Refusing to format adopted volume ${y.name}; no recognized filesystem`);d("mkfs.ext4",["-m","1",y.device]),P="ext4"}if(P!=="ext4")throw Error(`Refusing to replace ${P} filesystem on ${y.name}`);if(r.mkdirSync(y.mountPath,{recursive:!0}),h(y.mountPath)&&!D(y))throw Error(`Another filesystem occupies ${y.mountPath}`);if(!h(y.mountPath)&&r.readdirSync(y.mountPath).length)throw Error(`Refusing to hide existing files beneath ${y.mountPath}`);if(!h(y.mountPath))d("mount",["-o","noatime,nodev,nosuid",y.device,y.mountPath]);if(!D(y))throw Error(`Volume identity verification failed: ${y.name}`);d("resize2fs",[y.device]),y.allowFormat=!1}u("/etc/ts-cloud/compute-storage.json",e),x(),d("systemctl",["daemon-reload"])},{dlopen:V}=await import("bun:ffi"),se=V("libc.so.6",{flock:{args:["i32","i32"],returns:"i32"}}),ce=[],G=(y)=>{r.mkdirSync(n.dirname(y),{recursive:!0});let P=r.openSync(y,r.constants.O_CREAT|r.constants.O_RDWR|r.constants.O_NOFOLLOW,384);if(se.symbols.flock(P,2)!==0)throw r.closeSync(P),Error(`Could not acquire lock: ${y}`);ce.push(P)},oe=()=>{let y=[];for(let P of r.readdirSync("/proc").filter((M)=>/^\d+$/.test(M))){let M=[];try{M=r.readdirSync(`/proc/${P}/fd`)}catch{continue}for(let C of["cwd","exe",...M.map((F)=>`fd/${F}`)]){let F=`/proc/${P}/${C}`;try{let N=r.readlinkSync(F);if(!N.startsWith(`${e.webRoot}/`)||!N.includes("/releases/"))continue;let K=!1;if(C.startsWith("fd/")){let j=r.readFileSync(`/proc/${P}/fdinfo/${C.slice(3)}`,"utf8").match(/^flags:\s+(\d+)/m);K=!!j&&(Number.parseInt(j[1],8)&3)!==0&&r.statSync(F).isFile()}y.push({file:N,write:K,device:r.statSync(F).dev})}catch{}}}return y},Y=async(y,P)=>{r.mkdirSync(y.destination,{recursive:!0});let M=["rsync","-aHAXx","--numeric-ids","--delete",...P?["--checksum"]:[],`${y.source}/`,`${y.destination}/`],F=await Bun.spawn(M,{stdout:"inherit",stderr:"inherit"}).exited;if(F!==0&&!(F===24&&!P))throw Error(`rsync failed (${F}): ${y.source}`)},q=async()=>{let y=d("systemctl",["list-units","--type=service","--state=running","--no-legend","--plain"]).split(`
261
+ `;r.writeFileSync("/etc/fstab.ts-cloud-new",K),r.renameSync("/etc/fstab.ts-cloud-new","/etc/fstab")},H=()=>{for(let y of e.volumes){if(!r.existsSync(y.device)||!r.statSync(y.device).isBlockDevice())throw Error(`Volume device missing: ${y.device}`);let P=m("blkid",["-s","TYPE","-o","value",y.device]);if(!P){if(!y.allowFormat)throw Error(`Refusing to format adopted volume ${y.name}; no recognized filesystem`);d("mkfs.ext4",["-m","1",y.device]),P="ext4"}if(P!=="ext4")throw Error(`Refusing to replace ${P} filesystem on ${y.name}`);if(r.mkdirSync(y.mountPath,{recursive:!0}),h(y.mountPath)&&!I(y))throw Error(`Another filesystem occupies ${y.mountPath}`);if(!h(y.mountPath)&&r.readdirSync(y.mountPath).length)throw Error(`Refusing to hide existing files beneath ${y.mountPath}`);if(!h(y.mountPath))d("mount",["-o","noatime,nodev,nosuid",y.device,y.mountPath]);if(!I(y))throw Error(`Volume identity verification failed: ${y.name}`);d("resize2fs",[y.device]),y.allowFormat=!1}u("/etc/ts-cloud/compute-storage.json",e),x(),d("systemctl",["daemon-reload"])},{dlopen:V}=await import("bun:ffi"),se=V("libc.so.6",{flock:{args:["i32","i32"],returns:"i32"}}),ce=[],G=(y)=>{r.mkdirSync(n.dirname(y),{recursive:!0});let P=r.openSync(y,r.constants.O_CREAT|r.constants.O_RDWR|r.constants.O_NOFOLLOW,384);if(se.symbols.flock(P,2)!==0)throw r.closeSync(P),Error(`Could not acquire lock: ${y}`);ce.push(P)},oe=()=>{let y=[];for(let P of r.readdirSync("/proc").filter((M)=>/^\d+$/.test(M))){let M=[];try{M=r.readdirSync(`/proc/${P}/fd`)}catch{continue}for(let C of["cwd","exe",...M.map((F)=>`fd/${F}`)]){let F=`/proc/${P}/${C}`;try{let N=r.readlinkSync(F);if(!N.startsWith(`${e.webRoot}/`)||!N.includes("/releases/"))continue;let K=!1;if(C.startsWith("fd/")){let j=r.readFileSync(`/proc/${P}/fdinfo/${C.slice(3)}`,"utf8").match(/^flags:\s+(\d+)/m);K=!!j&&(Number.parseInt(j[1],8)&3)!==0&&r.statSync(F).isFile()}y.push({file:N,write:K,device:r.statSync(F).dev})}catch{}}}return y},Y=async(y,P)=>{r.mkdirSync(y.destination,{recursive:!0});let M=["rsync","-aHAXx","--numeric-ids","--delete",...P?["--checksum"]:[],`${y.source}/`,`${y.destination}/`],F=await Bun.spawn(M,{stdout:"inherit",stderr:"inherit"}).exited;if(F!==0&&!(F===24&&!P))throw Error(`rsync failed (${F}): ${y.source}`)},q=async()=>{let y=d("systemctl",["list-units","--type=service","--state=running","--no-legend","--plain"]).split(`
262
262
  `).map((K)=>K.trim().split(/\s+/)[0]).filter(Boolean),P={};if(y.length){let K=d("systemctl",["show",...y,"-p","Id","-p","MainPID","-p","WorkingDirectory"]);for(let j of K.split(`
263
263
 
264
264
  `)){let W=Object.fromEntries(j.split(`
265
- `).filter(Boolean).map((b)=>{let L=b.indexOf("=");return[b.slice(0,L),b.slice(L+1)]}));if(W.WorkingDirectory?.startsWith(`${e.webRoot}/`)||/^(?:mail|rpx-gateway|postgresql|mysql|redis)[@.]/.test(W.Id??""))P[W.Id]=Number(W.MainPID)}}let M=new Map;if(r.existsSync("/etc/rpx/sites.d"))for(let K of r.readdirSync("/etc/rpx/sites.d").filter((j)=>j.endsWith(".json"))){let j=JSON.parse(r.readFileSync(n.join("/etc/rpx/sites.d",K),"utf8"));for(let W of j.proxies??[]){if(typeof W.to!=="string"||!/^[a-zA-Z0-9.-]+$/.test(W.to))continue;let b=typeof W.path==="string"&&W.path.startsWith("/")?W.path:"/";M.set(`${W.to}${b}`,{domain:W.to,path:b})}}let C=[...M.values()],F=[],N=0;return await Promise.all(Array.from({length:Math.min(8,C.length)},async()=>{while(N<C.length){let K=C[N++],j=Bun.spawn(["curl","-sS","--max-time","12","--output","/dev/null","--write-out","%{http_code}","--resolve",`${K.domain}:443:127.0.0.1`,`https://${K.domain}${K.path}`],{stdout:"pipe",stderr:"pipe"}),[W,,b]=await Promise.all([new Response(j.stdout).text(),new Response(j.stderr).text(),j.exited]),L=Number(W);F.push({...K,status:L,ok:b===0&&L>=200&&L<500})}})),{routes:F.sort((K,j)=>`${K.domain}${K.path}`.localeCompare(`${j.domain}${j.path}`)),services:P}},ue=()=>{let y=[E.mountPath,...S.entries.map((M)=>M.source)],P=new Set(["rpx-gateway.service",...k?.dependentUnits??[]]);for(let M of r.readdirSync("/etc/systemd/system")){if(!M.endsWith(".service"))continue;try{if(r.readFileSync(`/etc/systemd/system/${M}`,"utf8").includes(e.webRoot))P.add(M)}catch{}}for(let M of P){let C=`/etc/systemd/system/${M}.d`;r.mkdirSync(C,{recursive:!0}),r.writeFileSync(`${C}/ts-cloud-storage.conf`,`[Unit]
265
+ `).filter(Boolean).map((b)=>{let L=b.indexOf("=");return[b.slice(0,L),b.slice(L+1)]}));if(W.WorkingDirectory?.startsWith(`${e.webRoot}/`)||/^(?:mail|rpx-gateway|postgresql|mysql|redis)[@.]/.test(W.Id??""))P[W.Id]=Number(W.MainPID)}}let M=new Map;if(r.existsSync("/etc/rpx/sites.d"))for(let K of r.readdirSync("/etc/rpx/sites.d").filter((j)=>j.endsWith(".json"))){let j=JSON.parse(r.readFileSync(n.join("/etc/rpx/sites.d",K),"utf8"));for(let W of j.proxies??[]){if(typeof W.to!=="string"||!/^[a-zA-Z0-9.-]+$/.test(W.to))continue;let b=typeof W.path==="string"&&W.path.startsWith("/")?W.path:"/";M.set(`${W.to}${b}`,{domain:W.to,path:b})}}let C=[...M.values()],F=[],N=0;return await Promise.all(Array.from({length:Math.min(8,C.length)},async()=>{while(N<C.length){let K=C[N++],j=Bun.spawn(["curl","-sS","--max-time","12","--output","/dev/null","--write-out","%{http_code}","--resolve",`${K.domain}:443:127.0.0.1`,`https://${K.domain}${K.path}`],{stdout:"pipe",stderr:"pipe"}),[W,,b]=await Promise.all([new Response(j.stdout).text(),new Response(j.stderr).text(),j.exited]),L=Number(W);F.push({...K,status:L,ok:b===0&&L>=200&&L<500})}})),{routes:F.sort((K,j)=>`${K.domain}${K.path}`.localeCompare(`${j.domain}${j.path}`)),services:P}},ue=()=>{let y=[O.mountPath,...S.entries.map((M)=>M.source)],P=new Set(["rpx-gateway.service",...k?.dependentUnits??[]]);for(let M of r.readdirSync("/etc/systemd/system")){if(!M.endsWith(".service"))continue;try{if(r.readFileSync(`/etc/systemd/system/${M}`,"utf8").includes(e.webRoot))P.add(M)}catch{}}for(let M of P){let C=`/etc/systemd/system/${M}.d`;r.mkdirSync(C,{recursive:!0}),r.writeFileSync(`${C}/ts-cloud-storage.conf`,`[Unit]
266
266
  RequiresMountsFor=${y.join(" ")}
267
- `)}d("systemctl",["daemon-reload"])};try{G("/run/lock/ts-cloud-compute-storage.lock"),S=l("/var/lib/ts-cloud/compute-storage-state.json",{entries:[]});let y=l("/etc/ts-cloud/compute-storage.json",null);if(y){for(let b of y.volumes)if(!e.volumes.some((L)=>L.id===b.id&&L.key===b.key&&L.mountPath===b.mountPath))throw Error(`Refusing to remove or relocate managed volume ${b.name}; migrate its data explicitly first`);if(S.entries.length&&(y.deploymentStorage?.volume!==k?.volume||y.deploymentStorage?.includeBackups!==!1!==(k?.includeBackups!==!1)))throw Error("Refusing to change an active deployment-storage policy; migrate its data explicitly first")}if(c==="apply")H();for(let b of e.volumes)if(!D(b))throw Error(`Required volume is not mounted: ${b.name}`);if(!k||!E)return{volumes:e.volumes};if(c==="ensure-site"){let[b,L]=t.slice(1);if(!b?.startsWith(`${e.webRoot}/`)||!/^[\w-]+$/.test(n.basename(b))||b.includes("..")||!/^[\w-]+$/.test(L??""))throw Error("Invalid deployment site path or project slug");if(r.mkdirSync(n.join(b,"releases"),{recursive:!0}),k.includeBackups!==!1)r.mkdirSync(n.join(e.webRoot,`${L}-shared`,"backups"),{recursive:!0})}let P=(c==="reclaim"?[]:O(c==="ensure-site"?t[1]:void 0,t[2])).filter((b)=>!S.entries.some((L)=>L.source===b.source));for(let b of S.entries)if(!h(b.source)||!f(b.source,b.destination))throw Error(`Recorded deployment mount is missing: ${b.source}`);if(!P.length&&c==="ensure-site")return{inherited:!0,volume:E.name};if(!k.migrateExisting&&P.some((b)=>r.readdirSync(b.source).length>0))throw Error("Existing deployments require deploymentStorage.migrateExisting: true");if(P.length){let b=d("du",["-scx","--block-size=1",...P.map((ee)=>ee.source)]).trim().split(`
268
- `).at(-1)?.split(/\s+/)[0],L=r.statfsSync(E.mountPath);if(Number(b)>L.bavail*L.bsize)throw Error("Insufficient free volume capacity for a verified deployment copy")}if(!r.existsSync("/run/ts-cloud-root-web"))r.mkdirSync("/run/ts-cloud-root-web");if(!h("/run/ts-cloud-root-web"))d("mount",["--bind",e.webRoot,"/run/ts-cloud-root-web"]);d("mount",["--make-private","/run/ts-cloud-root-web"]);let M=r.statSync(e.webRoot).dev;for(let b of S.entries){let L=n.join("/run/ts-cloud-root-web",n.relative(e.webRoot,b.source));if(r.existsSync(L)&&(r.statSync(L).dev!==M||f(L,b.destination)))throw Error(`Root recovery view contains a deployment mount: ${L}`)}for(let b=0;b<P.length;b++){if(h(P[b].source)&&f(P[b].source,P[b].destination))continue;console.log(`copy ${b+1}/${P.length}: ${P[b].source}`),await Y(P[b],!1)}for(let b of new Set([...k.locks??[],"/run/lock/ts-cloud-host-cleanup.lock"]))G(b);for(let b of r.readdirSync(e.webRoot,{withFileTypes:!0}).filter((L)=>L.isDirectory()).sort((L,ee)=>L.name.localeCompare(ee.name)))G(n.join(e.webRoot,b.name,".ts-cloud/deploy.lock"));for(let b of c==="reclaim"?[]:O(c==="ensure-site"?t[1]:void 0,t[2]))if(!S.entries.some((L)=>L.source===b.source)&&!P.some((L)=>L.source===b.source))P.push(b);if(P.length)console.log("Checking application services and HTTPS routes before activation");let C=P.length?await q():void 0;if(C)u("/var/lib/ts-cloud/compute-storage-health-before.json",C);let F=oe().filter((b)=>b.write);if(F.length)throw Error(`Live writable files must be shared before migration: ${F.map((b)=>b.file).join(", ")}`);let N={entries:[...S.entries],fstab:r.readFileSync("/etc/fstab","utf8")};if(P.length)d("sync",[]);let K=[];try{for(let b=0;b<P.length;b++){let L=P[b];if(h(L.source)){if(!f(L.source,L.destination))throw Error(`Unrecorded mount occupies ${L.source}`);S.entries.push(L),u("/var/lib/ts-cloud/compute-storage-state.json",S);continue}if(console.log(`verify and mount ${b+1}/${P.length}: ${L.source}`),await Y(L,!0),d("mount",["--bind",L.destination,L.source]),!f(L.source,L.destination))throw Error(`Bind verification failed: ${L.source}`);K.push(L),S.entries.push(L),u("/var/lib/ts-cloud/compute-storage-state.json",S),x()}if(x(),d("findmnt",["--verify"]),S.activatedAt=new Date().toISOString(),u("/var/lib/ts-cloud/compute-storage-state.json",S),ue(),C){console.log("Checking application services and HTTPS routes after activation");let b=await q();u("/var/lib/ts-cloud/compute-storage-health-after.json",b);let L=C.routes.filter((X)=>X.ok&&!b.routes.some((Ce)=>Ce.domain===X.domain&&Ce.path===X.path&&Ce.ok)),ee=Object.keys(C.services).filter((X)=>!b.services[X]);if(L.length||ee.length)throw Error(`Application verification failed: ${L.map((X)=>X.domain+X.path).concat(ee).join(", ")}`);console.log(`Verified ${b.routes.length} routes and ${Object.keys(b.services).length} services`)}}catch(b){let L=[];for(let ee of K.reverse())try{d("umount",[ee.source])}catch{L.push(ee),console.error(`Rollback mount busy, original data retained: ${ee.source}`)}if(S.entries=[...N.entries,...L],r.writeFileSync("/etc/fstab",N.fstab),L.length)x();throw u("/var/lib/ts-cloud/compute-storage-state.json",S),d("systemctl",["daemon-reload"]),b}let j=oe().filter((b)=>b.device===M).map((b)=>b.file);for(let b of S.entries){if(!h(b.source)||!f(b.source,b.destination))throw Error(`Lost deployment mount: ${b.source}`);let L=n.join("/run/ts-cloud-root-web",n.relative(e.webRoot,b.source));if(!r.existsSync(L))continue;if(r.statSync(L).dev!==M||f(L,b.destination))throw Error(`Refusing to clean a deployment volume through the root recovery view: ${L}`);let ee="";try{ee=n.basename(r.realpathSync(n.join(n.dirname(b.source),"current")))}catch{}for(let X of r.readdirSync(L,{withFileTypes:!0})){let Ce=n.join(L,X.name);if(n.basename(b.source)==="backups"){if(X.isFile()&&r.existsSync(n.join(b.destination,X.name)))r.unlinkSync(Ce)}else if(X.isDirectory()&&!X.isSymbolicLink()&&X.name!==ee&&!j.some((Ot)=>Ot===n.join(b.source,X.name)||Ot.startsWith(`${n.join(b.source,X.name)}/`)))r.rmSync(Ce,{recursive:!0})}}d("sync",[]);let W=z();return u("/var/lib/ts-cloud/compute-storage-status.json",W),console.log(JSON.stringify(W)),W}finally{for(let y of ce.reverse())se.symbols.flock(y,8),r.closeSync(y);se.close()}}var Ir="/etc/ts-cloud/compute-storage.json",Re="/usr/local/lib/ts-cloud/compute-storage.mjs";function Ar(e,t){let r=Object.entries(e.infrastructure?.compute?.volumes??{}).map(([s,o])=>{if(!/^[a-z][a-z0-9-]*$/.test(s))throw Error(`Invalid compute volume key: ${s}`);if(!Number.isInteger(o.size)||o.size<10||o.size>10240)throw Error(`compute.volumes.${s}.size must be a whole number from 10 to 10240 GB`);if(!o.mountPath.startsWith("/")||!o.mountPath.slice(1).split("/").every((a)=>/^[\w-]+$/.test(a))||o.mountPath==="/var"||o.mountPath==="/var/lib"||["/etc","/usr","/var/www","/root","/boot","/dev","/proc","/sys","/run","/bin","/sbin","/lib"].some((a)=>o.mountPath===a||o.mountPath.startsWith(`${a}/`)))throw Error(`Unsafe compute volume mount path: ${o.mountPath}`);let i=o.name??`${e.project.slug}-${t}-${s}`;if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(i))throw Error(`Invalid compute volume name: ${i}`);return{...o,key:s,name:i,mountPath:o.mountPath.replace(/\/+$/,"")}});for(let s of r)if(r.some((o)=>o!==s&&(o.name===s.name||o.mountPath===s.mountPath||o.mountPath.startsWith(`${s.mountPath}/`))))throw Error("Compute volumes must have distinct names and non-overlapping mount paths");let n=e.infrastructure?.compute?.deploymentStorage;for(let s of n?.locks??[])if(!s.startsWith("/run/lock/")||!s.slice(10).split("/").every((o)=>/^[\w.-]+$/.test(o)&&o!=="."&&o!=="..")||s==="/run/lock/ts-cloud-compute-storage.lock")throw Error(`Invalid deployment storage lock: ${s}`);for(let s of n?.dependentUnits??[])if(!/^[\w@.-]+\.service$/.test(s))throw Error(`Invalid deployment storage dependent unit: ${s}`);if(n&&!r.some((s)=>s.key===n.volume))throw Error(`deploymentStorage.volume references an undeclared compute volume: ${n.volume}`);return r}function Ut(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function Lr(e){let t=`${Ir}.candidate`,r=`#!/usr/bin/env bun
267
+ `)}d("systemctl",["daemon-reload"])};try{G("/run/lock/ts-cloud-compute-storage.lock"),S=l("/var/lib/ts-cloud/compute-storage-state.json",{entries:[]});let y=l("/etc/ts-cloud/compute-storage.json",null);if(y){for(let b of y.volumes)if(!e.volumes.some((L)=>L.id===b.id&&L.key===b.key&&L.mountPath===b.mountPath))throw Error(`Refusing to remove or relocate managed volume ${b.name}; migrate its data explicitly first`);if(S.entries.length&&(y.deploymentStorage?.volume!==k?.volume||y.deploymentStorage?.includeBackups!==!1!==(k?.includeBackups!==!1)))throw Error("Refusing to change an active deployment-storage policy; migrate its data explicitly first")}if(c==="apply")H();for(let b of e.volumes)if(!I(b))throw Error(`Required volume is not mounted: ${b.name}`);if(!k||!O)return{volumes:e.volumes};if(c==="ensure-site"){let[b,L]=t.slice(1);if(!b?.startsWith(`${e.webRoot}/`)||!/^[\w-]+$/.test(n.basename(b))||b.includes("..")||!/^[\w-]+$/.test(L??""))throw Error("Invalid deployment site path or project slug");if(r.mkdirSync(n.join(b,"releases"),{recursive:!0}),k.includeBackups!==!1)r.mkdirSync(n.join(e.webRoot,`${L}-shared`,"backups"),{recursive:!0})}let P=(c==="reclaim"?[]:D(c==="ensure-site"?t[1]:void 0,t[2])).filter((b)=>!S.entries.some((L)=>L.source===b.source));for(let b of S.entries)if(!h(b.source)||!f(b.source,b.destination))throw Error(`Recorded deployment mount is missing: ${b.source}`);if(!P.length&&c==="ensure-site")return{inherited:!0,volume:O.name};if(!k.migrateExisting&&P.some((b)=>r.readdirSync(b.source).length>0))throw Error("Existing deployments require deploymentStorage.migrateExisting: true");if(P.length){let b=d("du",["-scx","--block-size=1",...P.map((ee)=>ee.source)]).trim().split(`
268
+ `).at(-1)?.split(/\s+/)[0],L=r.statfsSync(O.mountPath);if(Number(b)>L.bavail*L.bsize)throw Error("Insufficient free volume capacity for a verified deployment copy")}if(!r.existsSync("/run/ts-cloud-root-web"))r.mkdirSync("/run/ts-cloud-root-web");if(!h("/run/ts-cloud-root-web"))d("mount",["--bind",e.webRoot,"/run/ts-cloud-root-web"]);d("mount",["--make-private","/run/ts-cloud-root-web"]);let M=r.statSync(e.webRoot).dev;for(let b of S.entries){let L=n.join("/run/ts-cloud-root-web",n.relative(e.webRoot,b.source));if(r.existsSync(L)&&(r.statSync(L).dev!==M||f(L,b.destination)))throw Error(`Root recovery view contains a deployment mount: ${L}`)}for(let b=0;b<P.length;b++){if(h(P[b].source)&&f(P[b].source,P[b].destination))continue;console.log(`copy ${b+1}/${P.length}: ${P[b].source}`),await Y(P[b],!1)}for(let b of new Set([...k.locks??[],"/run/lock/ts-cloud-host-cleanup.lock"]))G(b);for(let b of r.readdirSync(e.webRoot,{withFileTypes:!0}).filter((L)=>L.isDirectory()).sort((L,ee)=>L.name.localeCompare(ee.name)))G(n.join(e.webRoot,b.name,".ts-cloud/deploy.lock"));for(let b of c==="reclaim"?[]:D(c==="ensure-site"?t[1]:void 0,t[2]))if(!S.entries.some((L)=>L.source===b.source)&&!P.some((L)=>L.source===b.source))P.push(b);if(P.length)console.log("Checking application services and HTTPS routes before activation");let C=P.length?await q():void 0;if(C)u("/var/lib/ts-cloud/compute-storage-health-before.json",C);let F=oe().filter((b)=>b.write);if(F.length)throw Error(`Live writable files must be shared before migration: ${F.map((b)=>b.file).join(", ")}`);let N={entries:[...S.entries],fstab:r.readFileSync("/etc/fstab","utf8")};if(P.length)d("sync",[]);let K=[];try{for(let b=0;b<P.length;b++){let L=P[b];if(h(L.source)){if(!f(L.source,L.destination))throw Error(`Unrecorded mount occupies ${L.source}`);S.entries.push(L),u("/var/lib/ts-cloud/compute-storage-state.json",S);continue}if(console.log(`verify and mount ${b+1}/${P.length}: ${L.source}`),await Y(L,!0),d("mount",["--bind",L.destination,L.source]),!f(L.source,L.destination))throw Error(`Bind verification failed: ${L.source}`);K.push(L),S.entries.push(L),u("/var/lib/ts-cloud/compute-storage-state.json",S),x()}if(x(),d("findmnt",["--verify"]),S.activatedAt=new Date().toISOString(),u("/var/lib/ts-cloud/compute-storage-state.json",S),ue(),C){console.log("Checking application services and HTTPS routes after activation");let b=await q();u("/var/lib/ts-cloud/compute-storage-health-after.json",b);let L=C.routes.filter((X)=>X.ok&&!b.routes.some((Ce)=>Ce.domain===X.domain&&Ce.path===X.path&&Ce.ok)),ee=Object.keys(C.services).filter((X)=>!b.services[X]);if(L.length||ee.length)throw Error(`Application verification failed: ${L.map((X)=>X.domain+X.path).concat(ee).join(", ")}`);console.log(`Verified ${b.routes.length} routes and ${Object.keys(b.services).length} services`)}}catch(b){let L=[];for(let ee of K.reverse())try{d("umount",[ee.source])}catch{L.push(ee),console.error(`Rollback mount busy, original data retained: ${ee.source}`)}if(S.entries=[...N.entries,...L],r.writeFileSync("/etc/fstab",N.fstab),L.length)x();throw u("/var/lib/ts-cloud/compute-storage-state.json",S),d("systemctl",["daemon-reload"]),b}let j=oe().filter((b)=>b.device===M).map((b)=>b.file);for(let b of S.entries){if(!h(b.source)||!f(b.source,b.destination))throw Error(`Lost deployment mount: ${b.source}`);let L=n.join("/run/ts-cloud-root-web",n.relative(e.webRoot,b.source));if(!r.existsSync(L))continue;if(r.statSync(L).dev!==M||f(L,b.destination))throw Error(`Refusing to clean a deployment volume through the root recovery view: ${L}`);let ee="";try{ee=n.basename(r.realpathSync(n.join(n.dirname(b.source),"current")))}catch{}for(let X of r.readdirSync(L,{withFileTypes:!0})){let Ce=n.join(L,X.name);if(n.basename(b.source)==="backups"){if(X.isFile()&&r.existsSync(n.join(b.destination,X.name)))r.unlinkSync(Ce)}else if(X.isDirectory()&&!X.isSymbolicLink()&&X.name!==ee&&!j.some((Ot)=>Ot===n.join(b.source,X.name)||Ot.startsWith(`${n.join(b.source,X.name)}/`)))r.rmSync(Ce,{recursive:!0})}}d("sync",[]);let W=z();return u("/var/lib/ts-cloud/compute-storage-status.json",W),console.log(JSON.stringify(W)),W}finally{for(let y of ce.reverse())se.symbols.flock(y,8),r.closeSync(y);se.close()}}var Ir="/etc/ts-cloud/compute-storage.json",Re="/usr/local/lib/ts-cloud/compute-storage.mjs";function Ar(e,t){let r=Object.entries(e.infrastructure?.compute?.volumes??{}).map(([s,o])=>{if(!/^[a-z][a-z0-9-]*$/.test(s))throw Error(`Invalid compute volume key: ${s}`);if(!Number.isInteger(o.size)||o.size<10||o.size>10240)throw Error(`compute.volumes.${s}.size must be a whole number from 10 to 10240 GB`);if(!o.mountPath.startsWith("/")||!o.mountPath.slice(1).split("/").every((a)=>/^[\w-]+$/.test(a))||o.mountPath==="/var"||o.mountPath==="/var/lib"||["/etc","/usr","/var/www","/root","/boot","/dev","/proc","/sys","/run","/bin","/sbin","/lib"].some((a)=>o.mountPath===a||o.mountPath.startsWith(`${a}/`)))throw Error(`Unsafe compute volume mount path: ${o.mountPath}`);let i=o.name??`${e.project.slug}-${t}-${s}`;if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(i))throw Error(`Invalid compute volume name: ${i}`);return{...o,key:s,name:i,mountPath:o.mountPath.replace(/\/+$/,"")}});for(let s of r)if(r.some((o)=>o!==s&&(o.name===s.name||o.mountPath===s.mountPath||o.mountPath.startsWith(`${s.mountPath}/`))))throw Error("Compute volumes must have distinct names and non-overlapping mount paths");let n=e.infrastructure?.compute?.deploymentStorage;for(let s of n?.locks??[])if(!s.startsWith("/run/lock/")||!s.slice(10).split("/").every((o)=>/^[\w.-]+$/.test(o)&&o!=="."&&o!=="..")||s==="/run/lock/ts-cloud-compute-storage.lock")throw Error(`Invalid deployment storage lock: ${s}`);for(let s of n?.dependentUnits??[])if(!/^[\w@.-]+\.service$/.test(s))throw Error(`Invalid deployment storage dependent unit: ${s}`);if(n&&!r.some((s)=>s.key===n.volume))throw Error(`deploymentStorage.volume references an undeclared compute volume: ${n.volume}`);return r}function Ut(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function Lr(e){let t=`${Ir}.candidate`,r=`#!/usr/bin/env bun
269
269
  await (${Ps.toString()})(JSON.parse(await Bun.file(process.env.TS_CLOUD_STORAGE_POLICY || ${JSON.stringify(Ir)}).text()), process.argv.slice(2));
270
270
  `;return['command -v bun >/dev/null 2>&1 || { echo "Configured compute storage requires Bun on the host" >&2; exit 1; }',"install -d -m 0755 /etc/ts-cloud /usr/local/lib/ts-cloud /var/lib/ts-cloud",`printf %s ${Ut(Buffer.from(r).toString("base64"))} | base64 -d > ${Re}.new`,`chmod 0755 ${Re}.new && mv ${Re}.new ${Re}`,`printf %s ${Ut(JSON.stringify(e))} > ${t}`,`chmod 0644 ${t}`,`TS_CLOUD_STORAGE_POLICY=${t} bun ${Re} apply 2>&1 | tee /var/log/ts-cloud-compute-storage.log`,`rm -f ${t}`,"cat > /etc/systemd/system/ts-cloud-storage-check.service <<'TS_CLOUD_STORAGE_SERVICE'","[Unit]","Description=Check configured compute storage and deployment mounts","[Service]","Type=oneshot",`ExecStart=/usr/local/bin/bun ${Re} check`,"TS_CLOUD_STORAGE_SERVICE","cat > /etc/systemd/system/ts-cloud-storage-check.timer <<'TS_CLOUD_STORAGE_TIMER'","[Unit]","Description=Check compute storage every minute","[Timer]","OnBootSec=2min","OnUnitActiveSec=1min","[Install]","WantedBy=timers.target","TS_CLOUD_STORAGE_TIMER","systemctl daemon-reload","systemctl enable --now ts-cloud-storage-check.timer","cat > /etc/systemd/system/ts-cloud-storage-reclaim.service <<'TS_CLOUD_RECLAIM_SERVICE'","[Unit]","Description=Reclaim inactive root copies of volume-backed deployments","[Service]","Type=oneshot",`ExecStart=/usr/local/bin/bun ${Re} reclaim`,"Nice=19","IOSchedulingClass=idle","TS_CLOUD_RECLAIM_SERVICE","cat > /etc/systemd/system/ts-cloud-storage-reclaim.timer <<'TS_CLOUD_RECLAIM_TIMER'","[Unit]","Description=Reclaim retired deployment copies hourly","[Timer]","OnCalendar=hourly","RandomizedDelaySec=5min","Persistent=true","[Install]","WantedBy=timers.target","TS_CLOUD_RECLAIM_TIMER","systemctl daemon-reload","systemctl enable --now ts-cloud-storage-reclaim.timer"]}function Mt(e,t){return[`if [ -f ${Ir} ]; then bun ${Re} ensure-site ${Ut(e)} ${Ut(t)}; fi`]}function zt(e){return Object.entries(e).map(([t,r])=>`${t}=${Xa(String(r))}`).join(`
271
271
  `)}function Xa(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}var Ya=new Set(["sqlite","sqlite3"]),Ja=new Set([":memory:","memory"]);function Qa(e){let t=e?.DB_CONNECTION?.trim().toLowerCase();return t!=null&&Ya.has(t)}function Za(e){let t=e.trim().replace(/^\.\//,"");if(t===""||t.startsWith("/")||t.startsWith("~"))return;if(t.split("/").includes(".."))return;return t.replace(/\/+$/,"")}function Nr(e,t=[]){if(!Qa(e))return{};let r=e?.DB_DATABASE_PATH?.trim()||e?.DB_DATABASE?.trim();if(r&&Ja.has(r.toLowerCase()))return{};if(!r)return{warning:"DB_CONNECTION is sqlite but neither DB_DATABASE_PATH nor DB_DATABASE names a file, so ts-cloud cannot tell where the database lives. If it is written inside the release directory, the next deploy discards it. Set DB_DATABASE_PATH, or list the file in the site's `sharedPaths`."};let n=Za(r);if(!n)return{};if(t.some((s)=>Xs(s)===n))return{};return{path:n}}function Ft(e,t=[]){let{path:r}=Nr(e,t);return r?[r]:[]}var Ze="/var/ts-cloud/artifacts";var As=Object.freeze({stagingMaxAgeMinutes:60,artifactMaxAgeDays:2,artifactUploadMaxAgeMinutes:60,bunCacheMaxAgeDays:7,journalMaxAgeDays:14,journalMaxSizeMb:512,containerImageMaxAgeHours:168}),Ls=Object.freeze({artifactMaxAgeDays:0,bunCacheMaxAgeDays:1,journalMaxAgeDays:3,journalMaxSizeMb:256,containerImageMaxAgeHours:24});function xs(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function Me(e,t,r=0){if(!Number.isInteger(t)||t<r)throw Error(`hostCleanup: ${e} must be a whole number >= ${r} (got ${t})`)}function Rs(e,t){for(let[r,n]of Object.entries(t))Me(`${e}.${r}`,n);Me(`${e}.stagingMaxAgeMinutes`,t.stagingMaxAgeMinutes,15),Me(`${e}.artifactUploadMaxAgeMinutes`,t.artifactUploadMaxAgeMinutes,15),Me(`${e}.journalMaxSizeMb`,t.journalMaxSizeMb,1)}function ec(e,t){let r=`hostCleanup.paths[${t}]`,n=e.path?.replace(/\/+$/,"")??"";if(!n.startsWith("/")||n===""||/[\s'"`$\\]/.test(n)||n.split("/").includes(".."))throw Error(`${r}.path must be an absolute directory with no spaces, quotes or '..' (got ${JSON.stringify(e.path)})`);if(n==="/var/www"||n.startsWith("/var/www/"))throw Error(`${r}.path must not be under /var/www: releases are pruned by keepReleases`);if(!e.pattern||/^[*?]+$/.test(e.pattern)||e.pattern.includes("/")||/[\n'"`]/.test(e.pattern))throw Error(`${r}.pattern must be a file-name glob naming something, not a bare wildcard (got ${JSON.stringify(e.pattern)})`);if(Me(`${r}.maxAgeDays`,e.maxAgeDays),e.type!==void 0&&e.type!=="file"&&e.type!=="directory")throw Error(`${r}.type must be 'file' or 'directory'`)}function Bt(e){let t=typeof e==="object"&&e!==null?e:{},r=e!==!1,n={...As,...Es(t.retention)};Rs("hostCleanup.retention",n);let s=null;if(t.pressure!==!1){let a=typeof t.pressure==="object"?t.pressure:{},c=a.lowWaterPercent??50,l=a.highWaterPercent??85;if(Me("hostCleanup.pressure.lowWaterPercent",c),Me("hostCleanup.pressure.highWaterPercent",l,1),l>100||c>=l)throw Error(`hostCleanup.pressure: need 0 <= lowWaterPercent < highWaterPercent <= 100 (got ${c} and ${l})`);let u={...Ls,...Es(a.escalated)},d=Object.fromEntries(Object.keys(n).map((m)=>[m,Math.min(n[m],u[m]??n[m])]));Rs("hostCleanup.pressure.escalated",d),s={lowWaterPercent:c,highWaterPercent:l,escalated:d}}let o=t.schedule??"daily";if(!/^[\w*:,./~ -]+$/.test(o))throw Error(`hostCleanup.schedule must be a systemd OnCalendar expression (got ${JSON.stringify(o)})`);let i=t.paths??[];return i.forEach(ec),{enabled:r,timer:r&&t.timer!==!1,schedule:o,retention:n,pressure:s,paths:i}}function Es(e){return Object.fromEntries(Object.entries(e??{}).filter(([,t])=>t!==void 0))}var ft={stagingMaxAgeMinutes:"TS_CLOUD_HC_STAGING_MIN",artifactMaxAgeDays:"TS_CLOUD_HC_ARTIFACT_DAYS",artifactUploadMaxAgeMinutes:"TS_CLOUD_HC_UPLOAD_MIN",bunCacheMaxAgeDays:"TS_CLOUD_HC_BUN_DAYS",journalMaxAgeDays:"TS_CLOUD_HC_JOURNAL_DAYS",journalMaxSizeMb:"TS_CLOUD_HC_JOURNAL_MB",containerImageMaxAgeHours:"TS_CLOUD_HC_IMAGE_HOURS"};function Hr(e){return Object.keys(ft).map((t)=>`${ft[t]}=${e[t]}`).join(" ")}var Ee=(e)=>`"$${ft[e]}"`;function Os(e){return[`find /var/ts-cloud/staging -xdev -maxdepth 1 -type f -mmin +${Ee("stagingMaxAgeMinutes")} -delete 2>/dev/null || true`,`find /tmp -xdev -maxdepth 1 -type f -name "*-release.tar.gz" -mmin +${Ee("stagingMaxAgeMinutes")} -delete 2>/dev/null || true`,`find /var/ts-cloud/artifacts -xdev -maxdepth 1 -type f -name "*.tar.gz" -mtime +${Ee("artifactMaxAgeDays")} -delete 2>/dev/null || true`,`find /var/ts-cloud/artifacts -xdev -maxdepth 1 -type f -name ".*.tmp" -mmin +${Ee("artifactUploadMaxAgeMinutes")} -delete 2>/dev/null || true`,...e.map(tc),`journalctl --vacuum-time=${Ee("journalMaxAgeDays")}d --vacuum-size=${Ee("journalMaxSizeMb")}M >/dev/null 2>&1 || true`]}function tc(e){let t=xs(e.path.replace(/\/+$/,"")),r=xs(e.pattern);return e.type==="directory"?`find ${t} -xdev -mindepth 1 -maxdepth 1 -type d -name ${r} -mtime +${e.maxAgeDays} -exec rm -rf -- {} + 2>/dev/null || true`:`find ${t} -xdev -mindepth 1 -maxdepth 1 -type f -name ${r} -mtime +${e.maxAgeDays} -delete 2>/dev/null || true`}function Ds(){return[`find /root/.bun/install/cache -xdev -type f -mtime +${Ee("bunCacheMaxAgeDays")} -delete 2>/dev/null || true`,`find /root/.bun/install/cache -xdev -depth -type d -empty -mtime +${Ee("bunCacheMaxAgeDays")} -delete 2>/dev/null || true`,`if command -v docker >/dev/null 2>&1; then docker image prune --all --force --filter "until=\${${ft.containerImageMaxAgeHours}}h" >/dev/null 2>&1 || true; fi`,`if command -v podman >/dev/null 2>&1; then podman image prune --all --force --filter "until=\${${ft.containerImageMaxAgeHours}}h" >/dev/null 2>&1 || true; fi`,"if command -v apt-get >/dev/null 2>&1; then apt-get clean >/dev/null 2>&1 || true; fi"]}function Is(e){return[`${e}="$(df -P / 2>/dev/null | awk 'NR==2 {sub(/%/, "", $5); print $5}' || true)"`,`case "$${e}" in ''|*[!0-9]*) ${e}=-1 ;; esac`]}function Mr(e){let{retention:t,pressure:r,paths:n}=Bt(e),s='echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',o='echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"';if(!r)return['echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',Hr(t),...Os(n),...Ds(),'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"'];let{lowWaterPercent:i,highWaterPercent:a,escalated:c}=r;return['echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',...Is("TS_CLOUD_HC_BEFORE"),"TS_CLOUD_HC_TIER=normal",Hr(t),`if [ "$TS_CLOUD_HC_BEFORE" -ge 0 ] && [ "$TS_CLOUD_HC_BEFORE" -lt ${i} ]; then`," TS_CLOUD_HC_TIER=light",` echo "[ts-cloud] host cleanup: / at \${TS_CLOUD_HC_BEFORE}% (under ${i}%), skipping cache and image pruning"`,`elif [ "$TS_CLOUD_HC_BEFORE" -ge ${a} ]; then`," TS_CLOUD_HC_TIER=pressure",` ${Hr(c)}`,` echo "[ts-cloud] warning: / at \${TS_CLOUD_HC_BEFORE}% (at or above ${a}%), host cleanup is using shortened retention windows" >&2`,"fi",...Os(n),'if [ "$TS_CLOUD_HC_TIER" != light ]; then',...Ds().map((l)=>` ${l}`),"fi",'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"',...Is("TS_CLOUD_HC_AFTER"),`echo "[ts-cloud] host-cleanup {\\"event\\":\\"host-cleanup\\",\\"tier\\":\\"$TS_CLOUD_HC_TIER\\",\\"diskBeforePercent\\":$TS_CLOUD_HC_BEFORE,\\"diskAfterPercent\\":$TS_CLOUD_HC_AFTER,\\"lowWaterPercent\\":${i},\\"highWaterPercent\\":${a}}"`,"mkdir -p /var/lib/ts-cloud 2>/dev/null || true",'TS_CLOUD_HC_PREV="$(cat /var/lib/ts-cloud/host-cleanup.alert 2>/dev/null || echo ok)"',`if [ "$TS_CLOUD_HC_AFTER" -ge ${a} ]; then`,` echo "[ts-cloud] warning: / still at \${TS_CLOUD_HC_AFTER}% after host cleanup (high-water ${a}%); something outside ts-cloud's retention rules is filling the disk" >&2`,` if [ "$TS_CLOUD_HC_PREV" != alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "⚠️ $(hostname): / at \${TS_CLOUD_HC_AFTER}% after host cleanup (high-water ${a}%)" >/dev/null 2>&1 || true; fi`," echo alert > /var/lib/ts-cloud/host-cleanup.alert 2>/dev/null || true","else",` if [ "$TS_CLOUD_HC_PREV" = alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "✅ $(hostname): / back under ${a}% after host cleanup (\${TS_CLOUD_HC_AFTER}%)" >/dev/null 2>&1 || true; fi`," echo ok > /var/lib/ts-cloud/host-cleanup.alert 2>/dev/null || true","fi"]}function ks(e){return["#!/usr/bin/env bash","# Managed by ts-cloud: rewritten on every deploy. Configure compute.hostCleanup instead of editing.","set -uo pipefail","TS_CLOUD_HC_LOCK=/run/lock/ts-cloud-host-cleanup.lock","[ -d /run/lock ] || TS_CLOUD_HC_LOCK=/tmp/ts-cloud-host-cleanup.lock",'if command -v flock >/dev/null 2>&1 && exec 9>"$TS_CLOUD_HC_LOCK"; then',' if ! flock -n 9; then echo "[ts-cloud] host cleanup already running; skipping"; exit 0; fi',"fi",...Mr(e),"exit 0"]}function Ur(e,t,r,n,s){return[`cat > ${e}.ts-cloud-new <<'${r}' || true`,...t,r,`if [ -s ${e}.ts-cloud-new ] && ! cmp -s ${e}.ts-cloud-new ${e}; then chmod ${n} ${e}.ts-cloud-new && mv -f ${e}.ts-cloud-new ${e}${s?` && ${s}=1`:""} || true; else rm -f ${e}.ts-cloud-new; fi`]}function Ns(e){let t=Bt(e),r="/etc/systemd/system/ts-cloud-host-cleanup",n=["if [ -f /etc/systemd/system/ts-cloud-host-cleanup.timer ]; then"," systemctl disable --now ts-cloud-host-cleanup.timer >/dev/null 2>&1 || true"," rm -f /etc/systemd/system/ts-cloud-host-cleanup.timer /etc/systemd/system/ts-cloud-host-cleanup.service"," systemctl daemon-reload >/dev/null 2>&1 || true","fi"];if(!t.enabled)return[...n,"rm -f /usr/local/bin/ts-cloud-host-cleanup.sh"];let s=Ur("/usr/local/bin/ts-cloud-host-cleanup.sh",ks(e),"TS_CLOUD_HOST_CLEANUP_EOF","755");if(!t.timer)return[...s,...n];return[...s,"TS_CLOUD_HC_UNITS_CHANGED=0","if command -v systemctl >/dev/null 2>&1 && [ -d /etc/systemd/system ]; then",...Ur("/etc/systemd/system/ts-cloud-host-cleanup.service",["[Unit]","Description=ts-cloud host cleanup (bounded disk retention)","After=local-fs.target","","[Service]","Type=oneshot","ExecStart=/usr/local/bin/ts-cloud-host-cleanup.sh","Nice=19","IOSchedulingClass=idle"],"TS_CLOUD_HOST_CLEANUP_SVC_EOF","644","TS_CLOUD_HC_UNITS_CHANGED"),...Ur("/etc/systemd/system/ts-cloud-host-cleanup.timer",["[Unit]","Description=Run ts-cloud host cleanup on a schedule, independent of deploys","","[Timer]",`OnCalendar=${t.schedule}`,"RandomizedDelaySec=1h","Persistent=true","","[Install]","WantedBy=timers.target"],"TS_CLOUD_HOST_CLEANUP_TMR_EOF","644","TS_CLOUD_HC_UNITS_CHANGED"),' if [ "$TS_CLOUD_HC_UNITS_CHANGED" -eq 1 ]; then systemctl daemon-reload >/dev/null 2>&1 || true; fi'," systemctl enable --now ts-cloud-host-cleanup.timer >/dev/null 2>&1 || true","fi"]}function zr(e){let t=Ns(e);if(!Bt(e).enabled)return t;return[...t,'if [ -x /usr/local/bin/ts-cloud-host-cleanup.sh ]; then /usr/local/bin/ts-cloud-host-cleanup.sh < /dev/null || echo "[ts-cloud] warning: host cleanup exited $?" >&2; fi']}var rc=/\.(?:[cm]?[jt]sx?)$/;function Wr(e,t,r){let n=t==="bun"?"/usr/local/bin/bun":t==="deno"?"/usr/local/bin/deno":"/usr/local/bin/node",s=e.trim();if(/^(?:bun|node|deno)\s+/.test(s))return`${n} ${s.replace(/^(?:bun|node|deno)\s+/,"")}`;let[o="",...i]=s.split(/\s+/);if(o&&!rc.test(o)){let a=o.startsWith("/")?o:r&&o.startsWith("./")?`${r.replace(/\/+$/,"")}/${o.replace(/^\.\//,"")}`:void 0;if(a)return[a,...i].join(" ")}return`${n} ${s}`}function Hs(e){return["TS_CLOUD_MEM_MB=$(awk '/^MemTotal:/{print int($2/1024)}' /proc/meminfo)","TS_CLOUD_HIGH_MB=$((TS_CLOUD_MEM_MB / 8))",'[ "$TS_CLOUD_HIGH_MB" -lt 512 ] && TS_CLOUD_HIGH_MB=512','[ "$TS_CLOUD_HIGH_MB" -gt 4096 ] && TS_CLOUD_HIGH_MB=4096',`mkdir -p /etc/systemd/system/${e}.d`,`printf '# Written by ts-cloud: memoryHigh resolved from this box.
@@ -273,8 +273,8 @@ await (${Ps.toString()})(JSON.parse(await Bun.file(process.env.TS_CLOUD_STORAGE_
273
273
  [Service]
274
274
  MemoryAccounting=true
275
275
  MemoryHigh=%sM
276
- ' "$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)"',...jr()]}function Kt(e,t={auto:!0}){let r=t.auto===!1?[]:[`/etc/systemd/system/${e}.d/50-ts-cloud-memory.conf`];for(let n of["/etc/systemd/system.control","/run/systemd/system.control"]){if(t.high)r.push(`${n}/${e}.d/50-MemoryHigh.conf`);if(t.max)r.push(`${n}/${e}.d/50-MemoryMax.conf`)}if(r.length===0)return[];return["TS_CLOUD_MEM_CLEARED=0",...r.map((n)=>`if [ -f ${n} ]; then rm -f ${n}; TS_CLOUD_MEM_CLEARED=1; echo "[ts-cloud] removed ${n}: memory limits now come from config"; fi`),'if [ "$TS_CLOUD_MEM_CLEARED" = 1 ]; then systemctl daemon-reload; fi']}function jr(){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 nc(e){return[`TS_CLOUD_SLICE=$(systemctl show ${e} -p Slice --value 2>/dev/null || true)`,'if [ -n "$TS_CLOUD_SLICE" ] && [ "$TS_CLOUD_SLICE" != "system.slice" ]; then systemctl set-property --runtime "$TS_CLOUD_SLICE" MemoryHigh=infinity MemoryMax=infinity 2>/dev/null || true; systemctl set-property "$TS_CLOUD_SLICE" MemoryHigh=infinity MemoryMax=infinity 2>/dev/null || true; fi']}var ze={path:"/",intervalSeconds:60,failuresBeforeRestart:3,timeoutSeconds:10,startupGraceSeconds:600,maxBackoffSeconds:3600,backoffBaseSeconds:300};function ht(e,t,r){return typeof e==="number"&&Number.isFinite(e)?Math.max(r,Math.floor(e)):t}function Us(e){let{unitBase:t,unitPattern:r,port:n}=e,s=e.path&&e.path.startsWith("/")?e.path:ze.path,o=ht(e.intervalSeconds,ze.intervalSeconds,10),i=ht(e.failuresBeforeRestart,ze.failuresBeforeRestart,1),a=ht(e.timeoutSeconds,ze.timeoutSeconds,1),c=ht(e.startupGraceSeconds,ze.startupGraceSeconds,0),l=ht(e.maxBackoffSeconds,ze.maxBackoffSeconds,0),u=Math.min(ze.backoffBaseSeconds,l),d=`/usr/local/sbin/${t}-liveness`,m=`/run/${t}-liveness`,h=`${t}-liveness`,f=`127.0.0.1:${n}${s}`,k=r.includes("@*")?`TS_CLOUD_UNIT=$(systemctl list-units --plain --no-legend --type=service '${r}' 2>/dev/null | awk '{print $1}' | head -1)`:`TS_CLOUD_UNIT=${r}`;return[`cat > ${d} <<'TS_CLOUD_LIVENESS_EOF'`,"#!/bin/sh",`# Liveness check for ${t}, written by ts-cloud on every deploy.`,`# Settings: interval=${o}s timeout=${a}s failures=${i} startup-grace=${c}s max-backoff=${l}s`,"set -eu",`TS_CLOUD_STATE=${m}`,'exec 9>"$TS_CLOUD_STATE.lock"',"flock -n 9 || exit 0",k,'[ -n "$TS_CLOUD_UNIT" ] || exit 0','systemctl is-active --quiet "$TS_CLOUD_UNIT" || exit 0',"TS_CLOUD_RC=0",`curl -s -o /dev/null --max-time ${a} "http://${f}" || TS_CLOUD_RC=$?`,'if [ "$TS_CLOUD_RC" -eq 0 ]; then',' rm -f "$TS_CLOUD_STATE.fail"',' if [ -f "$TS_CLOUD_STATE.restarts" ]; then',` TS_CLOUD_LAST=$(awk '{print $2}' "$TS_CLOUD_STATE.restarts" 2>/dev/null || true)`,` case "$TS_CLOUD_LAST" in ''|*[!0-9]*) TS_CLOUD_LAST=0 ;; esac`,` [ $(($(date +%s) - TS_CLOUD_LAST)) -lt ${l} ] || rm -f "$TS_CLOUD_STATE.restarts"`," fi"," exit 0","fi",'case "$TS_CLOUD_RC" in'," 7) TS_CLOUD_WHY='connection refused' ;;",` 28) TS_CLOUD_WHY='no response within ${a}s' ;;`,' *) TS_CLOUD_WHY="curl exit $TS_CLOUD_RC" ;;',"esac",'TS_CLOUD_SINCE=$(systemctl show "$TS_CLOUD_UNIT" -p ActiveEnterTimestampMonotonic --value 2>/dev/null || true)',"TS_CLOUD_UPTIME=$(cut -d' ' -f1 /proc/uptime 2>/dev/null || true)",`TS_CLOUD_AGE=$(awk -v up="$TS_CLOUD_UPTIME" -v since="$TS_CLOUD_SINCE" 'BEGIN { if (since + 0 > 0 && up + 0 > 0) print int(up - since / 1000000); else print -1 }')`,`case "$TS_CLOUD_AGE" in ''|*[!0-9-]*) TS_CLOUD_AGE=-1 ;; esac`,'if [ "$TS_CLOUD_AGE" -lt 0 ]; then',' TS_CLOUD_PID=$(systemctl show "$TS_CLOUD_UNIT" -p MainPID --value 2>/dev/null || true)',` case "$TS_CLOUD_PID" in ''|0|*[!0-9]*) ;; *) TS_CLOUD_AGE=$(ps -o etimes= -p "$TS_CLOUD_PID" 2>/dev/null | tr -d ' ' || true) ;; esac`,` case "$TS_CLOUD_AGE" in ''|*[!0-9]*) TS_CLOUD_AGE=-1 ;; esac`,"fi",`if [ "$TS_CLOUD_AGE" -ge 0 ] && [ "$TS_CLOUD_AGE" -lt ${c} ]; then`,' rm -f "$TS_CLOUD_STATE.fail"',` logger -t ${h} "$TS_CLOUD_UNIT is \${TS_CLOUD_AGE}s old, inside its ${c}s startup grace; not counting this failed check on ${f} ($TS_CLOUD_WHY)"`," exit 0","fi",'TS_CLOUD_FAILS=$(cat "$TS_CLOUD_STATE.fail" 2>/dev/null || echo 0)',`case "$TS_CLOUD_FAILS" in ''|*[!0-9]*) TS_CLOUD_FAILS=0 ;; esac`,"TS_CLOUD_FAILS=$((TS_CLOUD_FAILS + 1))",'echo "$TS_CLOUD_FAILS" > "$TS_CLOUD_STATE.fail"',`if [ "$TS_CLOUD_FAILS" -lt ${i} ]; then`,` logger -t ${h} "check $TS_CLOUD_FAILS of ${i} failed on ${f} ($TS_CLOUD_WHY)"`," exit 0","fi","TS_CLOUD_NOW=$(date +%s)","TS_CLOUD_STREAK=0","TS_CLOUD_LAST=0",'[ ! -f "$TS_CLOUD_STATE.restarts" ] || read -r TS_CLOUD_STREAK TS_CLOUD_LAST < "$TS_CLOUD_STATE.restarts" || true',`case "$TS_CLOUD_STREAK" in ''|*[!0-9]*) TS_CLOUD_STREAK=0 ;; esac`,`case "$TS_CLOUD_LAST" in ''|*[!0-9]*) TS_CLOUD_LAST=0 ;; esac`,'if [ "$TS_CLOUD_STREAK" -gt 0 ]; then',` TS_CLOUD_WAIT=${u}`," TS_CLOUD_I=1",` while [ "$TS_CLOUD_I" -lt "$TS_CLOUD_STREAK" ] && [ "$TS_CLOUD_WAIT" -lt ${l} ]; do TS_CLOUD_WAIT=$((TS_CLOUD_WAIT * 2)); TS_CLOUD_I=$((TS_CLOUD_I + 1)); done`,` [ "$TS_CLOUD_WAIT" -le ${l} ] || TS_CLOUD_WAIT=${l}`," TS_CLOUD_ELAPSED=$((TS_CLOUD_NOW - TS_CLOUD_LAST))",' if [ "$TS_CLOUD_ELAPSED" -lt "$TS_CLOUD_WAIT" ]; then',` logger -t ${h} "holding off: $TS_CLOUD_STREAK liveness restart(s) in a row have not brought $TS_CLOUD_UNIT back; next restart allowed in $((TS_CLOUD_WAIT - TS_CLOUD_ELAPSED))s ($TS_CLOUD_WHY on ${f})"`," exit 0"," fi","fi","TS_CLOUD_STREAK=$((TS_CLOUD_STREAK + 1))",`logger -t ${h} "no HTTP response on ${f} after $TS_CLOUD_FAILS checks ($TS_CLOUD_WHY); restarting $TS_CLOUD_UNIT (liveness restart $TS_CLOUD_STREAK in a row)"`,'echo "$TS_CLOUD_STREAK $TS_CLOUD_NOW" > "$TS_CLOUD_STATE.restarts"','rm -f "$TS_CLOUD_STATE.fail"','systemctl restart "$TS_CLOUD_UNIT"',"TS_CLOUD_LIVENESS_EOF",`chmod +x ${d}`,`rm -f ${m}.fail ${m}.restarts`,`cat > /etc/systemd/system/${t}-liveness.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=Liveness check for ${t} (managed by ts-cloud)`,"","[Service]","Type=oneshot",`ExecStart=${d}`,"TS_CLOUD_UNIT_EOF",`cat > /etc/systemd/system/${t}-liveness.timer <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=Run the ${t} liveness check every ${o}s`,"","[Timer]",`OnUnitActiveSec=${o}s`,`OnBootSec=${o}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 Ms=20,Kr=3,sc=5,oc=60;function ic(e){let{paths:t,unitBase:r,releaseId:n,port:s}=e,o=`${r}@${n}.service`,i=`${r}.service`,a=Math.max(1,e.healthGateSeconds??5),c=e.healthCheckPath?e.healthCheckPath.startsWith("/")?e.healthCheckPath:`/${e.healthCheckPath}`:null,l=c?`curl -sf -o /dev/null --max-time ${sc} "http://127.0.0.1:${s}${c}"`:null,u=(d)=>`{ echo "[ts-cloud] release ${n} ${d}" >&2; ts_cloud_restore_previous; exit 1; }`;return[`TS_CLOUD_OLD_UNITS=$(systemctl list-units --plain --no-legend --type=service "${r}@*.service" 2>/dev/null | awk '{print $1}' | grep -v "^${o}$" || true)`,`TS_CLOUD_PREV_CURRENT="$(readlink ${t.current} 2>/dev/null || true)"`,"TS_CLOUD_LEGACY_STOPPED=0","ts_cloud_restore_previous() {",` journalctl -u ${o} -n 50 --no-pager >&2 || true`,` systemctl stop ${o} 2>/dev/null || true`,` systemctl disable ${o} 2>/dev/null || true`,` if [ -n "$TS_CLOUD_PREV_CURRENT" ] && [ -d "$TS_CLOUD_PREV_CURRENT" ]; then ln -sfn "$TS_CLOUD_PREV_CURRENT" ${t.current}.tmp && mv -Tf ${t.current}.tmp ${t.current}; fi`,' for TS_CLOUD_RU in ${TS_CLOUD_OLD_UNITS}; do systemctl enable "$TS_CLOUD_RU" 2>/dev/null || true; systemctl start "$TS_CLOUD_RU" 2>/dev/null || true; done',` if [ "$TS_CLOUD_LEGACY_STOPPED" -eq 1 ]; then systemctl start ${i} 2>/dev/null || true; fi`,' if [ -n "$TS_CLOUD_OLD_UNITS" ] || [ "$TS_CLOUD_LEGACY_STOPPED" -eq 1 ]; then echo "[ts-cloud] previous release restored and serving" >&2; else echo "[ts-cloud] there was no previous release to restore" >&2; fi',"}",`if [ -f /etc/systemd/system/${i} ] && systemctl is-active --quiet ${i}; then echo "[ts-cloud] retiring pre-zero-downtime unit ${i} (one-time restart cutover)"; systemctl stop ${i}; TS_CLOUD_LEGACY_STOPPED=1; fi`,'TS_CLOUD_STARTED_AT="@$(date +%s)"',`systemctl restart ${o}`,`TS_CLOUD_GATE_OK=1; for TS_CLOUD_I in $(seq 1 ${a}); do sleep 1; systemctl is-active --quiet ${o} || { TS_CLOUD_GATE_OK=0; break; }; done`,'if [ "$TS_CLOUD_GATE_OK" -ne 1 ]; then',` if journalctl -u ${o} --since "$TS_CLOUD_STARTED_AT" -o cat --no-pager 2>/dev/null | grep -iE 'EADDRINUSE|address already in use|port [0-9]+ (is )?in use|Failed to start server' >/dev/null; then`,` echo "[ts-cloud] release ${n} could not share :${s} with the previous release (no SO_REUSEPORT?) — retiring it and retrying" >&2`,' for TS_CLOUD_RU in ${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_RU" 2>/dev/null || true; done',` systemctl restart ${o}`,` for TS_CLOUD_I in $(seq 1 ${a}); do sleep 1; systemctl is-active --quiet ${o} || ${u("failed its health gate on the free port")}; done`," else",` ${u("crashed on start — the previous release was never stopped")}`," fi","fi",`if ss -ltnpH "sport = :${s}" >/dev/null 2>&1; then`," TS_CLOUD_BOUND=0",` for TS_CLOUD_I in $(seq 1 ${oc}); do`,` TS_CLOUD_NEW_PID="$(systemctl show -p MainPID --value ${o} 2>/dev/null || true)"`,` if [ -n "$TS_CLOUD_NEW_PID" ] && [ "$TS_CLOUD_NEW_PID" != "0" ] && ss -ltnpH "sport = :${s}" 2>/dev/null | grep "pid=$TS_CLOUD_NEW_PID," >/dev/null; then TS_CLOUD_BOUND=1; break; fi`,` systemctl is-active --quiet ${o} || break`,` sleep ${Kr}`," done",` [ "$TS_CLOUD_BOUND" -eq 1 ] || ${u(`never took :${s}`)}`,"else",' echo "[ts-cloud] cannot read listener PIDs on this host — the response probes run without the bind check" >&2',"fi",...l?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${Ms}); do if ${l}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${Kr}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${u(`never answered ${c}`)}`]:[],...hn(t),`systemctl enable ${o} 2>/dev/null || true`,'for TS_CLOUD_U in ${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done',`TS_CLOUD_LISTENING=0; for TS_CLOUD_I in $(seq 1 ${a}); do if ss -ltnH "sport = :${s}" 2>/dev/null | grep . >/dev/null; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done`,`if [ "$TS_CLOUD_LISTENING" -ne 1 ]; then echo "[ts-cloud] nothing is listening on ${s} after retiring the previous release — restarting ${o} on the now-free port" >&2; systemctl restart ${o}; for TS_CLOUD_I in $(seq 1 ${a}); do if ss -ltnH "sport = :${s}" 2>/dev/null | grep . >/dev/null; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done; fi`,`[ "$TS_CLOUD_LISTENING" -eq 1 ] || ${u(`is active but never bound :${s}`)}`,...l?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${Ms}); do if ${l}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${Kr}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${u(`stopped answering ${c} once it served alone`)}`]:[],...ta(t),`systemctl list-unit-files --plain --no-legend "${r}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v -e "^${o}$" -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/${i} ]; then systemctl disable ${i} 2>/dev/null || true; rm -f /etc/systemd/system/${i}; systemctl daemon-reload; fi`]}function Gr(e){let{siteName:t,slug:r,artifactFetch:n,releaseId:s,execStart:o,envEntries:i,port:a,keepReleases:c=_i,preStartCommands:l=[],healthCheckPath:u,healthGateSeconds:d=5,liveness:m,memoryHigh:h="auto",memoryMax:f,cpuWeight:S,ioWeight:k,tasksMax:E,stopTimeout:O}=e,D=[...S!=null?[`CPUWeight=${S}`]:[],...k!=null?[`IOWeight=${k}`]:[],...E!=null?[`TasksMax=${E}`]:[],...O?[`TimeoutStopSec=${O}`]:[]],R=e.zeroDowntime??a!=null,z=e.appDir??`/var/www/${t}`,x=Ht(z,s),H=`${r}-${t}`,V=`${H}.service`,se=St(r,t,s),ce=e.sharedPaths??[],G=Wc([".env",...ce,...Ft(i,ce)]),oe=zt(i),Y=l.length>0?[`cd ${x.release}`,...l]:[],q=["set -euo pipefail",...Qs(x),Zs(x),...n,...Oi(x,G),...Ys(x),`tar xzf ${se} -C "$TS_CLOUD_STAGED"`,`rm -f ${se}`,`cat > ${x.shared}/.env <<'TS_CLOUD_ENV_EOF'`,oe,"TS_CLOUD_ENV_EOF",`chmod 600 ${x.shared}/.env`,...ea(x),`find ${x.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' ${x.shared}/.env 2>/dev/null || true`,...Vo(x,G),...Y];if(R&&a!=null){let ue=`${H}@${s}.service`,y=u?u.startsWith("/")?u:`/${u}`:null;return[...q,`cat > /etc/systemd/system/${H}@.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} release %i (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${x.releases}/%i`,`ExecStart=${o}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...h&&h!=="auto"?[`MemoryHigh=${h}`]:[],...f?[`MemoryMax=${f}`]:[],...D,`EnvironmentFile=${x.releases}/%i/.env`,`Environment=PORT=${a}`,`Environment=STX_IMAGE_CACHE_DIR=${jo(x)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...h==="auto"?Hs(`${H}@.service`):[...Kt(`${H}@.service`),...jr()],...nc(ue),...ic({paths:x,unitBase:H,releaseId:s,port:a,healthCheckPath:y,healthGateSeconds:d}),...yn(x,c),...m===!1?[]:Us({...m,unitBase:H,unitPattern:`${H}@*.service`,port:a,path:m?.path??u})]}return[...q,`cat > /etc/systemd/system/${V} <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${x.current}`,`ExecStart=${o}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...h&&h!=="auto"?[`MemoryHigh=${h}`]:[],...f?[`MemoryMax=${f}`]:[],...D,`EnvironmentFile=${x.current}/.env`,...a?[`Environment=PORT=${a}`]:[],`Environment=STX_IMAGE_CACHE_DIR=${jo(x)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...Kt(V,{auto:h!=="auto",high:h!=="auto",max:Boolean(f)}),...h==="auto"?Hs(V):jr(),`systemctl enable ${V}`,`TS_CLOUD_PREV_CURRENT="$(readlink ${x.current} 2>/dev/null || true)"`,...hn(x),`systemctl restart ${V}`,`for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do sleep 1; systemctl is-active --quiet ${V} || { echo "[ts-cloud] release ${s} of ${V} did not stay up — restoring the previous release" >&2; journalctl -u ${V} -n 50 --no-pager >&2 || true; if [ -n "$TS_CLOUD_PREV_CURRENT" ] && [ -d "$TS_CLOUD_PREV_CURRENT" ] && [ "$(readlink -f "$TS_CLOUD_PREV_CURRENT")" != "$(readlink -f ${x.release})" ]; then ln -sfn "$TS_CLOUD_PREV_CURRENT" ${x.current}.tmp && mv -Tf ${x.current}.tmp ${x.current}; systemctl restart ${V} || true; fi; exit 1; }; done`,...ta(x),...yn(x,c),...m===!1||!a?[]:Us({...m,unitBase:H,unitPattern:V,port:a,path:m?.path??u})]}function Vr(e){let{siteName:t,artifactFetch:r,releaseId:n,keepReleases:s=_i,preStartCommands:o=[]}=e,i=e.appDir??`/var/www/${t}`,a=Ht(i,n),c=St(e.slug,t,n),l=o.length>0?[`cd ${a.release}`,...o]:[];return["set -euo pipefail",...Qs(a),Zs(a),...r,...Oi(a,[]),...Ys(a),`tar xzf ${c} -C "$TS_CLOUD_STAGED"`,...ea(a),`rm -f ${c}`,...l,...hn(a),...yn(a,s)]}function St(e,t,r){return`/tmp/${[e,t,r].filter(Boolean).join("-")}-release.tar.gz`}function qr(e,t,r,n){return[`aws s3 cp "s3://${e}/${t}" ${n} --region ${r}`]}function Xr(e,t){return[`mv "${e}" ${t}`]}function et(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function jt(e,t,r){return["set -euo pipefail",`chmod 600 ${et(e)}`,`mv -f -- ${et(e)} ${et(t)}`,`cp -- ${et(t)} ${et(r)}`].join(`
277
- `)}function Wt(e){return`rm -f -- ${et(e)} 2>/dev/null || true`}function Yr(e={}){let t=Math.max(1,e.appServers??e.instances??1),r=!!e.servicesServer||t>1,n=t>1||!!e.server?.loadBalancer;return{appServers:t,loadBalancer:n,dedicatedServices:r,servicesOnApp:!r}}function zs(e,t){let r={REDIS_HOST:e,MEILISEARCH_HOST:`http://${e}:7700`};if(t?.name){if(r.DB_CONNECTION=t.engine==="postgres"?"pgsql":"mysql",r.DB_HOST=e,r.DB_PORT=String(t.port??(t.engine==="postgres"?5432:3306)),r.DB_DATABASE=t.name,t.username)r.DB_USERNAME=t.username;if(t.password)r.DB_PASSWORD=t.password}return r}function Jr(e){let t=e.infrastructure?.compute??{},r=w(e);return[...Uo(t.managedServices??{mysql:!0,redis:!0},{bindPrivate:!0}),...Tt(r,t.managedServices??{mysql:!0}),...Pe(!0),...we(!0),...Ye(t.sshKeys),...He(e.notifications),...t.backups?.enabled?[...Fo({database:r,backups:t.backups})]:[]]}var Gt=["-S","ssh"];function Fs(e={},t="ssh"){let r=[];if(e.identityFile)r.push("-i",e.identityFile);if(e.port)r.push(t==="scp"?"-P":"-p",String(e.port));return r.push("-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR","-o",`ConnectTimeout=${e.connectTimeoutSec??10}`),r}async function Qr(e,t,r={}){let n=Bun.spawn(["ssh",...Fs(r),`${r.user??"root"}@${e}`,t],{stdout:"pipe",stderr:"pipe"}),[s,o]=await Promise.all([new Response(n.stdout).text(),new Response(n.stderr).text()]);return{code:await n.exited,stdout:s,stderr:o}}async function _e(e,t,r={}){let n=await Qr(e,t,r);if(n.code!==0)throw Error(`ssh \`${t}\` on ${e} failed (${n.code}): ${n.stderr.trim()||n.stdout.trim()}`);return n.stdout}async function Zr(e,t={}){let r=t.timeoutMs??180000,n=t.pollIntervalMs??5000,s=Date.now();while(Date.now()-s<r){let o=await Qr(e,"echo ready",t);if(o.code===0&&o.stdout.includes("ready"))return;await new Promise((i)=>setTimeout(i,n))}throw Error(`SSH not ready on ${e} after ${r}ms`)}function yt(e={}){return["set -e","ts_cloud_script=$(mktemp /tmp/ts-cloud-deploy.XXXXXXXX)",`trap 'rm -f "$ts_cloud_script"' EXIT`,'cat > "$ts_cloud_script"',e.sudo?'sudo -n -H bash "$ts_cloud_script" < /dev/null':'bash "$ts_cloud_script" < /dev/null'].join(`
276
+ ' "$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)"',...jr()]}function Kt(e,t={auto:!0}){let r=t.auto===!1?[]:[`/etc/systemd/system/${e}.d/50-ts-cloud-memory.conf`];for(let n of["/etc/systemd/system.control","/run/systemd/system.control"]){if(t.high)r.push(`${n}/${e}.d/50-MemoryHigh.conf`);if(t.max)r.push(`${n}/${e}.d/50-MemoryMax.conf`)}if(r.length===0)return[];return["TS_CLOUD_MEM_CLEARED=0",...r.map((n)=>`if [ -f ${n} ]; then rm -f ${n}; TS_CLOUD_MEM_CLEARED=1; echo "[ts-cloud] removed ${n}: memory limits now come from config"; fi`),'if [ "$TS_CLOUD_MEM_CLEARED" = 1 ]; then systemctl daemon-reload; fi']}function jr(){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 nc(e){return[`TS_CLOUD_SLICE=$(systemctl show ${e} -p Slice --value 2>/dev/null || true)`,'if [ -n "$TS_CLOUD_SLICE" ] && [ "$TS_CLOUD_SLICE" != "system.slice" ]; then systemctl set-property --runtime "$TS_CLOUD_SLICE" MemoryHigh=infinity MemoryMax=infinity 2>/dev/null || true; systemctl set-property "$TS_CLOUD_SLICE" MemoryHigh=infinity MemoryMax=infinity 2>/dev/null || true; fi']}var ze={path:"/",intervalSeconds:60,failuresBeforeRestart:3,timeoutSeconds:10,startupGraceSeconds:600,maxBackoffSeconds:3600,backoffBaseSeconds:300};function ht(e,t,r){return typeof e==="number"&&Number.isFinite(e)?Math.max(r,Math.floor(e)):t}function Us(e){let{unitBase:t,unitPattern:r,port:n}=e,s=e.path&&e.path.startsWith("/")?e.path:ze.path,o=ht(e.intervalSeconds,ze.intervalSeconds,10),i=ht(e.failuresBeforeRestart,ze.failuresBeforeRestart,1),a=ht(e.timeoutSeconds,ze.timeoutSeconds,1),c=ht(e.startupGraceSeconds,ze.startupGraceSeconds,0),l=ht(e.maxBackoffSeconds,ze.maxBackoffSeconds,0),u=Math.min(ze.backoffBaseSeconds,l),d=`/usr/local/sbin/${t}-liveness`,m=`/run/${t}-liveness`,h=`${t}-liveness`,f=`127.0.0.1:${n}${s}`,k=r.includes("@*")?`TS_CLOUD_UNIT=$(systemctl list-units --plain --no-legend --type=service '${r}' 2>/dev/null | awk '{print $1}' | head -1)`:`TS_CLOUD_UNIT=${r}`;return[`cat > ${d} <<'TS_CLOUD_LIVENESS_EOF'`,"#!/bin/sh",`# Liveness check for ${t}, written by ts-cloud on every deploy.`,`# Settings: interval=${o}s timeout=${a}s failures=${i} startup-grace=${c}s max-backoff=${l}s`,"set -eu",`TS_CLOUD_STATE=${m}`,'exec 9>"$TS_CLOUD_STATE.lock"',"flock -n 9 || exit 0",k,'[ -n "$TS_CLOUD_UNIT" ] || exit 0','systemctl is-active --quiet "$TS_CLOUD_UNIT" || exit 0',"TS_CLOUD_RC=0",`curl -s -o /dev/null --max-time ${a} "http://${f}" || TS_CLOUD_RC=$?`,'if [ "$TS_CLOUD_RC" -eq 0 ]; then',' rm -f "$TS_CLOUD_STATE.fail"',' if [ -f "$TS_CLOUD_STATE.restarts" ]; then',` TS_CLOUD_LAST=$(awk '{print $2}' "$TS_CLOUD_STATE.restarts" 2>/dev/null || true)`,` case "$TS_CLOUD_LAST" in ''|*[!0-9]*) TS_CLOUD_LAST=0 ;; esac`,` [ $(($(date +%s) - TS_CLOUD_LAST)) -lt ${l} ] || rm -f "$TS_CLOUD_STATE.restarts"`," fi"," exit 0","fi",'case "$TS_CLOUD_RC" in'," 7) TS_CLOUD_WHY='connection refused' ;;",` 28) TS_CLOUD_WHY='no response within ${a}s' ;;`,' *) TS_CLOUD_WHY="curl exit $TS_CLOUD_RC" ;;',"esac",'TS_CLOUD_SINCE=$(systemctl show "$TS_CLOUD_UNIT" -p ActiveEnterTimestampMonotonic --value 2>/dev/null || true)',"TS_CLOUD_UPTIME=$(cut -d' ' -f1 /proc/uptime 2>/dev/null || true)",`TS_CLOUD_AGE=$(awk -v up="$TS_CLOUD_UPTIME" -v since="$TS_CLOUD_SINCE" 'BEGIN { if (since + 0 > 0 && up + 0 > 0) print int(up - since / 1000000); else print -1 }')`,`case "$TS_CLOUD_AGE" in ''|*[!0-9-]*) TS_CLOUD_AGE=-1 ;; esac`,'if [ "$TS_CLOUD_AGE" -lt 0 ]; then',' TS_CLOUD_PID=$(systemctl show "$TS_CLOUD_UNIT" -p MainPID --value 2>/dev/null || true)',` case "$TS_CLOUD_PID" in ''|0|*[!0-9]*) ;; *) TS_CLOUD_AGE=$(ps -o etimes= -p "$TS_CLOUD_PID" 2>/dev/null | tr -d ' ' || true) ;; esac`,` case "$TS_CLOUD_AGE" in ''|*[!0-9]*) TS_CLOUD_AGE=-1 ;; esac`,"fi",`if [ "$TS_CLOUD_AGE" -ge 0 ] && [ "$TS_CLOUD_AGE" -lt ${c} ]; then`,' rm -f "$TS_CLOUD_STATE.fail"',` logger -t ${h} "$TS_CLOUD_UNIT is \${TS_CLOUD_AGE}s old, inside its ${c}s startup grace; not counting this failed check on ${f} ($TS_CLOUD_WHY)"`," exit 0","fi",'TS_CLOUD_FAILS=$(cat "$TS_CLOUD_STATE.fail" 2>/dev/null || echo 0)',`case "$TS_CLOUD_FAILS" in ''|*[!0-9]*) TS_CLOUD_FAILS=0 ;; esac`,"TS_CLOUD_FAILS=$((TS_CLOUD_FAILS + 1))",'echo "$TS_CLOUD_FAILS" > "$TS_CLOUD_STATE.fail"',`if [ "$TS_CLOUD_FAILS" -lt ${i} ]; then`,` logger -t ${h} "check $TS_CLOUD_FAILS of ${i} failed on ${f} ($TS_CLOUD_WHY)"`," exit 0","fi","TS_CLOUD_NOW=$(date +%s)","TS_CLOUD_STREAK=0","TS_CLOUD_LAST=0",'[ ! -f "$TS_CLOUD_STATE.restarts" ] || read -r TS_CLOUD_STREAK TS_CLOUD_LAST < "$TS_CLOUD_STATE.restarts" || true',`case "$TS_CLOUD_STREAK" in ''|*[!0-9]*) TS_CLOUD_STREAK=0 ;; esac`,`case "$TS_CLOUD_LAST" in ''|*[!0-9]*) TS_CLOUD_LAST=0 ;; esac`,'if [ "$TS_CLOUD_STREAK" -gt 0 ]; then',` TS_CLOUD_WAIT=${u}`," TS_CLOUD_I=1",` while [ "$TS_CLOUD_I" -lt "$TS_CLOUD_STREAK" ] && [ "$TS_CLOUD_WAIT" -lt ${l} ]; do TS_CLOUD_WAIT=$((TS_CLOUD_WAIT * 2)); TS_CLOUD_I=$((TS_CLOUD_I + 1)); done`,` [ "$TS_CLOUD_WAIT" -le ${l} ] || TS_CLOUD_WAIT=${l}`," TS_CLOUD_ELAPSED=$((TS_CLOUD_NOW - TS_CLOUD_LAST))",' if [ "$TS_CLOUD_ELAPSED" -lt "$TS_CLOUD_WAIT" ]; then',` logger -t ${h} "holding off: $TS_CLOUD_STREAK liveness restart(s) in a row have not brought $TS_CLOUD_UNIT back; next restart allowed in $((TS_CLOUD_WAIT - TS_CLOUD_ELAPSED))s ($TS_CLOUD_WHY on ${f})"`," exit 0"," fi","fi","TS_CLOUD_STREAK=$((TS_CLOUD_STREAK + 1))",`logger -t ${h} "no HTTP response on ${f} after $TS_CLOUD_FAILS checks ($TS_CLOUD_WHY); restarting $TS_CLOUD_UNIT (liveness restart $TS_CLOUD_STREAK in a row)"`,'echo "$TS_CLOUD_STREAK $TS_CLOUD_NOW" > "$TS_CLOUD_STATE.restarts"','rm -f "$TS_CLOUD_STATE.fail"','systemctl restart "$TS_CLOUD_UNIT"',"TS_CLOUD_LIVENESS_EOF",`chmod +x ${d}`,`rm -f ${m}.fail ${m}.restarts`,`cat > /etc/systemd/system/${t}-liveness.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=Liveness check for ${t} (managed by ts-cloud)`,"","[Service]","Type=oneshot",`ExecStart=${d}`,"TS_CLOUD_UNIT_EOF",`cat > /etc/systemd/system/${t}-liveness.timer <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=Run the ${t} liveness check every ${o}s`,"","[Timer]",`OnUnitActiveSec=${o}s`,`OnBootSec=${o}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 Ms=20,Kr=3,sc=5,oc=60;function ic(e){let{paths:t,unitBase:r,releaseId:n,port:s}=e,o=`${r}@${n}.service`,i=`${r}.service`,a=Math.max(1,e.healthGateSeconds??5),c=e.healthCheckPath?e.healthCheckPath.startsWith("/")?e.healthCheckPath:`/${e.healthCheckPath}`:null,l=c?`curl -sf -o /dev/null --max-time ${sc} "http://127.0.0.1:${s}${c}"`:null,u=(d)=>`{ echo "[ts-cloud] release ${n} ${d}" >&2; ts_cloud_restore_previous; exit 1; }`;return[`TS_CLOUD_OLD_UNITS=$(systemctl list-units --plain --no-legend --type=service "${r}@*.service" 2>/dev/null | awk '{print $1}' | grep -v "^${o}$" || true)`,`TS_CLOUD_PREV_CURRENT="$(readlink ${t.current} 2>/dev/null || true)"`,"TS_CLOUD_LEGACY_STOPPED=0","ts_cloud_restore_previous() {",` journalctl -u ${o} -n 50 --no-pager >&2 || true`,` systemctl stop ${o} 2>/dev/null || true`,` systemctl disable ${o} 2>/dev/null || true`,` if [ -n "$TS_CLOUD_PREV_CURRENT" ] && [ -d "$TS_CLOUD_PREV_CURRENT" ]; then ln -sfn "$TS_CLOUD_PREV_CURRENT" ${t.current}.tmp && mv -Tf ${t.current}.tmp ${t.current}; fi`,' for TS_CLOUD_RU in ${TS_CLOUD_OLD_UNITS}; do systemctl enable "$TS_CLOUD_RU" 2>/dev/null || true; systemctl start "$TS_CLOUD_RU" 2>/dev/null || true; done',` if [ "$TS_CLOUD_LEGACY_STOPPED" -eq 1 ]; then systemctl start ${i} 2>/dev/null || true; fi`,' if [ -n "$TS_CLOUD_OLD_UNITS" ] || [ "$TS_CLOUD_LEGACY_STOPPED" -eq 1 ]; then echo "[ts-cloud] previous release restored and serving" >&2; else echo "[ts-cloud] there was no previous release to restore" >&2; fi',"}",`if [ -f /etc/systemd/system/${i} ] && systemctl is-active --quiet ${i}; then echo "[ts-cloud] retiring pre-zero-downtime unit ${i} (one-time restart cutover)"; systemctl stop ${i}; TS_CLOUD_LEGACY_STOPPED=1; fi`,'TS_CLOUD_STARTED_AT="@$(date +%s)"',`systemctl restart ${o}`,`TS_CLOUD_GATE_OK=1; for TS_CLOUD_I in $(seq 1 ${a}); do sleep 1; systemctl is-active --quiet ${o} || { TS_CLOUD_GATE_OK=0; break; }; done`,'if [ "$TS_CLOUD_GATE_OK" -ne 1 ]; then',` if journalctl -u ${o} --since "$TS_CLOUD_STARTED_AT" -o cat --no-pager 2>/dev/null | grep -iE 'EADDRINUSE|address already in use|port [0-9]+ (is )?in use|Failed to start server' >/dev/null; then`,` echo "[ts-cloud] release ${n} could not share :${s} with the previous release (no SO_REUSEPORT?) — retiring it and retrying" >&2`,' for TS_CLOUD_RU in ${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_RU" 2>/dev/null || true; done',` systemctl restart ${o}`,` for TS_CLOUD_I in $(seq 1 ${a}); do sleep 1; systemctl is-active --quiet ${o} || ${u("failed its health gate on the free port")}; done`," else",` ${u("crashed on start — the previous release was never stopped")}`," fi","fi",`if ss -ltnpH "sport = :${s}" >/dev/null 2>&1; then`," TS_CLOUD_BOUND=0",` for TS_CLOUD_I in $(seq 1 ${oc}); do`,` TS_CLOUD_NEW_PID="$(systemctl show -p MainPID --value ${o} 2>/dev/null || true)"`,` if [ -n "$TS_CLOUD_NEW_PID" ] && [ "$TS_CLOUD_NEW_PID" != "0" ] && ss -ltnpH "sport = :${s}" 2>/dev/null | grep "pid=$TS_CLOUD_NEW_PID," >/dev/null; then TS_CLOUD_BOUND=1; break; fi`,` systemctl is-active --quiet ${o} || break`,` sleep ${Kr}`," done",` [ "$TS_CLOUD_BOUND" -eq 1 ] || ${u(`never took :${s}`)}`,"else",' echo "[ts-cloud] cannot read listener PIDs on this host — the response probes run without the bind check" >&2',"fi",...l?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${Ms}); do if ${l}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${Kr}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${u(`never answered ${c}`)}`]:[],...hn(t),`systemctl enable ${o} 2>/dev/null || true`,'for TS_CLOUD_U in ${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done',`TS_CLOUD_LISTENING=0; for TS_CLOUD_I in $(seq 1 ${a}); do if ss -ltnH "sport = :${s}" 2>/dev/null | grep . >/dev/null; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done`,`if [ "$TS_CLOUD_LISTENING" -ne 1 ]; then echo "[ts-cloud] nothing is listening on ${s} after retiring the previous release — restarting ${o} on the now-free port" >&2; systemctl restart ${o}; for TS_CLOUD_I in $(seq 1 ${a}); do if ss -ltnH "sport = :${s}" 2>/dev/null | grep . >/dev/null; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done; fi`,`[ "$TS_CLOUD_LISTENING" -eq 1 ] || ${u(`is active but never bound :${s}`)}`,...l?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${Ms}); do if ${l}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${Kr}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${u(`stopped answering ${c} once it served alone`)}`]:[],...ta(t),`systemctl list-unit-files --plain --no-legend "${r}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v -e "^${o}$" -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/${i} ]; then systemctl disable ${i} 2>/dev/null || true; rm -f /etc/systemd/system/${i}; systemctl daemon-reload; fi`]}function Gr(e){let{siteName:t,slug:r,artifactFetch:n,releaseId:s,execStart:o,envEntries:i,port:a,keepReleases:c=_i,preStartCommands:l=[],healthCheckPath:u,healthGateSeconds:d=5,liveness:m,memoryHigh:h="auto",memoryMax:f,cpuWeight:S,ioWeight:k,tasksMax:O,stopTimeout:D}=e,I=[...S!=null?[`CPUWeight=${S}`]:[],...k!=null?[`IOWeight=${k}`]:[],...O!=null?[`TasksMax=${O}`]:[],...D?[`TimeoutStopSec=${D}`]:[]],E=e.zeroDowntime??a!=null,z=e.appDir??`/var/www/${t}`,x=Ht(z,s),H=`${r}-${t}`,V=`${H}.service`,se=St(r,t,s),ce=e.sharedPaths??[],G=Wc([".env",...ce,...Ft(i,ce)]),oe=zt(i),Y=l.length>0?[`cd ${x.release}`,...l]:[],q=["set -euo pipefail",...Qs(x),Zs(x),...n,...Oi(x,G),...Ys(x),`tar xzf ${se} -C "$TS_CLOUD_STAGED"`,`rm -f ${se}`,`cat > ${x.shared}/.env <<'TS_CLOUD_ENV_EOF'`,oe,"TS_CLOUD_ENV_EOF",`chmod 600 ${x.shared}/.env`,...ea(x),`find ${x.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' ${x.shared}/.env 2>/dev/null || true`,...Vo(x,G),...Y];if(E&&a!=null){let ue=`${H}@${s}.service`,y=u?u.startsWith("/")?u:`/${u}`:null;return[...q,`cat > /etc/systemd/system/${H}@.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} release %i (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${x.releases}/%i`,`ExecStart=${o}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...h&&h!=="auto"?[`MemoryHigh=${h}`]:[],...f?[`MemoryMax=${f}`]:[],...I,`EnvironmentFile=${x.releases}/%i/.env`,`Environment=PORT=${a}`,`Environment=STX_IMAGE_CACHE_DIR=${jo(x)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...h==="auto"?Hs(`${H}@.service`):[...Kt(`${H}@.service`),...jr()],...nc(ue),...ic({paths:x,unitBase:H,releaseId:s,port:a,healthCheckPath:y,healthGateSeconds:d}),...yn(x,c),...m===!1?[]:Us({...m,unitBase:H,unitPattern:`${H}@*.service`,port:a,path:m?.path??u})]}return[...q,`cat > /etc/systemd/system/${V} <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${x.current}`,`ExecStart=${o}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...h&&h!=="auto"?[`MemoryHigh=${h}`]:[],...f?[`MemoryMax=${f}`]:[],...I,`EnvironmentFile=${x.current}/.env`,...a?[`Environment=PORT=${a}`]:[],`Environment=STX_IMAGE_CACHE_DIR=${jo(x)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...Kt(V,{auto:h!=="auto",high:h!=="auto",max:Boolean(f)}),...h==="auto"?Hs(V):jr(),`systemctl enable ${V}`,`TS_CLOUD_PREV_CURRENT="$(readlink ${x.current} 2>/dev/null || true)"`,...hn(x),`systemctl restart ${V}`,`for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do sleep 1; systemctl is-active --quiet ${V} || { echo "[ts-cloud] release ${s} of ${V} did not stay up — restoring the previous release" >&2; journalctl -u ${V} -n 50 --no-pager >&2 || true; if [ -n "$TS_CLOUD_PREV_CURRENT" ] && [ -d "$TS_CLOUD_PREV_CURRENT" ] && [ "$(readlink -f "$TS_CLOUD_PREV_CURRENT")" != "$(readlink -f ${x.release})" ]; then ln -sfn "$TS_CLOUD_PREV_CURRENT" ${x.current}.tmp && mv -Tf ${x.current}.tmp ${x.current}; systemctl restart ${V} || true; fi; exit 1; }; done`,...ta(x),...yn(x,c),...m===!1||!a?[]:Us({...m,unitBase:H,unitPattern:V,port:a,path:m?.path??u})]}function Vr(e){let{siteName:t,artifactFetch:r,releaseId:n,keepReleases:s=_i,preStartCommands:o=[]}=e,i=e.appDir??`/var/www/${t}`,a=Ht(i,n),c=St(e.slug,t,n),l=o.length>0?[`cd ${a.release}`,...o]:[];return["set -euo pipefail",...Qs(a),Zs(a),...r,...Oi(a,[]),...Ys(a),`tar xzf ${c} -C "$TS_CLOUD_STAGED"`,...ea(a),`rm -f ${c}`,...l,...hn(a),...yn(a,s)]}function St(e,t,r){return`/tmp/${[e,t,r].filter(Boolean).join("-")}-release.tar.gz`}function qr(e,t,r,n){return[`aws s3 cp "s3://${e}/${t}" ${n} --region ${r}`]}function Xr(e,t){return[`mv "${e}" ${t}`]}function et(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function jt(e,t,r){return["set -euo pipefail",`chmod 600 ${et(e)}`,`mv -f -- ${et(e)} ${et(t)}`,`cp -- ${et(t)} ${et(r)}`].join(`
277
+ `)}function Wt(e){return`rm -f -- ${et(e)} 2>/dev/null || true`}function Yr(e={}){let t=Math.max(1,e.appServers??e.instances??1),r=!!e.servicesServer||t>1,n=t>1||!!e.server?.loadBalancer;return{appServers:t,loadBalancer:n,dedicatedServices:r,servicesOnApp:!r}}function zs(e,t){let r={REDIS_HOST:e,MEILISEARCH_HOST:`http://${e}:7700`};if(t?.name){if(r.DB_CONNECTION=t.engine==="postgres"?"pgsql":"mysql",r.DB_HOST=e,r.DB_PORT=String(t.port??(t.engine==="postgres"?5432:3306)),r.DB_DATABASE=t.name,t.username)r.DB_USERNAME=t.username;if(t.password)r.DB_PASSWORD=t.password}return r}function Jr(e){let t=e.infrastructure?.compute??{},r=A(e);return[...Uo(t.managedServices??{mysql:!0,redis:!0},{bindPrivate:!0}),...Tt(r,t.managedServices??{mysql:!0}),...Pe(!0),...we(!0),...Ye(t.sshKeys),...He(e.notifications),...t.backups?.enabled?[...Fo({database:r,backups:t.backups})]:[]]}var Gt=["-S","ssh"];function Fs(e={},t="ssh"){let r=[];if(e.identityFile)r.push("-i",e.identityFile);if(e.port)r.push(t==="scp"?"-P":"-p",String(e.port));return r.push("-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR","-o",`ConnectTimeout=${e.connectTimeoutSec??10}`),r}async function Qr(e,t,r={}){let n=Bun.spawn(["ssh",...Fs(r),`${r.user??"root"}@${e}`,t],{stdout:"pipe",stderr:"pipe"}),[s,o]=await Promise.all([new Response(n.stdout).text(),new Response(n.stderr).text()]);return{code:await n.exited,stdout:s,stderr:o}}async function _e(e,t,r={}){let n=await Qr(e,t,r);if(n.code!==0)throw Error(`ssh \`${t}\` on ${e} failed (${n.code}): ${n.stderr.trim()||n.stdout.trim()}`);return n.stdout}async function Zr(e,t={}){let r=t.timeoutMs??180000,n=t.pollIntervalMs??5000,s=Date.now();while(Date.now()-s<r){let o=await Qr(e,"echo ready",t);if(o.code===0&&o.stdout.includes("ready"))return;await new Promise((i)=>setTimeout(i,n))}throw Error(`SSH not ready on ${e} after ${r}ms`)}function yt(e={}){return["set -e","ts_cloud_script=$(mktemp /tmp/ts-cloud-deploy.XXXXXXXX)",`trap 'rm -f "$ts_cloud_script"' EXIT`,'cat > "$ts_cloud_script"',e.sudo?'sudo -n -H bash "$ts_cloud_script" < /dev/null':'bash "$ts_cloud_script" < /dev/null'].join(`
278
278
  `)}var cn=yt();import{homedir as ac}from"node:os";import{join as cc}from"node:path";var Vt={location:"fsn1",image:"ubuntu-24.04",sshUser:"root",sshPrivateKeyPath:"~/.ssh/id_ed25519"};function tn(e){return e.startsWith("~/")?cc(ac(),e.slice(2)):e}function tt(...e){for(let t of e){let r=process.env[t]?.trim();if(r)return r}return}function rt(...e){for(let t of e){let r=t?.trim();if(r)return r}return}function vt(e,t){return rt(e,t?.hetzner?.apiToken,tt("HCLOUD_TOKEN","HETZNER_API_TOKEN"))}function ln(e,t){return rt(t,e?.hetzner?.location,tt("HCLOUD_LOCATION","HETZNER_LOCATION"))??Vt.location}function bt(e,t){let r=e?.infrastructure?.compute;return rt(t,r?.image,e?.hetzner?.image,tt("HCLOUD_IMAGE","HETZNER_IMAGE"))??Vt.image}function lc(e,t){return rt(t,e?.hetzner?.sshUser,tt("HCLOUD_SSH_USER","HETZNER_SSH_USER"))??Vt.sshUser}function Bs(e,t){return tn(rt(t,e?.hetzner?.sshPrivateKeyPath,tt("HCLOUD_SSH_KEY","HETZNER_SSH_KEY"))??Vt.sshPrivateKeyPath)}function uc(e,t,r){let n=rt(t,e?.hetzner?.sshPublicKeyPath,tt("HCLOUD_SSH_PUBLIC_KEY","HETZNER_SSH_PUBLIC_KEY"));if(n)return tn(n);return`${r??Bs(e)}.pub`}function ur(e,t={}){let r=Bs(e,t.sshPrivateKeyPath);return{apiToken:vt(t.apiToken,e),location:ln(e,t.location),image:bt(e,t.image),sshUser:lc(e,t.sshUser),sshPrivateKeyPath:r,sshPublicKeyPath:uc(e,t.sshPublicKeyPath,r)}}var pc="https://api.hetzner.cloud/v1";class qt extends Error{status;code;details;constructor(e,t,r,n){super(e);this.status=t;this.code=r;this.details=n;this.name="HetznerApiError"}}class Xt extends Error{action;constructor(e,t){super(e);this.action=t;this.name="HetznerActionError"}}class Je{name="hetzner";apiToken;baseUrl;fetchImpl;constructor(e){this.apiToken=e.apiToken,this.baseUrl=e.baseUrl??pc,this.fetchImpl=e.fetchImpl??fetch}async request(e,t,r){let n=await this.fetchImpl(`${this.baseUrl}${t}`,{method:e,headers:{Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},body:r===void 0?void 0:JSON.stringify(r)}),s=await n.text(),o;try{o=s?JSON.parse(s):{}}catch{if(!n.ok){let i=s.trim().slice(0,200)||n.statusText||"Hetzner API error";throw Error(`Hetzner API ${e} ${t} (${n.status}): ${i}`)}throw Error(`Hetzner API ${e} ${t}: unexpected non-JSON response`)}if(!n.ok){let i=o.error?.message||n.statusText||"Hetzner API error",a=o.error?.code?` [${o.error.code}]`:"";throw new qt(`Hetzner API ${e} ${t} (${n.status})${a}: ${i}`,n.status,o.error?.code,o.error?.details)}return o}async requestAll(e,t){let r=[],n=1;for(;;){let s=e.includes("?")?"&":"?",o=await this.request("GET",`${e}${s}per_page=50&page=${n}`);r.push(...o[t]??[]);let i=o.meta?.pagination?.next_page;if(!i)return r;n=i}}async listServers(){return this.requestAll("/servers","servers")}async getServer(e){return(await this.request("GET",`/servers/${e}`)).server}async listVolumes(){return this.requestAll("/volumes","volumes")}async getVolume(e){return(await this.request("GET",`/volumes/${e}`)).volume}async createVolume(e){return this.request("POST","/volumes",{...e,automount:!1})}async attachVolume(e,t){return(await this.request("POST",`/volumes/${e}/actions/attach`,{server:t,automount:!1})).action}async resizeVolume(e,t){return(await this.request("POST",`/volumes/${e}/actions/resize`,{size:t})).action}async protectVolume(e,t){return(await this.request("POST",`/volumes/${e}/actions/change_protection`,{delete:t})).action}async getServerMetrics(e,t){let r=new URLSearchParams({type:t.types.join(","),start:t.start.toISOString(),end:t.end.toISOString(),step:String(Math.max(60,Math.floor(t.step??60)))});return(await this.request("GET",`/servers/${e}/metrics?${r}`)).metrics}async listServerTypes(e){let t=e?`?name=${encodeURIComponent(e)}`:"";return this.requestAll(`/server_types${t}`,"server_types")}async getServerType(e){return(await this.listServerTypes(e)).find((t)=>t.name===e)??null}async createServer(e){let t=await this.request("POST","/servers",{name:e.name,server_type:e.serverType,image:e.image,location:e.location,datacenter:e.datacenter,ssh_keys:e.sshKeys,user_data:e.userData,labels:e.labels,firewalls:e.firewalls,networks:e.networks,start_after_create:!0});return{server:t.server,action:t.action}}async listNetworks(){return this.requestAll("/networks","networks")}async createNetwork(e){let t=e.ipRange??"10.0.0.0/16";return(await this.request("POST","/networks",{name:e.name,ip_range:t,subnets:[{type:"cloud",ip_range:t,network_zone:"eu-central"}],labels:e.labels})).network}async deleteNetwork(e){await this.request("DELETE",`/networks/${e}`)}async listLoadBalancers(){return this.requestAll("/load_balancers","load_balancers")}async createLoadBalancer(e){return(await this.request("POST","/load_balancers",{name:e.name,load_balancer_type:e.type??"lb11",location:e.location,network_zone:e.network?void 0:e.networkZone??"eu-central",network:e.network,labels:e.labels,targets:[{type:"label_selector",label_selector:{selector:e.labelSelector},use_private_ip:!!e.network}],services:e.services.map((r)=>({protocol:r.protocol??"tcp",listen_port:r.listenPort,destination_port:r.destinationPort,health_check:{protocol:"http",port:80,interval:15,timeout:10,retries:3,http:{path:"/",status_codes:["2??","3??"]}}}))})).load_balancer}async deleteLoadBalancer(e){await this.request("DELETE",`/load_balancers/${e}`)}async deleteServer(e){return(await this.request("DELETE",`/servers/${e}`)).action}async listFirewalls(){return this.requestAll("/firewalls","firewalls")}async createFirewall(e){let t=await this.request("POST","/firewalls",{name:e.name,rules:e.rules,labels:e.labels,apply_to:e.applyTo});return{firewall:t.firewall,actions:t.actions}}async setFirewallRules(e,t){return(await this.request("POST",`/firewalls/${e}/actions/set_rules`,{rules:t})).actions??[]}async deleteFirewall(e){await this.request("DELETE",`/firewalls/${e}`)}async applyFirewallToResources(e,t){return(await this.request("POST",`/firewalls/${e}/actions/apply_to_resources`,{apply_to:t})).actions}async listSshKeys(){return this.requestAll("/ssh_keys","ssh_keys")}async createSshKey(e){return(await this.request("POST","/ssh_keys",{name:e.name,public_key:e.publicKey,labels:e.labels})).ssh_key}async deleteSshKey(e){await this.request("DELETE",`/ssh_keys/${e}`)}async getAction(e){return(await this.request("GET",`/actions/${e}`)).action}async shutdownServer(e){return(await this.request("POST",`/servers/${e}/actions/shutdown`,{})).action}async powerOnServer(e){return(await this.request("POST",`/servers/${e}/actions/poweron`,{})).action}async changeServerType(e,t,r){return(await this.request("POST",`/servers/${e}/actions/change_type`,{server_type:t,upgrade_disk:r})).action}async powerOffServer(e){return(await this.request("POST",`/servers/${e}/actions/poweroff`,{})).action}async stopServer(e,t){if((await this.getServer(e)).status==="off")return;await this.shutdownServer(e);let n=t?.gracefulWaitMs??120000,s=t?.pollIntervalMs??3000,o=Date.now();while(Date.now()-o<n){if((await this.getServer(e)).status==="off")return;await new Promise((a)=>setTimeout(a,s))}let i=await this.powerOffServer(e);await this.waitForAction(i.id),await this.waitForServerStatus(e,"off")}async renameServer(e,t){return(await this.request("PUT",`/servers/${e}`,{name:t})).server}async listImages(e){let t=e?.type?`?type=${encodeURIComponent(e.type)}`:"";return this.requestAll(`/images${t}`,"images")}async getImage(e){return(await this.request("GET",`/images/${e}`)).image}async createImage(e,t){return this.request("POST",`/servers/${e}/actions/create_image`,{description:t.description,type:t.type??"snapshot",labels:t.labels})}async deleteImage(e){await this.request("DELETE",`/images/${e}`)}async rebuildServer(e,t){return(await this.request("POST",`/servers/${e}/actions/rebuild`,{image:t})).action}async listPrimaryIps(){return this.requestAll("/primary_ips","primary_ips")}async unassignPrimaryIp(e){return(await this.request("POST",`/primary_ips/${e}/actions/unassign`,{})).action}async assignPrimaryIp(e,t){return(await this.request("POST",`/primary_ips/${e}/actions/assign`,{assignee_id:t,assignee_type:"server"})).action}async waitForAction(e,t){let r=t?.pollIntervalMs??2000,n=t?.maxWaitMs??300000,s=Date.now();while(Date.now()-s<n){let o=await this.getAction(e);if(o.status==="success")return o;if(o.status==="error")throw new Xt(o.error?.message||"Hetzner action failed",o);await new Promise((i)=>setTimeout(i,r))}throw Error(`Timed out waiting for Hetzner action ${e}`)}async waitForServerRunning(e,t){let r=t?.pollIntervalMs??3000,n=t?.maxWaitMs??600000,s=Date.now();while(Date.now()-s<n){let o=await this.getServer(e);if(o.status==="running")return o;await new Promise((i)=>setTimeout(i,r))}throw Error(`Timed out waiting for server ${e} to reach running state`)}async waitForServerStatus(e,t,r){let n=r?.pollIntervalMs??3000,s=r?.maxWaitMs??600000,o=Date.now();while(Date.now()-o<s){let i=await this.getServer(e);if(i.status===t)return i;await new Promise((a)=>setTimeout(a,n))}throw Error(`Timed out waiting for server ${e} to reach ${t} state`)}}function pr(e,t){let r=vt(e,t);if(!r)throw Error("Hetzner API token required. Set hetzner.apiToken in cloud.config.ts or HCLOUD_TOKEN / HETZNER_API_TOKEN.");return r}function wt(e){let[t,r]=e.trim().split(/\s+/);return r?`${t} ${r}`:t}function Ks(e){if(!e)return"";return e.endsWith(`
279
279
  `)?e:`${e}
280
280
  `}function be(e,t={}){let r=t.scriptPath??"/var/lib/cloud/ts-cloud-bootstrap.sh",n=t.permissions??"0755",s=e.split(`
@@ -393,16 +393,16 @@ case "$root_fs" in
393
393
  xfs) xfs_growfs / ;;
394
394
  *) echo "Unsupported root filesystem: $root_fs" >&2; exit 1 ;;
395
395
  esac`,e)}async function Tc(e,t){let r=Buffer.from(t.join(`
396
- `)).toString("base64");await _e(e.host,`printf %s ${r} | base64 -d | while read -r unit; do [ -z "$unit" ] || systemctl is-active --quiet "$unit" || systemctl start "$unit"; done`,e)}async function gi(e,t,r,n={recovered:!1}){if(await Zr(e.host,{...e,timeoutMs:e.sshTimeoutMs??600000}),!n.recovered)await $c(e);if(r)await Tc(e,r.runningServices);let s=await nn(e),o=[],i=r?ot(r.runningServices,s.runningServices):[],a=r?ot(r.releaseLinks,s.releaseLinks):[],c=r?ot(r.routeFragments,s.routeFragments):[],l=r?ot(r.routeIds,s.routeIds):[],u=r?.persistentData.map((R)=>R.split("=")[0])??[],d=s.persistentData.map((R)=>R.split("=")[0]),m=ot(u,d),h=r?ot(r.dataCatalog,s.dataCatalog):[],f=s.routeProbes.filter((R)=>!R.ok),S=n.recovered&&r?r.cpuCores:t.cores??0,k=n.recovered&&r?r.memoryBytes:_c(t),E=s.cpuCores>=S,O=s.memoryBytes>=k*0.9,D=n.recovered||s.rootDiskBytes>=(t.disk??0)*1e9*0.95;if(s.failedUnits.length>0)o.push(`Failed services: ${s.failedUnits.join(", ")}`);if(i.length>0)o.push(`Services did not return: ${i.join(", ")}`);if(a.length>0)o.push(`Release links changed: ${a.join(", ")}`);if(c.length>0)o.push(`Route manifests changed: ${c.join(", ")}`);if(l.length>0)o.push(`Routes disappeared: ${l.join(", ")}`);if(m.length>0)o.push(`Persistent data paths disappeared: ${m.join(", ")}`);if(h.length>0)o.push(`Databases or volumes disappeared: ${h.join(", ")}`);if(f.length>0)o.push(`Unhealthy routes: ${f.map((R)=>R.domain).join(", ")}`);if(!E)o.push(`Expected at least ${S} CPU cores, found ${s.cpuCores}`);if(!O)o.push(`Expected at least ${k} bytes of RAM`);if(!D)o.push(`Expected approximately ${t.disk??0} GB root disk`);return{ok:o.length===0,checks:{cpuCores:s.cpuCores,memoryBytes:s.memoryBytes,rootDiskBytes:s.rootDiskBytes,rootFilesystemBytes:s.rootFilesystemBytes,runningServices:s.runningServices.length,releaseLinks:s.releaseLinks.length,routeFragments:s.routeFragments.length,routes:s.routeIds.length,healthyRoutes:s.routeProbes.filter((R)=>R.ok).length,persistentDataPaths:s.persistentData.length,databasesAndVolumes:s.dataCatalog.length,failedUnits:s.failedUnits.length},failures:o}}import{mkdir as Cc,readFile as Pc,rename as xc,writeFile as Rc}from"node:fs/promises";import{join as Ws}from"node:path";var mn="storage/cloud/state";function Oe(e=process.cwd()){return ca()?A(e,"state"):Ws(e,mn)}function it(e,t=process.cwd()){return Ws(Oe(t),`${e}.json`)}async function Fe(e,t=process.cwd()){try{let r=await Pc(it(e,t),"utf8");return JSON.parse(r)}catch{return null}}async function at(e,t,r=process.cwd()){let n=it(e,r);await Cc(Oe(r),{recursive:!0});let s=`${n}.${process.pid}.tmp`;await Rc(s,`${JSON.stringify(t,null,2)}
396
+ `)).toString("base64");await _e(e.host,`printf %s ${r} | base64 -d | while read -r unit; do [ -z "$unit" ] || systemctl is-active --quiet "$unit" || systemctl start "$unit"; done`,e)}async function gi(e,t,r,n={recovered:!1}){if(await Zr(e.host,{...e,timeoutMs:e.sshTimeoutMs??600000}),!n.recovered)await $c(e);if(r)await Tc(e,r.runningServices);let s=await nn(e),o=[],i=r?ot(r.runningServices,s.runningServices):[],a=r?ot(r.releaseLinks,s.releaseLinks):[],c=r?ot(r.routeFragments,s.routeFragments):[],l=r?ot(r.routeIds,s.routeIds):[],u=r?.persistentData.map((E)=>E.split("=")[0])??[],d=s.persistentData.map((E)=>E.split("=")[0]),m=ot(u,d),h=r?ot(r.dataCatalog,s.dataCatalog):[],f=s.routeProbes.filter((E)=>!E.ok),S=n.recovered&&r?r.cpuCores:t.cores??0,k=n.recovered&&r?r.memoryBytes:_c(t),O=s.cpuCores>=S,D=s.memoryBytes>=k*0.9,I=n.recovered||s.rootDiskBytes>=(t.disk??0)*1e9*0.95;if(s.failedUnits.length>0)o.push(`Failed services: ${s.failedUnits.join(", ")}`);if(i.length>0)o.push(`Services did not return: ${i.join(", ")}`);if(a.length>0)o.push(`Release links changed: ${a.join(", ")}`);if(c.length>0)o.push(`Route manifests changed: ${c.join(", ")}`);if(l.length>0)o.push(`Routes disappeared: ${l.join(", ")}`);if(m.length>0)o.push(`Persistent data paths disappeared: ${m.join(", ")}`);if(h.length>0)o.push(`Databases or volumes disappeared: ${h.join(", ")}`);if(f.length>0)o.push(`Unhealthy routes: ${f.map((E)=>E.domain).join(", ")}`);if(!O)o.push(`Expected at least ${S} CPU cores, found ${s.cpuCores}`);if(!D)o.push(`Expected at least ${k} bytes of RAM`);if(!I)o.push(`Expected approximately ${t.disk??0} GB root disk`);return{ok:o.length===0,checks:{cpuCores:s.cpuCores,memoryBytes:s.memoryBytes,rootDiskBytes:s.rootDiskBytes,rootFilesystemBytes:s.rootFilesystemBytes,runningServices:s.runningServices.length,releaseLinks:s.releaseLinks.length,routeFragments:s.routeFragments.length,routes:s.routeIds.length,healthyRoutes:s.routeProbes.filter((E)=>E.ok).length,persistentDataPaths:s.persistentData.length,databasesAndVolumes:s.dataCatalog.length,failedUnits:s.failedUnits.length},failures:o}}import{mkdir as Cc,readFile as Pc,rename as xc,writeFile as Rc}from"node:fs/promises";import{join as Ws}from"node:path";var mn="storage/cloud/state";function Oe(e=process.cwd()){return ca()?R(e,"state"):Ws(e,mn)}function it(e,t=process.cwd()){return Ws(Oe(t),`${e}.json`)}async function Fe(e,t=process.cwd()){try{let r=await Pc(it(e,t),"utf8");return JSON.parse(r)}catch{return null}}async function at(e,t,r=process.cwd()){let n=it(e,r);await Cc(Oe(r),{recursive:!0});let s=`${n}.${process.pid}.tmp`;await Rc(s,`${JSON.stringify(t,null,2)}
397
397
  `,"utf8"),await xc(s,n)}async function ge(e){return Fe(e)}async function mt(e,t){await at(e,t)}async function fn(e,t,r){let n=r.length?await e.listVolumes():[];return r.map((s)=>{let o=n.filter((l)=>l.name===s.name);if(o.length>1)throw Error(`Ambiguous volume name: ${s.name}`);let i=o[0];if(i&&i.server!==null&&i.server!==t.id)throw Error(`Volume ${i.name} belongs to another server; refusing to detach live storage`);let a=t.location?.name??t.datacenter?.location.name;if(i&&i.location.name!==a)throw Error(`Volume ${i.name} is in ${i.location.name}, server is in ${a}`);if(i&&i.size>s.size)throw Error(`Refusing to shrink volume ${i.name}: ${i.size} GB to ${s.size} GB`);let c=[];if(!i)c.push("create");else{if(i.server===null)c.push("attach");if(i.size<s.size)c.push("grow")}if(!i||i.protection.delete!==(s.deleteProtection!==!1))c.push("protect");return c.push("mount"),{declaration:s,existing:i,actions:c}})}async function gn(e,t,r){let n=[];for(let s of r){let o=s.existing,i=!o;if(!o){let a=await e.createVolume({name:s.declaration.name,size:s.declaration.size,server:t.id,labels:{...t.labels,"ts-cloud/volume":s.declaration.key}});await e.waitForAction(a.action.id);for(let c of a.next_actions??[])await e.waitForAction(c.id);o=await e.getVolume(a.volume.id)}if(o.server===null)await e.waitForAction((await e.attachVolume(o.id,t.id)).id),o=await e.getVolume(o.id);if(o.server!==t.id||o.location.name!==(t.location?.name??t.datacenter?.location.name))throw Error(`Volume attachment verification failed: ${o.name}`);if(o.linux_device!==`/dev/disk/by-id/scsi-0HC_Volume_${o.id}`)throw Error(`Unexpected Hetzner volume device: ${o.name}`);if(o.size<s.declaration.size)await e.waitForAction((await e.resizeVolume(o.id,s.declaration.size)).id);if(o.protection.delete!==(s.declaration.deleteProtection!==!1))await e.waitForAction((await e.protectVolume(o.id,s.declaration.deleteProtection!==!1)).id);n.push({...s.declaration,id:o.id,device:o.linux_device,allowFormat:i})}return n}var Sn=268435456;function _t(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function Lc(e){let t=Oc("sha256");for await(let r of Dc(e))t.update(r);return t.digest("hex")}class De{name="hetzner";usesCloudFormation=!1;client;sshPrivateKeyPath;sshPublicKeyPath;sshUser;location;stateOnly;waitForBoot;bootWait;async applyComputeChanges(e){let{config:t,environment:r}=e;if(t.cloud?.attachTo)throw Error("Only the compute owner may reconcile server size and volumes");let n=t.infrastructure?.compute;if(n?.resize&&!n.size)throw Error("compute.resize requires an explicit compute.size");let s=Ar(t,r),o=Yr(n??{});if(o.appServers>1||o.dedicatedServices)throw Error("Managed compute volumes currently require a single app server");let i=await this.getComputeOutputs(e);if(!i.appInstanceId)throw Error("No existing compute server found; provision the server first");let a=await this.client.getServer(Number(i.appInstanceId)),c=await fn(this.client,a,s),l=n?.resize&&n.size?await mr(this.client,a.id,Xe(n.size),n.resize.upgradeDisk!==!1):void 0,u={serverId:String(a.id),changes:c.flatMap((f)=>f.actions.map((S)=>({resource:f.declaration.name,action:S,detail:`${f.declaration.size} GB at ${f.declaration.mountPath}`})))};if(n?.deploymentStorage)u.changes.push({resource:n.deploymentStorage.volume,action:"place-deployments",detail:`Reconcile release directories${n.deploymentStorage.includeBackups!==!1?" and deployment backups":""} on the volume; ${n.deploymentStorage.migrateExisting?"verify and migrate existing files":"refuse nonempty directories"}`});if(l&&!l.alreadyComplete)if(!l.capacityAvailable){if(n?.resize?.whenUnavailable!=="keep-current")throw Error(`${l.targetType.name} is unavailable in ${l.location}`);u.waitingForCapacity=`${l.targetType.name} unavailable in ${l.location}; keeping ${a.server_type.name} running`}else u.changes.push({resource:a.name,action:"resize",detail:`${a.server_type.name} to ${l.targetType.name}`});if(e.dryRun)return u;if(u.waitingForCapacity)console.warn(`[ts-cloud] ${u.waitingForCapacity}`);let d=await gn(this.client,a,c),m=[{id:String(a.id),name:a.name,publicIp:a.public_net.ipv4?.ip}],h=[...He(t.notifications),...n?.volumes||n?.deploymentStorage?Lr({volumes:d,deploymentStorage:n?.deploymentStorage,webRoot:"/var/www"}):[],...n?.monitoring!==!1?we(n?.monitoring):[]];if(h.length){let f=await this.runRemoteDeploy({targets:m,commands:h,timeoutSeconds:7200,comment:"ts-cloud apply configured compute storage"});if(!f.success)throw Error(f.error||f.perInstance.map((S)=>S.error||S.output).join(`
398
- `))}if(l?.capacityAvailable&&!l.alreadyComplete){let f={host:m[0].publicIp,user:this.sshUser,identityFile:this.sshPrivateKeyPath},S=await pi({client:this.client,serverId:a.id,targetType:l.targetType.name,upgradeDisk:l.upgradeDisk,hooks:{preflight:()=>mi(f),afterBoot:(k,E,O,D)=>gi(f,E,O,D)}});if(S.status!=="completed"&&S.status!=="already-complete")throw Error(`Resize did not complete: ${S.status}`)}return u}constructor(e={}){let t=vt(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 Je({apiToken:t??""});let r=ur(void 0,{sshPrivateKeyPath:e.sshPrivateKeyPath,sshPublicKeyPath:e.sshPublicKeyPath,sshUser:e.sshUser,location:e.location});this.sshPrivateKeyPath=r.sshPrivateKeyPath,this.sshPublicKeyPath=r.sshPublicKeyPath,this.sshUser=r.sshUser,this.location=r.location,this.waitForBoot=e.waitForBoot??!0,this.bootWait={sshIntervalMs:e.bootWait?.sshIntervalMs??5000,sshTimeoutMs:e.bootWait?.sshTimeoutMs??300000,cloudInitIntervalMs:e.bootWait?.cloudInitIntervalMs??5000,cloudInitTimeoutMs:e.bootWait?.cloudInitTimeoutMs??600000}}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e,n=t.project.slug,s=t.infrastructure?.compute;if(!s)throw Error("infrastructure.compute is required to provision Hetzner compute");if(t.cloud?.attachTo)return this.attachToComputeInfrastructure(t.cloud.attachTo,t,r);let o=T(t,r),i=`${n}-${r}-app`,a=s.runtime==="php"||!!s.php,c=Yr(s);if(c.dedicatedServices||c.appServers>1)return a?this.provisionFleet(e,c):this.provisionBunFleet(e,c);let l=re(n,r,"app"),u=t.sites||{},d=Z(s)?[]:this.collectUpstreamPorts(u),m=`${n}-${r}-app-fw`,{firewall:h}=await this.ensureFirewall(m,l,rn({allowSsh:s.allowSsh!==!1,sitePorts:d,allowedPorts:[...s.firewall?.allowedPorts??[],...Ss(t.infrastructure?.sftp),...Fr(ne(t,{environment:r}))]})),f=await this.ensureSshKey(n,r,l),S=await ge(o);if(S?.serverId){let q=await this.tryGetServer(S.serverId);if(q&&q.status!=="off"){if(s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(S,q)}}let k=await this.findExistingServer(n,r,i);if(k&&k.status!=="off"){let q={provider:"hetzner",stackName:o,serverId:k.id,serverName:k.name,publicIp:k.public_net.ipv4?.ip,publicIpv6:me(k.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};if(await mt(o,q),s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(q,k)}let E=le(t,{environment:r}),O=E?.engine==="rpx"?ve({proxy:E,config:Te(u,{proxy:E,slug:t.project.slug,mail:ne(t,{environment:r})}),slug:t.project.slug,bunBin:s.runtime==="node"||s.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,D=Ue(t,{environment:r}),R=s.bakedImage===!0,z=de({runtime:D.runtime,runtimeVersion:D.runtimeVersion,systemPackages:s.systemPackages,database:t.infrastructure?.database,phpProvision:D.phpProvision,servicesProvision:D.servicesProvision,rpxProvision:O,baked:R,swapGb:s.swapGb}),x=be(z),H=Xe(s.size),V=bt(t),{server:se,action:ce}=await this.client.createServer({name:i,serverType:H,image:V,location:t.hetzner?.location||this.location,userData:x,labels:l,sshKeys:f?[f]:void 0,firewalls:[{firewall:h.id}]});await this.client.waitForAction(ce.id);let G=await this.client.waitForServerRunning(se.id),oe={provider:"hetzner",stackName:o,serverId:G.id,serverName:G.name,firewallId:h.id,publicIp:G.public_net.ipv4?.ip,publicIpv6:me(G.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};await mt(o,oe);let Y=G.public_net.ipv4?.ip;if(Y&&this.waitForBoot)await this.waitForSshReady(Y),await this.waitForCloudInit(Y);if(s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(oe,G)}async provisionFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,o=r.infrastructure.compute,i=T(r,n),a=Xe(o.size),c=bt(r),l=r.hetzner?.location||this.location,u=o.bakedImage===!0,d=await ge(i);if(d?.loadBalancerId){let F=(await this.client.listLoadBalancers().catch(()=>[])).find((N)=>N.id===d.loadBalancerId);if(F)return{appPublicIp:F.public_net?.ipv4?.ip,loadBalancerIp:F.public_net?.ipv4?.ip,servicesPrivateIp:d.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}let m=await this.ensureSshKey(s,n,re(s,n,"app")),h=`${s}-${n}-net`,S=(await this.client.listNetworks().catch(()=>[])).find((C)=>C.name===h)??await this.client.createNetwork({name:h,labels:re(s,n,"app")}),{firewall:k}=await this.ensureFirewall(`${s}-${n}-app-fw`,re(s,n,"app"),rn({allowSsh:!0,sitePorts:[],allowedPorts:o.firewall?.allowedPorts})),{firewall:E}=await this.ensureFirewall(`${s}-${n}-services-fw`,re(s,n,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[S.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[S.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[S.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[S.ip_range]}]),O=Jr(r),D=be(de({runtime:"php",servicesProvision:O,baked:u,swapGb:o.swapGb})),R=await this.client.listServers().catch(()=>[]),z=[],x=R.find((C)=>fe(C.labels,s,n,"services"));if(!x){let{server:C,action:F}=await this.client.createServer({name:`${s}-${n}-services`,serverType:Xe(typeof o.servicesServer==="object"?o.servicesServer.size:o.size),image:c,location:l,userData:D,labels:re(s,n,"services"),sshKeys:m?[m]:void 0,firewalls:[{firewall:E.id}],networks:[S.id]});await this.client.waitForAction(F.id),x=await this.client.waitForServerRunning(C.id),z.push(C.id)}let H=x.id,V=x.private_net?.[0]?.ip??(await this.client.getServer(H)).private_net?.[0]?.ip,se=[...Pe(!0),...we(!0),...Ye(o.sshKeys),...He(r.notifications)],ce=Dt({versions:o.php?.versions,default:o.php?.default,extensions:o.php?.extensions,installNginx:!Z(o),optimizeForProduction:o.php?.optimizeForProduction,ini:o.php?.ini}),G=be(de({runtime:"php",phpProvision:ce,servicesProvision:se,baked:u,swapGb:o.swapGb})),oe=R.filter((C)=>fe(C.labels,s,n,"app")),Y=oe.map((C)=>C.id);if(oe.length>t.appServers)for(let C of oe.slice(t.appServers))await this.client.deleteServer(C.id).catch(()=>{}),Y.splice(Y.indexOf(C.id),1);for(let C=oe.length;C<t.appServers;C++){let{server:F,action:N}=await this.client.createServer({name:`${s}-${n}-app-${C+1}`,serverType:a,image:c,location:l,userData:G,labels:re(s,n,"app"),sshKeys:m?[m]:void 0,firewalls:[{firewall:k.id}],networks:[S.id]});await this.client.waitForAction(N.id),Y.push(F.id),z.push(F.id)}if(this.waitForBoot&&z.length>0)await Promise.all(z.map(async(C)=>{let N=(await this.client.waitForServerRunning(C)).public_net.ipv4?.ip;if(N)await this.waitForSshReady(N),await this.waitForCloudInit(N)}));let q=`${s}-${n}-lb`,ue,y;if(t.loadBalancer){let F=(await this.client.listLoadBalancers().catch(()=>[])).find((N)=>N.name===q)??await this.client.createLoadBalancer({name:q,location:l,network:S.id,labels:re(s,n,"lb"),labelSelector:`ts-cloud/project=${s},ts-cloud/environment=${n},ts-cloud/role=app`,services:[{listenPort:80,destinationPort:80},{listenPort:443,destinationPort:443}]});y=F.id,ue=F.public_net?.ipv4?.ip}let P=ue??(await this.client.getServer(Y[0]).catch(()=>{return}))?.public_net.ipv4?.ip,M={provider:"hetzner",stackName:i,networkId:S.id,loadBalancerId:y,servicesServerId:H,servicesPrivateIp:V,publicIp:P,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await mt(i,M),{appPublicIp:P,loadBalancerIp:ue,servicesPrivateIp:V,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async provisionBunFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,o=r.infrastructure.compute,i=T(r,n),a=Xe(o.size),c=bt(r),l=r.hetzner?.location||this.location,u=o.bakedImage===!0,d=r.sites||{},m=await ge(i);if(m?.lbServerId){let N=await this.tryGetServer(m.lbServerId);if(N&&N.status!=="off"){let K=o.proxy?.engine==="rpx"?o.proxy:{engine:"rpx"},j=await this.findComputeTargets({slug:s,environment:n,role:"app",stackName:i});return this.refreshLbRoutes(N,d,j.map((W)=>({privateIp:W.privateIp,publicIp:W.publicIp})),K,s),{appPublicIp:N.public_net.ipv4?.ip??m.publicIp,loadBalancerIp:N.public_net.ipv4?.ip??m.publicIp,servicesPrivateIp:m.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}}let h=await this.ensureSshKey(s,n,re(s,n,"app")),f=`${s}-${n}-net`,k=(await this.client.listNetworks().catch(()=>[])).find((N)=>N.name===f)??await this.client.createNetwork({name:f,labels:re(s,n,"app")}),E=this.collectUpstreamPorts(d),{firewall:O}=await this.ensureFirewall(`${s}-${n}-app-fw`,re(s,n,"app"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},...E.map((N)=>({direction:"in",protocol:"tcp",port:String(N),source_ips:[k.ip_range],description:`ts-cloud port ${N} (private, LB-only)`}))]),{firewall:D}=await this.ensureFirewall(`${s}-${n}-lb-fw`,re(s,n,"lb"),rn({allowSsh:!0,sitePorts:[],allowedPorts:o.firewall?.allowedPorts})),R=await this.client.listServers().catch(()=>[]),z=[],x,H,V=!!o.servicesServer||!!o.managedServices,se=t.dedicatedServices&&V;if(se){let{firewall:N}=await this.ensureFirewall(`${s}-${n}-services-fw`,re(s,n,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[k.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[k.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[k.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[k.ip_range]}]),K=Jr(r),j=be(de({runtime:"bun",servicesProvision:K,baked:u,swapGb:o.swapGb})),W=R.find((b)=>fe(b.labels,s,n,"services"));if(!W){let{server:b,action:L}=await this.client.createServer({name:`${s}-${n}-services`,serverType:Xe(typeof o.servicesServer==="object"?o.servicesServer.size:o.size),image:c,location:l,userData:j,labels:re(s,n,"services"),sshKeys:h?[h]:void 0,firewalls:[{firewall:N.id}],networks:[k.id]});await this.client.waitForAction(L.id),W=await this.client.waitForServerRunning(b.id),z.push(b.id)}x=W.id,H=W.private_net?.[0]?.ip??(await this.client.getServer(x)).private_net?.[0]?.ip}let ce=se?{...o,managedServices:void 0,backups:void 0}:o,G=Ue({...r,infrastructure:{...r.infrastructure,compute:ce}},{environment:n}),oe=be(de({runtime:G.runtime,runtimeVersion:G.runtimeVersion,systemPackages:o.systemPackages,database:r.infrastructure?.database,servicesProvision:G.servicesProvision,baked:u,swapGb:o.swapGb})),Y=R.filter((N)=>fe(N.labels,s,n,"app")),q=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(()=>{}),q.splice(q.indexOf(N.id),1);for(let N=Y.length;N<t.appServers;N++){let{server:K,action:j}=await this.client.createServer({name:`${s}-${n}-app-${N+1}`,serverType:a,image:c,location:l,userData:oe,labels:re(s,n,"app"),sshKeys:h?[h]:void 0,firewalls:[{firewall:O.id}],networks:[k.id]});await this.client.waitForAction(j.id),q.push(K.id),z.push(K.id)}if(this.waitForBoot&&z.length>0)await Promise.all(z.map(async(N)=>{let j=(await this.client.waitForServerRunning(N)).public_net.ipv4?.ip;if(j)await this.waitForSshReady(j),await this.waitForCloudInit(j)}));let ue=[];for(let N of q){let K=R.find((j)=>j.id===N);if(!K||!K.private_net?.[0]?.ip)K=await this.client.getServer(N).catch(()=>K);ue.push({privateIp:K?.private_net?.[0]?.ip,publicIp:K?.public_net.ipv4?.ip})}let y=`${s}-${n}-lb`,P,M;if(t.loadBalancer){let N=R.find((j)=>fe(j.labels,s,n,"lb")),K=o.proxy?.engine==="rpx"?o.proxy:{engine:"rpx"};if(!N){let j=ve({proxy:K,config:qe(d,ue,{proxy:K,slug:s}),slug:s,bunBin:G.runtime==="node"||G.runtime==="deno"?void 0:"/usr/local/bin/bun"}),W=be(de({runtime:"bun",rpxProvision:j,baked:!1})),b=typeof o.loadBalancer==="object"?o.loadBalancer.size:void 0,{server:L,action:ee}=await this.client.createServer({name:y,serverType:Xe(b??"micro"),image:c,location:l,userData:W,labels:re(s,n,"lb"),sshKeys:h?[h]:void 0,firewalls:[{firewall:D.id}],networks:[k.id]});if(await this.client.waitForAction(ee.id),N=await this.client.waitForServerRunning(L.id),this.waitForBoot){let X=N.public_net.ipv4?.ip;if(X)await this.waitForSshReady(X),await this.waitForCloudInit(X)}}else this.refreshLbRoutes(N,d,ue,K,s);P=N.id,M=N.public_net.ipv4?.ip}let C=M??(await this.client.getServer(q[0]).catch(()=>{return}))?.public_net.ipv4?.ip,F={provider:"hetzner",stackName:i,networkId:k.id,lbServerId:P,appServerIds:q,servicesServerId:x,servicesPrivateIp:H,publicIp:C,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await mt(i,F),{appPublicIp:C,loadBalancerIp:M,servicesPrivateIp:H,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async destroyCompute(e){let{config:t,environment:r}=e,n=t.project.slug,s=T(t,r),o=await ge(s),i=[],a=`${n}-${r}-lb`,l=(await this.client.listLoadBalancers().catch(()=>[])).find((O)=>O.name===a);if(l)try{await this.client.deleteLoadBalancer(l.id),i.push(`load balancer ${a}`)}catch{}let u=await this.client.listServers().catch(()=>[]),d=new Set;for(let O of u)if(fe(O.labels,n,r,"app")||fe(O.labels,n,r,"services")||fe(O.labels,n,r,"lb"))d.add(O.id);if(o?.serverId)d.add(o.serverId);if(o?.servicesServerId)d.add(o.servicesServerId);if(o?.lbServerId)d.add(o.lbServerId);for(let O of o?.appServerIds??[])d.add(O);for(let O of d)try{await this.client.deleteServer(O),i.push(`server ${O}`)}catch{}let m=await this.client.listFirewalls().catch(()=>[]);for(let O of[`${n}-${r}-app-fw`,`${n}-${r}-services-fw`,`${n}-${r}-lb-fw`]){let D=m.find((R)=>R.name===O);if(!D)continue;for(let R=0;R<12;R++)try{await this.client.deleteFirewall(D.id),i.push(`firewall ${O}`);break}catch{await this.sleep(3000)}}let h=`${n}-${r}-net`,S=(await this.client.listNetworks().catch(()=>[])).find((O)=>O.name===h);if(S)for(let O=0;O<12;O++)try{await this.client.deleteNetwork(S.id),i.push(`network ${h}`);break}catch{await this.sleep(3000)}let E=(await this.client.listSshKeys().catch(()=>[])).filter((O)=>pn(O.labels,n,r));for(let O of E)try{await this.client.deleteSshKey(O.id),i.push(`ssh key ${O.name}`)}catch{}return await mt(s,{provider:"hetzner",stackName:s}).catch(()=>{}),{destroyed:i}}async getComputeOutputs(e){let t=T(e.config,e.environment),r=await ge(t);if(r?.serverId){let o=await this.tryGetServer(r.serverId);if(o)return this.outputsFromState(r,o)}if(r?.lbServerId){let i=(await this.tryGetServer(r.lbServerId))?.public_net.ipv4?.ip??r.publicIp;return{...this.outputsFromState(r),appPublicIp:i,loadBalancerIp:i}}if(r?.loadBalancerId||r?.servicesPrivateIp)return this.outputsFromState(r);let s=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:T(e.config,e.environment)}))[0];return{deployStoragePath:"/var/ts-cloud/staging",appInstanceId:s?.id,appPublicIp:s?.publicIp,sshUser:this.sshUser}}async uploadRelease(e){let t=e.targets?.length?e.targets:await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:T(e.config,e.environment)});if(t.length===0)throw Error("No Hetzner compute targets found for release upload");let s=`/var/ts-cloud/staging/${`${e.remoteKey.replace(/^releases\//,"").replace(/\.tar\.gz$/,"").replace(/\//g,"-")}-${qs()}.tar.gz`}`,o=await Lc(e.localPath),i=Ze,a=`${i}/${o}.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 ${_t(i)} /var/ts-cloud/staging`,`test -s ${_t(a)}`,`cp -- ${_t(a)} ${_t(s)}`].join(`
398
+ `))}if(l?.capacityAvailable&&!l.alreadyComplete){let f={host:m[0].publicIp,user:this.sshUser,identityFile:this.sshPrivateKeyPath},S=await pi({client:this.client,serverId:a.id,targetType:l.targetType.name,upgradeDisk:l.upgradeDisk,hooks:{preflight:()=>mi(f),afterBoot:(k,O,D,I)=>gi(f,O,D,I)}});if(S.status!=="completed"&&S.status!=="already-complete")throw Error(`Resize did not complete: ${S.status}`)}return u}constructor(e={}){let t=vt(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 Je({apiToken:t??""});let r=ur(void 0,{sshPrivateKeyPath:e.sshPrivateKeyPath,sshPublicKeyPath:e.sshPublicKeyPath,sshUser:e.sshUser,location:e.location});this.sshPrivateKeyPath=r.sshPrivateKeyPath,this.sshPublicKeyPath=r.sshPublicKeyPath,this.sshUser=r.sshUser,this.location=r.location,this.waitForBoot=e.waitForBoot??!0,this.bootWait={sshIntervalMs:e.bootWait?.sshIntervalMs??5000,sshTimeoutMs:e.bootWait?.sshTimeoutMs??300000,cloudInitIntervalMs:e.bootWait?.cloudInitIntervalMs??5000,cloudInitTimeoutMs:e.bootWait?.cloudInitTimeoutMs??600000}}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e,n=t.project.slug,s=t.infrastructure?.compute;if(!s)throw Error("infrastructure.compute is required to provision Hetzner compute");if(t.cloud?.attachTo)return this.attachToComputeInfrastructure(t.cloud.attachTo,t,r);let o=T(t,r),i=`${n}-${r}-app`,a=s.runtime==="php"||!!s.php,c=Yr(s);if(c.dedicatedServices||c.appServers>1)return a?this.provisionFleet(e,c):this.provisionBunFleet(e,c);let l=re(n,r,"app"),u=t.sites||{},d=Z(s)?[]:this.collectUpstreamPorts(u),m=`${n}-${r}-app-fw`,{firewall:h}=await this.ensureFirewall(m,l,rn({allowSsh:s.allowSsh!==!1,sitePorts:d,allowedPorts:[...s.firewall?.allowedPorts??[],...Ss(t.infrastructure?.sftp),...Fr(ne(t,{environment:r}))]})),f=await this.ensureSshKey(n,r,l),S=await ge(o);if(S?.serverId){let q=await this.tryGetServer(S.serverId);if(q&&q.status!=="off"){if(s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(S,q)}}let k=await this.findExistingServer(n,r,i);if(k&&k.status!=="off"){let q={provider:"hetzner",stackName:o,serverId:k.id,serverName:k.name,publicIp:k.public_net.ipv4?.ip,publicIpv6:me(k.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};if(await mt(o,q),s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(q,k)}let O=le(t,{environment:r}),D=O?.engine==="rpx"?ve({proxy:O,config:Te(u,{proxy:O,slug:t.project.slug,mail:ne(t,{environment:r})}),slug:t.project.slug,bunBin:s.runtime==="node"||s.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,I=Ue(t,{environment:r}),E=s.bakedImage===!0,z=de({runtime:I.runtime,runtimeVersion:I.runtimeVersion,systemPackages:s.systemPackages,database:t.infrastructure?.database,phpProvision:I.phpProvision,servicesProvision:I.servicesProvision,rpxProvision:D,baked:E,swapGb:s.swapGb}),x=be(z),H=Xe(s.size),V=bt(t),{server:se,action:ce}=await this.client.createServer({name:i,serverType:H,image:V,location:t.hetzner?.location||this.location,userData:x,labels:l,sshKeys:f?[f]:void 0,firewalls:[{firewall:h.id}]});await this.client.waitForAction(ce.id);let G=await this.client.waitForServerRunning(se.id),oe={provider:"hetzner",stackName:o,serverId:G.id,serverName:G.name,firewallId:h.id,publicIp:G.public_net.ipv4?.ip,publicIpv6:me(G.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};await mt(o,oe);let Y=G.public_net.ipv4?.ip;if(Y&&this.waitForBoot)await this.waitForSshReady(Y),await this.waitForCloudInit(Y);if(s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(oe,G)}async provisionFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,o=r.infrastructure.compute,i=T(r,n),a=Xe(o.size),c=bt(r),l=r.hetzner?.location||this.location,u=o.bakedImage===!0,d=await ge(i);if(d?.loadBalancerId){let F=(await this.client.listLoadBalancers().catch(()=>[])).find((N)=>N.id===d.loadBalancerId);if(F)return{appPublicIp:F.public_net?.ipv4?.ip,loadBalancerIp:F.public_net?.ipv4?.ip,servicesPrivateIp:d.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}let m=await this.ensureSshKey(s,n,re(s,n,"app")),h=`${s}-${n}-net`,S=(await this.client.listNetworks().catch(()=>[])).find((C)=>C.name===h)??await this.client.createNetwork({name:h,labels:re(s,n,"app")}),{firewall:k}=await this.ensureFirewall(`${s}-${n}-app-fw`,re(s,n,"app"),rn({allowSsh:!0,sitePorts:[],allowedPorts:o.firewall?.allowedPorts})),{firewall:O}=await this.ensureFirewall(`${s}-${n}-services-fw`,re(s,n,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[S.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[S.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[S.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[S.ip_range]}]),D=Jr(r),I=be(de({runtime:"php",servicesProvision:D,baked:u,swapGb:o.swapGb})),E=await this.client.listServers().catch(()=>[]),z=[],x=E.find((C)=>fe(C.labels,s,n,"services"));if(!x){let{server:C,action:F}=await this.client.createServer({name:`${s}-${n}-services`,serverType:Xe(typeof o.servicesServer==="object"?o.servicesServer.size:o.size),image:c,location:l,userData:I,labels:re(s,n,"services"),sshKeys:m?[m]:void 0,firewalls:[{firewall:O.id}],networks:[S.id]});await this.client.waitForAction(F.id),x=await this.client.waitForServerRunning(C.id),z.push(C.id)}let H=x.id,V=x.private_net?.[0]?.ip??(await this.client.getServer(H)).private_net?.[0]?.ip,se=[...Pe(!0),...we(!0),...Ye(o.sshKeys),...He(r.notifications)],ce=Dt({versions:o.php?.versions,default:o.php?.default,extensions:o.php?.extensions,installNginx:!Z(o),optimizeForProduction:o.php?.optimizeForProduction,ini:o.php?.ini}),G=be(de({runtime:"php",phpProvision:ce,servicesProvision:se,baked:u,swapGb:o.swapGb})),oe=E.filter((C)=>fe(C.labels,s,n,"app")),Y=oe.map((C)=>C.id);if(oe.length>t.appServers)for(let C of oe.slice(t.appServers))await this.client.deleteServer(C.id).catch(()=>{}),Y.splice(Y.indexOf(C.id),1);for(let C=oe.length;C<t.appServers;C++){let{server:F,action:N}=await this.client.createServer({name:`${s}-${n}-app-${C+1}`,serverType:a,image:c,location:l,userData:G,labels:re(s,n,"app"),sshKeys:m?[m]:void 0,firewalls:[{firewall:k.id}],networks:[S.id]});await this.client.waitForAction(N.id),Y.push(F.id),z.push(F.id)}if(this.waitForBoot&&z.length>0)await Promise.all(z.map(async(C)=>{let N=(await this.client.waitForServerRunning(C)).public_net.ipv4?.ip;if(N)await this.waitForSshReady(N),await this.waitForCloudInit(N)}));let q=`${s}-${n}-lb`,ue,y;if(t.loadBalancer){let F=(await this.client.listLoadBalancers().catch(()=>[])).find((N)=>N.name===q)??await this.client.createLoadBalancer({name:q,location:l,network:S.id,labels:re(s,n,"lb"),labelSelector:`ts-cloud/project=${s},ts-cloud/environment=${n},ts-cloud/role=app`,services:[{listenPort:80,destinationPort:80},{listenPort:443,destinationPort:443}]});y=F.id,ue=F.public_net?.ipv4?.ip}let P=ue??(await this.client.getServer(Y[0]).catch(()=>{return}))?.public_net.ipv4?.ip,M={provider:"hetzner",stackName:i,networkId:S.id,loadBalancerId:y,servicesServerId:H,servicesPrivateIp:V,publicIp:P,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await mt(i,M),{appPublicIp:P,loadBalancerIp:ue,servicesPrivateIp:V,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async provisionBunFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,o=r.infrastructure.compute,i=T(r,n),a=Xe(o.size),c=bt(r),l=r.hetzner?.location||this.location,u=o.bakedImage===!0,d=r.sites||{},m=await ge(i);if(m?.lbServerId){let N=await this.tryGetServer(m.lbServerId);if(N&&N.status!=="off"){let K=o.proxy?.engine==="rpx"?o.proxy:{engine:"rpx"},j=await this.findComputeTargets({slug:s,environment:n,role:"app",stackName:i});return this.refreshLbRoutes(N,d,j.map((W)=>({privateIp:W.privateIp,publicIp:W.publicIp})),K,s),{appPublicIp:N.public_net.ipv4?.ip??m.publicIp,loadBalancerIp:N.public_net.ipv4?.ip??m.publicIp,servicesPrivateIp:m.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}}let h=await this.ensureSshKey(s,n,re(s,n,"app")),f=`${s}-${n}-net`,k=(await this.client.listNetworks().catch(()=>[])).find((N)=>N.name===f)??await this.client.createNetwork({name:f,labels:re(s,n,"app")}),O=this.collectUpstreamPorts(d),{firewall:D}=await this.ensureFirewall(`${s}-${n}-app-fw`,re(s,n,"app"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},...O.map((N)=>({direction:"in",protocol:"tcp",port:String(N),source_ips:[k.ip_range],description:`ts-cloud port ${N} (private, LB-only)`}))]),{firewall:I}=await this.ensureFirewall(`${s}-${n}-lb-fw`,re(s,n,"lb"),rn({allowSsh:!0,sitePorts:[],allowedPorts:o.firewall?.allowedPorts})),E=await this.client.listServers().catch(()=>[]),z=[],x,H,V=!!o.servicesServer||!!o.managedServices,se=t.dedicatedServices&&V;if(se){let{firewall:N}=await this.ensureFirewall(`${s}-${n}-services-fw`,re(s,n,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[k.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[k.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[k.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[k.ip_range]}]),K=Jr(r),j=be(de({runtime:"bun",servicesProvision:K,baked:u,swapGb:o.swapGb})),W=E.find((b)=>fe(b.labels,s,n,"services"));if(!W){let{server:b,action:L}=await this.client.createServer({name:`${s}-${n}-services`,serverType:Xe(typeof o.servicesServer==="object"?o.servicesServer.size:o.size),image:c,location:l,userData:j,labels:re(s,n,"services"),sshKeys:h?[h]:void 0,firewalls:[{firewall:N.id}],networks:[k.id]});await this.client.waitForAction(L.id),W=await this.client.waitForServerRunning(b.id),z.push(b.id)}x=W.id,H=W.private_net?.[0]?.ip??(await this.client.getServer(x)).private_net?.[0]?.ip}let ce=se?{...o,managedServices:void 0,backups:void 0}:o,G=Ue({...r,infrastructure:{...r.infrastructure,compute:ce}},{environment:n}),oe=be(de({runtime:G.runtime,runtimeVersion:G.runtimeVersion,systemPackages:o.systemPackages,database:r.infrastructure?.database,servicesProvision:G.servicesProvision,baked:u,swapGb:o.swapGb})),Y=E.filter((N)=>fe(N.labels,s,n,"app")),q=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(()=>{}),q.splice(q.indexOf(N.id),1);for(let N=Y.length;N<t.appServers;N++){let{server:K,action:j}=await this.client.createServer({name:`${s}-${n}-app-${N+1}`,serverType:a,image:c,location:l,userData:oe,labels:re(s,n,"app"),sshKeys:h?[h]:void 0,firewalls:[{firewall:D.id}],networks:[k.id]});await this.client.waitForAction(j.id),q.push(K.id),z.push(K.id)}if(this.waitForBoot&&z.length>0)await Promise.all(z.map(async(N)=>{let j=(await this.client.waitForServerRunning(N)).public_net.ipv4?.ip;if(j)await this.waitForSshReady(j),await this.waitForCloudInit(j)}));let ue=[];for(let N of q){let K=E.find((j)=>j.id===N);if(!K||!K.private_net?.[0]?.ip)K=await this.client.getServer(N).catch(()=>K);ue.push({privateIp:K?.private_net?.[0]?.ip,publicIp:K?.public_net.ipv4?.ip})}let y=`${s}-${n}-lb`,P,M;if(t.loadBalancer){let N=E.find((j)=>fe(j.labels,s,n,"lb")),K=o.proxy?.engine==="rpx"?o.proxy:{engine:"rpx"};if(!N){let j=ve({proxy:K,config:qe(d,ue,{proxy:K,slug:s}),slug:s,bunBin:G.runtime==="node"||G.runtime==="deno"?void 0:"/usr/local/bin/bun"}),W=be(de({runtime:"bun",rpxProvision:j,baked:!1})),b=typeof o.loadBalancer==="object"?o.loadBalancer.size:void 0,{server:L,action:ee}=await this.client.createServer({name:y,serverType:Xe(b??"micro"),image:c,location:l,userData:W,labels:re(s,n,"lb"),sshKeys:h?[h]:void 0,firewalls:[{firewall:I.id}],networks:[k.id]});if(await this.client.waitForAction(ee.id),N=await this.client.waitForServerRunning(L.id),this.waitForBoot){let X=N.public_net.ipv4?.ip;if(X)await this.waitForSshReady(X),await this.waitForCloudInit(X)}}else this.refreshLbRoutes(N,d,ue,K,s);P=N.id,M=N.public_net.ipv4?.ip}let C=M??(await this.client.getServer(q[0]).catch(()=>{return}))?.public_net.ipv4?.ip,F={provider:"hetzner",stackName:i,networkId:k.id,lbServerId:P,appServerIds:q,servicesServerId:x,servicesPrivateIp:H,publicIp:C,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await mt(i,F),{appPublicIp:C,loadBalancerIp:M,servicesPrivateIp:H,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async destroyCompute(e){let{config:t,environment:r}=e,n=t.project.slug,s=T(t,r),o=await ge(s),i=[],a=`${n}-${r}-lb`,l=(await this.client.listLoadBalancers().catch(()=>[])).find((D)=>D.name===a);if(l)try{await this.client.deleteLoadBalancer(l.id),i.push(`load balancer ${a}`)}catch{}let u=await this.client.listServers().catch(()=>[]),d=new Set;for(let D of u)if(fe(D.labels,n,r,"app")||fe(D.labels,n,r,"services")||fe(D.labels,n,r,"lb"))d.add(D.id);if(o?.serverId)d.add(o.serverId);if(o?.servicesServerId)d.add(o.servicesServerId);if(o?.lbServerId)d.add(o.lbServerId);for(let D of o?.appServerIds??[])d.add(D);for(let D of d)try{await this.client.deleteServer(D),i.push(`server ${D}`)}catch{}let m=await this.client.listFirewalls().catch(()=>[]);for(let D of[`${n}-${r}-app-fw`,`${n}-${r}-services-fw`,`${n}-${r}-lb-fw`]){let I=m.find((E)=>E.name===D);if(!I)continue;for(let E=0;E<12;E++)try{await this.client.deleteFirewall(I.id),i.push(`firewall ${D}`);break}catch{await this.sleep(3000)}}let h=`${n}-${r}-net`,S=(await this.client.listNetworks().catch(()=>[])).find((D)=>D.name===h);if(S)for(let D=0;D<12;D++)try{await this.client.deleteNetwork(S.id),i.push(`network ${h}`);break}catch{await this.sleep(3000)}let O=(await this.client.listSshKeys().catch(()=>[])).filter((D)=>pn(D.labels,n,r));for(let D of O)try{await this.client.deleteSshKey(D.id),i.push(`ssh key ${D.name}`)}catch{}return await mt(s,{provider:"hetzner",stackName:s}).catch(()=>{}),{destroyed:i}}async getComputeOutputs(e){let t=T(e.config,e.environment),r=await ge(t);if(r?.serverId){let o=await this.tryGetServer(r.serverId);if(o)return this.outputsFromState(r,o)}if(r?.lbServerId){let i=(await this.tryGetServer(r.lbServerId))?.public_net.ipv4?.ip??r.publicIp;return{...this.outputsFromState(r),appPublicIp:i,loadBalancerIp:i}}if(r?.loadBalancerId||r?.servicesPrivateIp)return this.outputsFromState(r);let s=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:T(e.config,e.environment)}))[0];return{deployStoragePath:"/var/ts-cloud/staging",appInstanceId:s?.id,appPublicIp:s?.publicIp,sshUser:this.sshUser}}async uploadRelease(e){let t=e.targets?.length?e.targets:await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:T(e.config,e.environment)});if(t.length===0)throw Error("No Hetzner compute targets found for release upload");let s=`/var/ts-cloud/staging/${`${e.remoteKey.replace(/^releases\//,"").replace(/\.tar\.gz$/,"").replace(/\//g,"-")}-${qs()}.tar.gz`}`,o=await Lc(e.localPath),i=Ze,a=`${i}/${o}.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 ${_t(i)} /var/ts-cloud/staging`,`test -s ${_t(a)}`,`cp -- ${_t(a)} ${_t(s)}`].join(`
399
399
  `);try{this.sshExec(c.publicIp,l);continue}catch{}let u=`${i}/.${o}-${qs()}.tmp`;try{this.scpToHost(c.publicIp,e.localPath,u),this.sshExec(c.publicIp,jt(u,a,s))}catch(d){try{this.sshExec(c.publicIp,Wt(u))}catch{}throw d}}return{artifactRef:s}}async findComputeTargets(e){let t=e.role||"app",r=(o)=>({id:String(o.id),name:o.name,publicIp:o.public_net.ipv4?.ip,publicIpv6:me(o.public_net.ipv6?.ip),privateIp:o.private_net?.[0]?.ip,status:o.status});if(t==="app"||t==="lb"||t==="services"){let o=await ge(e.stackName??`${e.slug}-${e.environment}`),i=[...new Set(t==="app"?[o?.serverId,...o?.appServerIds??[]]:t==="lb"?[o?.lbServerId]:[o?.servicesServerId])].filter((l)=>typeof l==="number");if(this.stateOnly){if(i.length>0&&o?.publicIp)return i.map((l)=>({id:String(l),name:l===o.serverId?o.serverName:void 0,publicIp:o.publicIp,publicIpv6:o.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(i.length>0){let l=[];for(let u of i){let d=a.find((m)=>m.id===u)??await this.tryGetServer(u);if(u===o?.serverId&&o.serverName&&d?.name!==o.serverName)continue;if(d&&d.status!=="off")l.push(d)}if(l.length>0)return l.map(r)}let c=a.filter((l)=>fe(l.labels,e.slug,e.environment,t));if(c.length>0)return c.map(r);if(t==="app"){let l=a.filter((u)=>u.status!=="off"&&u.labels?.[`${te}/managed-by`]==="ts-cloud"&&u.labels?.[`${te}/environment`]===e.environment&&u.labels?.[`${te}/role`]==="app");if(l.length===1)return l.map(r)}return[]}if(this.stateOnly)throw Error(`Hetzner API token required to discover '${t}' compute targets.`);let s=(await this.client.listServers()).filter((o)=>fe(o.labels,e.slug,e.environment,t));if(s.length>0)return s.map(r);return[]}async attachToComputeInfrastructure(e,t,r){let n=await this.client.listServers(),s=(m)=>n.filter((h)=>h.status!=="off"&&fe(h.labels,e,r,m)),o=s("app");if(o.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 i=s("lb")[0],a=s("services")[0],c=o[0],l=i??c,u=T(t,r),d={provider:"hetzner",stackName:u,serverId:c.id,serverName:c.name,appServerIds:o.map((m)=>m.id),lbServerId:i?.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(u,d),this.outputsFromState(d)}async listReachableResources(){return(await this.client.listServers()).map((t)=>({name:t.name,labels:t.labels}))}async runRemoteDeploy(e){if(e.targets.length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets provided"};let t=e.commands.join(`
400
400
  `),r=[];for(let s of e.targets){if(!s.publicIp){r.push({instanceId:s.id,status:"Failed",error:"Missing public IP"});continue}try{let o=this.sshExec(s.publicIp,t);je(o),r.push({instanceId:s.id,status:"Success",output:o})}catch(o){r.push({instanceId:s.id,status:"Failed",error:o.message})}}let n=r.every((s)=>s.status==="Success");return{success:n,instanceCount:e.targets.length,perInstance:r,error:n?void 0:Ne(r,"One or more SSH deploy commands failed")}}async ensureSshKey(e,t,r){if(!Ic(this.sshPublicKeyPath))throw Error(`SSH public key not found at ${this.sshPublicKeyPath}. ts-cloud deploys to Hetzner over SSH and needs a public key to authorize on the server. Generate one (\`ssh-keygen -t ed25519\`) or set hetzner.sshPrivateKeyPath / HCLOUD_SSH_PUBLIC_KEY.`);let n=Ac(this.sshPublicKeyPath,"utf8").trim(),s=wt(n),i=(await this.client.listSshKeys()).find((c)=>wt(c.public_key)===s);if(i)return i.id;return(await this.client.createSshKey({name:`${e}-${t}-deploy`,publicKey:n,labels:r})).id}async tryGetServer(e){try{return await this.client.getServer(e)}catch{return null}}refreshLbRoutes(e,t,r,n,s){let o=e.public_net.ipv4?.ip;if(!o){console.warn(`[ts-cloud] LB server '${e.name}' has no public IP — skipping the rpx route refresh; its routes may be stale.`);return}let i=r.filter((c)=>c.privateIp||c.publicIp);if(i.length===0){console.warn(`[ts-cloud] No routable app boxes found for LB '${e.name}' — leaving its current rpx routes untouched.`);return}let a=qe(t,i,{proxy:n,slug:s});this.sshExec(o,Ke({config:a,slug:s}).join(`
401
401
  `))}async findExistingServer(e,t,r){let n=await this.client.listServers(),s=n.find((i)=>fe(i.labels,e,t,"app")||i.name===r);if(s)return s;let o=n.filter((i)=>i.status!=="off"&&i.labels?.[`${te}/managed-by`]==="ts-cloud"&&i.labels?.[`${te}/environment`]===t&&i.labels?.[`${te}/role`]==="app");if(o.length===1){let i=o[0],a=i.labels?.[`${te}/project`]??"unknown";return console.warn(`[ts-cloud] No server named '${r}' found; adopting existing ts-cloud app server '${i.name}' (project label '${a}') for project '${e}' — `+"updating it in place instead of provisioning a new server."),i}return}async ensureFirewall(e,t,r){let s=(await this.client.listFirewalls()).find((i)=>i.name===e);if(s)return await this.client.setFirewallRules(s.id,r),{firewall:s};let{firewall:o}=await this.client.createFirewall({name:e,labels:t,rules:r});return{firewall:o}}collectUpstreamPorts(e){let t=new Set;for(let r of Object.values(e))if(typeof r.port==="number")t.add(r.port);return[...t].filter((r)=>![80,443].includes(r))}async sleep(e){await new Promise((t)=>setTimeout(t,e))}async waitForSshReady(e){let{sshIntervalMs:t,sshTimeoutMs:r}=this.bootWait,n=Date.now(),s;while(Date.now()-n<r)try{Vs(`ssh ${this.sshBaseArgs(e,["-o","ConnectTimeout=5"]).map(_t).join(" ")} true`,{stdio:"pipe",maxBuffer:Sn});return}catch(o){s=o,await this.sleep(t)}throw Error(`Timed out waiting for SSH on ${e} after ${r}ms: ${s?.message??"unknown error"}`)}async waitForCloudInit(e){let{cloudInitIntervalMs:t,cloudInitTimeoutMs:r}=this.bootWait,n=Date.now();while(Date.now()-n<r){try{let s=this.sshExec(e,"if command -v cloud-init >/dev/null 2>&1; then cloud-init status --long 2>/dev/null || true; else echo 'status: done'; fi");if(/status:\s*error/.test(s))throw Error(`cloud-init reported an error on ${e}:
402
402
  ${s}`);if(/status:\s*(?:done|degraded)/.test(s))return}catch(s){if(s instanceof Error&&/cloud-init reported an error/.test(s.message))throw s}await this.sleep(t)}throw Error(`Timed out waiting for cloud-init to finish on ${e} after ${r}ms`)}outputsFromState(e,t){return{deployStoragePath:e.deployStoragePath||"/var/ts-cloud/staging",appInstanceId:e.serverId?String(e.serverId):void 0,appPublicIp:t?.public_net.ipv4?.ip||e.publicIp,appPublicIpv6:me(t?.public_net.ipv6?.ip)||e.publicIpv6,sshUser:e.sshUser||this.sshUser,servicesPrivateIp:e.servicesPrivateIp}}static SSH_HOST_KEY_OPTS=["-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR"];static SSH_KEEPALIVE_OPTS=["-o","ConnectTimeout=30","-o","ServerAliveInterval=15","-o","ServerAliveCountMax=4"];sshBaseArgs(e,t=[]){return["-i",this.sshPrivateKeyPath,...De.SSH_HOST_KEY_OPTS,...De.SSH_KEEPALIVE_OPTS,"-o","BatchMode=yes",...t,`${this.sshUser}@${e}`]}scpToHost(e,t,r){let n=["scp",...Gt,"-i",this.sshPrivateKeyPath,...De.SSH_HOST_KEY_OPTS,...De.SSH_KEEPALIVE_OPTS,"-o","BatchMode=yes",t,`${this.sshUser}@${e}:${r}`].map((o)=>`"${o.replace(/"/g,"\\\"")}"`).join(" "),s=3;for(let o=1;o<=3;o++)try{Vs(n,{stdio:"pipe",maxBuffer:Sn});return}catch(i){if(o===3)throw Error(ke(i))}}sshExec(e,t){try{return Ec("ssh",[...this.sshBaseArgs(e),cn],{encoding:"utf8",input:t,stdio:["pipe","pipe","pipe"],maxBuffer:Sn})}catch(r){throw Error(`${ke(r)}${ut(r,t)}`)}}}class Qt{name="ssh";usesCloudFormation=!1;async getComputeOutputs(){return{appPublicIp:"127.0.0.1",sshUser:"root"}}async uploadRelease(e){return{artifactRef:e.localPath}}async findComputeTargets(e){if((e.role||"app")!=="app")return[];return[{id:"localhost",name:"localhost",publicIp:"127.0.0.1",status:"running"}]}async runRemoteDeploy(e){let t=e.commands.join(`
403
403
  `);try{let r=Bun.spawn(["bash","-c",t],{stdout:"pipe",stderr:"pipe",env:process.env}),[n,s,o]=await Promise.all([new Response(r.stdout).text(),new Response(r.stderr).text(),r.exited]);return{success:o===0,instanceCount:1,perInstance:[{instanceId:"localhost",status:o===0?"Success":"Failed",output:n,error:s}]}}catch(r){return{success:!1,instanceCount:1,perInstance:[{instanceId:"localhost",status:"Failed",error:r?.message??String(r)}],error:r?.message??String(r)}}}}function vn(){let e=process.env.TS_CLOUD_DASHBOARD_BOX;return e!=null&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}import{createHash as Jc,randomUUID as Io}from"node:crypto";import{createReadStream as Qc}from"node:fs";import{isIP as Zc}from"node:net";import{createHash as kc}from"node:crypto";import{appendFile as Nc,mkdir as Hc,readFile as Uc}from"node:fs/promises";import{dirname as Mc}from"node:path";var Js=268435456,lo=async(e,t)=>{let r=Bun.spawn(e,{stdin:t===void 0?"ignore":Buffer.from(t),stdout:"pipe",stderr:"pipe"}),[n,s,o]=await Promise.all([r.exited,new Response(r.stdout).text(),new Response(r.stderr).text()]);return{code:n,signal:r.signalCode,stdout:s.slice(-Js),stderr:o.slice(-Js)}},uo=["-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR"],po=["-o","ConnectTimeout=30","-o","ServerAliveInterval=15","-o","ServerAliveCountMax=4"];function mo(e){if(e.hostKey==="insecure")return[...uo];return["-o",`StrictHostKeyChecking=${e.hostKey.policy==="pin"?"yes":"accept-new"}`,"-o",`UserKnownHostsFile=${e.hostKey.knownHostsFile}`,"-o","LogLevel=ERROR"]}function fo(e){let t=[...po];if(e.connectTimeoutSec!==void 0)t[1]=`ConnectTimeout=${e.connectTimeoutSec}`;return t}function bn(e,t,r=[]){return["-i",e.identityFile,"-p",String(e.port??22),...mo(e),...fo(e),"-o","BatchMode=yes",...r,`${e.user}@${t}`]}function go(e,t,r,n){return["-i",e.identityFile,"-P",String(e.port??22),...mo(e),...fo(e),"-o","BatchMode=yes",r,`${e.user}@${t}:${n}`]}function gr(e){return`SHA256:${kc("sha256").update(Buffer.from(e,"base64")).digest("base64").replace(/=+$/,"")}`}async function no(e,t=22,r=lo){let n=await r(["ssh-keyscan","-T","10","-p",String(t),"-t","ed25519",e]),s=n.stdout.split(`
404
404
  `).find((o)=>o&&!o.startsWith("#"))?.trim().split(/\s+/);if(n.code!==0||!s?.[1]||!s[2])throw Error(`SSH host-key scan failed: ${n.stderr.trim()||"no key returned"}`);return{algorithm:s[1],key:s[2]}}function wn(e,t=22){return t===22?e:`[${e}]:${t}`}function ho(e,t,r){return`${wn(e,t)} ${r.algorithm} ${r.key}`}function So(e,t,r=22){let n=wn(t,r);for(let s of e.split(`
405
- `)){let o=s.trim();if(!o||o.startsWith("#")||o.startsWith("@"))continue;let[i,a,c]=o.split(/\s+/);if(!i||!a||!c)continue;if(i.split(",").includes(n))return{algorithm:a,key:c}}return null}function _n(e=process.cwd()){return A(e,"ssh","known_hosts")}async function zc(e){try{return await Uc(e,"utf8")}catch{return""}}async function Fc(e,t){await Hc(Mc(e),{recursive:!0}),await Nc(e,`${t}
405
+ `)){let o=s.trim();if(!o||o.startsWith("#")||o.startsWith("@"))continue;let[i,a,c]=o.split(/\s+/);if(!i||!a||!c)continue;if(i.split(",").includes(n))return{algorithm:a,key:c}}return null}function _n(e=process.cwd()){return R(e,"ssh","known_hosts")}async function zc(e){try{return await Uc(e,"utf8")}catch{return""}}async function Fc(e,t){await Hc(Mc(e),{recursive:!0}),await Nc(e,`${t}
406
406
  `,{mode:384})}class Zt{options;run;scan;readKnownHosts;appendKnownHosts;constructor(e,t={}){this.options=e;this.run=t.run??lo,this.scan=t.scan??no,this.readKnownHosts=t.readKnownHosts??zc,this.appendKnownHosts=t.appendKnownHosts??Fc}runnerFor(e={}){if(e.sudo!==void 0)return yt({sudo:e.sudo});return this.options.runner??yt()}async exec(e,t,r={}){let n=await this.run(["ssh",...bn(this.options,e),this.runnerFor(r)],t);if(n.code!==0){let s={status:n.code,signal:n.signal,stdout:n.stdout,stderr:n.stderr};throw Error(`${ke(s)}${ut(s,t)}`)}return n.stdout}async scp(e,t,r){let n=["scp",...Gt,...go(this.options,e,t,r)],s=3;for(let o=1;o<=3;o++){let i=await this.run(n);if(i.code===0)return;if(o===3)throw Error(ke({status:i.code,signal:i.signal,stdout:i.stdout,stderr:i.stderr}))}}async probe(e){return(await this.run(["ssh",...bn(this.options,e,["-o","ConnectTimeout=5"]),"true"])).code===0}async ensureHostKey(e){let t=this.options.port??22;if(this.options.hostKey==="insecure")try{return{fingerprint:gr((await this.scan(e,t,this.run)).key),pinnedNow:!1}}catch{return{fingerprint:"",pinnedNow:!1}}let{policy:r,knownHostsFile:n}=this.options.hostKey,s=So(await this.readKnownHosts(n),e,t);if(s)return{fingerprint:gr(s.key),pinnedNow:!1};let o=await this.scan(e,t,this.run);if(r==="pin")return await this.appendKnownHosts(n,ho(e,t,o)),{fingerprint:gr(o.key),pinnedNow:!0};return{fingerprint:gr(o.key),pinnedNow:!1}}}import{isIP as Bc}from"node:net";var Ie=1,$n="/var/lib/ts-cloud";function vo(e=Ie){return`${$n}/bootstrap.v${e}`}var bo=1;function Kc(e){return e==="aarch64"||e==="arm64"}function yo(e){let t=e.lanIp?.trim()||e.facts?.lanIp?.trim();return t&&Bc(t)!==0?t:void 0}function er(e,t,r){if(!ki(e.infrastructure?.compute?.managedServices?.vitess))return;if(t==="raspberry-pi"||Kc(r))throw Error(`managedServices.vitess is enabled, but Vitess publishes only x86_64 release tarballs and this host is ${r??"a Raspberry Pi (arm64)"}. Drop managedServices.vitess or deploy it to an x86_64 host.`)}function Be(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function jc(){return`
407
407
  # A Pi 5 has no battery-backed RTC and boots in 1970 until NTP answers. apt
408
408
  # rejects Release files "from the future" and ACME rejects a skewed clock, so
@@ -434,27 +434,27 @@ systemctl restart systemd-journald
434
434
  # The deploy user uploads releases as itself (scp), while the scripts run as
435
435
  # root through sudo. setgid group-writable directories let both write.
436
436
  install -d -m 2775 -g "$(id -gn ${Be(e)})" /var/ts-cloud/artifacts /var/ts-cloud/staging
437
- `}function Xc(e){let t=Be(e),r=`/home/${e}`;return[`chown -R ${t}:"$(id -gn ${t})" ${Be(`${r}/.ssh`)}`,`chmod 700 ${Be(`${r}/.ssh`)}`]}function fr(e){let{config:t,environment:r,profile:n,sudoUser:s}=e;er(t,n,e.facts?.arch);let o={...t.infrastructure?.compute,proxy:le(t,{environment:e.environment,environmentType:e.environment})},i=t.sites??{},a=t.project.slug,c=e.lan?{...e.lan.hostname?{hostname:e.lan.hostname}:{},tls:e.lan.tls??"local-ca",...yo(e)?{ip:yo(e)}:{}}:void 0,l=o.proxy?.engine==="rpx"?Te(i,{proxy:o.proxy,slug:a,lan:c,mail:ne(t,{environment:e.environment,environmentType:e.environment})}):void 0,u=o.proxy?.engine==="rpx"&&l?ve({proxy:o.proxy,config:l,slug:a,profile:n,bunBin:o.runtime==="node"||o.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,d=o.proxy?.engine==="rpx"&&l?Ke({config:l,slug:a}):void 0,m=s?`/home/${s}/.ssh/authorized_keys`:void 0,h=Ue(t,{environment:r,authorizedKeysPath:m}),f=s?[...h.servicesProvision??[],...Xc(s)]:h.servicesProvision,S=[...new Set([...o.systemPackages??[],"psmisc","ca-certificates"])],k=o.swapGb??(n==="raspberry-pi"?bo:void 0),E=de({runtime:h.runtime,runtimeVersion:h.runtimeVersion,systemPackages:S,database:t.infrastructure?.database,phpProvision:h.phpProvision,servicesProvision:f,rpxProvision:u,swapGb:k}).replace(/^#!\/bin\/bash\nset -euo pipefail\n/,""),O=vo(),D=l?.localCa?` lan=${l.localCa.hosts.join(",")} tls=local-ca`:c?` lan=${c.hostname??`${a}.local`} tls=${c.tls??"local-ca"}`:"",R=`#!/bin/bash
437
+ `}function Xc(e){let t=Be(e),r=`/home/${e}`;return[`chown -R ${t}:"$(id -gn ${t})" ${Be(`${r}/.ssh`)}`,`chmod 700 ${Be(`${r}/.ssh`)}`]}function fr(e){let{config:t,environment:r,profile:n,sudoUser:s}=e;er(t,n,e.facts?.arch);let o={...t.infrastructure?.compute,proxy:le(t,{environment:e.environment,environmentType:e.environment})},i=t.sites??{},a=t.project.slug,c=e.lan?{...e.lan.hostname?{hostname:e.lan.hostname}:{},tls:e.lan.tls??"local-ca",...yo(e)?{ip:yo(e)}:{}}:void 0,l=o.proxy?.engine==="rpx"?Te(i,{proxy:o.proxy,slug:a,lan:c,mail:ne(t,{environment:e.environment,environmentType:e.environment})}):void 0,u=o.proxy?.engine==="rpx"&&l?ve({proxy:o.proxy,config:l,slug:a,profile:n,bunBin:o.runtime==="node"||o.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,d=o.proxy?.engine==="rpx"&&l?Ke({config:l,slug:a}):void 0,m=s?`/home/${s}/.ssh/authorized_keys`:void 0,h=Ue(t,{environment:r,authorizedKeysPath:m}),f=s?[...h.servicesProvision??[],...Xc(s)]:h.servicesProvision,S=[...new Set([...o.systemPackages??[],"psmisc","ca-certificates"])],k=o.swapGb??(n==="raspberry-pi"?bo:void 0),O=de({runtime:h.runtime,runtimeVersion:h.runtimeVersion,systemPackages:S,database:t.infrastructure?.database,phpProvision:h.phpProvision,servicesProvision:f,rpxProvision:u,swapGb:k}).replace(/^#!\/bin\/bash\nset -euo pipefail\n/,""),D=vo(),I=l?.localCa?` lan=${l.localCa.hosts.join(",")} tls=local-ca`:c?` lan=${c.hostname??`${a}.local`} tls=${c.tls??"local-ca"}`:"",E=`#!/bin/bash
438
438
  set -euo pipefail
439
- # ts-cloud ssh bootstrap v${Ie} profile=${n}${D}
439
+ # ts-cloud ssh bootstrap v${Ie} profile=${n}${I}
440
440
 
441
441
  # Idempotence guard. This script may run again (a cloud-init rerun, a repeated
442
442
  # adopt, a deploy): once this version has been applied, only the gateway's
443
443
  # route fragment is refreshed, so a rerun cannot re-download the runtime or
444
444
  # re-create swap on every boot.
445
- if [ -e ${Be(O)} ]; then
445
+ if [ -e ${Be(D)} ]; then
446
446
  echo "[ts-cloud] bootstrap v${Ie} already applied; refreshing the gateway fragment only"
447
- `;if(d){let z=d[0]==="set -euo pipefail"?d.slice(1):d;R+=`${z.join(`
447
+ `;if(d){let z=d[0]==="set -euo pipefail"?d.slice(1):d;E+=`${z.join(`
448
448
  `)}
449
- `}if(R+=` exit 0
449
+ `}if(E+=` exit 0
450
450
  fi
451
- `,R+=jc(),n==="raspberry-pi")R+=Vc();if(s)R+=qc(s);if(R+=`
452
- ${E}`,R+=`
451
+ `,E+=jc(),n==="raspberry-pi")E+=Vc();if(s)E+=qc(s);if(E+=`
452
+ ${O}`,E+=`
453
453
  install -d -m 0755 ${Be($n)}
454
- date -u +%Y-%m-%dT%H:%M:%SZ > ${Be(O)}
454
+ date -u +%Y-%m-%dT%H:%M:%SZ > ${Be(D)}
455
455
  echo "[ts-cloud] bootstrap v${Ie} applied (${n}); gateway fragment at ${pe}/${a}.json"
456
- `,l?.localCa)R+=`echo "[ts-cloud] LAN certificate authority for ${l.localCa.hosts.join(", ")} at ${At(l.localCa.dir)} (copy it to a client to trust this box)"
457
- `;return R}var Ae={user:"root",port:22,privateKeyPath:"~/.ssh/id_ed25519",hostKey:"pin",profile:"generic",publicIp:"auto"},wo=["pin","accept-new","insecure"],_o=["raspberry-pi","generic"];function ct(...e){for(let t of e){let r=process.env[t]?.trim();if(r)return r}return}function Pt(...e){for(let t of e){let r=t?.trim();if(r)return r}return}function $o(e,t){if(t?.length)return t;if(e?.ssh?.hosts?.length)return e.ssh.hosts;let r=ct("TS_CLOUD_SSH_HOST");if(r)return[{host:r}];throw Error("No ssh host configured. Set ssh.hosts in cloud.config.ts or TS_CLOUD_SSH_HOST.")}function To(e,t){return Pt(t,e?.user,ct("TS_CLOUD_SSH_USER"))??Ae.user}function Co(e,t){let r=[{source:"the explicit port",value:t},{source:`ssh.hosts[].port for ${e?.host??"the host"}`,value:e?.port},{source:"TS_CLOUD_SSH_PORT",value:ct("TS_CLOUD_SSH_PORT")}];for(let{source:n,value:s}of r){if(s===void 0||s==="")continue;let o=typeof s==="number"?s:Number(s);if(!Number.isInteger(o)||o<1||o>65535)throw Error(`Invalid SSH port from ${n}: ${String(s)}`);return o}return Ae.port}function Po(e,t){return tn(Pt(t,e?.privateKeyPath,ct("TS_CLOUD_SSH_KEY"))??Ae.privateKeyPath)}function xo(e,t){let r=Pt(t,e?.ssh?.hostKey,ct("TS_CLOUD_SSH_HOST_KEY"))??Ae.hostKey;if(!wo.includes(r))throw Error(`Invalid ssh.hostKey '${r}'. Use one of: ${wo.join(", ")}.`);return r}function Ro(e,t=Ae.user,r){return r??e?.ssh?.sudo??t!=="root"}function Eo(e,t){let r=Pt(t,e?.ssh?.profile,ct("TS_CLOUD_SSH_PROFILE"))??Ae.profile;if(!_o.includes(r))throw Error(`Invalid ssh.profile '${r}'. Use one of: ${_o.join(", ")}.`);return r}function Oo(e,t){return Pt(t,e?.ssh?.publicIp)??Ae.publicIp}function Do(e,t){return t??e?.ssh?.lan}function hr(e,t={}){let r=$o(e,t.hosts).map((n)=>({host:n.host,user:To(n,t.user),port:Co(n,t.port),privateKeyPath:Po(n,t.privateKeyPath),role:n.role??"app"}));return{hosts:r,hostKey:xo(e,t.hostKey),sudo:Ro(e,r[0]?.user,t.sudo),profile:Eo(e,t.profile),publicIp:Oo(e,t.publicIp),lan:Do(e,t.lan)}}var Tn=`set -u
456
+ `,l?.localCa)E+=`echo "[ts-cloud] LAN certificate authority for ${l.localCa.hosts.join(", ")} at ${At(l.localCa.dir)} (copy it to a client to trust this box)"
457
+ `;return E}var Ae={user:"root",port:22,privateKeyPath:"~/.ssh/id_ed25519",hostKey:"pin",profile:"generic",publicIp:"auto"},wo=["pin","accept-new","insecure"],_o=["raspberry-pi","generic"];function ct(...e){for(let t of e){let r=process.env[t]?.trim();if(r)return r}return}function Pt(...e){for(let t of e){let r=t?.trim();if(r)return r}return}function $o(e,t){if(t?.length)return t;if(e?.ssh?.hosts?.length)return e.ssh.hosts;let r=ct("TS_CLOUD_SSH_HOST");if(r)return[{host:r}];throw Error("No ssh host configured. Set ssh.hosts in cloud.config.ts or TS_CLOUD_SSH_HOST.")}function To(e,t){return Pt(t,e?.user,ct("TS_CLOUD_SSH_USER"))??Ae.user}function Co(e,t){let r=[{source:"the explicit port",value:t},{source:`ssh.hosts[].port for ${e?.host??"the host"}`,value:e?.port},{source:"TS_CLOUD_SSH_PORT",value:ct("TS_CLOUD_SSH_PORT")}];for(let{source:n,value:s}of r){if(s===void 0||s==="")continue;let o=typeof s==="number"?s:Number(s);if(!Number.isInteger(o)||o<1||o>65535)throw Error(`Invalid SSH port from ${n}: ${String(s)}`);return o}return Ae.port}function Po(e,t){return tn(Pt(t,e?.privateKeyPath,ct("TS_CLOUD_SSH_KEY"))??Ae.privateKeyPath)}function xo(e,t){let r=Pt(t,e?.ssh?.hostKey,ct("TS_CLOUD_SSH_HOST_KEY"))??Ae.hostKey;if(!wo.includes(r))throw Error(`Invalid ssh.hostKey '${r}'. Use one of: ${wo.join(", ")}.`);return r}function Ro(e,t=Ae.user,r){return r??e?.ssh?.sudo??t!=="root"}function Eo(e,t){let r=Pt(t,e?.ssh?.profile,ct("TS_CLOUD_SSH_PROFILE"))??Ae.profile;if(!_o.includes(r))throw Error(`Invalid ssh.profile '${r}'. Use one of: ${_o.join(", ")}.`);return r}function Oo(e,t){return Pt(t,e?.ssh?.publicIp)??Ae.publicIp}function Do(e,t){return t??e?.ssh?.lan}function hr(e,t={}){let r=$o(e,t.hosts).map((n)=>({host:n.host,user:To(n,t.user),port:Co(n,t.port),privateKeyPath:Po(n,t.privateKeyPath),role:n.role??"app"}));return{hosts:r,hostKey:xo(e,t.hostKey),sudo:Ro(e,r[0]?.user,t.sudo),profile:Eo(e,t.profile),publicIp:Oo(e,t.publicIp),lan:Do(e,t.lan)}}var Tn=`set -u
458
458
  . /etc/os-release 2>/dev/null || true
459
459
  # Strings are stripped of quotes, backslashes and newlines rather than escaped:
460
460
  # nothing reported here legitimately contains them, and a probe that cannot
@@ -538,11 +538,11 @@ console.log(JSON.stringify({
538
538
  `,"utf8"),await Yo(r,t)}async function ms(e,t=1800000){let r=Qo(e);await rr(Oe(),{recursive:!0});try{await rr(r)}catch(n){if(Date.now()-(await hl(r)).mtimeMs<=t)throw Error(`Another resize process holds ${r}.`);await Yo(r,`${r}.stale-${Date.now()}`),await rr(r)}return await Jo(nr(r,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
539
539
  `,"utf8"),async()=>{await Sl(nr(r,"owner.json")).catch(()=>{}),await gl(r).catch(()=>{})}}import{copyFileSync as Wl}from"node:fs";import{tmpdir as Gl}from"node:os";import{join as Vl}from"node:path";var _l=`${te}/project`;function Zo(e,t){let r=t.ownerSlug.trim(),n=t.selfSlug?.trim(),s={total:e.length,owner:[],self:[],others:new Map,unmanaged:[]};for(let o of e){let i=o.labels?.[_l]?.trim();if(!i){s.unmanaged.push(o.name);continue}if(i===r){s.owner.push(o.name);continue}if(n&&i===n){s.self.push(o.name);continue}let a=s.others.get(i);if(a)a.push(o.name);else s.others.set(i,[o.name])}return s}function En(e){let t=e.unmanaged.length;for(let r of e.others.values())t+=r.length;return t}function ei(e,t){let r=En(e),n=[];if(n.push(`Attaching to '${t.ownerSlug}' shares one provider project, so this deploy's credential can write to all ${e.total} server(s) it can see.`),r===0)return n.push("Nothing outside the two projects being joined is reachable with it."),n;n.push(`${r} of them belong to neither project:`);for(let s of[...e.others.keys()].sort())n.push(` ${s}: ${[...e.others.get(s)].sort().join(", ")}`);if(e.unmanaged.length>0)n.push(` not managed by ts-cloud: ${[...e.unmanaged].sort().join(", ")}`);return n.push("A compromised CI run or a mistargeted teardown in this project now reaches those. Keep the app in its own provider project instead if that is not acceptable, which rules out attaching."),n}var $l=new Set(["laravel","php","statamic","wordpress"]);function sn(e){if(e.framework)return e.framework;if(e.type&&$l.has(e.type))return"laravel";return"stacks"}var ti=`eval "$(cd ${U} && pantry env 2>/dev/null)"`,ri="/usr/local/bin/bun",Tl="node_modules/@stacksjs/ts-cloud/dist/bin/stacks-scheduler.js",Cl="node_modules/@stacksjs/ts-cloud/dist/bin/stacks-queue-worker.js",ni={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:()=>`${ri} ${Tl}`,queueWorkerCommand:(e,{current:t})=>{let r=[`--queue=${e.queue||"default"}`,`--sleep=${e.sleep??3}`,`--tries=${e.tries??3}`,`--timeout=${e.timeout??60}`];return`${ri} ${t}/${Cl} ${r.join(" ")}`}},Pl={id:"laravel",wrapExec:(e)=>`/bin/sh -lc '${ti}; exec ${e}'`,schedulerMode:"cron",schedulerCommand:({current:e})=>`cd ${e} && ${ti} && php artisan schedule:run`,queueWorkerCommand:(e,{current:t})=>{let r=`${t}/artisan`;if(e.horizon)return`php ${r} horizon`;let n=[e.connection||"default",`--queue=${e.queue||"default"}`,`--sleep=${e.sleep??3}`,`--tries=${e.tries??3}`,`--timeout=${e.timeout??60}`,`--memory=${e.memory??128}`];if(e.maxJobs)n.push(`--max-jobs=${e.maxJobs}`);if(e.maxTime)n.push(`--max-time=${e.maxTime}`);return`php ${r} queue:work ${n.join(" ")}`}},xl={stacks:ni,laravel:Pl};function si(e){return xl[e]??ni}function oi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Rl(e){return`'${e.split("'").join("'\\''")}'`}function ii(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"unnamed"}function El(e,t,r){return`${e}-${t}-queue-${r}`}function Ol(e,t,r,n){return`${e}-${t}-daemon-${r.name?ii(r.name):ii(r.command).slice(0,32)||String(n)}`}function On(e){let t=["[Unit]",`Description=${e.description}`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${e.workingDir}`,...Object.entries(e.environment??{}).map(([r,n])=>`Environment="${r}=${n}"`),`ExecStart=${e.execStart}`,`Restart=${e.restart||"always"}`,"RestartSec=5","MemoryAccounting=true",`MemoryHigh=${e.memoryHigh??"2G"}`,...e.memoryMax?[`MemoryMax=${e.memoryMax}`]:[]];if(e.user)t.push(`User=${e.user}`);if(typeof e.stopWaitSecs==="number")t.push(`TimeoutStopSec=${e.stopWaitSecs}`);return t.push("","[Install]","WantedBy=multi-user.target"),`${t.join(`
540
540
  `)}
541
- `}function Dn(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_UNIT_EOF'`,t.replace(/\n$/,""),"TS_CLOUD_UNIT_EOF"]}function Dl(e,t){return`/etc/cron.d/${e}-${t}-scheduler`}function In(e){let{slug:t,siteName:r,site:n}=e,o=`${e.appBase??`/var/www/${r}`}/current`,i=si(sn(n)),a={current:o},c=[],l=[];(n.queues||[]).forEach((E,O)=>{let D=Math.max(1,E.processes??1);for(let R=0;R<D;R++){let z=El(t,r,l.length);l.push(z),c.push(...Dn(z,On({description:`${r} queue worker ${O}.${R} (managed by ts-cloud)`,workingDir:o,execStart:i.wrapExec(i.queueWorkerCommand(E,a)),environment:i.execEnv,stopWaitSecs:E.stopWaitSecs??90})))}}),(n.daemons||[]).forEach((E,O)=>{let D=Math.max(1,E.processes??1);for(let R=0;R<D;R++){let z=`${Ol(t,r,E,O)}-${R}`;l.push(z),c.push(...Dn(z,On({description:`${r} daemon ${E.name||E.command} (managed by ts-cloud)`,workingDir:E.directory||o,execStart:i.wrapExec(E.command),environment:i.execEnv,restart:E.restart,user:E.user})))}});let m=n.scheduler,h=m===!0||typeof m==="object"&&m!==null,f=`${t}-${r}-scheduler`;if(h&&i.schedulerMode==="daemon"){l.push(f);let E=typeof m==="object"&&m!==null?m:{};c.push(...Dn(f,On({description:`${r} scheduler (managed by ts-cloud)`,workingDir:o,execStart:i.wrapExec(i.schedulerCommand(a)),environment:i.execEnv,memoryHigh:E.memoryHigh,memoryMax:E.memoryMax})),...Kt(`${f}.service`,{auto:!1,high:Boolean(E.memoryHigh),max:Boolean(E.memoryMax)}))}let S=l.map((E)=>`${E}.service`).join(" ");c.push("systemctl daemon-reload",`TS_CLOUD_DESIRED="${S}"`,`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E '^${oi(t)}-${oi(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 E of l)c.push(`systemctl enable ${E}.service`,`systemctl restart ${E}.service`);let k=Dl(t,r);if(h&&i.schedulerMode==="cron"){let E=typeof m==="object"&&m!==null?m:void 0,O=`${i.schedulerCommand(a)} >> /dev/null 2>&1`;if(E?.heartbeatUrl){let R=E.heartbeatMethod||"GET",z=R==="GET"?"":`-X ${R} `;O+=` && curl -fsS -m 10 ${z}${Rl(E.heartbeatUrl)} >/dev/null 2>&1`}let D=`* * * * * root ${O}
542
- `.replace(/%/g,"\\%");c.push(`cat > ${k} <<'TS_CLOUD_CRON_EOF'`,D.replace(/\n$/,""),"TS_CLOUD_CRON_EOF",`chmod 644 ${k}`)}else c.push(`rm -f ${k}`);return c}function An(e){return!!(e.queues?.length||e.daemons?.length||e.scheduler)}function Ln(e){if(e.ssl?.provider)return e.ssl.provider;return e.domain?"letsencrypt":"none"}var ai={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 ci(e){return`/etc/letsencrypt/ts-cloud-${e}.ini`}function Il(e){let t=e?ai[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 Al(e){if(!e.credentials||Object.keys(e.credentials).length===0)return[];let t=ci(e.provider),r=Object.entries(e.credentials).map(([n,s])=>`${n} = ${s}`).join(`
541
+ `}function Dn(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_UNIT_EOF'`,t.replace(/\n$/,""),"TS_CLOUD_UNIT_EOF"]}function Dl(e,t){return`/etc/cron.d/${e}-${t}-scheduler`}function In(e){let{slug:t,siteName:r,site:n}=e,o=`${e.appBase??`/var/www/${r}`}/current`,i=si(sn(n)),a={current:o},c=[],l=[];(n.queues||[]).forEach((O,D)=>{let I=Math.max(1,O.processes??1);for(let E=0;E<I;E++){let z=El(t,r,l.length);l.push(z),c.push(...Dn(z,On({description:`${r} queue worker ${D}.${E} (managed by ts-cloud)`,workingDir:o,execStart:i.wrapExec(i.queueWorkerCommand(O,a)),environment:i.execEnv,stopWaitSecs:O.stopWaitSecs??90})))}}),(n.daemons||[]).forEach((O,D)=>{let I=Math.max(1,O.processes??1);for(let E=0;E<I;E++){let z=`${Ol(t,r,O,D)}-${E}`;l.push(z),c.push(...Dn(z,On({description:`${r} daemon ${O.name||O.command} (managed by ts-cloud)`,workingDir:O.directory||o,execStart:i.wrapExec(O.command),environment:i.execEnv,restart:O.restart,user:O.user})))}});let m=n.scheduler,h=m===!0||typeof m==="object"&&m!==null,f=`${t}-${r}-scheduler`;if(h&&i.schedulerMode==="daemon"){l.push(f);let O=typeof m==="object"&&m!==null?m:{};c.push(...Dn(f,On({description:`${r} scheduler (managed by ts-cloud)`,workingDir:o,execStart:i.wrapExec(i.schedulerCommand(a)),environment:i.execEnv,memoryHigh:O.memoryHigh,memoryMax:O.memoryMax})),...Kt(`${f}.service`,{auto:!1,high:Boolean(O.memoryHigh),max:Boolean(O.memoryMax)}))}let S=l.map((O)=>`${O}.service`).join(" ");c.push("systemctl daemon-reload",`TS_CLOUD_DESIRED="${S}"`,`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E '^${oi(t)}-${oi(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 O of l)c.push(`systemctl enable ${O}.service`,`systemctl restart ${O}.service`);let k=Dl(t,r);if(h&&i.schedulerMode==="cron"){let O=typeof m==="object"&&m!==null?m:void 0,D=`${i.schedulerCommand(a)} >> /dev/null 2>&1`;if(O?.heartbeatUrl){let E=O.heartbeatMethod||"GET",z=E==="GET"?"":`-X ${E} `;D+=` && curl -fsS -m 10 ${z}${Rl(O.heartbeatUrl)} >/dev/null 2>&1`}let I=`* * * * * root ${D}
542
+ `.replace(/%/g,"\\%");c.push(`cat > ${k} <<'TS_CLOUD_CRON_EOF'`,I.replace(/\n$/,""),"TS_CLOUD_CRON_EOF",`chmod 644 ${k}`)}else c.push(`rm -f ${k}`);return c}function An(e){return!!(e.queues?.length||e.daemons?.length||e.scheduler)}function Ln(e){if(e.ssl?.provider)return e.ssl.provider;return e.domain?"letsencrypt":"none"}var ai={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 ci(e){return`/etc/letsencrypt/ts-cloud-${e}.ini`}function Il(e){let t=e?ai[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 Al(e){if(!e.credentials||Object.keys(e.credentials).length===0)return[];let t=ci(e.provider),r=Object.entries(e.credentials).map(([n,s])=>`${n} = ${s}`).join(`
543
543
  `);return[`cat > ${t} <<'TS_CLOUD_DNSCREDS_EOF'`,r,"TS_CLOUD_DNSCREDS_EOF",`chmod 600 ${t}`]}function Ll(e){let t=e.dns,r=e.wildcard?[`*.${e.domain}`,e.domain]:[e.domain,...e.aliases||[]].filter(Boolean),n=["certbot","--non-interactive","--agree-tos","--keep-until-expiring"];if(t){let s=ai[t.provider].plugin;if(n.push(`--${s}`),t.provider!=="route53"&&t.credentials)n.push(`--${s}-credentials ${ci(t.provider)}`);if(typeof t.propagationSeconds==="number"&&t.provider!=="route53")n.push(`--${s}-propagation-seconds ${t.propagationSeconds}`);n.push("certonly")}else n.push("--nginx",`--nginx-ctl ${xe}`,e.redirect===!1?"--no-redirect":"--redirect");if(e.email)n.push(`-m ${e.email}`);else n.push("--register-unsafely-without-email");for(let s of r)n.push(`-d ${s}`);return[n.join(" ")]}function kn(e){if(Ln(e)!=="letsencrypt"||!e.domain)return[];let t=e.ssl,r=t?.dns,n=t?.wildcard===!0;if(n&&!r)return[];return[...Il(r),...r?Al(r):[],...Ll({domain:e.domain,aliases:e.aliases,email:t?.email,wildcard:n,dns:r})]}function li(e){let{repository:t,releaseDir:r,commit:n}=e,s=t.branch||"main",o=t.url,i=[`rm -rf ${r}`,`mkdir -p ${r}`];if(t.strategy==="tag")if(t.tag)i.push(`git clone -q --depth 1 --branch ${Se(t.tag)} ${Se(o)} ${r}`),i.push(`printf '%s' ${Se(t.tag)} > ${r}/.ts-cloud-tag`);else{let a=t.tagPattern||"v*";i.push(`TS_CLOUD_TAG="$(git ls-remote --tags --refs --sort=-v:refname ${Se(o)} ${Se(`refs/tags/${a}`)} | head -n1 | sed 's#.*refs/tags/##')"`,`test -n "$TS_CLOUD_TAG" || { echo "no tags matching" ${Se(a)} "found in" ${Se(o)} >&2; exit 1; }`,`git clone -q --depth 1 --branch "$TS_CLOUD_TAG" ${Se(o)} ${r}`,`printf '%s' "$TS_CLOUD_TAG" > ${r}/.ts-cloud-tag`)}else if(n)i.push(`git -C ${r} init -q`,`git -C ${r} remote add origin ${Se(o)}`,`git -C ${r} fetch -q --depth 1 origin ${Se(n)}`,`git -C ${r} checkout -q FETCH_HEAD`);else i.push(`git clone -q --depth 1 --branch ${Se(s)} ${Se(o)} ${r}`);return i.push(`git -C ${r} rev-parse HEAD > ${r}/.ts-cloud-sha`),i}function Se(e){return`'${e.split("'").join("'\\''")}'`}var sr="$CREATE_RELEASE",or="$ACTIVATE_RELEASE",yi="$RESTART_QUEUES",di="composer install --no-interaction --prefer-dist --optimize-autoloader --no-dev",kl=["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 Nl(e){switch(e){case"laravel":case"statamic":return[sr,di,...kl,or,yi];case"php":case"wordpress":return[sr,`${di} || true`,or];case"static":case"spa":return[sr,or]}}function Hl(e,t){return e.replace(/^php\s+/,`${t} `).replace(/(\s)php\s+artisan\s+/g,`$1${t} artisan `)}function Ul(e,t){let r=zt(t);return[`cat > ${e} <<'TS_CLOUD_ENV_EOF'`,r,"TS_CLOUD_ENV_EOF",`chmod 600 ${e}`]}function Si(e,t,r){return[`cat > ${e} <<'${r}'`,t.replace(/\n$/,""),r,`chmod 600 ${e}`]}function Ml(e,t){if(!t)return[];let r=[];if(t.composerAuth){let n=typeof t.composerAuth==="string"?t.composerAuth:JSON.stringify(t.composerAuth,null,2);r.push(...Si(`${e}/auth.json`,n,"TS_CLOUD_AUTHJSON_EOF"))}if(t.npmrc)r.push(...Si(`${e}/.npmrc`,t.npmrc,"TS_CLOUD_NPMRC_EOF"));return r}function vi(e){let t=e.healthCheck?.path;if(!t||!e.domain)return[];let n=`http://127.0.0.1${t.startsWith("/")?t:`/${t}`}`;return[`echo "[ts-cloud] health check ${n} (Host: ${e.domain})"`,"TS_CLOUD_HC_OK=0",`for i in $(seq 1 10); do TS_CLOUD_HC=$(curl -s -o /dev/null -w "%{http_code}" -H "Host: ${e.domain}" -m 10 "${n}" 2>/dev/null || echo 000); case "$TS_CLOUD_HC" in 2*|3*) TS_CLOUD_HC_OK=1; break ;; esac; sleep 3; done`,'[ "$TS_CLOUD_HC_OK" = 1 ] && echo "health check passed ($TS_CLOUD_HC)" || { echo "health check FAILED (last=$TS_CLOUD_HC)" >&2; exit 1; }']}function bi(e){let{siteName:t,site:r,releaseId:n,commit:s}=e;if(!r.repository?.url)throw Error(`Site '${t}' is a PHP/git site but has no repository.url to clone`);let o=e.appBase??`/var/www/${t}`,i="php",a=Ht(o,n),c=r.sharedPaths??Bo,l=[...c,...Ft(r.env,c)],u=r.keepReleases??_i,d=r.deployScript?.length?r.deployScript:Nl(r.type??"laravel"),m=["set -euo pipefail",'export HOME="${HOME:-/root}"','export COMPOSER_HOME="${COMPOSER_HOME:-/root/.composer}"',"export COMPOSER_ALLOW_SUPERUSER=1",Ct()];if(m.push(...zo(o,{releaseId:n,commit:s,branch:r.repository.branch,keepLogs:u})),m.push(...Oi(a,l)),r.env&&Object.keys(r.env).length>0)m.push(...Ul(`${a.shared}/.env`,r.env));for(let h of d){let f=h.trim();if(f===sr)m.push(...li({repository:r.repository,releaseDir:a.release,commit:s})),m.push(...Vo(a,l)),m.push(`cd ${a.release}`),m.push(...Ml(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(f===or)m.push(...hn(a)),m.push(...yn(a,u)),m.push(`(cd ${U} && pantry restart php-fpm) 2>/dev/null || true`);else if(f===yi)m.push(`${i} artisan queue:restart || true`);else m.push(Hl(h,i))}return m}var ir={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"]}},Et="ts-cloud-service:";function zl(e){return e===!0||typeof e==="object"&&e!=null}function wi(e){if(!e)return[];return Object.keys(ir).filter((t)=>zl(e[t]))}function $i(e){if(e.length===0)return[];return[Ct(),"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 "${Et}$TS_CLOUD_SVC:present"; return 0; fi`," done",` if ts_cloud_port_open "$TS_CLOUD_PORT"; then echo "${Et}$TS_CLOUD_SVC:present"; return 0; fi`,` echo "${Et}$TS_CLOUD_SVC:missing"`," return 0","}",...e.filter((t)=>ir[t]).map((t)=>`ts_cloud_probe ${t} ${ir[t].port} ${ir[t].binaries.join(" ")}`),"exit 0"]}function Ti(e,t){if(!e)return[];let r=new Map;for(let n of e.split(`
544
544
  `)){let s=n.indexOf(Et);if(s===-1)continue;let[o,i]=n.slice(s+Et.length).trim().split(":");if(o)r.set(o,i)}return t.filter((n)=>r.get(n)==="missing")}function Ci(e,t,r){let n=r?` on ${r}`:"",s=e.map((i)=>`managedServices.${i}`).join(", "),o=e.length===1?`no ${e[0]}`:`none of ${e.join(", ")}`;return`This project declares ${s}, but '${t}' has ${o}${n}. Attach mode does not provision services on the owner's box, so nothing will install ${e.length===1?"it":"them"}. Point the app at an external service, or ask the owner of '${t}' to add ${e.length===1?"it":"them"} to their own config and re-provision.`}var Pi="/var/lib/pantry/php-fpm/pool.d",Fl=9100,Bl=400;function ar(e){return(e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"site").slice(0,28)}function xi(e){return`web_${ar(e)}`}function Kl(e){let t=ar(e),r=0;for(let n=0;n<t.length;n++)r=r*31+t.charCodeAt(n)>>>0;return Fl+r%Bl}function Nn(e){return`127.0.0.1:${Kl(e)}`}function jl(e){let t=ar(e.siteName),r=xi(e.siteName),n=e.maxChildren??10;return[`; ts-cloud-managed pool for ${e.siteName} (site isolation)`,`[${t}]`,`user = ${r}`,`group = ${r}`,`listen = ${Nn(e.siteName)}`,"pm = dynamic",`pm.max_children = ${n}`,"pm.start_servers = 2","pm.min_spare_servers = 1","pm.max_spare_servers = 3","pm.max_requests = 500","catch_workers_output = yes",`php_admin_value[open_basedir] = ${e.appBase}:/tmp`,""].join(`
545
- `)}function Ri(e){let t=xi(e.siteName),r=ar(e.siteName),n=`${Pi}/${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 ${Pi}`,`cat > ${n} <<'TS_CLOUD_FPMPOOL_EOF'`,jl(e).replace(/\n$/,""),"TS_CLOUD_FPMPOOL_EOF",`(cd ${U} && pantry restart php-fpm) 2>/dev/null || true`]}var lr={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};function ql(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function Ii(e,t,r=lr){let{config:n,environment:s,siteName:o,site:i,slug:a,sha:c,runtime:l,localTarballPath:u}=t,d=`releases/${o}/${c}.tar.gz`,m=T(n,s),h=await e.getComputeOutputs({config:n,environment:s}),f=await e.findComputeTargets({slug:a,environment:s,role:"app",stackName:m});if(f.length===0)return{success:!1,error:e.name==="aws"?`Stack '${m}' has no EC2 instances tagged Project=${a} Environment=${s} 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=${s} ts-cloud/role=app, and storage/cloud/state/${m}.json pins no live server. For a shared box, record its serverId there.`};let S=h.servicesPrivateIp?zs(h.servicesPrivateIp,w(n)):Gc(w(n)),k=da(ne(n,{environment:s})),E=n.infrastructure?.compute,O=zr(E?.hostCleanup),D=Z({...E,proxy:le(n,{environment:s})})?{HOST:"127.0.0.1"}:{},R=s==="production"?{APP_ENV:"production",NODE_ENV:"production"}:{},z={...S,...k,...D,...i.env||{},...R},x=Nr(z,i.sharedPaths??[]);if(x.warning)r.warn(`Site '${o}': ${x.warning}`);else if(x.path)r.info(`Site '${o}': sharing '${x.path}' so the SQLite database survives deploys.`);if(Di(i)){let C=i.phpVersion??E?.php?.default??E?.php?.versions?.[0],F=J(a,o),N=Object.keys(S).length>0?{...i,env:z}:i,K=bi({siteName:o,site:N,releaseId:c,appBase:F,defaultPhpVersion:C}),j=!Z(E),b=Ln(i)==="custom"&&i.ssl?.certPath&&i.ssl?.keyPath?{certPath:i.ssl.certPath,keyPath:i.ssl.keyPath}:void 0,L=i.isolation?Ri({siteName:o,appBase:F}):[],ee=j?_r({siteName:o,domain:i.domain||o,aliases:i.aliases,type:i.type,appDir:`${F}/current`,webDirectory:i.webDirectory,phpVersion:C,fastcgiPass:i.isolation?Nn(o):void 0,redirects:i.redirects,ssl:b,auth:i.auth&&i.auth.enabled!==!1&&i.auth.password?{username:i.auth.username||"admin",password:i.auth.password,realm:i.auth.realm}:void 0,serverSnippet:vr(i.nginx,E?.nginxTemplates),clientMaxBodySize:i.nginx?.clientMaxBodySize,hsts:i.ssl?.hsts,tlsProtocols:i.ssl?.tlsProtocols,security:i.security}):[],X=j?kn(i):[],Ce=An(i)?In({slug:a,siteName:o,site:i,phpVersion:C,appBase:F}):[],Ot=j?vi(i):[];r.step(`Deploying PHP site '${o}' to ${f.length} target(s)...`);let Le=await e.runRemoteDeploy({targets:f,commands:[...ra(F,a),...Mt(F,a),...K,...L,...ee,...X,...Ce,...Ot,...O],comment:`ts-cloud deploy ${a}/${o}@${c}`,tags:{Project:a,Environment:s,Role:"app"}}),Kn=qn(n.notifications,i.notifications);if(!Le.success)return await Ei(e,f,O,r),await Tr(Kn,"deploy-failed",`❌ Deploy of ${a}/${o}@${c} failed: ${Le.error||"unknown error"}`),{success:!1,error:Le.error||"Remote PHP deploy failed",instanceCount:Le.instanceCount,perInstance:Le.perInstance};let Gi=i.domain?` → https://${i.domain}`:"";return await Tr(Kn,"deploy",`✅ Deployed ${a}/${o}@${c}${Gi}`),{success:!0,instanceCount:Le.instanceCount,perInstance:Le.perInstance}}if(!u)return{success:!1,error:`Site '${o}' requires a release tarball but none was provided`};let H=await e.uploadRelease({config:n,environment:s,localPath:u,remoteKey:d,targets:f}),V=St(a,o,c),se=e.name==="aws"?qr(h.deployBucketName,d,n.project.region||"us-east-1",V):Xr(H.artifactRef,V),ce=I(i),G=J(a,o),oe=ce==="server-static"?Vr({siteName:o,slug:a,appDir:G,artifactFetch:se,releaseId:c,preStartCommands:i.preStart}):Gr({siteName:o,slug:a,appDir:G,artifactFetch:se,releaseId:c,execStart:Wr(i.start,l,`${G.replace(/\/+$/,"")}/releases/%i`),envEntries:z,port:i.port,preStartCommands:i.preStart,sharedPaths:i.sharedPaths,zeroDowntime:i.zeroDowntime!==!1,healthCheckPath:i.healthCheck?.path,liveness:i.liveness,memoryHigh:i.memoryHigh,memoryMax:i.memoryMax,cpuWeight:i.cpuWeight,ioWeight:i.ioWeight,tasksMax:i.tasksMax,stopTimeout:i.stopTimeout}),Y=ce==="server-static"&&!Z(E)&&!!i.domain,q=Y?_r({siteName:o,domain:i.domain,aliases:i.aliases,type:i.type==="spa"?"spa":"static",appDir:`${G}/current`,webDirectory:"",redirects:i.redirects,auth:i.auth&&i.auth.enabled!==!1&&i.auth.password?{username:i.auth.username||"admin",password:i.auth.password,realm:i.auth.realm}:void 0,serverSnippet:vr(i.nginx,E?.nginxTemplates),clientMaxBodySize:i.nginx?.clientMaxBodySize,hsts:i.ssl?.hsts,tlsProtocols:i.ssl?.tlsProtocols,security:i.security}):[],ue=Y?kn(i):[],y=An(i)?In({slug:a,siteName:o,site:i,appBase:G}):[],P=[...zo(G,{releaseId:c,commit:c,branch:i.repository?.branch??"main"}),...ra(G,a),...Mt(G,a),...oe,...q,...ue,...y,...O];r.step(`Deploying to ${f.length} target(s)...`);let M=await e.runRemoteDeploy({targets:f,commands:P,comment:`ts-cloud deploy ${a}/${o}@${c}`,tags:{Project:a,Environment:s,Role:"app"}});if(!M.success)return await Ei(e,f,O,r),{success:!1,error:M.error||"Remote deploy failed",instanceCount:M.instanceCount,perInstance:M.perInstance};return{success:!0,instanceCount:M.instanceCount,perInstance:M.perInstance}}async function Ei(e,t,r,n){if(r.length===0)return;try{let s=await e.runRemoteDeploy({targets:t,commands:r,comment:"ts-cloud host cleanup after failed deploy"});if(!s.success)n.warn(`Host cleanup after the failed deploy did not complete: ${s.error||"unknown error"}`)}catch(s){n.warn(`Host cleanup after the failed deploy did not run: ${s.message}`)}}function cr(e){return`'${e.replaceAll("'","'\\''")}'`}function Xl(e,t,r=!1,n=[]){let s=`${e}-dashboard-`,o=t.map((a)=>`${e}-${a}.service`),i=r?[`export TS_CLOUD_DASHBOARD_KEEP_DOMAINS=${cr(JSON.stringify(n))}`,"rm -f /run/ts-cloud-dashboard-routes-changed",`/usr/local/bin/bun --bun -e ${cr(`
545
+ `)}function Ri(e){let t=xi(e.siteName),r=ar(e.siteName),n=`${Pi}/${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 ${Pi}`,`cat > ${n} <<'TS_CLOUD_FPMPOOL_EOF'`,jl(e).replace(/\n$/,""),"TS_CLOUD_FPMPOOL_EOF",`(cd ${U} && pantry restart php-fpm) 2>/dev/null || true`]}var lr={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};function ql(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function Ii(e,t,r=lr){let{config:n,environment:s,siteName:o,site:i,slug:a,sha:c,runtime:l,localTarballPath:u}=t,d=`releases/${o}/${c}.tar.gz`,m=T(n,s),h=await e.getComputeOutputs({config:n,environment:s}),f=await e.findComputeTargets({slug:a,environment:s,role:"app",stackName:m});if(f.length===0)return{success:!1,error:e.name==="aws"?`Stack '${m}' has no EC2 instances tagged Project=${a} Environment=${s} 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=${s} ts-cloud/role=app, and storage/cloud/state/${m}.json pins no live server. For a shared box, record its serverId there.`};let S=h.servicesPrivateIp?zs(h.servicesPrivateIp,A(n)):Gc(A(n)),k=da(ne(n,{environment:s})),O=n.infrastructure?.compute,D=zr(O?.hostCleanup),I=Z({...O,proxy:le(n,{environment:s})})?{HOST:"127.0.0.1"}:{},E=s==="production"?{APP_ENV:"production",NODE_ENV:"production"}:{},z={...S,...k,...I,...i.env||{},...E},x=Nr(z,i.sharedPaths??[]);if(x.warning)r.warn(`Site '${o}': ${x.warning}`);else if(x.path)r.info(`Site '${o}': sharing '${x.path}' so the SQLite database survives deploys.`);if(Di(i)){let C=i.phpVersion??O?.php?.default??O?.php?.versions?.[0],F=J(a,o),N=Object.keys(S).length>0?{...i,env:z}:i,K=bi({siteName:o,site:N,releaseId:c,appBase:F,defaultPhpVersion:C}),j=!Z(O),b=Ln(i)==="custom"&&i.ssl?.certPath&&i.ssl?.keyPath?{certPath:i.ssl.certPath,keyPath:i.ssl.keyPath}:void 0,L=i.isolation?Ri({siteName:o,appBase:F}):[],ee=j?_r({siteName:o,domain:i.domain||o,aliases:i.aliases,type:i.type,appDir:`${F}/current`,webDirectory:i.webDirectory,phpVersion:C,fastcgiPass:i.isolation?Nn(o):void 0,redirects:i.redirects,ssl:b,auth:i.auth&&i.auth.enabled!==!1&&i.auth.password?{username:i.auth.username||"admin",password:i.auth.password,realm:i.auth.realm}:void 0,serverSnippet:vr(i.nginx,O?.nginxTemplates),clientMaxBodySize:i.nginx?.clientMaxBodySize,hsts:i.ssl?.hsts,tlsProtocols:i.ssl?.tlsProtocols,security:i.security}):[],X=j?kn(i):[],Ce=An(i)?In({slug:a,siteName:o,site:i,phpVersion:C,appBase:F}):[],Ot=j?vi(i):[];r.step(`Deploying PHP site '${o}' to ${f.length} target(s)...`);let Le=await e.runRemoteDeploy({targets:f,commands:[...ra(F,a),...Mt(F,a),...K,...L,...ee,...X,...Ce,...Ot,...D],comment:`ts-cloud deploy ${a}/${o}@${c}`,tags:{Project:a,Environment:s,Role:"app"}}),Kn=qn(n.notifications,i.notifications);if(!Le.success)return await Ei(e,f,D,r),await Tr(Kn,"deploy-failed",`❌ Deploy of ${a}/${o}@${c} failed: ${Le.error||"unknown error"}`),{success:!1,error:Le.error||"Remote PHP deploy failed",instanceCount:Le.instanceCount,perInstance:Le.perInstance};let Gi=i.domain?` → https://${i.domain}`:"";return await Tr(Kn,"deploy",`✅ Deployed ${a}/${o}@${c}${Gi}`),{success:!0,instanceCount:Le.instanceCount,perInstance:Le.perInstance}}if(!u)return{success:!1,error:`Site '${o}' requires a release tarball but none was provided`};let H=await e.uploadRelease({config:n,environment:s,localPath:u,remoteKey:d,targets:f}),V=St(a,o,c),se=e.name==="aws"?qr(h.deployBucketName,d,n.project.region||"us-east-1",V):Xr(H.artifactRef,V),ce=w(i),G=J(a,o),oe=ce==="server-static"?Vr({siteName:o,slug:a,appDir:G,artifactFetch:se,releaseId:c,preStartCommands:i.preStart}):Gr({siteName:o,slug:a,appDir:G,artifactFetch:se,releaseId:c,execStart:Wr(i.start,l,`${G.replace(/\/+$/,"")}/releases/%i`),envEntries:z,port:i.port,preStartCommands:i.preStart,sharedPaths:i.sharedPaths,zeroDowntime:i.zeroDowntime!==!1,healthCheckPath:i.healthCheck?.path,liveness:i.liveness,memoryHigh:i.memoryHigh,memoryMax:i.memoryMax,cpuWeight:i.cpuWeight,ioWeight:i.ioWeight,tasksMax:i.tasksMax,stopTimeout:i.stopTimeout}),Y=ce==="server-static"&&!Z(O)&&!!i.domain,q=Y?_r({siteName:o,domain:i.domain,aliases:i.aliases,type:i.type==="spa"?"spa":"static",appDir:`${G}/current`,webDirectory:"",redirects:i.redirects,auth:i.auth&&i.auth.enabled!==!1&&i.auth.password?{username:i.auth.username||"admin",password:i.auth.password,realm:i.auth.realm}:void 0,serverSnippet:vr(i.nginx,O?.nginxTemplates),clientMaxBodySize:i.nginx?.clientMaxBodySize,hsts:i.ssl?.hsts,tlsProtocols:i.ssl?.tlsProtocols,security:i.security}):[],ue=Y?kn(i):[],y=An(i)?In({slug:a,siteName:o,site:i,appBase:G}):[],P=[...zo(G,{releaseId:c,commit:c,branch:i.repository?.branch??"main"}),...ra(G,a),...Mt(G,a),...oe,...q,...ue,...y,...D];r.step(`Deploying to ${f.length} target(s)...`);let M=await e.runRemoteDeploy({targets:f,commands:P,comment:`ts-cloud deploy ${a}/${o}@${c}`,tags:{Project:a,Environment:s,Role:"app"}});if(!M.success)return await Ei(e,f,D,r),{success:!1,error:M.error||"Remote deploy failed",instanceCount:M.instanceCount,perInstance:M.perInstance};return{success:!0,instanceCount:M.instanceCount,perInstance:M.perInstance}}async function Ei(e,t,r,n){if(r.length===0)return;try{let s=await e.runRemoteDeploy({targets:t,commands:r,comment:"ts-cloud host cleanup after failed deploy"});if(!s.success)n.warn(`Host cleanup after the failed deploy did not complete: ${s.error||"unknown error"}`)}catch(s){n.warn(`Host cleanup after the failed deploy did not run: ${s.message}`)}}function cr(e){return`'${e.replaceAll("'","'\\''")}'`}function Xl(e,t,r=!1,n=[]){let s=`${e}-dashboard-`,o=t.map((a)=>`${e}-${a}.service`),i=r?[`export TS_CLOUD_DASHBOARD_KEEP_DOMAINS=${cr(JSON.stringify(n))}`,"rm -f /run/ts-cloud-dashboard-routes-changed",`/usr/local/bin/bun --bun -e ${cr(`
546
546
  const { chmodSync, existsSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } = require('node:fs')
547
547
  const { basename, join } = require('node:path')
548
548
  const root = '/etc/rpx/sites.d'
@@ -570,7 +570,7 @@ console.log(JSON.stringify({
570
570
  changed = true
571
571
  }
572
572
  if (changed) writeFileSync('/run/ts-cloud-dashboard-routes-changed', '')
573
- `)}`,"if [ -e /run/ts-cloud-dashboard-routes-changed ]; then"," systemctl restart rpx-gateway.service"," rm -f /run/ts-cloud-dashboard-routes-changed","fi"]:[];return["set -euo pipefail",`TS_CLOUD_DASHBOARD_PREFIX=${cr(s)}`,`TS_CLOUD_DASHBOARD_SERVER_OWNER=${r?"1":"0"}`,`TS_CLOUD_DASHBOARD_DESIRED=${cr(` ${o.join(" ")} `)}`,"for TS_CLOUD_UNIT_FILE in /etc/systemd/system/*.service; do",' [ -e "$TS_CLOUD_UNIT_FILE" ] || continue',' TS_CLOUD_UNIT=$(basename "$TS_CLOUD_UNIT_FILE")',' case "$TS_CLOUD_UNIT" in'," *-dashboard-*.service)",' if [ "$TS_CLOUD_DASHBOARD_SERVER_OWNER" != 1 ]; then',' case "$TS_CLOUD_UNIT" in "$TS_CLOUD_DASHBOARD_PREFIX"*.service) ;; *) continue ;; esac'," fi",' case "$TS_CLOUD_DASHBOARD_DESIRED" in',' *" $TS_CLOUD_UNIT "*) ;;'," *)",' systemctl disable --now "$TS_CLOUD_UNIT" 2>/dev/null || true',' rm -f "$TS_CLOUD_UNIT_FILE"'," ;;"," esac"," ;;"," esac","done","systemctl daemon-reload","systemctl reset-failed",...i]}async function Yl(e,t,r,n){let{config:s,environment:o}=t,i=s.project.slug,a=T(s,o),c=await e.findComputeTargets({slug:i,environment:o,role:"app",stackName:a});if(c.length===0)return!0;let l=await e.runRemoteDeploy({targets:c,commands:Xl(i,r,!s.cloud?.attachTo,r.map((u)=>s.sites?.[u]?.domain).filter((u)=>typeof u==="string")),comment:`ts-cloud reconcile management dashboard ${i}`,tags:{Project:i,Environment:o,Role:"app"}});if(!l.success)return n.error(`Management dashboard reconciliation failed: ${l.error||"unknown error"}`),!1;return!0}async function Jl(e,t,r){let{config:n}=t,s=n.cloud?.attachTo;if(!s||!e.listReachableResources)return;let o;try{o=await e.listReachableResources()}catch(c){r.warn(`Could not determine this credential's reach: ${c instanceof Error?c.message:String(c)}`);return}let i=Zo(o,{ownerSlug:s,selfSlug:n.project.slug}),a=En(i)>0;for(let c of ei(i,{ownerSlug:s,selfSlug:n.project.slug}))if(a)r.warn(c);else r.info(c)}async function Ql(e,t,r){let{config:n,environment:s}=t,o=n.cloud?.attachTo;if(!o)return!0;let i=wi(n.infrastructure?.compute?.managedServices);if(i.length===0)return!0;let a=n.project.slug,c=T(n,s),l=await e.findComputeTargets({slug:a,environment:s,role:"app",stackName:c});if(l.length===0)return!0;let u=await e.runRemoteDeploy({targets:l,commands:$i(i),comment:`ts-cloud preflight managed services ${a}`,tags:{Project:a,Environment:s,Role:"app"}});if(!u.success)return r.warn(`Could not check '${o}' for the declared services: ${u.error||"unknown error"}`),!0;let d=new Set;for(let m of u.perInstance)for(let h of Ti(m.output,i))d.add(h);if(d.size===0)return!0;return r.error(Ci([...d],o,l[0]?.publicIp)),!1}async function Zl(e,t,r){let{config:n,environment:s}=t;if(!n.cloud?.attachTo)return!0;let o=n.infrastructure?.compute,i=w(n),a=Tt(i,o?.managedServices??{});if(a.length===0)return!0;let c=n.project.slug,l=T(n,s),u=await e.findComputeTargets({slug:c,environment:s,role:"app",stackName:l});if(u.length===0)return!0;r.step(`Ensuring database '${i?.name}' + role exist on the shared box...`);let d=await e.runRemoteDeploy({targets:u,commands:a,comment:`ts-cloud ensure database ${c}/${i?.name}`,tags:{Project:c,Environment:s,Role:"app"}});if(!d.success)return r.error(`Ensuring database '${i?.name}' failed: ${d.error||"unknown error"}`),!1;return r.success(`Database '${i?.name}' is ready on ${d.instanceCount} target(s)`),!0}async function ao(e){let{config:t,environment:r,driver:n,sha:s,runtime:o,tarballForSite:i,logger:a=lr}=e,c=t.project.slug,l=e.cwd??process.cwd(),u=e.managementDashboard!==!1,d=Jt(t);if(u)ko(t,{cwd:l,logger:{info:a.info,warn:a.warn}});let m=!u||d?[]:No(t);if(u&&e.rpxConfig&&e.rpxConfig!==t&&!Jt(e.rpxConfig))ko(e.rpxConfig,{cwd:l,logger:{info:()=>{},warn:()=>{}}});if(u&&!await Yl(n,e,No(t),a))return!1;let h=null,f=new Map;if(m.length>0)if(h=$s(t.sites?.[m[0]],{cwd:l,slug:c,sha:s,siteName:m[0],logger:{info:a.info,warn:a.warn}}),!h){a.warn("Management dashboard: no artifact available — skipping dashboard site(s) for this deploy.");for(let D of m)if(t.sites)delete t.sites[D]}else for(let D of m){if(D===m[0]){f.set(D,h);continue}try{let R=Vl(Gl(),`${c}-${D}-${s}.tar.gz`);Wl(h,R),f.set(D,R)}catch{f.set(D,h)}}let S=t.sites||{},k=Object.entries(S).filter(([D,R])=>{if(!R)return!1;let z=I(R);if(z==="bucket")return a.warn(`Site '${D}' targets a bucket — skipping (handled by the static-site path, not compute).`),!1;if(z==="redirect")return!1;if(z==="proxy")return!1;return!0});if(k.length===0)return Hn(e);if(await Jl(n,e,a),!await Ql(n,e,a))return!1;if(!await Zl(n,e,a))return!1;let E=(D)=>f.get(D)??i(D);for(let[D,R]of k){a.step(`Deploying site: ${D}`);let z=Di(R)?void 0:E(D),x=await Ii(n,{config:t,environment:r,siteName:D,site:R,slug:c,sha:s,runtime:o,localTarballPath:z},a);if(!x.success){if(a.error(`Deploy of '${D}' failed: ${x.error||"unknown error"}`),x.perInstance)for(let H of x.perInstance)a.error(` ${H.instanceId}: ${H.status}${H.error?` — ${H.error}`:""}`);return!1}if(a.success(`Deployed ${c}/${D}@${s} to ${x.instanceCount} target(s)`),x.perInstance)for(let H of x.perInstance)a.info(` ✓ ${H.instanceId}: ${H.status}`)}if(!await Hn(e))return!1;return!0}async function eu(e,t,r){let n=ro(e);if(!n||n.tls==="off")return n;let s=await Fe(t,r),o=s?.provider==="ssh"?s.lanIp:void 0;return o?{...n,ip:o}:n}async function Hn(e){let{config:t,environment:r,driver:n,logger:s=lr}=e,o=e.rpxConfig??t,i=le(o,{environment:r})??le(t,{environment:r});if(i?.engine!=="rpx")return!0;let a=o.sites||{},c=t.project.slug,l=T(t,r),u=await n.findComputeTargets({slug:c,environment:r,role:"lb",stackName:l});if(u.length>0){let O=(await n.findComputeTargets({slug:c,environment:r,role:"app",stackName:l})).map((z)=>({privateIp:z.privateIp,publicIp:z.publicIp})),D=qe(a,O,{proxy:i,slug:c});if(D.proxies.length===0)return s.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;s.step(`Reloading the load balancer's rpx gateway with ${D.proxies.length} route(s)...`);let R=await n.runRemoteDeploy({targets:u,commands:Ke({config:D,slug:c,preserveManagementDashboardRoutes:e.managementDashboard===!1}),comment:`ts-cloud rpx gateway reload ${c}`,tags:{Project:c,Environment:r,Role:"lb"}});if(!R.success)return s.error(`rpx gateway reload failed: ${R.error||"unknown error"}`),!1;return s.success(`rpx gateway reloaded on ${R.instanceCount} load balancer(s)`),!0}let d=await eu(t,l,e.cwd),m=Te(a,{proxy:i,slug:c,lan:d,mail:ne(t,{environment:r})});if(m.proxies.length===0)return s.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;let h=await n.findComputeTargets({slug:c,environment:r,role:"app",stackName:l});if(h.length===0)return s.warn("rpx gateway: no compute targets found — skipping gateway reload."),!0;let f=Boolean(t.cloud?.attachTo);if(f&&(i.version||i.tlsxVersion))s.warn(`rpx gateway: ignoring proxy.version/tlsxVersion — this project attaches to '${t.cloud?.attachTo}' and the gateway belongs to that box's owner.`);s.step(`Reloading rpx gateway with ${m.proxies.length} route(s)...`);let S=ve({proxy:i,config:m,slug:c,tenant:f,profile:Qn(t),preserveManagementDashboardRoutes:e.managementDashboard===!1}),k=await n.runRemoteDeploy({targets:h,commands:S,comment:`ts-cloud rpx gateway reload ${c}`,tags:{Project:c,Environment:r,Role:"app"}});if(!k.success)return s.error(`rpx gateway reload failed: ${k.error||"unknown error"}`),!1;return s.success(`rpx gateway reloaded on ${k.instanceCount} target(s)`),!0}async function co(e){let{config:t,environment:r,driver:n,logger:s=lr}=e,o=e.rpxConfig??t,i=le(o,{environment:r})??le(t,{environment:r});if(i?.engine!=="rpx"||!i.onDemandTls)return!0;let a=Te(o.sites||{},{proxy:i,slug:t.project.slug,mail:ne(t,{environment:r})});if(a.proxies.length===0)return!0;let c=Or(a);if(c.length===0)return!0;let l=t.project.slug,u=T(t,r),d="lb",m=await n.findComputeTargets({slug:l,environment:r,role:d,stackName:u});if(m.length===0)d="app",m=await n.findComputeTargets({slug:l,environment:r,role:d,stackName:u});if(m.length===0)return s.warn("rpx TLS: no gateway targets found - skipping certificate issuance."),!0;s.step("Issuing rpx TLS certificates after DNS reconciliation...");let h=c.map((S)=>`test -s ${ql(`${a.productionCerts.certsDir}/${S}.crt`)}`).join(" && "),f=await n.runRemoteDeploy({targets:m,commands:[`systemctl start ${Er(l)}`,h],comment:`ts-cloud rpx TLS issuance ${l}`,tags:{Project:l,Environment:r,Role:d}});if(!f.success)return s.error(`rpx TLS issuance failed: ${f.error||"unknown error"}`),!1;return s.success(`rpx TLS certificates reconciled on ${f.instanceCount} gateway target(s)`),!0}import{existsSync as cu,readFileSync as lu}from"node:fs";import{createHash as tu}from"node:crypto";function fc(e){let t=Un(e.name),r=Mn(e.publicKey),n=nu([...e.existingKeys??[],{name:t,publicKey:r}]);return Li(e.configText,n)}function hc(e){let t=Un(e.name),r=(e.existingKeys??[]).filter((n)=>n.name!==t);if((e.existingKeys??[]).length===r.length)throw Error(`SSH key '${t}' does not exist in compute.sshKeys`);return Li(e.configText,r)}function $t(e=[]){return e.map((t)=>({name:t.name,publicKey:t.publicKey,type:su(t.publicKey),fingerprint:ou(t.publicKey),added:"configured"}))}function Li(e,t){let r=iu(e,"compute"),n=ru(t),s=au(e,r.start,r.end,"sshKeys");if(s){let c=s.propertyStart;while(c>0&&e[c-1]!==`
573
+ `)}`,"if [ -e /run/ts-cloud-dashboard-routes-changed ]; then"," systemctl restart rpx-gateway.service"," rm -f /run/ts-cloud-dashboard-routes-changed","fi"]:[];return["set -euo pipefail",`TS_CLOUD_DASHBOARD_PREFIX=${cr(s)}`,`TS_CLOUD_DASHBOARD_SERVER_OWNER=${r?"1":"0"}`,`TS_CLOUD_DASHBOARD_DESIRED=${cr(` ${o.join(" ")} `)}`,"for TS_CLOUD_UNIT_FILE in /etc/systemd/system/*.service; do",' [ -e "$TS_CLOUD_UNIT_FILE" ] || continue',' TS_CLOUD_UNIT=$(basename "$TS_CLOUD_UNIT_FILE")',' case "$TS_CLOUD_UNIT" in'," *-dashboard-*.service)",' if [ "$TS_CLOUD_DASHBOARD_SERVER_OWNER" != 1 ]; then',' case "$TS_CLOUD_UNIT" in "$TS_CLOUD_DASHBOARD_PREFIX"*.service) ;; *) continue ;; esac'," fi",' case "$TS_CLOUD_DASHBOARD_DESIRED" in',' *" $TS_CLOUD_UNIT "*) ;;'," *)",' systemctl disable --now "$TS_CLOUD_UNIT" 2>/dev/null || true',' rm -f "$TS_CLOUD_UNIT_FILE"'," ;;"," esac"," ;;"," esac","done","systemctl daemon-reload","systemctl reset-failed",...i]}async function Yl(e,t,r,n){let{config:s,environment:o}=t,i=s.project.slug,a=T(s,o),c=await e.findComputeTargets({slug:i,environment:o,role:"app",stackName:a});if(c.length===0)return!0;let l=await e.runRemoteDeploy({targets:c,commands:Xl(i,r,!s.cloud?.attachTo,r.map((u)=>s.sites?.[u]?.domain).filter((u)=>typeof u==="string")),comment:`ts-cloud reconcile management dashboard ${i}`,tags:{Project:i,Environment:o,Role:"app"}});if(!l.success)return n.error(`Management dashboard reconciliation failed: ${l.error||"unknown error"}`),!1;return!0}async function Jl(e,t,r){let{config:n}=t,s=n.cloud?.attachTo;if(!s||!e.listReachableResources)return;let o;try{o=await e.listReachableResources()}catch(c){r.warn(`Could not determine this credential's reach: ${c instanceof Error?c.message:String(c)}`);return}let i=Zo(o,{ownerSlug:s,selfSlug:n.project.slug}),a=En(i)>0;for(let c of ei(i,{ownerSlug:s,selfSlug:n.project.slug}))if(a)r.warn(c);else r.info(c)}async function Ql(e,t,r){let{config:n,environment:s}=t,o=n.cloud?.attachTo;if(!o)return!0;let i=wi(n.infrastructure?.compute?.managedServices);if(i.length===0)return!0;let a=n.project.slug,c=T(n,s),l=await e.findComputeTargets({slug:a,environment:s,role:"app",stackName:c});if(l.length===0)return!0;let u=await e.runRemoteDeploy({targets:l,commands:$i(i),comment:`ts-cloud preflight managed services ${a}`,tags:{Project:a,Environment:s,Role:"app"}});if(!u.success)return r.warn(`Could not check '${o}' for the declared services: ${u.error||"unknown error"}`),!0;let d=new Set;for(let m of u.perInstance)for(let h of Ti(m.output,i))d.add(h);if(d.size===0)return!0;return r.error(Ci([...d],o,l[0]?.publicIp)),!1}async function Zl(e,t,r){let{config:n,environment:s}=t;if(!n.cloud?.attachTo)return!0;let o=n.infrastructure?.compute,i=A(n),a=Tt(i,o?.managedServices??{});if(a.length===0)return!0;let c=n.project.slug,l=T(n,s),u=await e.findComputeTargets({slug:c,environment:s,role:"app",stackName:l});if(u.length===0)return!0;r.step(`Ensuring database '${i?.name}' + role exist on the shared box...`);let d=await e.runRemoteDeploy({targets:u,commands:a,comment:`ts-cloud ensure database ${c}/${i?.name}`,tags:{Project:c,Environment:s,Role:"app"}});if(!d.success)return r.error(`Ensuring database '${i?.name}' failed: ${d.error||"unknown error"}`),!1;return r.success(`Database '${i?.name}' is ready on ${d.instanceCount} target(s)`),!0}async function ao(e){let{config:t,environment:r,driver:n,sha:s,runtime:o,tarballForSite:i,logger:a=lr}=e,c=t.project.slug,l=e.cwd??process.cwd(),u=e.managementDashboard!==!1,d=Jt(t);if(u)ko(t,{cwd:l,logger:{info:a.info,warn:a.warn}});let m=!u||d?[]:No(t);if(u&&e.rpxConfig&&e.rpxConfig!==t&&!Jt(e.rpxConfig))ko(e.rpxConfig,{cwd:l,logger:{info:()=>{},warn:()=>{}}});if(u&&!await Yl(n,e,No(t),a))return!1;let h=null,f=new Map;if(m.length>0)if(h=$s(t.sites?.[m[0]],{cwd:l,slug:c,sha:s,siteName:m[0],logger:{info:a.info,warn:a.warn}}),!h){a.warn("Management dashboard: no artifact available — skipping dashboard site(s) for this deploy.");for(let I of m)if(t.sites)delete t.sites[I]}else for(let I of m){if(I===m[0]){f.set(I,h);continue}try{let E=Vl(Gl(),`${c}-${I}-${s}.tar.gz`);Wl(h,E),f.set(I,E)}catch{f.set(I,h)}}let S=t.sites||{},k=Object.entries(S).filter(([I,E])=>{if(!E)return!1;let z=w(E);if(z==="bucket")return a.warn(`Site '${I}' targets a bucket — skipping (handled by the static-site path, not compute).`),!1;if(z==="redirect")return!1;if(z==="proxy")return!1;return!0});if(k.length===0)return Hn(e);if(await Jl(n,e,a),!await Ql(n,e,a))return!1;if(!await Zl(n,e,a))return!1;let O=(I)=>f.get(I)??i(I);for(let[I,E]of k){a.step(`Deploying site: ${I}`);let z=Di(E)?void 0:O(I),x=await Ii(n,{config:t,environment:r,siteName:I,site:E,slug:c,sha:s,runtime:o,localTarballPath:z},a);if(!x.success){if(a.error(`Deploy of '${I}' failed: ${x.error||"unknown error"}`),x.perInstance)for(let H of x.perInstance)a.error(` ${H.instanceId}: ${H.status}${H.error?` — ${H.error}`:""}`);return!1}if(a.success(`Deployed ${c}/${I}@${s} to ${x.instanceCount} target(s)`),x.perInstance)for(let H of x.perInstance)a.info(` ✓ ${H.instanceId}: ${H.status}`)}if(!await Hn(e))return!1;return!0}async function eu(e,t,r){let n=ro(e);if(!n||n.tls==="off")return n;let s=await Fe(t,r),o=s?.provider==="ssh"?s.lanIp:void 0;return o?{...n,ip:o}:n}async function Hn(e){let{config:t,environment:r,driver:n,logger:s=lr}=e,o=e.rpxConfig??t,i=le(o,{environment:r})??le(t,{environment:r});if(i?.engine!=="rpx")return!0;let a=o.sites||{},c=t.project.slug,l=T(t,r),u=await n.findComputeTargets({slug:c,environment:r,role:"lb",stackName:l});if(u.length>0){let D=(await n.findComputeTargets({slug:c,environment:r,role:"app",stackName:l})).map((z)=>({privateIp:z.privateIp,publicIp:z.publicIp})),I=qe(a,D,{proxy:i,slug:c});if(I.proxies.length===0)return s.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;s.step(`Reloading the load balancer's rpx gateway with ${I.proxies.length} route(s)...`);let E=await n.runRemoteDeploy({targets:u,commands:Ke({config:I,slug:c,preserveManagementDashboardRoutes:e.managementDashboard===!1}),comment:`ts-cloud rpx gateway reload ${c}`,tags:{Project:c,Environment:r,Role:"lb"}});if(!E.success)return s.error(`rpx gateway reload failed: ${E.error||"unknown error"}`),!1;return s.success(`rpx gateway reloaded on ${E.instanceCount} load balancer(s)`),!0}let d=await eu(t,l,e.cwd),m=Te(a,{proxy:i,slug:c,lan:d,mail:ne(t,{environment:r})});if(m.proxies.length===0)return s.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;let h=await n.findComputeTargets({slug:c,environment:r,role:"app",stackName:l});if(h.length===0)return s.warn("rpx gateway: no compute targets found — skipping gateway reload."),!0;let f=Boolean(t.cloud?.attachTo);if(f&&(i.version||i.tlsxVersion))s.warn(`rpx gateway: ignoring proxy.version/tlsxVersion — this project attaches to '${t.cloud?.attachTo}' and the gateway belongs to that box's owner.`);s.step(`Reloading rpx gateway with ${m.proxies.length} route(s)...`);let S=ve({proxy:i,config:m,slug:c,tenant:f,profile:Qn(t),preserveManagementDashboardRoutes:e.managementDashboard===!1}),k=await n.runRemoteDeploy({targets:h,commands:S,comment:`ts-cloud rpx gateway reload ${c}`,tags:{Project:c,Environment:r,Role:"app"}});if(!k.success)return s.error(`rpx gateway reload failed: ${k.error||"unknown error"}`),!1;return s.success(`rpx gateway reloaded on ${k.instanceCount} target(s)`),!0}async function co(e){let{config:t,environment:r,driver:n,logger:s=lr}=e,o=e.rpxConfig??t,i=le(o,{environment:r})??le(t,{environment:r});if(i?.engine!=="rpx"||!i.onDemandTls)return!0;let a=Te(o.sites||{},{proxy:i,slug:t.project.slug,mail:ne(t,{environment:r})});if(a.proxies.length===0)return!0;let c=Or(a);if(c.length===0)return!0;let l=t.project.slug,u=T(t,r),d="lb",m=await n.findComputeTargets({slug:l,environment:r,role:d,stackName:u});if(m.length===0)d="app",m=await n.findComputeTargets({slug:l,environment:r,role:d,stackName:u});if(m.length===0)return s.warn("rpx TLS: no gateway targets found - skipping certificate issuance."),!0;s.step("Issuing rpx TLS certificates after DNS reconciliation...");let h=c.map((S)=>`test -s ${ql(`${a.productionCerts.certsDir}/${S}.crt`)}`).join(" && "),f=await n.runRemoteDeploy({targets:m,commands:[`systemctl start ${Er(l)}`,h],comment:`ts-cloud rpx TLS issuance ${l}`,tags:{Project:l,Environment:r,Role:d}});if(!f.success)return s.error(`rpx TLS issuance failed: ${f.error||"unknown error"}`),!1;return s.success(`rpx TLS certificates reconciled on ${f.instanceCount} gateway target(s)`),!0}import{existsSync as cu,readFileSync as lu}from"node:fs";import{createHash as tu}from"node:crypto";function fc(e){let t=Un(e.name),r=Mn(e.publicKey),n=nu([...e.existingKeys??[],{name:t,publicKey:r}]);return Li(e.configText,n)}function hc(e){let t=Un(e.name),r=(e.existingKeys??[]).filter((n)=>n.name!==t);if((e.existingKeys??[]).length===r.length)throw Error(`SSH key '${t}' does not exist in compute.sshKeys`);return Li(e.configText,r)}function $t(e=[]){return e.map((t)=>({name:t.name,publicKey:t.publicKey,type:su(t.publicKey),fingerprint:ou(t.publicKey),added:"configured"}))}function Li(e,t){let r=iu(e,"compute"),n=ru(t),s=au(e,r.start,r.end,"sshKeys");if(s){let c=s.propertyStart;while(c>0&&e[c-1]!==`
574
574
  `&&/\s/.test(e[c-1]))c--;return`${e.slice(0,c)}${n}${e.slice(s.end+1)}`}let o=e.slice(0,r.end).trimEnd(),i=e.slice(r.end),a=o.endsWith(",")||o.endsWith("{")?"":",";return`${o}${a}
575
575
  ${n},
576
576
  ${i}`}function ru(e){if(e.length===0)return" sshKeys: []";return` sshKeys: [
@@ -733,8 +733,8 @@ $(free -m 2>/dev/null | awk '/^Mem:/{total=$2; used=$3; available=$7; cache=$6}
733
733
  EOF`,'echo "MEMTOTAL=${MEMTOTAL:-0}"','echo "MEMUSED=${MEMUSED:-0}"','echo "MEMAVAILABLE=${MEMAVAILABLE:-0}"','echo "MEMCACHE=${MEMCACHE:-0}"','echo "SWAPTOTAL=${SWAPTOTAL:-0}"','echo "SWAPUSED=${SWAPUSED:-0}"',`read DISKTOTG DISKUSEDG DISKPCT <<EOF
734
734
  $(df -BG -P / 2>/dev/null | awk 'NR==2{gsub("G","",$2); gsub("G","",$3); gsub("%","",$5); print $2, $3, $5}')
735
735
  EOF`,'echo "DISKPCT=${DISKPCT:-0}"','echo "DISKUSEDG=${DISKUSEDG:-0}"','echo "DISKTOTG=${DISKTOTG:-0}"','if [ -r /var/lib/ts-cloud/compute-storage-status.json ]; then echo "STORAGE=$(base64 -w0 /var/lib/ts-cloud/compute-storage-status.json)"; fi','if [ -r /var/lib/ts-cloud/metrics.json ]; then echo "COLLECTOR=$(base64 -w0 /var/lib/ts-cloud/metrics.json)"; fi',`echo "INODEPCT=$(df -Pi / 2>/dev/null | awk 'NR==2{gsub("%","",$5);print $5}')"`,`echo "NETRX=$(awk -F'[: ]+' 'NR>2 && $2!="lo"{sum+=$3} END{print sum+0}' /proc/net/dev 2>/dev/null)"`,`echo "NETTX=$(awk -F'[: ]+' 'NR>2 && $2!="lo"{sum+=$11} END{print sum+0}' /proc/net/dev 2>/dev/null)"`,". /var/lib/ts-cloud/bandwidth-state 2>/dev/null || true",'echo "NETRXRATE=${RX_RATE:-0}"','echo "NETTXRATE=${TX_RATE:-0}"','echo "NETRXTODAY=${DAY_RX:-0}"','echo "NETTXTODAY=${DAY_TX:-0}"','echo "NETRXMONTH=${MONTH_RX:-0}"','echo "NETTXMONTH=${MONTH_TX:-0}"','echo "NETMONTHKEY=${MONTH_KEY:-}"',`echo "PROCESSES=$(ps -e --no-headers 2>/dev/null | awk 'END{print NR+0}')"`,`echo "UPTIME=$(uptime -p 2>/dev/null | sed 's/^up //' || echo unknown)"`,`echo "UPTIME_SECONDS=$(cut -d' ' -f1 /proc/uptime 2>/dev/null || echo 0)"`,'echo "OS=$(. /etc/os-release 2>/dev/null; echo "$PRETTY_NAME")"'];if(e.includeServices!==!1)t.push(`for s in ${uu.join(" ")}; do st=$(systemctl is-active "$s" 2>/dev/null); if [ -n "$st" ] && [ "$st" != "inactive" ] && [ "$st" != "unknown" ]; then mem=$(systemctl show "$s" -p MemoryCurrent --value 2>/dev/null); en=$(systemctl is-enabled "$s" 2>/dev/null); since=$(systemctl show "$s" -p ActiveEnterTimestamp --value 2>/dev/null); echo "SVC=$s=$st=$mem=$en=$since"; fi; done`);if(e.includeSites!==!1)t.push(pu(e.projectFilter));return t.push("true"),t}function mu(e){let t={services:[],discoveredSites:[]};for(let r of e.split(`
736
- `)){let n=r.trim();if(n.startsWith("DISCOVERED_SITE="))try{let s=JSON.parse(Buffer.from(n.slice(16),"base64").toString("utf8"));if(s?.domain&&s?.route)t.discoveredSites.push(s)}catch{}else if(n.startsWith("SVC=")){let[,s,o,i,a,c]=/^SVC=([^=]+)=([^=]+)(?:=([^=]*)(?:=([^=]*)(?:=(.*))?)?)?$/.exec(n)??[];if(s)t.services.push({name:s,status:o,memBytes:Number(i||0),enabled:a||ae,since:c||ae})}else{let s=n.indexOf("=");if(s>0)t[n.slice(0,s)]=n.slice(s+1)}}return t}function Hi(e){let t=e.infrastructure?.compute,r=[];if(t?.webServer==="rpx"||t?.proxy?.engine==="rpx")r.push({name:"rpx-gateway",status:"configured"});else if(t?.webServer==="nginx"||t?.webServer==null)r.push({name:"ts-cloud-nginx",status:"configured"});let n=t?.php?.versions??(t?.runtime==="php"?["8.3"]:[]);for(let i of n)r.push({name:`php${i}-fpm`,status:"configured"});let s=t?.managedServices??{},o=[["mysql","mysql"],["mariadb","mariadb"],["postgres","postgresql"],["redis","redis"],["memcached","memcached"],["meilisearch","meilisearch"]];for(let[i,a]of o)if(s[i])r.push({name:a,status:"configured"});return r}function fu(e){let t=e.infrastructure?.compute?.backups,r=!!t?.enabled,n=t?.schedule??"0 2 * * *";return{enabled:r,schedule:n,destination:r?t?.bucket??"local":"off",retention:r?t?.retentionCount??5:0,last:r?"pending first run":"not configured",size:r?ae:"0 MB"}}function Ui(e){return e.infrastructure?.compute?.provider??e.cloud?.provider??e.provider??"aws"}function gu(e){if(Ui(e)==="hetzner")return ln(e);return e.project.region??"us-east-1"}function hu(e){let t=e.infrastructure?.compute?.monitoring,r=Number(typeof t==="object"?t?.alerts?.bandwidthTb??0:0);return Number.isFinite(r)&&r>0?Math.round(r*1000000000000):0}function Su(e,t){let r=it(T(e,t));if(!cu(r))return null;try{return JSON.parse(lu(r,"utf8"))}catch{return null}}function yu(e){let t=e.sites??{},r=[];for(let[n,s]of Object.entries(t)){let o=s.queues??s.workers;if(Array.isArray(o)){for(let i of o)if(typeof i==="string")r.push({name:`${n}:${i}`,site:n,processes:1,status:"configured"});else if(i?.name)r.push({name:`${n}:${i.name}`,site:n,processes:i.processes??1,status:"configured"})}}return r}function Mi(e){if(!e||e==="")return"/";return e.startsWith("/")?e:`/${e}`}function vu(e){let t=Mi(e.path);if(!e.domain)return{route:"internal"};return{route:t==="/"?e.domain:`${e.domain}${t}`,href:`https://${e.domain}${t==="/"?"":t}`}}function Ni(e,t){let r=I(t);if(r==="redirect")return"redirect";if(r==="proxy")return"proxy";let n=String(t.build??"").toLowerCase(),s=String(t.start??"").toLowerCase();if(e==="main"||s.includes("buddy/src/cli.ts serve"))return"stacks";if(e==="api"||s.includes("/serve/api"))return"api";if(n.includes("buildblog"))return"bunpress blog";if(n.includes("bunpress"))return"bunpress";if(n.includes("site:build")||n.includes("stx"))return"stx static";if(r==="server-static")return t.spa?"spa":"static";if(r==="server-app")return"app";if(r==="server-php")return t.type??"php";return"bucket"}function bu(e){let t=I(e);if(t==="redirect"||t==="proxy")return"—";let r=`${e.start??""} ${e.build??""}`.toLowerCase();if(t==="server-static")return r.includes("bunpress")||r.includes("bun ")||r.includes("bunx ")?"static/bun":"static";if(t==="server-app")return r.includes("bun")?"bun":"node";if(t==="server-php")return`php ${e.php??e.phpVersion??"8.3"}`;return"static"}function wu(e){let t=I(e);if(t==="redirect")return"redirect";if(t==="proxy")return"proxy";if(t==="server-app")return"service";if(t==="server-static")return"server static";if(t==="server-php")return"php release";return"bucket"}function _u(e){let t=new Map;return Object.entries(e.sites??{}).map(([r,n])=>{let s=Mi(n.path),{route:o,href:i}=vu(n),a=n.domain?`${n.domain}${s}`:"",c=a?t.get(a):void 0;if(a&&!c)t.set(a,r);return{name:r,route:o,href:i,domain:n.domain??"internal",path:s,kind:Ni(r,n),type:Ni(r,n),runtime:bu(n),deploy:wu(n),tls:n.domain?n.ssl===!1?"http":"https":"loopback",ssl:n.domain?n.ssl!==!1:!1,status:c?"shadowed":"live",shadowedBy:c,lastDeploy:ae}})}function $u(e,t,r){let n=new Map(e.map((s)=>[String(s.route),{...s,project:r,managedBy:"owner"}]));for(let s of t){let o=n.get(s.route),i=o?.name??`${s.project}:${s.name}`;n.set(s.route,{...o,...s,name:i,kind:o?.kind??s.kind,type:o?.type??s.kind,runtime:o?.runtime??s.runtime,deploy:o?.deploy??s.deploy,root:o?.root??s.root,branch:o?.branch??s.branch,managedBy:s.project===r?"owner":"attached"})}return[...n.values()].sort((s,o)=>{if(s.managedBy!==o.managedBy)return s.managedBy==="owner"?-1:1;return String(s.route).localeCompare(String(o.route))})}function zn(e){return`'${e.replaceAll("'","'\\''")}'`}function zi(e){return e.replace(/[\\&/]/g,"\\$&")}function Tu(e,t){if(e.length===0)return["true"];return["set +e",...e.map((r)=>{let n=zn(`${J(t,r)}/.ts-cloud/deploy-history.log`),s=zi(r);return`TS_CLOUD_HISTORY=${n}; { [ -f "$TS_CLOUD_HISTORY" ] && tail -n 24 "$TS_CLOUD_HISTORY" | sed "s/^/DEPLOY=${s}\\t/"; } || true`}),"true"]}function Fi(e){return[...new Set(Object.values(e.sites??{}).map((t)=>t.domain).filter((t)=>typeof t==="string"&&t.length>0))]}function Cu(e){return["set +e",'if command -v ss >/dev/null 2>&1; then ss -H -lntup 2>/dev/null | while read -r proto _state _recv _send local _peer rest; do [ -n "$proto" ] && [ -n "$local" ] && printf "PORT=%s\\t%s\\t%s\\n" "$proto" "$local" "$rest"; done; fi','if command -v ufw >/dev/null 2>&1; then ufw status numbered 2>/dev/null | sed "s/^/FIREWALL=/"; else echo "FIREWALL=ufw unavailable"; fi','journalctl _COMM=sshd --no-pager -n 30 -o short-iso 2>/dev/null | sed "s/^/AUTH=/" || true',...Fi(e).map((r)=>`TS_CLOUD_DOMAIN=${zn(r)}; TS_CLOUD_EXPIRY=$(echo | timeout 8 openssl s_client -servername "$TS_CLOUD_DOMAIN" -connect "$TS_CLOUD_DOMAIN:443" 2>/dev/null | openssl x509 -noout -enddate 2>/dev/null | cut -d= -f2-); [ -n "$TS_CLOUD_EXPIRY" ] && printf "CERT=%s\\t%s\\n" "$TS_CLOUD_DOMAIN" "$TS_CLOUD_EXPIRY" || printf "CERT=%s\\tunavailable\\n" "$TS_CLOUD_DOMAIN"`),"true"]}function Pu(e){let t=new Map,r=(o,i)=>{if(o&&i&&!t.has(i))t.set(i,{pattern:o,label:i})},n=e.infrastructure?.compute,s=e.project.slug;if(n?.webServer==="rpx"||n?.proxy?.engine==="rpx")r("rpx-gateway","rpx-gateway");else r("nginx","nginx");for(let o of Hi(e))r(o.name,o.name);for(let[o,i]of Object.entries(e.sites??{})){if(I(i)!=="server-app")continue;if(r(`${s}-${o}`,`${s}-${o}`),Array.isArray(i.queues??i.workers)&&(i.queues??i.workers).length)r(`${s}-${o}-queue-*`,`${s}-${o}-queues`);if(Array.isArray(i.daemons)&&i.daemons.length)r(`${s}-${o}-daemon-*`,`${s}-${o}-daemons`)}return[...t.values()]}function xu(e){let t=Pu(e);if(t.length===0)return["true"];return["set +e",...t.map((r)=>{let n=zn(r.pattern),s=zi(r.label);return`journalctl -u ${n} --no-pager -n 150 -o short-iso 2>/dev/null | sed "s/^/LOG=${s}\\t/" || true`}),'[ -f /var/log/ts-cloud-backup.log ] && tail -n 60 /var/log/ts-cloud-backup.log 2>/dev/null | sed "s/^/LOG=backups\\t/" || true',"true"]}function Fn(e){let t=new Date(e);if(Number.isNaN(t.getTime()))return e||ae;let r=Math.max(0,Math.round((Date.now()-t.getTime())/1000));if(r<60)return`${r}s ago`;let n=Math.round(r/60);if(n<60)return`${n}m ago`;let s=Math.round(n/60);if(s<48)return`${s}h ago`;return`${Math.round(s/24)}d ago`}function Bi(e){if(/(?:error|failed|panic|fatal|exception|denied|unhealthy)/i.test(e))return"error";if(/(?:warn|warning|retry|restart|deprecated|timeout)/i.test(e))return"warn";return"info"}function Ru(e){let t=[];for(let r of e.split(`
736
+ `)){let n=r.trim();if(n.startsWith("DISCOVERED_SITE="))try{let s=JSON.parse(Buffer.from(n.slice(16),"base64").toString("utf8"));if(s?.domain&&s?.route)t.discoveredSites.push(s)}catch{}else if(n.startsWith("SVC=")){let[,s,o,i,a,c]=/^SVC=([^=]+)=([^=]+)(?:=([^=]*)(?:=([^=]*)(?:=(.*))?)?)?$/.exec(n)??[];if(s)t.services.push({name:s,status:o,memBytes:Number(i||0),enabled:a||ae,since:c||ae})}else{let s=n.indexOf("=");if(s>0)t[n.slice(0,s)]=n.slice(s+1)}}return t}function Hi(e){let t=e.infrastructure?.compute,r=[];if(t?.webServer==="rpx"||t?.proxy?.engine==="rpx")r.push({name:"rpx-gateway",status:"configured"});else if(t?.webServer==="nginx"||t?.webServer==null)r.push({name:"ts-cloud-nginx",status:"configured"});let n=t?.php?.versions??(t?.runtime==="php"?["8.3"]:[]);for(let i of n)r.push({name:`php${i}-fpm`,status:"configured"});let s=t?.managedServices??{},o=[["mysql","mysql"],["mariadb","mariadb"],["postgres","postgresql"],["redis","redis"],["memcached","memcached"],["meilisearch","meilisearch"]];for(let[i,a]of o)if(s[i])r.push({name:a,status:"configured"});return r}function fu(e){let t=e.infrastructure?.compute?.backups,r=!!t?.enabled,n=t?.schedule??"0 2 * * *";return{enabled:r,schedule:n,destination:r?t?.bucket??"local":"off",retention:r?t?.retentionCount??5:0,last:r?"pending first run":"not configured",size:r?ae:"0 MB"}}function Ui(e){return e.infrastructure?.compute?.provider??e.cloud?.provider??e.provider??"aws"}function gu(e){if(Ui(e)==="hetzner")return ln(e);return e.project.region??"us-east-1"}function hu(e){let t=e.infrastructure?.compute?.monitoring,r=Number(typeof t==="object"?t?.alerts?.bandwidthTb??0:0);return Number.isFinite(r)&&r>0?Math.round(r*1000000000000):0}function Su(e,t){let r=it(T(e,t));if(!cu(r))return null;try{return JSON.parse(lu(r,"utf8"))}catch{return null}}function yu(e){let t=e.sites??{},r=[];for(let[n,s]of Object.entries(t)){let o=s.queues??s.workers;if(Array.isArray(o)){for(let i of o)if(typeof i==="string")r.push({name:`${n}:${i}`,site:n,processes:1,status:"configured"});else if(i?.name)r.push({name:`${n}:${i.name}`,site:n,processes:i.processes??1,status:"configured"})}}return r}function Mi(e){if(!e||e==="")return"/";return e.startsWith("/")?e:`/${e}`}function vu(e){let t=Mi(e.path);if(!e.domain)return{route:"internal"};return{route:t==="/"?e.domain:`${e.domain}${t}`,href:`https://${e.domain}${t==="/"?"":t}`}}function Ni(e,t){let r=w(t);if(r==="redirect")return"redirect";if(r==="proxy")return"proxy";let n=String(t.build??"").toLowerCase(),s=String(t.start??"").toLowerCase();if(e==="main"||s.includes("buddy/src/cli.ts serve"))return"stacks";if(e==="api"||s.includes("/serve/api"))return"api";if(n.includes("buildblog"))return"bunpress blog";if(n.includes("bunpress"))return"bunpress";if(n.includes("site:build")||n.includes("stx"))return"stx static";if(r==="server-static")return t.spa?"spa":"static";if(r==="server-app")return"app";if(r==="server-php")return t.type??"php";return"bucket"}function bu(e){let t=w(e);if(t==="redirect"||t==="proxy")return"—";let r=`${e.start??""} ${e.build??""}`.toLowerCase();if(t==="server-static")return r.includes("bunpress")||r.includes("bun ")||r.includes("bunx ")?"static/bun":"static";if(t==="server-app")return r.includes("bun")?"bun":"node";if(t==="server-php")return`php ${e.php??e.phpVersion??"8.3"}`;return"static"}function wu(e){let t=w(e);if(t==="redirect")return"redirect";if(t==="proxy")return"proxy";if(t==="server-app")return"service";if(t==="server-static")return"server static";if(t==="server-php")return"php release";return"bucket"}function _u(e){let t=new Map;return Object.entries(e.sites??{}).map(([r,n])=>{let s=Mi(n.path),{route:o,href:i}=vu(n),a=n.domain?`${n.domain}${s}`:"",c=a?t.get(a):void 0;if(a&&!c)t.set(a,r);return{name:r,route:o,href:i,domain:n.domain??"internal",path:s,kind:Ni(r,n),type:Ni(r,n),runtime:bu(n),deploy:wu(n),tls:n.domain?n.ssl===!1?"http":"https":"loopback",ssl:n.domain?n.ssl!==!1:!1,status:c?"shadowed":"live",shadowedBy:c,lastDeploy:ae}})}function $u(e,t,r){let n=new Map(e.map((s)=>[String(s.route),{...s,project:r,managedBy:"owner"}]));for(let s of t){let o=n.get(s.route),i=o?.name??`${s.project}:${s.name}`;n.set(s.route,{...o,...s,name:i,kind:o?.kind??s.kind,type:o?.type??s.kind,runtime:o?.runtime??s.runtime,deploy:o?.deploy??s.deploy,root:o?.root??s.root,branch:o?.branch??s.branch,managedBy:s.project===r?"owner":"attached"})}return[...n.values()].sort((s,o)=>{if(s.managedBy!==o.managedBy)return s.managedBy==="owner"?-1:1;return String(s.route).localeCompare(String(o.route))})}function zn(e){return`'${e.replaceAll("'","'\\''")}'`}function zi(e){return e.replace(/[\\&/]/g,"\\$&")}function Tu(e,t){if(e.length===0)return["true"];return["set +e",...e.map((r)=>{let n=zn(`${J(t,r)}/.ts-cloud/deploy-history.log`),s=zi(r);return`TS_CLOUD_HISTORY=${n}; { [ -f "$TS_CLOUD_HISTORY" ] && tail -n 24 "$TS_CLOUD_HISTORY" | sed "s/^/DEPLOY=${s}\\t/"; } || true`}),"true"]}function Fi(e){return[...new Set(Object.values(e.sites??{}).map((t)=>t.domain).filter((t)=>typeof t==="string"&&t.length>0))]}function Cu(e){return["set +e",'if command -v ss >/dev/null 2>&1; then ss -H -lntup 2>/dev/null | while read -r proto _state _recv _send local _peer rest; do [ -n "$proto" ] && [ -n "$local" ] && printf "PORT=%s\\t%s\\t%s\\n" "$proto" "$local" "$rest"; done; fi','if command -v ufw >/dev/null 2>&1; then ufw status numbered 2>/dev/null | sed "s/^/FIREWALL=/"; else echo "FIREWALL=ufw unavailable"; fi','journalctl _COMM=sshd --no-pager -n 30 -o short-iso 2>/dev/null | sed "s/^/AUTH=/" || true',...Fi(e).map((r)=>`TS_CLOUD_DOMAIN=${zn(r)}; TS_CLOUD_EXPIRY=$(echo | timeout 8 openssl s_client -servername "$TS_CLOUD_DOMAIN" -connect "$TS_CLOUD_DOMAIN:443" 2>/dev/null | openssl x509 -noout -enddate 2>/dev/null | cut -d= -f2-); [ -n "$TS_CLOUD_EXPIRY" ] && printf "CERT=%s\\t%s\\n" "$TS_CLOUD_DOMAIN" "$TS_CLOUD_EXPIRY" || printf "CERT=%s\\tunavailable\\n" "$TS_CLOUD_DOMAIN"`),"true"]}function Pu(e){let t=new Map,r=(o,i)=>{if(o&&i&&!t.has(i))t.set(i,{pattern:o,label:i})},n=e.infrastructure?.compute,s=e.project.slug;if(n?.webServer==="rpx"||n?.proxy?.engine==="rpx")r("rpx-gateway","rpx-gateway");else r("nginx","nginx");for(let o of Hi(e))r(o.name,o.name);for(let[o,i]of Object.entries(e.sites??{})){if(w(i)!=="server-app")continue;if(r(`${s}-${o}`,`${s}-${o}`),Array.isArray(i.queues??i.workers)&&(i.queues??i.workers).length)r(`${s}-${o}-queue-*`,`${s}-${o}-queues`);if(Array.isArray(i.daemons)&&i.daemons.length)r(`${s}-${o}-daemon-*`,`${s}-${o}-daemons`)}return[...t.values()]}function xu(e){let t=Pu(e);if(t.length===0)return["true"];return["set +e",...t.map((r)=>{let n=zn(r.pattern),s=zi(r.label);return`journalctl -u ${n} --no-pager -n 150 -o short-iso 2>/dev/null | sed "s/^/LOG=${s}\\t/" || true`}),'[ -f /var/log/ts-cloud-backup.log ] && tail -n 60 /var/log/ts-cloud-backup.log 2>/dev/null | sed "s/^/LOG=backups\\t/" || true',"true"]}function Fn(e){let t=new Date(e);if(Number.isNaN(t.getTime()))return e||ae;let r=Math.max(0,Math.round((Date.now()-t.getTime())/1000));if(r<60)return`${r}s ago`;let n=Math.round(r/60);if(n<60)return`${n}m ago`;let s=Math.round(n/60);if(s<48)return`${s}h ago`;return`${Math.round(s/24)}d ago`}function Bi(e){if(/(?:error|failed|panic|fatal|exception|denied|unhealthy)/i.test(e))return"error";if(/(?:warn|warning|retry|restart|deprecated|timeout)/i.test(e))return"warn";return"info"}function Ru(e){let t=[];for(let r of e.split(`
737
737
  `)){let n=r.trim();if(!n.startsWith("LOG="))continue;let s=n.indexOf("\t");if(s<0)continue;let o=n.slice(4,s),i=n.slice(s+1),a=/^(\d{4}-\d{2}-\d{2}T[^\s]+)\s+(\S+)\s+(.*)$/.exec(i),c=a?.[1]??"",l=a?.[2]??"",u=(a?.[3]??i).trim();if(!u)continue;t.push({source:o,timestamp:c,when:c?Fn(c):ae,host:l,message:u,level:Bi(u)})}return t.sort((r,n)=>String(n.timestamp).localeCompare(String(r.timestamp))).slice(0,600)}function Ki(e){if(/^(?:127\.|localhost:|\[?::1\]?)/.test(e))return"loopback";if(/^(?:10\.|192\.168\.|172\.(?:1[6-9]|2\d|3[01])\.|169\.254\.|\[?f[cd][0-9a-f:])/i.test(e))return"private";return"public"}function Eu(e){if(Ki(e)!=="public")return"ok";if(/:(?:22|80|443)$/.test(e)||/^\*:(?:22|80|443)$/.test(e))return"ok";return"warn"}function Ou(e){if(e==null)return"warn";if(e<8)return"bad";if(e<30)return"warn";return"ok"}function Du(e){let t=[],r=[],n=[],s=[];for(let a of e.split(`
738
738
  `)){let c=a.trim();if(c.startsWith("PORT=")){let[l="",u="",d=""]=c.slice(5).split("\t");if(l&&u)t.push({proto:l,listen:u,processName:d||ae,exposure:Ki(u),tone:Eu(u)})}else if(c.startsWith("FIREWALL=")){let l=c.slice(9).trim();if(l)r.push(l)}else if(c.startsWith("AUTH=")){let l=c.slice(5),u=/^(\d{4}-\d{2}-\d{2}T[^\s]+)\s+(\S+)\s+(.*)$/.exec(l),d=(u?.[3]??l).trim();if(d)n.push({timestamp:u?.[1]??"",when:u?.[1]?Fn(u[1]):ae,host:u?.[2]??"",message:d,level:Bi(d)})}else if(c.startsWith("CERT=")){let[l="",u=""]=c.slice(5).split("\t");if(!l)continue;let d=new Date(u),m=Number.isNaN(d.getTime())?null:Math.ceil((d.getTime()-Date.now())/86400000);s.push({domain:l,expires:Number.isNaN(d.getTime())?u||ae:d.toISOString().slice(0,10),daysRemaining:m,status:Ou(m)})}}let o=r.some((a)=>/Status:\s*active/i.test(a)),i=r.some((a)=>/unavailable/i.test(a));return{ports:t.slice(0,80),firewall:{status:o?"active":i?"unavailable":"inactive",summary:o?"ufw active":i?"ufw unavailable":"ufw inactive or not configured",rules:r.filter((a)=>a&&!/^Status:/i.test(a)).slice(0,60)},tlsCertificates:s,authEvents:n.sort((a,c)=>String(c.timestamp).localeCompare(String(a.timestamp))).slice(0,30)}}function Bn(e){let r=e.infrastructure?.compute?.firewall??{},n=[...new Set([22,80,443,...r.allowedPorts??[]])],s=Fi(e);return{ports:n.map((o)=>({proto:"tcp",listen:`0.0.0.0:${o}`,processName:"configured firewall",exposure:"public",tone:[22,80,443].includes(Number(o))?"ok":"warn"})),firewall:{status:r.enabled===!1?"disabled":"configured",summary:r.enabled===!1?"host firewall disabled in config":"host firewall configured declaratively",rules:n.map((o)=>`ALLOW ${o}/tcp`)},tlsCertificates:s.map((o)=>({domain:o,expires:ae,daysRemaining:null,status:"warn"})),authEvents:[]}}function ji(e,t){let r=t.security??Bn(e),n=!!t._serverReachable&&!t.metricsUnavailable,s=t.sites??[],o=s.filter((l)=>l.status==="shadowed"),i=(t.services??[]).filter((l)=>["failed","stopped"].includes(l.status)),a=(r.tlsCertificates??[]).filter((l)=>l.status!=="ok"),c=t.sshKeys??[];return[{name:"Live server probe",status:n?"pass":"warn",detail:n?"Metrics and remote checks are coming from the compute box.":"The dashboard is rendering config/state data until the box probe succeeds."},{name:"Managed services",status:i.length?"fail":"pass",detail:i.length?`${i.length} service(s) need attention.`:`${(t.services??[]).length} service(s) reported healthy or configured.`},{name:"Route conflicts",status:o.length?"warn":"pass",detail:o.length?`${o.map((l)=>l.name).join(", ")} is shadowed by an earlier route.`:`${s.length} site route(s) are unshadowed.`},{name:"SSH access",status:c.length?"pass":"warn",detail:c.length?`${c.length} declarative authorized key(s) configured.`:"No declarative SSH keys are configured."},{name:"Firewall",status:["active","configured"].includes(r.firewall?.status)?"pass":"warn",detail:r.firewall?.summary??"Firewall status unavailable."},{name:"TLS certificates",status:a.length?"warn":"pass",detail:a.length?`${a.length} certificate(s) need renewal visibility.`:`${(r.tlsCertificates??[]).length} certificate(s) look healthy.`}]}function Wi(e){let t=[];for(let r of e.serverDeploymentsDetail??e.serverDeployments??[])t.push({type:"deploy",tone:r.status==="failed"?"bad":"ok",title:`${r.site} deployed ${r.sha}`,detail:`${r.branch} · ${r.status}`,when:r.when,timestamp:r.timestamp});for(let r of e.serverLogs??[])if(r.level==="error"||r.level==="warn")t.push({type:"log",tone:r.level==="error"?"bad":"warn",title:`${r.source} ${r.level}`,detail:r.message,when:r.when,timestamp:r.timestamp});for(let r of e.sshKeys??[])t.push({type:"ssh",tone:"ok",title:`${r.name} authorized`,detail:r.fingerprint,when:r.added??ae,timestamp:""});return t.sort((r,n)=>String(n.timestamp).localeCompare(String(r.timestamp))).slice(0,80)}function Iu(e,t={}){let r=[];for(let n of e.split(`
739
- `)){let s=n.trim();if(!s.startsWith("DEPLOY="))continue;let o=s.split("\t"),i=o[0]?.replace(/^DEPLOY=/,"")??"",[a,c,l,u,d]=o.slice(1);if(!i||!a||!c)continue;let m=t[i]??{},h=I(m),f=(l||c).slice(0,7);r.push({sha:f,release:c,commit:l||c,site:i,branch:m.branch??(h==="server-static"?"build artifact":"main"),status:u||"unknown",when:Fn(a),timestamp:a,took:"-",by:"ts-cloud",rc:d?.replace(/^rc=/,"")??"",steps:h==="server-static"?["upload artifact","publish static files"]:["upload artifact","restart service"]})}return r.sort((n,s)=>String(s.timestamp).localeCompare(String(n.timestamp)))}function Au(e,t){let r=Su(e,t),n=Hi(e),s=_u(e),o=Math.max(1,Number(e.infrastructure?.compute?.disk?.size??1)),i={server:{name:r?.serverName??`${e.project.slug}-${t}-app`,provider:r?.provider??Ui(e),region:gu(e),ip:r?.publicIp??ae,os:"Linux",uptime:ae,probeStatus:"unavailable"},systemMetrics:{load:0,load5:0,load15:0,cpuUsedPct:0,cpus:Math.max(1,Number(e.infrastructure?.compute?.instances??1)),memUsedMb:0,memTotalMb:0,memAvailableMb:0,memCacheMb:0,swapUsedMb:0,swapTotalMb:0,diskUsedPct:0,diskUsedGb:0,diskTotalGb:o,inodeUsedPct:0,networkRxBytes:0,networkTxBytes:0,networkRxBytesPerSec:0,networkTxBytesPerSec:0,networkRxBytesToday:0,networkTxBytesToday:0,networkRxBytesMonth:0,networkTxBytesMonth:0,networkMonthKey:"",processes:0,uptimeSeconds:0},metricsUnavailable:!0,bandwidthBudgetBytes:hu(e),services:n,servicesDetail:n.map((a)=>({...a,since:ae,memMb:0,auto:!0})),backup:fu(e),backupHistory:[],workers:yu(e),serverScheduler:{enabled:!1,lastRun:"not configured"},serverDeployments:[],serverDeploymentsDetail:[],deploymentsEmptyReason:"No deployment history has been recorded yet. Future server deploys will write /var/www/<site>/.ts-cloud/deploy-history.log.",serverLogs:[],serverLogsEmptyReason:"Live server logs are unavailable until the dashboard can reach the compute box.",security:Bn(e),securityEmptyReason:"Live security checks are unavailable until the dashboard can reach the compute box.",sites:s,sitesDetail:s.map((a)=>{let c=e.sites?.[a.name]??{},l=I(c);return{...a,root:l==="server-static"?J(e.project.slug,a.name):`${J(e.project.slug,a.name)}/current`,branch:l==="server-static"?"build artifact":"main",build:c.build,php:c.php??c.phpVersion,aliases:Array.isArray(c.aliases)?c.aliases:[],redirects:c.redirects&&typeof c.redirects==="object"?c.redirects:{},envKeys:Object.keys(c.env??c.environment??{})}}),siteHealth:[],sshKeys:$t(e.infrastructure?.compute?.sshKeys??[]),_serverReachable:!1,_metricsStatus:"unavailable"};return i.diagnostics=ji(e,i),i.activity=Wi(i),i.topology=an(i,{project:e.project.name,environment:t}),i}async function hi(e,t,r={}){if(!e.infrastructure?.compute)return null;let n=null;try{n=_({config:e})}catch{n=null}let s=null,o=0,i=[];if(n)try{if(i=await n.findComputeTargets({slug:e.project.slug,environment:t,role:"app"}),o=i.length,i.length){let d=(await n.runRemoteDeploy({targets:[i[0]],commands:du({includeServices:!r.telemetryOnly,includeSites:r.includeSiteHealth!==!1,projectFilter:e.cloud?.attachTo?e.project.slug:void 0}),comment:`ts-cloud dashboard:build ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output;if(d)s=mu(d)}}catch{}let a=Au(e,t),c=(u,d=0)=>{let m=Number(u);return Number.isFinite(m)?m:d};if(a.server.os=s?.OS||a.server.os,a.server.uptime=s?.UPTIME||a.server.uptime,s){a.server.probeStatus="live",a.metricsUnavailable=!1,a._metricsStatus="live";try{a.storage=JSON.parse(Buffer.from(s.STORAGE||"","base64").toString("utf8"))}catch{a.storage=null}let u=[];try{u=JSON.parse(Buffer.from(s.COLLECTOR||"","base64").toString("utf8")).disks??[]}catch{}if(a.systemMetrics={disks:u,load:c(s.LOAD),load5:c(s.LOAD5),load15:c(s.LOAD15),cpuUsedPct:c(s.CPUUSED),cpus:c(s.CPUS,1),memUsedMb:c(s.MEMUSED),memTotalMb:c(s.MEMTOTAL,1),memAvailableMb:c(s.MEMAVAILABLE),memCacheMb:c(s.MEMCACHE),swapUsedMb:c(s.SWAPUSED),swapTotalMb:c(s.SWAPTOTAL),diskUsedPct:c(s.DISKPCT),diskUsedGb:c(s.DISKUSEDG),diskTotalGb:c(s.DISKTOTG,1),inodeUsedPct:c(s.INODEPCT),networkRxBytes:c(s.NETRX),networkTxBytes:c(s.NETTX),networkRxBytesPerSec:c(s.NETRXRATE),networkTxBytesPerSec:c(s.NETTXRATE),networkRxBytesToday:c(s.NETRXTODAY),networkTxBytesToday:c(s.NETTXTODAY),networkRxBytesMonth:c(s.NETRXMONTH),networkTxBytesMonth:c(s.NETTXMONTH),networkMonthKey:s.NETMONTHKEY||"",processes:c(s.PROCESSES),uptimeSeconds:c(s.UPTIME_SECONDS)},s.services.length){let d=[...new Map(s.services.map((m)=>[m.name,m])).values()];a.services=d.map((m)=>({name:m.name,status:m.status==="active"?"running":m.status})),a.servicesDetail=d.map((m)=>({name:m.name,status:m.status==="active"?"running":m.status,since:m.since&&m.since!==ae?m.since:a.server.uptime,memMb:Math.max(0,Math.round(Number(m.memBytes??0)/1024/1024)),auto:m.enabled?!["disabled","static","masked"].includes(m.enabled):!0}))}if(s.discoveredSites.length)a.sitesDetail=$u(a.sitesDetail,s.discoveredSites,e.project.slug),a.sites=a.sitesDetail.map((d)=>({name:d.name,project:d.project,managedBy:d.managedBy,route:d.route,href:d.href,domain:d.domain,path:d.path,kind:d.kind,type:d.type,runtime:d.runtime,deploy:d.deploy,tls:d.tls,status:d.status,httpStatus:d.httpStatus,responseMs:d.responseMs,tlsDaysRemaining:d.tlsDaysRemaining,checkedAt:d.checkedAt})),a.siteHealth=a.sitesDetail.map((d)=>({name:d.name,project:d.project,route:d.route,status:d.status,httpStatus:d.httpStatus,responseMs:d.responseMs,tlsDaysRemaining:d.tlsDaysRemaining,checkedAt:d.checkedAt}))}if(n&&i.length&&!r.telemetryOnly)await Promise.all([(async()=>{try{let u=Object.keys(e.sites??{}),m=(await n.runRemoteDeploy({targets:[i[0]],commands:Tu(u,e.project.slug),comment:`ts-cloud dashboard:deploy-history ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",h=Iu(m,e.sites);a.serverDeployments=h.slice(0,5),a.serverDeploymentsDetail=h.slice(0,50),a.deploymentsEmptyReason=h.length?void 0:"No deployment history was found on the server yet. Deploy again to populate this timeline."}catch{a.deploymentsEmptyReason="Deployment history could not be read from the server."}})(),(async()=>{try{let d=(await n.runRemoteDeploy({targets:[i[0]],commands:xu(e),comment:`ts-cloud dashboard:server-logs ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",m=Ru(d);a.serverLogs=m,a.serverLogsEmptyReason=m.length?void 0:"No recent journal entries were found for the managed server units."}catch{a.serverLogsEmptyReason="Server logs could not be read from the box."}})(),(async()=>{try{let d=(await n.runRemoteDeploy({targets:[i[0]],commands:Cu(e),comment:`ts-cloud dashboard:security ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",m=Du(d),h=Bn(e);if(!m.ports.length)m.ports=h.ports;if(!m.tlsCertificates.length)m.tlsCertificates=h.tlsCertificates;a.security=m,a.securityEmptyReason=void 0}catch{a.securityEmptyReason="Server security checks could not be read from the box."}})()]);else if(n&&o===0)a.deploymentsEmptyReason="No app server target was found for this environment.";let l=e.infrastructure?.compute?.sshKeys??e.infrastructure?.ssh?.keys??e.infrastructure?.sshKeys;if(Array.isArray(l)&&l.length)a.sshKeys=$t(l);return a._serverReachable=o>0&&!!s,a.diagnostics=ji(e,a),a.activity=Wi(a),a.topology=an(a,{project:e.project.name,environment:t}),a}
739
+ `)){let s=n.trim();if(!s.startsWith("DEPLOY="))continue;let o=s.split("\t"),i=o[0]?.replace(/^DEPLOY=/,"")??"",[a,c,l,u,d]=o.slice(1);if(!i||!a||!c)continue;let m=t[i]??{},h=w(m),f=(l||c).slice(0,7);r.push({sha:f,release:c,commit:l||c,site:i,branch:m.branch??(h==="server-static"?"build artifact":"main"),status:u||"unknown",when:Fn(a),timestamp:a,took:"-",by:"ts-cloud",rc:d?.replace(/^rc=/,"")??"",steps:h==="server-static"?["upload artifact","publish static files"]:["upload artifact","restart service"]})}return r.sort((n,s)=>String(s.timestamp).localeCompare(String(n.timestamp)))}function Au(e,t){let r=Su(e,t),n=Hi(e),s=_u(e),o=Math.max(1,Number(e.infrastructure?.compute?.disk?.size??1)),i={server:{name:r?.serverName??`${e.project.slug}-${t}-app`,provider:r?.provider??Ui(e),region:gu(e),ip:r?.publicIp??ae,os:"Linux",uptime:ae,probeStatus:"unavailable"},systemMetrics:{load:0,load5:0,load15:0,cpuUsedPct:0,cpus:Math.max(1,Number(e.infrastructure?.compute?.instances??1)),memUsedMb:0,memTotalMb:0,memAvailableMb:0,memCacheMb:0,swapUsedMb:0,swapTotalMb:0,diskUsedPct:0,diskUsedGb:0,diskTotalGb:o,inodeUsedPct:0,networkRxBytes:0,networkTxBytes:0,networkRxBytesPerSec:0,networkTxBytesPerSec:0,networkRxBytesToday:0,networkTxBytesToday:0,networkRxBytesMonth:0,networkTxBytesMonth:0,networkMonthKey:"",processes:0,uptimeSeconds:0},metricsUnavailable:!0,bandwidthBudgetBytes:hu(e),services:n,servicesDetail:n.map((a)=>({...a,since:ae,memMb:0,auto:!0})),backup:fu(e),backupHistory:[],workers:yu(e),serverScheduler:{enabled:!1,lastRun:"not configured"},serverDeployments:[],serverDeploymentsDetail:[],deploymentsEmptyReason:"No deployment history has been recorded yet. Future server deploys will write /var/www/<site>/.ts-cloud/deploy-history.log.",serverLogs:[],serverLogsEmptyReason:"Live server logs are unavailable until the dashboard can reach the compute box.",security:Bn(e),securityEmptyReason:"Live security checks are unavailable until the dashboard can reach the compute box.",sites:s,sitesDetail:s.map((a)=>{let c=e.sites?.[a.name]??{},l=w(c);return{...a,root:l==="server-static"?J(e.project.slug,a.name):`${J(e.project.slug,a.name)}/current`,branch:l==="server-static"?"build artifact":"main",build:c.build,php:c.php??c.phpVersion,aliases:Array.isArray(c.aliases)?c.aliases:[],redirects:c.redirects&&typeof c.redirects==="object"?c.redirects:{},envKeys:Object.keys(c.env??c.environment??{})}}),siteHealth:[],sshKeys:$t(e.infrastructure?.compute?.sshKeys??[]),_serverReachable:!1,_metricsStatus:"unavailable"};return i.diagnostics=ji(e,i),i.activity=Wi(i),i.topology=an(i,{project:e.project.name,environment:t}),i}async function hi(e,t,r={}){if(!e.infrastructure?.compute)return null;let n=null;try{n=_({config:e})}catch{n=null}let s=null,o=0,i=[];if(n)try{if(i=await n.findComputeTargets({slug:e.project.slug,environment:t,role:"app"}),o=i.length,i.length){let d=(await n.runRemoteDeploy({targets:[i[0]],commands:du({includeServices:!r.telemetryOnly,includeSites:r.includeSiteHealth!==!1,projectFilter:e.cloud?.attachTo?e.project.slug:void 0}),comment:`ts-cloud dashboard:build ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output;if(d)s=mu(d)}}catch{}let a=Au(e,t),c=(u,d=0)=>{let m=Number(u);return Number.isFinite(m)?m:d};if(a.server.os=s?.OS||a.server.os,a.server.uptime=s?.UPTIME||a.server.uptime,s){a.server.probeStatus="live",a.metricsUnavailable=!1,a._metricsStatus="live";try{a.storage=JSON.parse(Buffer.from(s.STORAGE||"","base64").toString("utf8"))}catch{a.storage=null}let u=[];try{u=JSON.parse(Buffer.from(s.COLLECTOR||"","base64").toString("utf8")).disks??[]}catch{}if(a.systemMetrics={disks:u,load:c(s.LOAD),load5:c(s.LOAD5),load15:c(s.LOAD15),cpuUsedPct:c(s.CPUUSED),cpus:c(s.CPUS,1),memUsedMb:c(s.MEMUSED),memTotalMb:c(s.MEMTOTAL,1),memAvailableMb:c(s.MEMAVAILABLE),memCacheMb:c(s.MEMCACHE),swapUsedMb:c(s.SWAPUSED),swapTotalMb:c(s.SWAPTOTAL),diskUsedPct:c(s.DISKPCT),diskUsedGb:c(s.DISKUSEDG),diskTotalGb:c(s.DISKTOTG,1),inodeUsedPct:c(s.INODEPCT),networkRxBytes:c(s.NETRX),networkTxBytes:c(s.NETTX),networkRxBytesPerSec:c(s.NETRXRATE),networkTxBytesPerSec:c(s.NETTXRATE),networkRxBytesToday:c(s.NETRXTODAY),networkTxBytesToday:c(s.NETTXTODAY),networkRxBytesMonth:c(s.NETRXMONTH),networkTxBytesMonth:c(s.NETTXMONTH),networkMonthKey:s.NETMONTHKEY||"",processes:c(s.PROCESSES),uptimeSeconds:c(s.UPTIME_SECONDS)},s.services.length){let d=[...new Map(s.services.map((m)=>[m.name,m])).values()];a.services=d.map((m)=>({name:m.name,status:m.status==="active"?"running":m.status})),a.servicesDetail=d.map((m)=>({name:m.name,status:m.status==="active"?"running":m.status,since:m.since&&m.since!==ae?m.since:a.server.uptime,memMb:Math.max(0,Math.round(Number(m.memBytes??0)/1024/1024)),auto:m.enabled?!["disabled","static","masked"].includes(m.enabled):!0}))}if(s.discoveredSites.length)a.sitesDetail=$u(a.sitesDetail,s.discoveredSites,e.project.slug),a.sites=a.sitesDetail.map((d)=>({name:d.name,project:d.project,managedBy:d.managedBy,route:d.route,href:d.href,domain:d.domain,path:d.path,kind:d.kind,type:d.type,runtime:d.runtime,deploy:d.deploy,tls:d.tls,status:d.status,httpStatus:d.httpStatus,responseMs:d.responseMs,tlsDaysRemaining:d.tlsDaysRemaining,checkedAt:d.checkedAt})),a.siteHealth=a.sitesDetail.map((d)=>({name:d.name,project:d.project,route:d.route,status:d.status,httpStatus:d.httpStatus,responseMs:d.responseMs,tlsDaysRemaining:d.tlsDaysRemaining,checkedAt:d.checkedAt}))}if(n&&i.length&&!r.telemetryOnly)await Promise.all([(async()=>{try{let u=Object.keys(e.sites??{}),m=(await n.runRemoteDeploy({targets:[i[0]],commands:Tu(u,e.project.slug),comment:`ts-cloud dashboard:deploy-history ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",h=Iu(m,e.sites);a.serverDeployments=h.slice(0,5),a.serverDeploymentsDetail=h.slice(0,50),a.deploymentsEmptyReason=h.length?void 0:"No deployment history was found on the server yet. Deploy again to populate this timeline."}catch{a.deploymentsEmptyReason="Deployment history could not be read from the server."}})(),(async()=>{try{let d=(await n.runRemoteDeploy({targets:[i[0]],commands:xu(e),comment:`ts-cloud dashboard:server-logs ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",m=Ru(d);a.serverLogs=m,a.serverLogsEmptyReason=m.length?void 0:"No recent journal entries were found for the managed server units."}catch{a.serverLogsEmptyReason="Server logs could not be read from the box."}})(),(async()=>{try{let d=(await n.runRemoteDeploy({targets:[i[0]],commands:Cu(e),comment:`ts-cloud dashboard:security ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",m=Du(d),h=Bn(e);if(!m.ports.length)m.ports=h.ports;if(!m.tlsCertificates.length)m.tlsCertificates=h.tlsCertificates;a.security=m,a.securityEmptyReason=void 0}catch{a.securityEmptyReason="Server security checks could not be read from the box."}})()]);else if(n&&o===0)a.deploymentsEmptyReason="No app server target was found for this environment.";let l=e.infrastructure?.compute?.sshKeys??e.infrastructure?.ssh?.keys??e.infrastructure?.sshKeys;if(Array.isArray(l)&&l.length)a.sshKeys=$t(l);return a._serverReachable=o>0&&!!s,a.diagnostics=ji(e,a),a.activity=Wi(a),a.topology=an(a,{project:e.project.name,environment:t}),a}
740
740
  export{We,cs,me,Yi,ui,Zi,eo,en,to,ro,Te,Z,Ke,_e,tn,ur,Je,pr,rn,Xe,mr,pi,nn,mi,gi,ge,mt,gr,no,fr,hr,yr,on,br,_,io,oo,gc,so,ls,ds,us,ps,gt,ms,sn,ao,co,fc,hc,$t,fi,hi};