@stacksjs/ts-cloud 0.11.1 → 0.11.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/aws/index.js +1 -1
- package/dist/bin/{chunk-6vjrts39.js → chunk-0zwknfwp.js} +1 -1
- package/dist/bin/chunk-104xrc2w.js +1 -0
- package/dist/bin/{chunk-jce28gnz.js → chunk-3aph4c1w.js} +2 -2
- package/dist/bin/{chunk-4a97kbk1.js → chunk-4q6tad44.js} +2 -2
- package/dist/bin/{chunk-md2k3n21.js → chunk-4xhj37nj.js} +1 -1
- package/dist/bin/{chunk-ftse39wf.js → chunk-56wvjysz.js} +2 -2
- package/dist/bin/chunk-5nkqza92.js +1 -0
- package/dist/bin/chunk-64vczwwt.js +1 -0
- package/dist/bin/{chunk-y3rm37z1.js → chunk-6tfwm33r.js} +3 -3
- package/dist/bin/chunk-7g2ahkse.js +1 -0
- package/dist/bin/{chunk-9rsn48qg.js → chunk-81hmza39.js} +2 -2
- package/dist/bin/{chunk-gskbezam.js → chunk-82mj52xr.js} +2 -2
- package/dist/bin/{chunk-mwgxyc0z.js → chunk-8khgprf6.js} +1 -1
- package/dist/bin/{chunk-mbnwt3r5.js → chunk-9a88fp00.js} +2 -2
- package/dist/bin/{chunk-21gggxvf.js → chunk-a7w13qfm.js} +2 -2
- package/dist/bin/{chunk-wzepfqf4.js → chunk-b0e39tpv.js} +6 -6
- package/dist/bin/{chunk-r6x7beew.js → chunk-b4wt9jcg.js} +2 -2
- package/dist/bin/{chunk-4a85nk2q.js → chunk-btsyjhk7.js} +2 -2
- package/dist/bin/{chunk-nmkm1f68.js → chunk-c0bdafbx.js} +2 -2
- package/dist/bin/{chunk-67jsyn0g.js → chunk-cbsys5v8.js} +2 -2
- package/dist/bin/{chunk-kbtrr0c3.js → chunk-cd0ps58j.js} +1 -1
- package/dist/bin/{chunk-fpcghdr3.js → chunk-cq9mca3h.js} +3 -3
- package/dist/bin/{chunk-9mydnqr6.js → chunk-d7ke90zt.js} +2 -2
- package/dist/bin/chunk-djg4zyqk.js +1 -0
- package/dist/bin/chunk-dkaz333b.js +1 -0
- package/dist/bin/{chunk-ww770qpn.js → chunk-dz1ec589.js} +2 -2
- package/dist/bin/{chunk-xev7qr2h.js → chunk-e2bybahr.js} +2 -2
- package/dist/bin/{chunk-dbv8w56s.js → chunk-e5ab5twy.js} +2 -2
- package/dist/bin/chunk-edvvx3hg.js +1 -0
- package/dist/bin/{chunk-ks4ewy1s.js → chunk-ehc63fvs.js} +1 -1
- package/dist/bin/chunk-f06c5np9.js +1 -0
- package/dist/bin/{chunk-nkpf91d3.js → chunk-g0fm1xcs.js} +1 -1
- package/dist/bin/chunk-gq8794k6.js +1 -0
- package/dist/bin/{chunk-4vdv41nh.js → chunk-hq9x489e.js} +1 -1
- package/dist/bin/{chunk-0y89hs67.js → chunk-ja1vjdn1.js} +1 -1
- package/dist/bin/{chunk-zwwnt4x1.js → chunk-k3120rx6.js} +1 -1
- package/dist/bin/{chunk-q182t9ba.js → chunk-kg61p5hw.js} +3 -3
- package/dist/bin/chunk-m189194f.js +1 -0
- package/dist/bin/{chunk-hej39dwr.js → chunk-mcr0r4at.js} +2 -2
- package/dist/bin/chunk-mfrf9q4b.js +2 -0
- package/dist/bin/{chunk-4kbhbfq8.js → chunk-my3ewh3a.js} +2 -2
- package/dist/bin/chunk-nw3d4k52.js +1 -0
- package/dist/bin/chunk-p70bc9yr.js +1 -0
- package/dist/bin/{chunk-neampxq1.js → chunk-r6b3pq31.js} +2 -2
- package/dist/bin/{chunk-c1j9v7ee.js → chunk-s4yzes15.js} +2 -2
- package/dist/bin/{chunk-41yqpdv7.js → chunk-sj5csg49.js} +1 -1
- package/dist/bin/chunk-tvz9c388.js +1 -0
- package/dist/bin/{chunk-e1bfd1yv.js → chunk-w32xv8n4.js} +2 -2
- package/dist/bin/chunk-wkx799z2.js +1 -0
- package/dist/bin/{chunk-nyc2jxd8.js → chunk-xhwqpgwq.js} +1 -1
- package/dist/bin/{chunk-zejwh9cy.js → chunk-xk08030d.js} +2 -2
- package/dist/bin/chunk-y1h63vpm.js +1 -0
- package/dist/bin/chunk-zdt2rjk6.js +1 -0
- package/dist/bin/chunk-zh2d4704.js +1 -0
- package/dist/bin/{chunk-35xstvnq.js → chunk-znnawt0k.js} +1 -1
- package/dist/bin/{chunk-26cj89s6.js → chunk-zpe64t4r.js} +1 -1
- package/dist/bin/{chunk-a2t1e5yb.js → chunk-zsf6pccz.js} +1 -1
- package/dist/bin/cli.js +234 -234
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/cdn/cloudflare.d.ts +20 -0
- package/dist/{chunk-2m09t0c0.js → chunk-6v4k9ekm.js} +2 -2
- package/dist/{chunk-rcxq9aaa.js → chunk-7pff0rv9.js} +1 -1
- package/dist/chunk-hwan3cev.js +2 -0
- package/dist/{chunk-mch30cyc.js → chunk-m4vqpkpp.js} +1 -1
- package/dist/deploy/index.js +1 -1
- package/dist/dns/cloudflare.d.ts +17 -0
- package/dist/dns/godaddy.d.ts +19 -1
- package/dist/dns/index.js +1 -1
- package/dist/dns/zone-migration.d.ts +0 -8
- package/dist/index.js +16 -16
- package/dist/ui/404.html +1 -1
- package/dist/ui/accept-invitation.html +1 -1
- package/dist/ui/access-denied.html +1 -1
- package/dist/ui/account/automation.html +5 -5
- package/dist/ui/account/security.html +2 -2
- package/dist/ui/applications/compose.html +6 -6
- package/dist/ui/applications/new.html +2 -2
- package/dist/ui/data/backups.html +6 -6
- package/dist/ui/data/services.html +6 -6
- package/dist/ui/data/volumes.html +6 -6
- package/dist/ui/index.html +6 -6
- package/dist/ui/infrastructure/topology.html +5 -5
- package/dist/ui/integrations.html +2 -2
- package/dist/ui/operations/alerts.html +6 -6
- package/dist/ui/operations/configuration.html +6 -6
- package/dist/ui/operations/jobs.html +6 -6
- package/dist/ui/operations/maintenance.html +5 -5
- package/dist/ui/operations/observability.html +6 -6
- package/dist/ui/operations/previews.html +6 -6
- package/dist/ui/operations/queue.html +6 -6
- package/dist/ui/operations/regions.html +5 -5
- package/dist/ui/operations/releases.html +6 -6
- package/dist/ui/operations/spend.html +6 -6
- package/dist/ui/operations/workloads.html +6 -6
- package/dist/ui/security.html +2 -2
- package/dist/ui/server/actions.html +5 -5
- package/dist/ui/server/activity.html +1 -1
- package/dist/ui/server/capacity.html +6 -6
- package/dist/ui/server/database.html +6 -6
- package/dist/ui/server/deployments.html +5 -5
- package/dist/ui/server/diagnostics.html +1 -1
- package/dist/ui/server/firewall.html +5 -5
- package/dist/ui/server/fleet.html +6 -6
- package/dist/ui/server/logs.html +6 -6
- package/dist/ui/server/metrics.html +5 -5
- package/dist/ui/server/security.html +2 -2
- package/dist/ui/server/services.html +1 -1
- package/dist/ui/server/sites.html +6 -6
- package/dist/ui/server/ssh-keys.html +6 -6
- package/dist/ui/server/team.html +6 -6
- package/dist/ui/server/terminal.html +2 -2
- package/dist/ui/serverless/alarms.html +6 -6
- package/dist/ui/serverless/assets.html +2 -2
- package/dist/ui/serverless/cost.html +2 -2
- package/dist/ui/serverless/data.html +6 -6
- package/dist/ui/serverless/deployments.html +2 -2
- package/dist/ui/serverless/firewall.html +1 -1
- package/dist/ui/serverless/functions.html +6 -6
- package/dist/ui/serverless/logs.html +5 -5
- package/dist/ui/serverless/metrics.html +2 -2
- package/dist/ui/serverless/queues.html +5 -5
- package/dist/ui/serverless/secrets.html +5 -5
- package/dist/ui/serverless/traces.html +5 -5
- package/dist/ui/serverless.html +5 -5
- package/package.json +3 -3
- package/dist/bin/chunk-0djsffn6.js +0 -1
- package/dist/bin/chunk-0t3sev1j.js +0 -1
- package/dist/bin/chunk-6tct7e89.js +0 -1
- package/dist/bin/chunk-7v5ff3vc.js +0 -1
- package/dist/bin/chunk-80nra92y.js +0 -1
- package/dist/bin/chunk-akbfefwq.js +0 -1
- package/dist/bin/chunk-b704nznp.js +0 -1
- package/dist/bin/chunk-cjz36ths.js +0 -1
- package/dist/bin/chunk-cxd5cevb.js +0 -2
- package/dist/bin/chunk-dxchg0g1.js +0 -1
- package/dist/bin/chunk-g0ewbkbq.js +0 -1
- package/dist/bin/chunk-gvs85t2j.js +0 -1
- package/dist/bin/chunk-khrye4x9.js +0 -1
- package/dist/bin/chunk-memfxrcn.js +0 -1
- package/dist/bin/chunk-pqr8jqnd.js +0 -1
- package/dist/bin/chunk-rfqk5xym.js +0 -1
- package/dist/bin/chunk-wy20ztb6.js +0 -1
- package/dist/bin/chunk-xcqmwphz.js +0 -1
- package/dist/chunk-qtp90j44.js +0 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{af as Kr}from"./chunk-4xhj37nj.js";import{hf as jr}from"./chunk-8khgprf6.js";import{kf as cn}from"./chunk-r6b3pq31.js";import{sf as vr,tf as Sr,uf as as}from"./chunk-xk08030d.js";import{$f as er,Ef as ie,Ff as et,Gf as be,Hf as Qe,If as Ar,Mf as nt,Nf as Ce,Of as os,Qf as st,Sf as qn,Tf as Ge,Vf as We,Wf as On,Xf as An,Yf as Ve,Zf as Qt,_f as Zt,ag as tr,bg as vt,cg as Ae,eg as Ne,fg as yr,gg as wt,vf as Se,wf as wr,xf as zr,yf as F}from"./chunk-56wvjysz.js";import{hg as Pr}from"./chunk-xhwqpgwq.js";import{jg as an}from"./chunk-a7w13qfm.js";import{qg as on}from"./chunk-btsyjhk7.js";import{dh as Ir}from"./chunk-ja1vjdn1.js";import{Gh as ue,Ih as rt,Jh as Qr,Kh as is,Lh as xe,Vh as D,nj as hr}from"./chunk-4q6tad44.js";import{op as Ws}from"./chunk-ehc63fvs.js";import{existsSync as Zo,readFileSync as ea}from"node:fs";import{join as ta}from"node:path";import{readFileSync as ln}from"node:fs";import{join as ui}from"node:path";function xa(e={}){let t=new Set;for(let r of Object.values(e)){if(!r.domain)continue;if(r.redirect||r.deploy==="server"||r.start)t.add(r.domain)}return t}function Ct(e){return e.replace(/\.$/,"").toLowerCase()}function _s(e,t,r){let n=Ct(e.name),s=Ct(t),i=Ct(r),o=i===s?"@":i.endsWith(`.${s}`)?i.slice(0,-(s.length+1)):i;return n===i||n===o||o==="@"&&(n===""||n===s)}async function Ps(e,t,r,n,s="A"){let i=await e.listRecords(t);if(!i.success)return[`could not list ${s} records: ${i.message||"unknown provider error"}`];let o=i.records.filter((l)=>l.type===s&&_s(l,t,r)),a=o.findIndex((l)=>l.content===n);if(o.length<=1||a===-1)return[];let c=[];for(let[l,u]of o.entries()){if(l===a)continue;let p=await e.deleteRecord(t,u);if(!p.success)c.push(`could not remove stale ${u.name} ${s} ${u.content}: ${p.message||"unknown provider error"}`)}return c}function re(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 xs=new Set(["mail","smtp","imap","mx"]);function Cs(e){return!xs.has(e.split(".")[0]??"")}async function Ca(e){let{provider:t,zone:r,fqdn:n,ipv4:s,ipv6:i,ttl:o=600}=e,a={published:[],warnings:[]},c=[{type:"A",content:s}];if(i&&Cs(n))c.push({type:"AAAA",content:i});for(let{type:l,content:u}of c){let p=await t.upsertRecord(r,{name:n,type:l,content:u,ttl:o});if(p?.success===!1){a.warnings.push(`${n} → ${u} failed: ${p.error||p.message||"unknown error"}`);continue}if(a.warnings.push(...(await Ps(t,r,n,u,l)).map((d)=>`${n} cleanup: ${d}`)),await Rs(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 Rs(e,t,r,n,s){try{if(typeof e?.listRecords!=="function")return!0;let i=await e.listRecords(t);if(!i?.success||!Array.isArray(i.records))return!0;return i.records.some((o)=>{let a=typeof o?.name==="string"?o.name.replace(/\.$/,""):"";return o?.type===s&&a===r&&o?.content===n})}catch{return!0}}function Es(e){return e.length>4000?`…
|
|
2
2
|
${e.slice(-4000)}`:e}function Ye(e,t){let r=e.filter((o)=>o.status!=="Success");if(r.length===0)return t;let n=r.slice(0,3).map((o)=>{let a=(o.error||o.output||"").trim(),c=`${o.instanceId}: ${o.status}`;return a?`${c}
|
|
3
3
|
${Es(a)}`:c}),s=r.length-n.length,i=s>0?[`(+${s} more instance${s===1?"":"s"} failed)`]:[];return[t,...n,...i].join(`
|
|
4
4
|
`)}class Je{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new Ir}async putParameter(e){let t={Name:e.Name,Value:e.Value};if(e.Type)t.Type=e.Type;if(e.Description)t.Description=e.Description;if(e.KeyId)t.KeyId=e.KeyId;if(e.Overwrite!==void 0)t.Overwrite=e.Overwrite;if(e.AllowedPattern)t.AllowedPattern=e.AllowedPattern;if(e.Tags&&e.Tags.length>0)t.Tags=e.Tags;if(e.Tier)t.Tier=e.Tier;if(e.DataType)t.DataType=e.DataType;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.PutParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Version:r.Version,Tier:r.Tier}}async getParameter(e){let t={Name:e.Name};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameter:r.Parameter?this.parseParameter(r.Parameter):void 0}}async getParameters(e){let t={Names:e.Names};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:r.Parameters?.map((n)=>this.parseParameter(n)),InvalidParameters:r.InvalidParameters}}async getParametersByPath(e){let t={Path:e.Path};if(e.Recursive!==void 0)t.Recursive=e.Recursive;if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;if(e.MaxResults)t.MaxResults=e.MaxResults;if(e.NextToken)t.NextToken=e.NextToken;if(e.ParameterFilters&&e.ParameterFilters.length>0)t.ParameterFilters=e.ParameterFilters;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParametersByPath","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:r.Parameters?.map((n)=>this.parseParameter(n)),NextToken:r.NextToken}}async deleteParameter(e){let t={Name:e.Name};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DeleteParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async deleteParameters(e){let t={Names:e},r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DeleteParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{DeletedParameters:r.DeletedParameters,InvalidParameters:r.InvalidParameters}}async describeParameters(e){let t={};if(e?.Filters&&e.Filters.length>0)t.Filters=e.Filters;if(e?.ParameterFilters&&e.ParameterFilters.length>0)t.ParameterFilters=e.ParameterFilters;if(e?.MaxResults)t.MaxResults=e.MaxResults;if(e?.NextToken)t.NextToken=e.NextToken;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DescribeParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:r.Parameters?.map((n)=>this.parseParameter(n)),NextToken:r.NextToken}}async getParameterHistory(e){let t={Name:e.Name};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;if(e.MaxResults)t.MaxResults=e.MaxResults;if(e.NextToken)t.NextToken=e.NextToken;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameterHistory","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:r.Parameters?.map((n)=>({Name:n.Name,Type:n.Type,KeyId:n.KeyId,LastModifiedDate:n.LastModifiedDate,LastModifiedUser:n.LastModifiedUser,Description:n.Description,Value:n.Value,Version:n.Version,Labels:n.Labels,Tier:n.Tier})),NextToken:r.NextToken}}async labelParameterVersion(e){let t={Name:e.Name,Labels:e.Labels};if(e.ParameterVersion!==void 0)t.ParameterVersion=e.ParameterVersion;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.LabelParameterVersion","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{InvalidLabels:r.InvalidLabels,ParameterVersion:r.ParameterVersion}}async addTagsToResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId,Tags:e.Tags};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.AddTagsToResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async removeTagsFromResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId,TagKeys:e.TagKeys};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.RemoveTagsFromResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async listTagsForResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId};return{TagList:(await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.ListTagsForResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})).TagList}}async setString(e,t,r){return this.putParameter({Name:e,Value:t,Type:"String",Description:r?.description,Overwrite:r?.overwrite??!0,Tags:r?.tags})}async setSecureString(e,t,r){return this.putParameter({Name:e,Value:t,Type:"SecureString",Description:r?.description,Overwrite:r?.overwrite??!0,KeyId:r?.kmsKeyId,Tags:r?.tags})}async getValue(e){return(await this.getParameter({Name:e,WithDecryption:!0})).Parameter?.Value}async getAllByPath(e,t=!0){let r=[],n;do{let s=await this.getParametersByPath({Path:e,Recursive:t,WithDecryption:!0,NextToken:n});if(s.Parameters)r.push(...s.Parameters);n=s.NextToken}while(n);return r}parseParameter(e){return{Name:e.Name,Type:e.Type,Value:e.Value,Version:e.Version,LastModifiedDate:e.LastModifiedDate,ARN:e.ARN,DataType:e.DataType,Description:e.Description,AllowedPattern:e.AllowedPattern,KeyId:e.KeyId,Tier:e.Tier}}async sendCommand(e){if(!e.InstanceIds&&!e.Targets)throw Error("SendCommand requires either InstanceIds or Targets");let t={DocumentName:e.DocumentName};if(e.InstanceIds)t.InstanceIds=e.InstanceIds;if(e.Targets)t.Targets=e.Targets;if(e.Parameters)t.Parameters=e.Parameters;if(e.TimeoutSeconds)t.TimeoutSeconds=e.TimeoutSeconds;if(e.Comment)t.Comment=e.Comment;if(e.OutputS3BucketName)t.OutputS3BucketName=e.OutputS3BucketName;if(e.OutputS3KeyPrefix)t.OutputS3KeyPrefix=e.OutputS3KeyPrefix;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.SendCommand","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{CommandId:r.Command?.CommandId,Status:r.Command?.Status,StatusDetails:r.Command?.StatusDetails}}async getCommandInvocation(e){let t={CommandId:e.CommandId,InstanceId:e.InstanceId},r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetCommandInvocation","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Status:r.Status,StatusDetails:r.StatusDetails,StandardOutputContent:r.StandardOutputContent,StandardErrorContent:r.StandardErrorContent,ResponseCode:r.ResponseCode}}async runShellCommand(e,t,r){let n=await this.sendCommand({InstanceIds:[e],DocumentName:"AWS-RunShellScript",Parameters:{commands:t},TimeoutSeconds:r?.timeoutSeconds||600});if(!n.CommandId)return{success:!1,error:"Failed to send command"};if(r?.waitForCompletion===!1)return{success:!0,status:"Pending"};let s=r?.pollIntervalMs||2000,i=r?.maxWaitMs||300000,o=Date.now();while(Date.now()-o<i){await new Promise((a)=>setTimeout(a,s));try{let a=await this.getCommandInvocation({CommandId:n.CommandId,InstanceId:e});if(a.Status==="Success")return{success:!0,output:a.StandardOutputContent,error:a.StandardErrorContent,status:a.Status};if(a.Status==="Failed"||a.Status==="Cancelled"||a.Status==="TimedOut")return{success:!1,output:a.StandardOutputContent,error:a.StandardErrorContent||a.StatusDetails,status:a.Status}}catch(a){if(!a.message?.includes("InvocationDoesNotExist"))return{success:!1,error:a.message}}}return{success:!1,error:"Command timed out waiting for completion"}}async listCommandInvocations(e){let t={CommandId:e.CommandId};if(e.Details)t.Details=!0;return((await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.ListCommandInvocations","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})).CommandInvocations||[]).map((s)=>({InstanceId:s.InstanceId,Status:s.Status,StatusDetails:s.StatusDetails,StandardOutputContent:s.CommandPlugins?.[0]?.Output,StandardErrorContent:s.CommandPlugins?.[0]?.StandardErrorUrl}))}async sendCommandByTags(e){let t=Object.entries(e.tags).map(([c,l])=>({Key:`tag:${c}`,Values:[l]})),r=await this.sendCommand({Targets:t,DocumentName:"AWS-RunShellScript",Parameters:{commands:e.commands},TimeoutSeconds:e.timeoutSeconds||600,Comment:e.comment});if(!r.CommandId)return{success:!1,instanceCount:0,perInstance:[],error:"Failed to send command"};let n=e.pollIntervalMs||3000,s=e.maxWaitMs||600000,i=Date.now(),o=new Set(["Success","Failed","Cancelled","TimedOut"]),a=[];while(Date.now()-i<s){await new Promise((c)=>setTimeout(c,n));try{if(a=await this.listCommandInvocations({CommandId:r.CommandId,Details:!0}),a.length===0)continue;if(a.every((l)=>o.has(l.Status||""))){let l=a.map((p)=>({instanceId:p.InstanceId,status:p.Status||"Unknown",output:p.StandardOutputContent,error:p.StandardErrorContent||p.StatusDetails})),u=a.every((p)=>p.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 Is(e){return`/etc/ts-cloud/${e}-upgrade.env`}function Ds(e){return`${e}-upgrade`}function Dr(e){if(!e||e.length===0)return[];let t=["mkdir -p /etc/ts-cloud"],r=[];for(let n of e){if(n.enabled===!1)continue;if(!n.service||!n.binary)continue;let{service:s,binary:i,command:o="upgrade",channel:a="stable",schedule:c="daily",randomizedDelay:l="4h",args:u=[]}=n,p=Ds(s),d=Is(s),m=[`--path ${i}`,`--service ${s}`,...a==="canary"?["--canary"]:[],...u].join(" ");t.push(`if [ ! -f ${d} ]; then`,` cat > ${d} <<'TS_CLOUD_APPUPD_ENV_EOF'`,"# Set to false to pause automatic updates without disabling the timer.","ENABLED=true","# Extra flags appended to the update command.","ARGS=","TS_CLOUD_APPUPD_ENV_EOF","fi",`chmod 644 ${d}`,`cat > /etc/systemd/system/${p}.service <<'TS_CLOUD_APPUPD_SVC_EOF'`,"[Unit]",`Description=Check for and install ${s} updates`,"After=network-online.target","Wants=network-online.target","","[Service]","Type=oneshot",`EnvironmentFile=-${d}`,`ExecStart=/bin/sh -c 'if [ "\${ENABLED:-true}" != "true" ]; then echo "auto-update disabled via ${d}"; exit 0; fi; exec ${i} ${o} ${m} $ARGS'`,"TS_CLOUD_APPUPD_SVC_EOF",`cat > /etc/systemd/system/${p}.timer <<'TS_CLOUD_APPUPD_TMR_EOF'`,"[Unit]",`Description=Scheduled ${s} update check`,"","[Timer]",`OnCalendar=${c}`,`RandomizedDelaySec=${l}`,"Persistent=true","","[Install]","WantedBy=timers.target","TS_CLOUD_APPUPD_TMR_EOF"),r.push(`systemctl enable --now ${p}.timer`)}if(r.length===0)return[];return[...t,"systemctl daemon-reload",...r]}function ne(e=!0){if(!e)return[];return["export DEBIAN_FRONTEND=noninteractive","dpkg-query -W -f='${Status}' unattended-upgrades 2>/dev/null | grep -q 'ok installed' || apt-get install -y unattended-upgrades","cat > /etc/apt/apt.conf.d/20auto-upgrades <<'TS_CLOUD_AUTOUPD_EOF'",'APT::Periodic::Update-Package-Lists "1";','APT::Periodic::Unattended-Upgrade "1";','APT::Periodic::Download-Upgradeable-Packages "1";','APT::Periodic::AutocleanInterval "7";',"TS_CLOUD_AUTOUPD_EOF","systemctl enable --now unattended-upgrades 2>/dev/null || true"]}var Or=[["nginx",80],["https",443],["phpFpm",9074],["mysql",3306],["postgres",5432],["redis",6379],["meilisearch",7700],["typesense",8108],["smtp",25]];function Os(e=!0){let t=typeof e==="object"?e:{},r=typeof e==="boolean"?e:e.enabled!==!1,n=Number(t.alerts?.bandwidthTb??0);return{enabled:r,cpuLoadPerCore:t.alerts?.cpuLoadPerCore??2,memPercent:t.alerts?.memPercent??90,diskPercent:t.alerts?.diskPercent??90,bandwidthTb:Number.isFinite(n)&&n>0?n:0,bandwidthPercent:t.alerts?.bandwidthPercent??80}}function se(e=!0){let{enabled:t,cpuLoadPerCore:r,memPercent:n,diskPercent:s,bandwidthTb:i,bandwidthPercent:o}=Os(e);if(!t)return[];let a=Math.round(i*1000000000000),c=Or.map(([u,p])=>`SVC_${u.toUpperCase()}=$(probe ${p})`),l=Or.map(([u])=>`"${u}":"$SVC_${u.toUpperCase()}"`).join(",");return["if ! command -v sadf >/dev/null 2>&1; then export DEBIAN_FRONTEND=noninteractive; apt-get update -qq; apt-get install -y -qq sysstat; fi","systemctl enable --now sysstat.service 2>/dev/null || true","mkdir -p /var/lib/ts-cloud","cat > /usr/local/bin/ts-cloud-metrics.sh <<'TS_CLOUD_METRICS_EOF'","#!/bin/bash","set -uo pipefail","LOAD=$(cut -d' ' -f1 /proc/loadavg)","CPUS=$(nproc)",`read MEM_TOTAL MEM_USED SWAP_TOTAL SWAP_USED <<EOF
|
|
@@ -7,7 +7,7 @@ EOF`,`DISK_PCT=$(df -P / | awk 'NR==2{gsub("%","",$5); print $5}')`,"UPTIME_SEC=
|
|
|
7
7
|
`)}
|
|
8
8
|
`}return`${["server {"," listen 80;"," listen [::]:80;",` server_name ${r};`,...n,"}"].join(`
|
|
9
9
|
`)}
|
|
10
|
-
`}function Et(e){let t=`/etc/nginx/sites-available/${e.siteName}`,r=`/etc/nginx/sites-enabled/${e.siteName}`,n=Gs(e),s=[...It()];if(e.auth){let i=kr(e.siteName),o=(l)=>l.split("'").join("'\\''"),a=o(e.auth.password),c=o(e.auth.username);s.push(`TS_CLOUD_HTPASS=$(openssl passwd -apr1 '${a}')`,`printf '%s:%s\\n' '${c}' "$TS_CLOUD_HTPASS" > ${i}`,`chmod 640 ${i}`,`chown root:www-data ${i} 2>/dev/null || true`)}return 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",`${oe} -t`,"systemctl reload ts-cloud-nginx 2>/dev/null || systemctl restart ts-cloud-nginx 2>/dev/null || true"),s}var oe="/usr/local/bin/ts-cloud-nginx";function It(e="/opt/pantry"){return[...et(),...Qe(["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 > ${oe} <<'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 ${oe}`,"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=${oe} -t`,`ExecStart=${oe} -g 'daemon off;'`,`ExecReload=${oe} -s reload`,"Restart=always","RestartSec=3","","[Install]","WantedBy=multi-user.target","TS_CLOUD_NGINXUNIT_EOF","systemctl daemon-reload","systemctl enable ts-cloud-nginx","ls /etc/nginx/sites-enabled/* >/dev/null 2>&1 && systemctl restart ts-cloud-nginx || true"]}function ze(e,t){return!e.events||e.events.includes(t)}async function Dt(e,t,r,n={}){if(!e)return[];let s=n.fetchImpl??globalThis.fetch,i=[],o=[],a=(c,l)=>s(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)}).catch(()=>{return});if(e.slack?.webhookUrl&&ze(e,t))i.push("slack"),o.push(a(e.slack.webhookUrl,{text:r}));if(e.discord?.webhookUrl&&ze(e,t))i.push("discord"),o.push(a(e.discord.webhookUrl,{content:r}));if(e.telegram?.botToken&&e.telegram.chatId&&ze(e,t)){i.push("telegram");let c=`https://api.telegram.org/bot${e.telegram.botToken}/sendMessage`;o.push(a(c,{chat_id:e.telegram.chatId,text:r}))}if(e.webhook?.url&&ze(e,t))if(i.push("webhook"),(e.webhook.method||"POST")==="GET"){let c=e.webhook.url.includes("?")?"&":"?",l=`${e.webhook.url}${c}event=${encodeURIComponent(t)}&message=${encodeURIComponent(r)}`;o.push(s(l,{method:"GET"}).catch(()=>{return}))}else o.push(a(e.webhook.url,{event:t,message:r}));if(e.email?.to&&ze(e,t))i.push("email"),o.push(Vs(e.email,t,r));return await Promise.all(o),i}async function Vs(e,t,r){try{await(await import("./chunk-
|
|
10
|
+
`}function Et(e){let t=`/etc/nginx/sites-available/${e.siteName}`,r=`/etc/nginx/sites-enabled/${e.siteName}`,n=Gs(e),s=[...It()];if(e.auth){let i=kr(e.siteName),o=(l)=>l.split("'").join("'\\''"),a=o(e.auth.password),c=o(e.auth.username);s.push(`TS_CLOUD_HTPASS=$(openssl passwd -apr1 '${a}')`,`printf '%s:%s\\n' '${c}' "$TS_CLOUD_HTPASS" > ${i}`,`chmod 640 ${i}`,`chown root:www-data ${i} 2>/dev/null || true`)}return 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",`${oe} -t`,"systemctl reload ts-cloud-nginx 2>/dev/null || systemctl restart ts-cloud-nginx 2>/dev/null || true"),s}var oe="/usr/local/bin/ts-cloud-nginx";function It(e="/opt/pantry"){return[...et(),...Qe(["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 > ${oe} <<'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 ${oe}`,"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=${oe} -t`,`ExecStart=${oe} -g 'daemon off;'`,`ExecReload=${oe} -s reload`,"Restart=always","RestartSec=3","","[Install]","WantedBy=multi-user.target","TS_CLOUD_NGINXUNIT_EOF","systemctl daemon-reload","systemctl enable ts-cloud-nginx","ls /etc/nginx/sites-enabled/* >/dev/null 2>&1 && systemctl restart ts-cloud-nginx || true"]}function ze(e,t){return!e.events||e.events.includes(t)}async function Dt(e,t,r,n={}){if(!e)return[];let s=n.fetchImpl??globalThis.fetch,i=[],o=[],a=(c,l)=>s(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)}).catch(()=>{return});if(e.slack?.webhookUrl&&ze(e,t))i.push("slack"),o.push(a(e.slack.webhookUrl,{text:r}));if(e.discord?.webhookUrl&&ze(e,t))i.push("discord"),o.push(a(e.discord.webhookUrl,{content:r}));if(e.telegram?.botToken&&e.telegram.chatId&&ze(e,t)){i.push("telegram");let c=`https://api.telegram.org/bot${e.telegram.botToken}/sendMessage`;o.push(a(c,{chat_id:e.telegram.chatId,text:r}))}if(e.webhook?.url&&ze(e,t))if(i.push("webhook"),(e.webhook.method||"POST")==="GET"){let c=e.webhook.url.includes("?")?"&":"?",l=`${e.webhook.url}${c}event=${encodeURIComponent(t)}&message=${encodeURIComponent(r)}`;o.push(s(l,{method:"GET"}).catch(()=>{return}))}else o.push(a(e.webhook.url,{event:t,message:r}));if(e.email?.to&&ze(e,t))i.push("email"),o.push(Vs(e.email,t,r));return await Promise.all(o),i}async function Vs(e,t,r){try{await(await import("./chunk-5nkqza92.js")).email.send({to:e.to,from:e.from,subject:`[ts-cloud] ${t}`,text:r})}catch{}}function Hr(e,t){return t??e}function we(e){if(!e)return[];let t=[];if(e.slack?.webhookUrl)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"text\\":\\"$MSG\\"}" ${e.slack.webhookUrl} || true`);if(e.discord?.webhookUrl)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"content\\":\\"$MSG\\"}" ${e.discord.webhookUrl} || true`);if(e.telegram?.botToken&&e.telegram.chatId)t.push(`curl -fsS -X POST "https://api.telegram.org/bot${e.telegram.botToken}/sendMessage" --data-urlencode "chat_id=${e.telegram.chatId}" --data-urlencode "text=$MSG" || true`);if(e.webhook?.url)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"message\\":\\"$MSG\\"}" ${e.webhook.url} || true`);if(t.length===0)return[];return["cat > /usr/local/bin/ts-cloud-notify <<'TS_CLOUD_NOTIFY_EOF'","#!/bin/bash",'MSG="$1"',...t,"TS_CLOUD_NOTIFY_EOF","chmod +x /usr/local/bin/ts-cloud-notify"]}var Nt="/etc/rpx/certs";function kt(e){return e.split(".").length===2}function qs(e,t={}){let r=new Set;for(let n of Object.values(e)){if(!n?.domain)continue;if(F(n)==="bucket")continue;r.add(n.domain)}if(t.autoWww!==!1)for(let n of[...r]){if(!kt(n))continue;r.add(`www.${n}`)}return[...r]}var Xs=["1.1.1.1","8.8.8.8"],Ys="/var/www/acme-challenge";function Js(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 Qs(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 Lr(e){if(!e||e==="/")return;let t=`/${e}`.replace(/\/+/g,"/").replace(/\/+$/,"");if(!t.startsWith("/"))t=`/${t}`;return t===""||t==="/"?void 0:t}function Ot(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 Zs(e,t){if(!t||t.length===0)return`localhost:${e}`;return t.map((r)=>`${r.privateIp??r.publicIp}:${e}`)}function Mr(e,t,r){let n=(t.wwwRoot??"/var/www").replace(/\/+$/,""),s=t.slug??"app",i=t.proxy.certsDir??Nt,o=t.proxy.loadBalancer,a=[],c=new Set;for(let[d,m]of Object.entries(e)){if(!m||!m.domain)continue;let g=F(m);if(g==="bucket")continue;let w=Lr(m.path),S=Ot(m.domain,w),h=Qs(m);if(g==="redirect"){a.push({to:m.domain,path:w,redirect:Js(m.redirect),id:S,...h?{auth:h}:{}}),c.add(m.domain);continue}if(g==="proxy"){let f=zr(m);if(f.length===0)continue;let T=f.length===1?f[0]:f;a.push({to:m.domain,path:w,from:T,id:S,...h?{auth:h}:{},...Array.isArray(T)&&o?{loadBalancer:o}:{}}),c.add(m.domain);continue}if(g==="server-app"){if(typeof m.port!=="number")continue;let f=Zs(m.port,r);a.push({to:m.domain,path:w,from:f,id:S,...h?{auth:h}:{},...Array.isArray(f)&&o?{loadBalancer:o}:{}})}else a.push({to:m.domain,path:w,static:{dir:`${n}/${s}-${d}/current`,spa:m.spa??!1,pathRewriteStyle:m.pathRewriteStyle??"directory"},cleanUrls:m.pathRewriteStyle!=="flat",...h?{auth:h}:{},id:S});c.add(m.domain)}if(t.proxy.autoWww!==!1)for(let d of[...c]){if(!kt(d))continue;let m=`www.${d}`;if(c.has(m))continue;a.push({to:m,redirect:{to:`https://${d}`},id:Ot(m)}),c.add(m)}a.sort((d,m)=>{if(d.to!==m.to)return d.to.localeCompare(m.to);return(m.path?.length??0)-(d.path?.length??0)});let l={proxies:a,productionCerts:{certsDir:i,certsDirServerNames:[...c]},https:!0,hostsManagement:!1,cleanup:{hosts:!1,certs:!1}};if(t.proxy.onDemandTls&&c.size>0)l.onDemandTls={enabled:!0,allowedSuffixes:[...c],email:t.proxy.onDemandTlsEmail,certsDir:i,staging:t.proxy.onDemandTlsStaging??!1};if(t.proxy.onDemandTls)l.acmeChallengeWebroot=t.proxy.acmeWebroot??Ys;let u=t.proxy.cdn,p=u?.frontedHosts?.length?u.frontedHosts:[...c];if(u?.secret&&p.length>0)l.originGuard={header:u.secretHeader??"X-Origin-Verify",value:u.secret,hosts:p};return l}function ce(e,t){return Mr(e,t)}function Te(e,t,r){return Mr(e,r,t)}function q(e){return e?.webServer==="rpx"||e?.proxy?.engine==="rpx"}var Me="/etc/rpx",M="/opt/rpx-gateway",At="/etc/rpx/gateway.ts",Le="/etc/rpx/gateway",ae="rpx-gateway.service",ge="/etc/rpx/sites.d";function ei(e=ge,t=Nt){return`// Generated by ts-cloud — rpx gateway assembler.
|
|
11
11
|
// Merges every app's fragment in ${e} so independent deploys compose
|
|
12
12
|
// without clobbering each other. Each deploy writes only its own <slug>.json.
|
|
13
13
|
import { startProxies } from '@stacksjs/rpx'
|
|
@@ -582,4 +582,4 @@ EOF`,'echo "DISKPCT=${DISKPCT:-0}"','echo "DISKUSEDG=${DISKUSEDG:-0}"','echo "DI
|
|
|
582
582
|
`)){let n=r.trim();if(!n.startsWith("LOG="))continue;let s=n.indexOf("\t");if(s<0)continue;let i=n.slice(4,s),o=n.slice(s+1),a=/^(\d{4}-\d{2}-\d{2}T[^\s]+)\s+(\S+)\s+(.*)$/.exec(o),c=a?.[1]??"",l=a?.[2]??"",u=(a?.[3]??o).trim();if(!u)continue;t.push({source:i,timestamp:c,when:c?Cr(c):z,host:l,message:u,level:vs(u)})}return t.sort((r,n)=>String(n.timestamp).localeCompare(String(r.timestamp))).slice(0,600)}function Ss(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 wa(e){if(Ss(e)!=="public")return"ok";if(/:(?:22|80|443)$/.test(e)||/^\*:(?:22|80|443)$/.test(e))return"ok";return"warn"}function $a(e){if(e==null)return"warn";if(e<8)return"bad";if(e<30)return"warn";return"ok"}function Ta(e){let t=[],r=[],n=[],s=[];for(let a of e.split(`
|
|
583
583
|
`)){let c=a.trim();if(c.startsWith("PORT=")){let[l="",u="",p=""]=c.slice(5).split("\t");if(l&&u)t.push({proto:l,listen:u,processName:p||z,exposure:Ss(u),tone:wa(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),p=(u?.[3]??l).trim();if(p)n.push({timestamp:u?.[1]??"",when:u?.[1]?Cr(u[1]):z,host:u?.[2]??"",message:p,level:vs(p)})}else if(c.startsWith("CERT=")){let[l="",u=""]=c.slice(5).split("\t");if(!l)continue;let p=new Date(u),d=Number.isNaN(p.getTime())?null:Math.ceil((p.getTime()-Date.now())/86400000);s.push({domain:l,expires:Number.isNaN(p.getTime())?u||z:p.toISOString().slice(0,10),daysRemaining:d,status:$a(d)})}}let i=r.some((a)=>/Status:\s*active/i.test(a)),o=r.some((a)=>/unavailable/i.test(a));return{ports:t.slice(0,80),firewall:{status:i?"active":o?"unavailable":"inactive",summary:i?"ufw active":o?"ufw unavailable":"ufw inactive or not configured",rules:r.filter((a)=>a&&!/^Status:/i.test(a)).slice(0,60)},tlsCertificates:s,authEvents:n.sort((a,c)=>String(c.timestamp).localeCompare(String(a.timestamp))).slice(0,30)}}function Rr(e){let r=e.infrastructure?.compute?.firewall??{},n=[...new Set([22,80,443,...r.allowedPorts??[]])],s=ys(e);return{ports:n.map((i)=>({proto:"tcp",listen:`0.0.0.0:${i}`,processName:"configured firewall",exposure:"public",tone:[22,80,443].includes(Number(i))?"ok":"warn"})),firewall:{status:r.enabled===!1?"disabled":"configured",summary:r.enabled===!1?"host firewall disabled in config":"host firewall configured declaratively",rules:n.map((i)=>`ALLOW ${i}/tcp`)},tlsCertificates:s.map((i)=>({domain:i,expires:z,daysRemaining:null,status:"warn"})),authEvents:[]}}function bs(e,t){let r=t.security??Rr(e),n=!!t._serverReachable&&!t.metricsUnavailable,s=t.sites??[],i=s.filter((l)=>l.status==="shadowed"),o=(t.services??[]).filter((l)=>["failed","stopped"].includes(l.status)),a=(r.tlsCertificates??[]).filter((l)=>l.status!=="ok"),c=t.sshKeys??[];return[{name:"Live server probe",status:n?"pass":"warn",detail:n?"Metrics and remote checks are coming from the compute box.":"The dashboard is rendering config/state data until the box probe succeeds."},{name:"Managed services",status:o.length?"fail":"pass",detail:o.length?`${o.length} service(s) need attention.`:`${(t.services??[]).length} service(s) reported healthy or configured.`},{name:"Route conflicts",status:i.length?"warn":"pass",detail:i.length?`${i.map((l)=>l.name).join(", ")} is shadowed by an earlier route.`:`${s.length} site route(s) are unshadowed.`},{name:"SSH access",status:c.length?"pass":"warn",detail:c.length?`${c.length} declarative authorized key(s) configured.`:"No declarative SSH keys are configured."},{name:"Firewall",status:["active","configured"].includes(r.firewall?.status)?"pass":"warn",detail:r.firewall?.summary??"Firewall status unavailable."},{name:"TLS certificates",status:a.length?"warn":"pass",detail:a.length?`${a.length} certificate(s) need renewal visibility.`:`${(r.tlsCertificates??[]).length} certificate(s) look healthy.`}]}function ws(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??z,timestamp:""});return t.sort((r,n)=>String(n.timestamp).localeCompare(String(r.timestamp))).slice(0,80)}function _a(e,t={}){let r=[];for(let n of e.split(`
|
|
584
584
|
`)){let s=n.trim();if(!s.startsWith("DEPLOY="))continue;let i=s.split("\t"),o=i[0]?.replace(/^DEPLOY=/,"")??"",[a,c,l,u,p]=i.slice(1);if(!o||!a||!c)continue;let d=t[o]??{},m=F(d),g=(l||c).slice(0,7);r.push({sha:g,release:c,commit:l||c,site:o,branch:d.branch??(m==="server-static"?"build artifact":"main"),status:u||"unknown",when:Cr(a),timestamp:a,took:"-",by:"ts-cloud",rc:p?.replace(/^rc=/,"")??"",steps:m==="server-static"?["upload artifact","publish static files"]:["upload artifact","restart service"]})}return r.sort((n,s)=>String(s.timestamp).localeCompare(String(n.timestamp)))}function Pa(e,t){let r=la(e,t),n=ms(e),s=ga(e),i=Math.max(1,Number(e.infrastructure?.compute?.disk?.size??1)),o={server:{name:r?.serverName??`${e.project.slug}-${t}-app`,provider:r?.provider??gs(e),region:aa(e),ip:r?.publicIp??z,os:"Linux",uptime:z,probeStatus:"unavailable"},systemMetrics:{load:0,load5:0,load15:0,cpuUsedPct:0,cpus:Math.max(1,Number(e.infrastructure?.compute?.instances??1)),memUsedMb:0,memTotalMb:0,memAvailableMb:0,memCacheMb:0,swapUsedMb:0,swapTotalMb:0,diskUsedPct:0,diskUsedGb:0,diskTotalGb:i,inodeUsedPct:0,networkRxBytes:0,networkTxBytes:0,networkRxBytesPerSec:0,networkTxBytesPerSec:0,networkRxBytesToday:0,networkTxBytesToday:0,networkRxBytesMonth:0,networkTxBytesMonth:0,networkMonthKey:"",processes:0,uptimeSeconds:0},metricsUnavailable:!0,bandwidthBudgetBytes:ca(e),services:n,servicesDetail:n.map((a)=>({...a,since:z,memMb:0,auto:!0})),backup:oa(e),backupHistory:[],workers:ua(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:Rr(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=F(c);return{...a,root:l==="server-static"?Se(e.project.slug,a.name):`${Se(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:$r(e.infrastructure?.compute?.sshKeys??[]),_serverReachable:!1,_metricsStatus:"unavailable"};return o.diagnostics=bs(e,o),o.activity=ws(o),o.topology=Pr(o,{project:e.project.name,environment:t}),o}async function _p(e,t,r={}){if(!e.infrastructure?.compute)return null;let n=null;try{n=Gt({config:e})}catch{n=null}let s=null,i=0,o=[];if(n)try{if(o=await n.findComputeTargets({slug:e.project.slug,environment:t,role:"app"}),i=o.length,o.length){let p=(await n.runRemoteDeploy({targets:[o[0]],commands:sa({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(p)s=ia(p)}}catch{}let a=Pa(e,t),c=(u,p=0)=>{let d=Number(u);return Number.isFinite(d)?d:p};if(a.server.os=s?.OS||a.server.os,a.server.uptime=s?.UPTIME||a.server.uptime,s){if(a.server.probeStatus="live",a.metricsUnavailable=!1,a._metricsStatus="live",a.systemMetrics={load:c(s.LOAD),load5:c(s.LOAD5),load15:c(s.LOAD15),cpuUsedPct:c(s.CPUUSED),cpus:c(s.CPUS,1),memUsedMb:c(s.MEMUSED),memTotalMb:c(s.MEMTOTAL,1),memAvailableMb:c(s.MEMAVAILABLE),memCacheMb:c(s.MEMCACHE),swapUsedMb:c(s.SWAPUSED),swapTotalMb:c(s.SWAPTOTAL),diskUsedPct:c(s.DISKPCT),diskUsedGb:c(s.DISKUSEDG),diskTotalGb:c(s.DISKTOTG,1),inodeUsedPct:c(s.INODEPCT),networkRxBytes:c(s.NETRX),networkTxBytes:c(s.NETTX),networkRxBytesPerSec:c(s.NETRXRATE),networkTxBytesPerSec:c(s.NETTXRATE),networkRxBytesToday:c(s.NETRXTODAY),networkTxBytesToday:c(s.NETTXTODAY),networkRxBytesMonth:c(s.NETRXMONTH),networkTxBytesMonth:c(s.NETTXMONTH),networkMonthKey:s.NETMONTHKEY||"",processes:c(s.PROCESSES),uptimeSeconds:c(s.UPTIME_SECONDS)},s.services.length){let u=[...new Map(s.services.map((p)=>[p.name,p])).values()];a.services=u.map((p)=>({name:p.name,status:p.status==="active"?"running":p.status})),a.servicesDetail=u.map((p)=>({name:p.name,status:p.status==="active"?"running":p.status,since:p.since&&p.since!==z?p.since:a.server.uptime,memMb:Math.max(0,Math.round(Number(p.memBytes??0)/1024/1024)),auto:p.enabled?!["disabled","static","masked"].includes(p.enabled):!0}))}if(s.discoveredSites.length)a.sitesDetail=fa(a.sitesDetail,s.discoveredSites,e.project.slug),a.sites=a.sitesDetail.map((u)=>({name:u.name,project:u.project,managedBy:u.managedBy,route:u.route,href:u.href,domain:u.domain,path:u.path,kind:u.kind,type:u.type,runtime:u.runtime,deploy:u.deploy,tls:u.tls,status:u.status,httpStatus:u.httpStatus,responseMs:u.responseMs,tlsDaysRemaining:u.tlsDaysRemaining,checkedAt:u.checkedAt})),a.siteHealth=a.sitesDetail.map((u)=>({name:u.name,project:u.project,route:u.route,status:u.status,httpStatus:u.httpStatus,responseMs:u.responseMs,tlsDaysRemaining:u.tlsDaysRemaining,checkedAt:u.checkedAt}))}if(n&&o.length&&!r.telemetryOnly)await Promise.all([(async()=>{try{let u=Object.keys(e.sites??{}),d=(await n.runRemoteDeploy({targets:[o[0]],commands:ha(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??"",m=_a(d,e.sites);a.serverDeployments=m.slice(0,5),a.serverDeploymentsDetail=m.slice(0,50),a.deploymentsEmptyReason=m.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 p=(await n.runRemoteDeploy({targets:[o[0]],commands:Sa(e),comment:`ts-cloud dashboard:server-logs ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",d=ba(p);a.serverLogs=d,a.serverLogsEmptyReason=d.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 p=(await n.runRemoteDeploy({targets:[o[0]],commands:ya(e),comment:`ts-cloud dashboard:security ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",d=Ta(p),m=Rr(e);if(!d.ports.length)d.ports=m.ports;if(!d.tlsCertificates.length)d.tlsCertificates=m.tlsCertificates;a.security=d,a.securityEmptyReason=void 0}catch{a.securityEmptyReason="Server security checks could not be read from the box."}})()]);else if(n&&i===0)a.deploymentsEmptyReason="No app server target was found for this environment.";let l=e.infrastructure?.compute?.sshKeys??e.infrastructure?.ssh?.keys??e.infrastructure?.sshKeys;if(Array.isArray(l)&&l.length)a.sshKeys=$r(l);return a._serverReachable=i>0&&!!s,a.diagnostics=bs(e,a),a.activity=ws(a),a.topology=Pr(a,{project:e.project.name,environment:t}),a}
|
|
585
|
-
export{Je as
|
|
585
|
+
export{Je as $d,xa as ae,re as be,Cs as ce,Ca as de,Rs as ee,Dr as fe,Nt as ge,qs as he,ce as ie,q as je,Ue as ke,gn as le,ut as me,yi as ne,pt as oe,fe as pe,ye as qe,ve as re,Gt as se,$n as te,Di as ue,ee as ve,Xt as we,zi as xe,Fi as ye,Al as ze,Cn as Ae,Wi as Be,Vi as Ce,qi as De,Zi as Ee,eo as Fe,to as Ge,Ln as He,Ko as Ie,Go as Je,gp as Ke,fp as Le,$r as Me,ps as Ne,na as Oe,sa as Pe,ia as Qe,fa as Re,va as Se,ba as Te,Ta as Ue,_a as Ve,Pa as We,_p as Xe};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{d as
|
|
1
|
+
import{dh as u}from"./chunk-ja1vjdn1.js";class d{client;region;constructor(e="us-east-1",i){this.region=e,this.client=new u}async createQueue(e){let t={Action:"CreateQueue",QueueName:e.fifo&&!e.queueName.endsWith(".fifo")?`${e.queueName}.fifo`:e.queueName,Version:"2012-11-05"},s=1;if(e.visibilityTimeout!==void 0)t[`Attribute.${s}.Name`]="VisibilityTimeout",t[`Attribute.${s}.Value`]=e.visibilityTimeout.toString(),s++;if(e.messageRetentionPeriod!==void 0)t[`Attribute.${s}.Name`]="MessageRetentionPeriod",t[`Attribute.${s}.Value`]=e.messageRetentionPeriod.toString(),s++;if(e.delaySeconds!==void 0)t[`Attribute.${s}.Name`]="DelaySeconds",t[`Attribute.${s}.Value`]=e.delaySeconds.toString(),s++;if(e.maxMessageSize!==void 0)t[`Attribute.${s}.Name`]="MaximumMessageSize",t[`Attribute.${s}.Value`]=e.maxMessageSize.toString(),s++;if(e.receiveMessageWaitTime!==void 0)t[`Attribute.${s}.Name`]="ReceiveMessageWaitTimeSeconds",t[`Attribute.${s}.Value`]=e.receiveMessageWaitTime.toString(),s++;if(e.fifo){if(t[`Attribute.${s}.Name`]="FifoQueue",t[`Attribute.${s}.Value`]="true",s++,e.contentBasedDeduplication)t[`Attribute.${s}.Name`]="ContentBasedDeduplication",t[`Attribute.${s}.Value`]="true",s++}if(e.deadLetterTargetArn&&e.maxReceiveCount)t[`Attribute.${s}.Name`]="RedrivePolicy",t[`Attribute.${s}.Value`]=JSON.stringify({deadLetterTargetArn:e.deadLetterTargetArn,maxReceiveCount:e.maxReceiveCount}),s++;if(e.tags&&Object.keys(e.tags).length>0){let a=1;for(let[n,g]of Object.entries(e.tags))t[`Tag.${a}.Key`]=n,t[`Tag.${a}.Value`]=g,a++}let r=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{QueueUrl:r.QueueUrl||r.CreateQueueResult?.QueueUrl}}async listQueues(e){let i={Action:"ListQueues",Version:"2012-11-05"};if(e)i.QueueNamePrefix=e;let t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()}),s=[];if(t.QueueUrl)s.push(t.QueueUrl);else if(t.ListQueuesResult?.QueueUrl)if(Array.isArray(t.ListQueuesResult.QueueUrl))s.push(...t.ListQueuesResult.QueueUrl);else s.push(t.ListQueuesResult.QueueUrl);return{QueueUrls:s}}async getQueueAttributes(e){let i={Action:"GetQueueAttributes",QueueUrl:e,Version:"2012-11-05","AttributeName.1":"All"},t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()});return{Attributes:t.Attributes||t.GetQueueAttributesResult?.Attributes||{}}}async getQueueUrl(e){let i={Action:"GetQueueUrl",QueueName:e,Version:"2012-11-05"},t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()});return{QueueUrl:t.QueueUrl||t.GetQueueUrlResult?.QueueUrl}}async deleteQueue(e){let i={Action:"DeleteQueue",QueueUrl:e,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()})}async purgeQueue(e){let i={Action:"PurgeQueue",QueueUrl:e,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()})}async sendMessage(e){let i={Action:"SendMessage",QueueUrl:e.queueUrl,MessageBody:e.messageBody,Version:"2012-11-05"};if(e.delaySeconds!==void 0)i.DelaySeconds=e.delaySeconds;if(e.messageGroupId)i.MessageGroupId=e.messageGroupId;if(e.messageDeduplicationId)i.MessageDeduplicationId=e.messageDeduplicationId;let t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()});return{MessageId:t.MessageId||t.SendMessageResult?.MessageId}}async receiveMessages(e){let i={Action:"ReceiveMessage",QueueUrl:e.queueUrl,Version:"2012-11-05"};if(e.maxMessages!==void 0)i.MaxNumberOfMessages=e.maxMessages;if(e.visibilityTimeout!==void 0)i.VisibilityTimeout=e.visibilityTimeout;if(e.waitTimeSeconds!==void 0)i.WaitTimeSeconds=e.waitTimeSeconds;let t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()}),s=[],r=t.Message||t.ReceiveMessageResult?.Message;if(r)if(Array.isArray(r))s.push(...r.map((a)=>({MessageId:a.MessageId,ReceiptHandle:a.ReceiptHandle,Body:a.Body})));else s.push({MessageId:r.MessageId,ReceiptHandle:r.ReceiptHandle,Body:r.Body});return{Messages:s}}async deleteMessage(e,i){let t={Action:"DeleteMessage",QueueUrl:e,ReceiptHandle:i,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()})}}
|
|
2
|
+
export{d as Hd};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Xa as a}from"./chunk-sj5csg49.js";import"./chunk-ehc63fvs.js";export{a as encodeDashboardPayload};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{_d as a}from"./chunk-c0bdafbx.js";import"./chunk-ja1vjdn1.js";import"./chunk-ehc63fvs.js";export{a as LambdaClient};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Bh as ie}from"./chunk-4q6tad44.js";var C=["project:read","config:read","config:write","deployments:read","deployments:create","deployments:cancel","deployments:rollback","runtime:read","runtime:restart","runtime:logs","runtime:terminal","data:read","data:write","data:admin","backups:read","backups:create","backups:restore","secrets:read","secrets:write","fleet:read","fleet:manage","users:read","users:manage","users:transfer-ownership","audit:read","billing:read","billing:manage","security:read","security:manage","security:waive","sources:read","sources:manage","applications:read","applications:manage","automation:read","automation:manage","tags:manage"],K=["project:read","config:read","deployments:read","runtime:read","runtime:logs","data:read","backups:read","security:read","sources:read","applications:read","billing:read"],se={owner:new Set(C),admin:new Set(C.filter((e)=>e!=="users:transfer-ownership")),deployer:new Set([...K,"deployments:create","deployments:cancel","deployments:rollback","sources:manage","applications:manage"]),operator:new Set([...K,"runtime:restart","backups:create","security:manage","sources:manage","applications:manage"]),viewer:new Set(K),auditor:new Set(["project:read","config:read","deployments:read","runtime:read","data:read","backups:read","audit:read","security:read","sources:read","applications:read"])};function I(e){return se[e]}function P(e,t){if(e.type==="organization")return e.id===void 0||e.id===t.organizationId;if(!e.id)return!1;if(e.type==="project")return e.id===t.projectId;if(e.type==="environment")return e.id===t.environmentId;return e.id===t.resourceId}function Z(e){let{membership:t,capability:r,target:i}=e;if(!t||t.status!=="active"||t.organizationId!==i.organizationId)return{allowed:!1,reason:"inactive-membership"};let a=e.grants.filter((s)=>s.organizationId===i.organizationId&&s.membershipId===t.id&&s.capability===r&&P(s.scope,i)),E=a.find((s)=>s.effect==="deny");if(E)return{allowed:!1,reason:"explicit-deny",inheritedFrom:{kind:"grant",id:E.id,scope:E.scope}};let T=a.find((s)=>s.effect==="allow");if(T)return{allowed:!0,reason:"explicit-allow",inheritedFrom:{kind:"grant",id:T.id,scope:T.scope}};if(!P(t.scope,i))return{allowed:!1,reason:"scope-mismatch"};if(I(t.roleTemplate).has(r))return{allowed:!0,reason:"role-template",inheritedFrom:{kind:"membership",id:t.id,scope:t.scope}};return{allowed:!1,reason:"missing-capability"}}function de(e){return C.filter((t)=>Z({...e,capability:t}).allowed)}import{createHash as h,randomBytes as Ne}from"node:crypto";import{chmodSync as H,existsSync as ee,mkdirSync as ce,statSync as Le}from"node:fs";import{dirname as te}from"node:path";import{Database as _e}from"bun:sqlite";var l=40,j=[{version:1,name:"core_control_plane",sql:`
|
|
2
2
|
CREATE TABLE projects (
|
|
3
3
|
id TEXT PRIMARY KEY,
|
|
4
4
|
slug TEXT NOT NULL UNIQUE,
|
|
@@ -1504,4 +1504,4 @@ import{Ah as ie}from"./chunk-4a97kbk1.js";var C=["project:read","config:read","c
|
|
|
1504
1504
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i.id,i.organizationId,i.membershipId,i.effect,i.capability,i.scope.type,i.scope.id??null,i.source??"manual",i.createdAt,i.updatedAt]);for(let i of e.operations)o(this.database,`INSERT INTO operations (id, project_id, environment_id, resource_id, actor_id, kind, state, correlation_id, idempotency_key,
|
|
1505
1505
|
input, output, error, attempt, priority, lease_owner, lease_expires_at, cancel_requested_at, started_at, finished_at, version, created_at, updated_at)
|
|
1506
1506
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i.id,i.projectId??null,i.environmentId??null,i.resourceId??null,i.actorId??null,i.kind,i.state,i.correlationId,i.idempotencyKey??null,N(i.input),N(i.output),M(i.error)??null,i.attempt,i.priority,i.leaseOwner??null,i.leaseExpiresAt??null,i.cancelRequestedAt??null,i.startedAt??null,i.finishedAt??null,i.version,i.createdAt,i.updatedAt]);for(let i of e.events)o(this.database,`INSERT INTO events (sequence, id, organization_id, project_id, operation_id, resource_id, actor_id, correlation_id, type, level, payload, created_at)
|
|
1507
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i.sequence,i.id,i.organizationId??null,i.projectId??null,i.operationId??null,i.resourceId??null,i.actorId??null,i.correlationId,i.type,i.level,N(i.payload),i.createdAt]);for(let[i,a]of Object.entries(e.settings))o(this.database,"INSERT INTO settings (key, value, updated_at) VALUES (?, ?, ?)",[i,N(a),this.now()]);for(let i of e.tags??[])o(this.database,"INSERT INTO tags (id, project_id, name, normalized_name, color, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[i.id,i.projectId,i.name,i.normalizedName,i.color,i.createdAt,i.updatedAt]);for(let i of e.resourceTags??[])o(this.database,"INSERT INTO resource_tags (resource_id, tag_id, created_at) VALUES (?, ?, ?)",[i.resourceId,i.tagId,i.createdAt]);for(let i of e.savedFilters??[])o(this.database,"INSERT INTO saved_filters (id, actor_key, name, route_id, query, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[i.id,i.actorKey,i.name,i.routeId,N(i.query),i.createdAt,i.updatedAt]);for(let i of e.navigationItems??[])o(this.database,"INSERT INTO navigation_items (actor_key, entity_type, entity_id, favorite, last_visited_at, visit_count) VALUES (?, ?, ?, ?, ?, ?)",[i.actorKey,i.entityType,i.entityId,i.favorite?1:0,i.lastVisitedAt,i.visitCount])})}}var Oe=new Set(["domain","domains","hostname","hostnames","url","repository","repo","image","label","labels"]),Re=new Set(["sha","commit","commitsha","release","releaseid"]);function oe(e,t){if(!e||typeof e!=="object"||Array.isArray(e))return[];let r=[];for(let[i,a]of Object.entries(e)){if(!t.has(i.toLowerCase()))continue;if(typeof a==="string")r.push(a);else if(Array.isArray(a))r.push(...a.filter((E)=>typeof E==="string"))}return r}function Q(e){return e.toLowerCase().trim().replace(/[^a-z0-9._:/@-]+/g," ")}function W(e,t,r){let i=Q(e),a=Q(t),E=Q(r);if(!i)return 0;if(a===i)return 1000;if(a.startsWith(i))return 800-Math.min(100,a.length-i.length);if(a.includes(i))return 650-Math.min(100,a.indexOf(i));let T=i.split(/\s+/).filter(Boolean);if(T.every((c)=>E.includes(c)))return 400+T.length*10;let s=0;for(let c of i){if(s=E.indexOf(c,s),s<0)return 0;s++}return Math.max(1,180-Math.floor(E.length/20))}function ge(e,t){let r=e.kind.toLowerCase();if(r==="server"||r==="compute")return{type:"server",href:`/server/metrics?env=${encodeURIComponent(t)}`};if(r.includes("database")||["mysql","postgres","postgresql","sqlite","redis"].includes(r))return{type:"database",href:`/server/database?env=${encodeURIComponent(t)}&database=${encodeURIComponent(e.slug)}`};return{type:"service",href:`/server/sites?env=${encodeURIComponent(t)}&service=${encodeURIComponent(e.slug)}`}}function Ue(e,t){let r=e.getProject(t.projectId);if(!r)return[];let i=e.listEnvironments(r.id),a=new Map(i.map((n)=>[n.id,n])),E=e.listResourceTags(r.id),T=new Map;for(let n of E){let L=T.get(n.resourceId)??[];L.push({id:n.tag.id,name:n.tag.name,color:n.tag.color}),T.set(n.resourceId,L)}let s=[],c=t.allowedResourceSlugs!==void 0;if(!c){s.push({type:"project",id:r.id,title:r.name,subtitle:r.slug,href:`/?project=${encodeURIComponent(r.slug)}`,tags:[],score:0});for(let n of i)s.push({type:"environment",id:n.id,title:n.name,subtitle:`${r.name} · ${n.kind}`,href:`/?env=${encodeURIComponent(n.slug)}`,environment:n.slug,tags:[],score:0})}let V=e.listResources(r.id).filter((n)=>!t.allowedResourceSlugs||t.allowedResourceSlugs.has(n.slug));for(let n of V){let L=n.environmentId?a.get(n.environmentId):void 0,O=T.get(n.id)??[],A=oe(n.desiredState,Oe),m=[n.name,n.slug,n.kind,n.provider,n.providerId,L?.slug,...A,...O.map((Te)=>Te.name)].filter(Boolean).join(" "),X=ge(n,L?.slug??i[0]?.slug??"");s.push({type:X.type,id:n.id,title:n.name,subtitle:[n.kind,...A.slice(0,2)].join(" · "),href:X.href,environment:L?.slug,provider:n.provider,tags:O,score:W(t.query,n.name,m)})}if(!c)for(let n of e.listOperations({projectId:r.id,limit:500})){let L=n.environmentId?a.get(n.environmentId):void 0,O=oe(n.input,Re),A=n.kind.includes("deploy"),m=O[0]??n.kind,X=[n.kind,n.id,n.correlationId,n.state,...O].join(" ");s.push({type:A?"deployment":"operation",id:n.id,title:m,subtitle:`${n.kind} · ${n.state}`,href:`/server/activity?env=${encodeURIComponent(L?.slug??i[0]?.slug??"")}&operation=${encodeURIComponent(n.id)}`,environment:L?.slug,status:n.state,tags:[],score:W(t.query,m,X)})}for(let n of s)if(n.score===0)n.score=W(t.query,n.title,`${n.title} ${n.subtitle} ${n.environment??""} ${n.provider??""}`);let J={service:0,server:1,database:2,deployment:3,environment:4,project:5,operation:6};return s.filter((n)=>n.score>0).sort((n,L)=>L.score-n.score||J[n.type]-J[L.type]||n.title.localeCompare(L.title)||n.id.localeCompare(L.id)).slice(0,Math.min(50,Math.max(1,t.limit??20)))}export{C as
|
|
1507
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i.sequence,i.id,i.organizationId??null,i.projectId??null,i.operationId??null,i.resourceId??null,i.actorId??null,i.correlationId,i.type,i.level,N(i.payload),i.createdAt]);for(let[i,a]of Object.entries(e.settings))o(this.database,"INSERT INTO settings (key, value, updated_at) VALUES (?, ?, ?)",[i,N(a),this.now()]);for(let i of e.tags??[])o(this.database,"INSERT INTO tags (id, project_id, name, normalized_name, color, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[i.id,i.projectId,i.name,i.normalizedName,i.color,i.createdAt,i.updatedAt]);for(let i of e.resourceTags??[])o(this.database,"INSERT INTO resource_tags (resource_id, tag_id, created_at) VALUES (?, ?, ?)",[i.resourceId,i.tagId,i.createdAt]);for(let i of e.savedFilters??[])o(this.database,"INSERT INTO saved_filters (id, actor_key, name, route_id, query, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[i.id,i.actorKey,i.name,i.routeId,N(i.query),i.createdAt,i.updatedAt]);for(let i of e.navigationItems??[])o(this.database,"INSERT INTO navigation_items (actor_key, entity_type, entity_id, favorite, last_visited_at, visit_count) VALUES (?, ?, ?, ?, ?, ?)",[i.actorKey,i.entityType,i.entityId,i.favorite?1:0,i.lastVisitedAt,i.visitCount])})}}var Oe=new Set(["domain","domains","hostname","hostnames","url","repository","repo","image","label","labels"]),Re=new Set(["sha","commit","commitsha","release","releaseid"]);function oe(e,t){if(!e||typeof e!=="object"||Array.isArray(e))return[];let r=[];for(let[i,a]of Object.entries(e)){if(!t.has(i.toLowerCase()))continue;if(typeof a==="string")r.push(a);else if(Array.isArray(a))r.push(...a.filter((E)=>typeof E==="string"))}return r}function Q(e){return e.toLowerCase().trim().replace(/[^a-z0-9._:/@-]+/g," ")}function W(e,t,r){let i=Q(e),a=Q(t),E=Q(r);if(!i)return 0;if(a===i)return 1000;if(a.startsWith(i))return 800-Math.min(100,a.length-i.length);if(a.includes(i))return 650-Math.min(100,a.indexOf(i));let T=i.split(/\s+/).filter(Boolean);if(T.every((c)=>E.includes(c)))return 400+T.length*10;let s=0;for(let c of i){if(s=E.indexOf(c,s),s<0)return 0;s++}return Math.max(1,180-Math.floor(E.length/20))}function ge(e,t){let r=e.kind.toLowerCase();if(r==="server"||r==="compute")return{type:"server",href:`/server/metrics?env=${encodeURIComponent(t)}`};if(r.includes("database")||["mysql","postgres","postgresql","sqlite","redis"].includes(r))return{type:"database",href:`/server/database?env=${encodeURIComponent(t)}&database=${encodeURIComponent(e.slug)}`};return{type:"service",href:`/server/sites?env=${encodeURIComponent(t)}&service=${encodeURIComponent(e.slug)}`}}function Ue(e,t){let r=e.getProject(t.projectId);if(!r)return[];let i=e.listEnvironments(r.id),a=new Map(i.map((n)=>[n.id,n])),E=e.listResourceTags(r.id),T=new Map;for(let n of E){let L=T.get(n.resourceId)??[];L.push({id:n.tag.id,name:n.tag.name,color:n.tag.color}),T.set(n.resourceId,L)}let s=[],c=t.allowedResourceSlugs!==void 0;if(!c){s.push({type:"project",id:r.id,title:r.name,subtitle:r.slug,href:`/?project=${encodeURIComponent(r.slug)}`,tags:[],score:0});for(let n of i)s.push({type:"environment",id:n.id,title:n.name,subtitle:`${r.name} · ${n.kind}`,href:`/?env=${encodeURIComponent(n.slug)}`,environment:n.slug,tags:[],score:0})}let V=e.listResources(r.id).filter((n)=>!t.allowedResourceSlugs||t.allowedResourceSlugs.has(n.slug));for(let n of V){let L=n.environmentId?a.get(n.environmentId):void 0,O=T.get(n.id)??[],A=oe(n.desiredState,Oe),m=[n.name,n.slug,n.kind,n.provider,n.providerId,L?.slug,...A,...O.map((Te)=>Te.name)].filter(Boolean).join(" "),X=ge(n,L?.slug??i[0]?.slug??"");s.push({type:X.type,id:n.id,title:n.name,subtitle:[n.kind,...A.slice(0,2)].join(" · "),href:X.href,environment:L?.slug,provider:n.provider,tags:O,score:W(t.query,n.name,m)})}if(!c)for(let n of e.listOperations({projectId:r.id,limit:500})){let L=n.environmentId?a.get(n.environmentId):void 0,O=oe(n.input,Re),A=n.kind.includes("deploy"),m=O[0]??n.kind,X=[n.kind,n.id,n.correlationId,n.state,...O].join(" ");s.push({type:A?"deployment":"operation",id:n.id,title:m,subtitle:`${n.kind} · ${n.state}`,href:`/server/activity?env=${encodeURIComponent(L?.slug??i[0]?.slug??"")}&operation=${encodeURIComponent(n.id)}`,environment:L?.slug,status:n.state,tags:[],score:W(t.query,m,X)})}for(let n of s)if(n.score===0)n.score=W(t.query,n.title,`${n.title} ${n.subtitle} ${n.environment??""} ${n.provider??""}`);let J={service:0,server:1,database:2,deployment:3,environment:4,project:5,operation:6};return s.filter((n)=>n.score>0).sort((n,L)=>L.score-n.score||J[n.type]-J[L.type]||n.title.localeCompare(L.title)||n.id.localeCompare(L.id)).slice(0,Math.min(50,Math.max(1,t.limit??20)))}export{C as Ag,I as Bg,Z as Cg,de as Dg,ne as Eg,Ee as Fg,Ue as Gg};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{Gd as he}from"./chunk-9mydnqr6.js";import{Rd as ge,Wd as pe}from"./chunk-q182t9ba.js";import{Zd as de}from"./chunk-nmkm1f68.js";import{hg as ye}from"./chunk-nyc2jxd8.js";import{ig as le}from"./chunk-21gggxvf.js";import{og as V,pg as Z}from"./chunk-4a85nk2q.js";import{ch as N,dh as te}from"./chunk-0y89hs67.js";import{_h as ce,mo as ue}from"./chunk-4a97kbk1.js";class j{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new N(V(t))}async query(e){let t=new URLSearchParams(te({Version:"2010-08-01",...e})).toString();return this.client.request({service:"monitoring",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t})}async getMetricStatistics(e){let t={Action:"GetMetricStatistics",Namespace:e.Namespace,MetricName:e.MetricName,StartTime:e.StartTime.toISOString(),EndTime:e.EndTime.toISOString(),Period:e.Period};(e.Statistics??[]).forEach((o,h)=>{t[`Statistics.member.${h+1}`]=o}),(e.ExtendedStatistics??[]).forEach((o,h)=>{t[`ExtendedStatistics.member.${h+1}`]=o}),(e.Dimensions??[]).forEach((o,h)=>{t[`Dimensions.member.${h+1}.Name`]=o.Name,t[`Dimensions.member.${h+1}.Value`]=o.Value});let r=await this.query(t),s=(r.GetMetricStatisticsResult||r)?.Datapoints?.member??[];if(!Array.isArray(s))s=s?[s]:[];return s.map((o)=>{let h={},m=o.ExtendedStatistics?.entry;if(m){if(!Array.isArray(m))m=[m];for(let d of m)if(d?.key!=null)h[d.key]=Number(d.value)}return{Timestamp:o.Timestamp,Sum:o.Sum!=null?Number(o.Sum):void 0,Average:o.Average!=null?Number(o.Average):void 0,Maximum:o.Maximum!=null?Number(o.Maximum):void 0,Minimum:o.Minimum!=null?Number(o.Minimum):void 0,Percentiles:Object.keys(h).length?h:void 0,Unit:o.Unit}})}async getMetricSeries(e){let t=/^p\d/.test(e.Stat);return(await this.getMetricStatistics({Namespace:e.Namespace,MetricName:e.MetricName,Dimensions:e.Dimensions,StartTime:e.StartTime,EndTime:e.EndTime,Period:e.Period,Statistics:t?[]:[e.Stat],ExtendedStatistics:t?[e.Stat]:[]})).slice().sort((a,s)=>new Date(a.Timestamp??0).getTime()-new Date(s.Timestamp??0).getTime()).map((a)=>t?a.Percentiles?.[e.Stat]??0:a[e.Stat]??0)}async describeAlarms(e){let t={Action:"DescribeAlarms"};if(e?.AlarmNamePrefix)t.AlarmNamePrefix=e.AlarmNamePrefix;if(e?.MaxRecords)t.MaxRecords=e.MaxRecords;let r=await this.query(t),s=(r.DescribeAlarmsResult||r)?.MetricAlarms?.member??[];if(!Array.isArray(s))s=s?[s]:[];return s.map((o)=>({AlarmName:o.AlarmName,StateValue:o.StateValue,MetricName:o.MetricName,ComparisonOperator:o.ComparisonOperator,Threshold:o.Threshold!=null?Number(o.Threshold):void 0,Namespace:o.Namespace}))}async putMetricAlarm(e){let t={Action:"PutMetricAlarm",AlarmName:e.AlarmName,Namespace:e.Namespace,MetricName:e.MetricName,ComparisonOperator:e.ComparisonOperator,Threshold:e.Threshold,EvaluationPeriods:e.EvaluationPeriods,Period:e.Period,Statistic:e.Statistic};if(e.AlarmDescription)t.AlarmDescription=e.AlarmDescription;(e.Dimensions??[]).forEach((r,a)=>{t[`Dimensions.member.${a+1}.Name`]=r.Name,t[`Dimensions.member.${a+1}.Value`]=r.Value}),(e.AlarmActions??[]).forEach((r,a)=>{t[`AlarmActions.member.${a+1}`]=r}),await this.query(t)}async deleteAlarms(e){if(!e.length)return;let t={Action:"DeleteAlarms"};e.forEach((r,a)=>{t[`AlarmNames.member.${a+1}`]=r}),await this.query(t)}}class K{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new N(void 0,{profile:t})}async createLogGroup(e,t){await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.CreateLogGroup","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({logGroupName:e,...t?{tags:t}:{}})})}async putRetentionPolicy(e,t){if(![1,3,5,7,14,30,60,90,120,150,180,365,400,545,731,1096,1827,2192,2557,2922,3288,3653].includes(t))throw Error("Unsupported CloudWatch Logs retention period");await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.PutRetentionPolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({logGroupName:e,retentionInDays:t})})}async describeLogStreams(e){let t={logGroupName:e.logGroupName};if(e.logStreamNamePrefix)t.logStreamNamePrefix=e.logStreamNamePrefix;if(e.orderBy)t.orderBy=e.orderBy;if(e.descending!==void 0)t.descending=e.descending;if(e.limit)t.limit=e.limit;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.DescribeLogStreams","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async getLogEvents(e){let t={logGroupName:e.logGroupName,logStreamName:e.logStreamName};if(e.startTime)t.startTime=e.startTime;if(e.endTime)t.endTime=e.endTime;if(e.limit)t.limit=e.limit;if(e.startFromHead!==void 0)t.startFromHead=e.startFromHead;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.GetLogEvents","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async describeLogGroups(e){let t={};if(e?.logGroupNamePrefix)t.logGroupNamePrefix=e.logGroupNamePrefix;if(e?.limit)t.limit=e.limit;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.DescribeLogGroups","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async deleteLogGroup(e){await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.DeleteLogGroup","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({logGroupName:e})})}async filterLogEvents(e){let t={logGroupName:e.logGroupName};if(e.logStreamNames)t.logStreamNames=e.logStreamNames;if(e.startTime)t.startTime=e.startTime;if(e.endTime)t.endTime=e.endTime;if(e.filterPattern)t.filterPattern=e.filterPattern;if(e.limit)t.limit=e.limit;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.FilterLogEvents","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}}import{createHash as fe}from"node:crypto";import{existsSync as re,mkdirSync as Se,readdirSync as Ce,readFileSync as Te,rmSync as be,writeFileSync as Ne}from"node:fs";import{homedir as Ae}from"node:os";import{join as I}from"node:path";var se=1,ie=3600000,Me=24*ie,ve=ie,xe=30*Me;function H(){let e=process.env.XDG_CACHE_HOME;return I(e&&e.trim()?e:I(Ae(),".cache"),"ts-cloud","cost-explorer")}function B(e){return I(H(),e??"__default__")}function ae(e){let t={s:e.start,e:e.end,g:e.granularity,m:[...e.metrics].sort(),gb:[...e.groupBy].map((r)=>`${r.Type}:${r.Key}`).sort(),f:e.filter??null};return fe("sha256").update(JSON.stringify(t)).digest("hex").slice(0,24)}function De(e,t){let r=Date.parse(`${t}T00:00:00Z`);if(Number.isNaN(r))return!1;let a=new Date,s=Date.UTC(a.getUTCFullYear(),a.getUTCMonth(),1);return r<=s}function Pe(e){return De(e.start,e.end)?xe:ve}function ne(e,t){let r=I(B(e),`${ae(t)}.json`);if(!re(r))return null;let a;try{a=JSON.parse(Te(r,"utf-8"))}catch{return null}if(a.schema!==se)return null;let s=Date.now()-a.savedAt;if(s<0||s>Pe(t))return null;return{response:a.response,ageSeconds:Math.floor(s/1000)}}function oe(e,t,r){let a=B(e);Se(a,{recursive:!0});let s={schema:se,savedAt:Date.now(),key:t,response:r};Ne(I(a,`${ae(t)}.json`),JSON.stringify(s))}function We(e){let t=e===void 0?H():B(e);if(!re(t))return{deletedFiles:0,scope:e??"all profiles"};let r=0;function a(s){for(let o of Ce(s,{withFileTypes:!0})){let h=I(s,o.name);if(o.isDirectory())a(h);else if(o.isFile()&&o.name.endsWith(".json"))r++}}return a(t),be(t,{recursive:!0,force:!0}),{deletedFiles:r,scope:e??"all profiles"}}function Ge(e){return e===void 0?H():B(e)}class Y{client;profile;useCache;lastCacheAgeSeconds=null;constructor(e,t){this.profile=e,this.useCache=t?.useCache??!0,this.client=new N(V(e))}async getCostByService(e){return(await this.getCostByDimension({...e,dimension:"SERVICE"})).map((r)=>({service:r.key,amount:r.amount,unit:r.unit}))}async getCostByDimension(e){let{start:t,end:r,dimension:a,granularity:s="MONTHLY",filter:o}=e,h=["UnblendedCost"],m=[{Type:"DIMENSION",Key:a}],d={start:t,end:r,granularity:s,metrics:h,groupBy:m,filter:o};if(this.useCache){let C=ne(this.profile,d);if(C)return this.lastCacheAgeSeconds=C.ageSeconds,C.response}this.lastCacheAgeSeconds=null;let p=new Map,i;do{let C={TimePeriod:{Start:t,End:r},Granularity:s,Metrics:h,GroupBy:m};if(o)C.Filter=o;if(i)C.NextPageToken=i;let D=await this.client.request({service:"ce",region:"us-east-1",method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"AWSInsightsIndexService.GetCostAndUsage"},body:JSON.stringify(C)});for(let G of D?.ResultsByTime??[])for(let T of G?.Groups??[]){let O=T.Keys?.[0]??"Unknown",_=Number.parseFloat(T.Metrics?.UnblendedCost?.Amount??"0"),q=T.Metrics?.UnblendedCost?.Unit??"USD",P=p.get(O);p.set(O,{key:O,amount:(P?.amount??0)+_,unit:q})}i=D?.NextPageToken||void 0}while(i);let E=[...p.values()].filter((C)=>C.amount>0).sort((C,D)=>D.amount-C.amount);if(this.useCache)oe(this.profile,d,E);return E}async getDailyTotals(e){return((await this.client.request({service:"ce",region:"us-east-1",method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"AWSInsightsIndexService.GetCostAndUsage"},body:JSON.stringify({TimePeriod:{Start:e.start,End:e.end},Granularity:"DAILY",Metrics:["UnblendedCost"]})}))?.ResultsByTime??[]).map((a)=>Number.parseFloat(a.Total?.UnblendedCost?.Amount??"0"))}}class J{client;region;constructor(e="us-east-1"){this.region=e,this.client=new N}async describeFileSystems(e){let t=[];if(e?.FileSystemId)t.push(`FileSystemId=${encodeURIComponent(e.FileSystemId)}`);if(e?.CreationToken)t.push(`CreationToken=${encodeURIComponent(e.CreationToken)}`);let r=`/2015-02-01/file-systems${t.length>0?`?${t.join("&")}`:""}`;return{FileSystems:((await this.client.request({service:"elasticfilesystem",region:this.region,method:"GET",path:r,headers:{"Content-Type":"application/json"}})).FileSystems||[]).map((s)=>({FileSystemId:s.FileSystemId,Name:s.Name,CreationTime:s.CreationTime,LifeCycleState:s.LifeCycleState,NumberOfMountTargets:s.NumberOfMountTargets,SizeInBytes:s.SizeInBytes?{Value:s.SizeInBytes.Value,Timestamp:s.SizeInBytes.Timestamp}:void 0,PerformanceMode:s.PerformanceMode,Encrypted:s.Encrypted,ThroughputMode:s.ThroughputMode,Tags:s.Tags}))}}}class Q{client;region;constructor(e="us-east-1"){this.region=e,this.client=new N}async call(e,t){return this.client.request({service:"wafv2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`AWSWAF_20190729.${e}`},body:JSON.stringify(t)})}async listWebACLs(e="REGIONAL"){return(await this.call("ListWebACLs",{Scope:e,Limit:100}))?.WebACLs??[]}async getWebACLRules(e,t,r="REGIONAL"){return((await this.call("GetWebACL",{Name:e,Id:t,Scope:r}))?.WebACL?.Rules??[]).map((o)=>({Name:o.Name,Priority:o.Priority,Action:o.Action?Object.keys(o.Action)[0]:o.OverrideAction?Object.keys(o.OverrideAction)[0]:"count"}))}}function me(e){return String(e).padStart(2,"0")}function F(e){return`${e.getUTCFullYear()}-${me(e.getUTCMonth()+1)}-${me(e.getUTCDate())}`}function we(e){let t=Math.max(0,Math.round((Date.now()-e)/1000));if(t<60)return`${t}s ago`;let r=Math.round(t/60);if(r<60)return`${r}m ago`;let a=Math.round(r/60);if(a<48)return`${a}h ago`;return`${Math.round(a/24)}d ago`}async function k(e,t,r,a,s,o){let h=await e.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:r,Dimensions:[{Name:"FunctionName",Value:t}],StartTime:s,EndTime:o,Period:86400,Statistics:[a]}).catch(()=>[]);if(!h.length)return 0;if(a==="Sum")return h.reduce((m,d)=>m+(d.Sum??0),0);if(a==="Maximum")return Math.max(...h.map((m)=>m.Maximum??0));return h.reduce((m,d)=>m+(d.Average??0),0)/h.length}async function W(e,t,r,a,s,o,h){let m=await e.getMetricStatistics({Namespace:t,MetricName:r,Dimensions:a,StartTime:o,EndTime:h,Period:86400,Statistics:[s]}).catch(()=>[]);if(!m.length)return 0;if(s==="Sum")return m.reduce((d,p)=>d+(p.Sum??0),0);if(s==="Maximum")return Math.max(...m.map((d)=>d.Maximum??0));return m.reduce((d,p)=>d+(p.Average??0),0)/m.length}async function X(e,t,r,a,s){let o=await e.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"Duration",Dimensions:[{Name:"FunctionName",Value:t}],StartTime:a,EndTime:s,Period:86400,ExtendedStatistics:[r]}).catch(()=>[]);return Math.round(o.reduce((h,m)=>h+(m.Percentiles?.[r]??0),0))}async function mt(e,t){let r=await pe(e,t),a=r.region,s=new j(a),o=new de(a),h=new K(a),m=new Date,d=new Date(m.getTime()-86400000),p=e.environments?.[t]?.app,i={};i.app={name:r.slug,env:t,region:a,runtime:p?.kind==="php"?`php-${p?.phpVersion??"8.3"} (fpm)`:p?.kind??"node",url:r.endpoint??"",build:r.lastRelease?.sha?.slice(0,7)??"—",deployedAt:r.lastRelease?.timestamp??"—"},i.maintenance={enabled:!1},i.scheduler={enabled:r.scheduler!=="off",expression:r.scheduler==="sub-minute"?"rate(1 minute) · sub-minute":"rate(1 minute)",lastRun:"—"};let E=0,C=0,D=0,G=[],T=[],O=[];for(let n of r.functions){let[u,l,c,f,g,S,b,A,w]=await Promise.all([k(s,n.name,"Invocations","Sum",d,m),k(s,n.name,"Errors","Sum",d,m),k(s,n.name,"Throttles","Sum",d,m),k(s,n.name,"Duration","Average",d,m),o.getFunction(n.name).catch(()=>null),X(s,n.name,"p50",d,m),X(s,n.name,"p95",d,m),X(s,n.name,"p99",d,m),s.getMetricSeries({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:[{Name:"FunctionName",Value:n.name}],StartTime:new Date(m.getTime()-43200000),EndTime:m,Period:3600,Stat:"Sum"}).catch(()=>[])]);E+=u,C+=l,D=Math.max(D,f);let R=g?.Configuration?.MemorySize??0,M=Object.keys(g?.Configuration?.Environment?.Variables??{}),U=[],y=0;try{let{events:z=[]}=await h.filterLogEvents({logGroupName:`/aws/lambda/${n.name}`,startTime:d.getTime(),limit:120});for(let x of z){let L=(x.message??"").trim(),ee=/Max Memory Used:\s*(\d+)\s*MB/.exec(L);if(ee)y=Math.max(y,Number(ee[1]));if(L&&!/^(?:START|END|REPORT|INIT_START)/.test(L))O.push({source:n.mode||n.name,timestamp:new Date(x.timestamp??0).toISOString(),when:we(x.timestamp??0),message:L.slice(0,400),level:/error|exception|fatal|panic|traceback/i.test(L)?"error":/warn|warning|timeout|retr(?:y|ies)|throttl/i.test(L)?"warn":"info"})}U=z.filter((x)=>!/^(?:START|END|REPORT|INIT_START)/.test((x.message??"").trim())).slice(-6).map((x)=>({ts:new Date(x.timestamp??0).toISOString().slice(11,19),msg:(x.message??"").trim().slice(0,120),err:/error|exception|fatal/i.test(x.message??"")}))}catch{}let v=Math.max(1,...w);G.push({key:n.mode,name:n.name,version:n.version,memory:R,timeout:g?.Configuration?.Timeout??0,runtime:g?.Configuration?.Runtime??"provided.al2023",invocations:Math.round(u),errors:Math.round(l),p95:b||Math.round(f),status:"active",provisioned:n.provisioned?`${n.provisioned.allocated}/${n.provisioned.requested}`:void 0}),T.push({key:n.mode,name:n.name,runtime:g?.Configuration?.Runtime??"provided.al2023",arch:g?.Configuration?.Architectures?.[0]??"x86_64",memory:R,timeout:g?.Configuration?.Timeout??0,ephemeral:g?.Configuration?.EphemeralStorage?.Size??512,version:n.version,concurrency:p?.concurrency??"—",invocations:Math.round(u),errors:Math.round(l),throttles:Math.round(c),p50:S||Math.round(f),p95:b||Math.round(f),p99:A||Math.round(f),maxMem:y,spark:w.length?w.map((z)=>Math.round(z/v*100)):[0],env:M.length?M:["(none)"],recent:U.length?U:[{ts:"—",msg:"no recent events",err:!1}]})}i.functions=G,i.functionsDetail=T,i.serverlessLogs=O.sort((n,u)=>String(u.timestamp).localeCompare(String(n.timestamp))).slice(0,600),i.serverlessLogsEmptyReason=O.length?void 0:"No recent function logs were found in CloudWatch for this environment.";let _=E?Number((C/E*100).toFixed(2)):0,q=Math.round(await k(s,r.functions[0]?.name??"","ConcurrentExecutions","Maximum",d,m));i.metrics={invocations:Math.round(E),errorRatePct:_,p95Ms:Math.round(D),coldStartPct:void 0,concurrency:q,estCostUsd:void 0};try{let n=new he(a),u=[],l=[],c=0;try{let{QueueUrl:g}=await n.getQueueUrl(`${r.slug}-${t}-dlq`),{Attributes:S}=await n.getQueueAttributes(g);c=Number(S.ApproximateNumberOfMessages??0)}catch{}let f=p?ue(p,r.slug,t):[];for(let g of f){let S=g.name.replace(`${r.slug}-${t}-`,""),b=0,A=0;try{let{QueueUrl:R}=await n.getQueueUrl(g.name),{Attributes:M}=await n.getQueueAttributes(R);b=Number(M.ApproximateNumberOfMessages??0),A=Number(M.ApproximateNumberOfMessagesNotVisible??0)}catch{}let w=Math.round(await W(s,"AWS/SQS","NumberOfMessagesDeleted",[{Name:"QueueName",Value:g.name}],"Sum",d,m));u.push({name:S,visible:b,inFlight:A,processed:w,dlq:c}),l.push({name:g.name,short:S,visible:b,inFlight:A,delayed:0,processed:w,oldestSec:0,concurrency:g.concurrency??p?.queueConcurrency??"—",tries:p?.queueTries??3,visTimeout:(p?.queueTimeout??120)*6,dlq:c})}if(u.length)i.queues=u;if(l.length)i.queuesDetail=l;i.dlqItems=[]}catch{}try{let n=new le(a),{Stacks:u}=await n.describeStacks({stackName:ce(e,t)}),l={};for(let c of u?.[0]?.Outputs??[])if(c.OutputKey)l[c.OutputKey]=c.OutputValue??"";if(p?.database?.connection==="aurora-serverless"){let c=`${r.slug}-${t}-db`,f=[{Name:"DBClusterIdentifier",Value:c}],[g,S]=await Promise.all([W(s,"AWS/RDS","ServerlessDatabaseCapacity",f,"Average",d,m),W(s,"AWS/RDS","DatabaseConnections",f,"Maximum",d,m)]);if(i.aurora={id:c,engine:"aurora-mysql",minAcu:p?.database?.minCapacity??0.5,maxAcu:p?.database?.maxCapacity??4,currentAcu:g?Number(g.toFixed(1)):p?.database?.minCapacity??0.5,database:"app",connections:Math.round(S),status:l.DbEndpoint?"available":"creating"},p?.rdsProxy)i.proxy={name:`${r.slug}-${t}-proxy`,endpoint:l.DbProxyEndpoint??"—",pooledConns:Math.round(S),status:"available"}}if(p?.cache?.driver==="elasticache"){let c=`${r.slug}-${t}-cache`,f=[{Name:"CacheClusterId",Value:`${c}-001`}],[g,S]=await Promise.all([W(s,"AWS/ElastiCache","CacheHits",f,"Sum",d,m),W(s,"AWS/ElastiCache","CacheMisses",f,"Sum",d,m)]),b=g+S>0?Number((g/(g+S)*100).toFixed(1)):0;i.redis={id:c,node:"cache.t4g.micro",engine:"redis",hitRate:b,status:l.CacheEndpoint?"available":"creating"}}if(p?.efs){let c=0;try{if(l.EfsFileSystemId){let f=new J(a),{FileSystems:g}=await f.describeFileSystems({FileSystemId:l.EfsFileSystemId});c=Number(((g?.[0]?.SizeInBytes?.Value??0)/1048576).toFixed(1))}}catch{}i.efs={id:l.EfsFileSystemId??"efs",mount:"/mnt/local",sizeMb:c,status:"available"}}i.assetsInfo=l.AssetsCdnDomain?{bucket:l.AssetsBucketName??`${r.slug}-${t}-assets`,cdn:l.AssetsCdnDomain,customDomain:p?.assetDomain??"—",assetUrl:r.assetUrl??"—",files:0,sizeMb:0,cacheHitPct:0,build:i.app.build}:void 0}catch{}if(i.assetsInfo)try{let u=await new Z(a).list({bucket:i.assetsInfo.bucket,maxKeys:1000});i.assetsInfo.files=u.length,i.assetsInfo.sizeMb=Number((u.reduce((l,c)=>l+(c.Size??0),0)/1048576).toFixed(1)),i.assetsRecent=u.slice(0,8).map((l)=>({path:`/${l.Key}`,size:`${Math.max(1,Math.round((l.Size??0)/1024))} KB`,type:l.Key.split(".").pop()??""}))}catch{}try{if(p?.secrets){let n=Array.isArray(p.secrets)?p.secrets.map((u)=>({key:u.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),source:u})):Object.entries(p.secrets).map(([u,l])=>({key:u,source:String(l)}));i.secretsList=n.map((u)=>({...u,updated:"—"}))}}catch{}try{let n=new Z(a),u=`${r.slug}-${t}-deployments`,l=await n.getObjectJson(u,`deployments/${r.slug}/${t}/history.json`).catch(()=>null);if(l?.records?.length)i.deploymentsDetail=l.records.slice(-12).reverse().map((c)=>({sha:(c.sha??"").slice(0,7),status:c.status??"success",when:c.timestamp??"—",took:c.took??"—",by:c.by??"—",version:c.version??"—",hooks:c.hooks??[]}))}catch{}i.metricsTotals={invocations:i.metrics.invocations,errors:Math.round(C),errorRatePct:_,p95Ms:i.metrics.p95Ms,throttles:T.reduce((n,u)=>n+u.throttles,0),coldStartPct:void 0,estCostUsd:void 0,concurrency:q},i.metricsPerFn=T.map((n)=>({key:n.key,invocations:n.invocations,errors:n.errors,throttles:n.throttles,avgMs:n.p50,maxMs:n.p99,costUsd:void 0}));try{i.invSpark=await s.getMetricSeries({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:[{Name:"FunctionName",Value:r.functions.find((n)=>n.mode==="http")?.name??""}],StartTime:new Date(m.getTime()-86400000),EndTime:m,Period:3600,Stat:"Sum"})}catch{}try{let n=new Y,u=m,l=new Date(Date.UTC(u.getUTCFullYear(),u.getUTCMonth(),1)),c=new Date(Date.UTC(u.getUTCFullYear(),u.getUTCMonth()-1,1)),[f,g]=await Promise.all([n.getCostByService({start:F(l),end:F(u),granularity:"MONTHLY"}).catch(()=>[]),n.getCostByService({start:F(c),end:F(l),granularity:"MONTHLY"}).catch(()=>[])]);if(f.length){let S=f.reduce((y,v)=>y+v.amount,0),b=g.reduce((y,v)=>y+v.amount,0),A=u.getUTCDate(),w=new Date(Date.UTC(u.getUTCFullYear(),u.getUTCMonth()+1,0)).getUTCDate();i.costSummary={monthToDateUsd:Number(S.toFixed(2)),projectedUsd:Number((S/A*w).toFixed(2)),lastMonthUsd:Number(b.toFixed(2)),dailyAvgUsd:Number((S/A).toFixed(2))},i.costServices=f.filter((y)=>y.amount>0).sort((y,v)=>v.amount-y.amount).slice(0,12).map((y)=>({name:y.service,usd:Number(y.amount.toFixed(2)),note:""})),i.metrics.estCostUsd=Number((S/A).toFixed(2)),i.metricsTotals.estCostUsd=i.metrics.estCostUsd,i.costTrend=await n.getDailyTotals({start:F(l),end:F(u)}).catch(()=>[]);let R=f.find((y)=>/lambda/i.test(y.service))?.amount??0,M=(y)=>y.invocations*(y.p50/1000)*(y.memory/1024),U=T.reduce((y,v)=>y+M(v),0)||1;i.costPerFn=T.map((y)=>({key:y.key,requests:y.invocations,gbSec:Math.round(M(y)),usd:Number((R*(M(y)/U)).toFixed(2))}))}}catch{}if(p?.firewall)try{let n=await s.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"BlockedRequests",StartTime:d,EndTime:m,Period:86400,Statistics:["Sum"]}).catch(()=>[]),u=await s.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"AllowedRequests",StartTime:d,EndTime:m,Period:86400,Statistics:["Sum"]}).catch(()=>[]);i.waf={enabled:!0,scope:"REGIONAL",acl:`${r.slug}-${t}-waf`,allowed24h:Math.round(u.reduce((l,c)=>l+(c.Sum??0),0)),blocked24h:Math.round(n.reduce((l,c)=>l+(c.Sum??0),0))};try{let l=new Q(a),c=await l.listWebACLs("REGIONAL"),f=c.find((g)=>g.Name?.includes(`${r.slug}-${t}`))??c[0];if(f?.Name&&f.Id){i.waf.acl=f.Name;let g=await l.getWebACLRules(f.Name,f.Id,"REGIONAL");if(g.length)i.wafRules=g.map((S)=>({name:S.Name??"—",detail:`priority ${S.Priority??0}`,action:S.Action??"count",blocked24h:0}))}}catch{}}catch{}let P=[];if(i.aurora)P.push({name:"Aurora Serverless v2",detail:`${i.aurora.id} · ${i.aurora.minAcu}-${i.aurora.maxAcu} ACU`,status:i.aurora.status});if(i.proxy)P.push({name:"RDS Proxy",detail:i.proxy.name,status:i.proxy.status});if(i.redis)P.push({name:`ElastiCache (${i.redis.engine})`,detail:`${i.redis.node} · ${i.redis.hitRate}% hit rate`,status:i.redis.status});if(i.efs)P.push({name:"EFS",detail:`${i.efs.mount} · ${i.efs.sizeMb} MB`,status:i.efs.status});if(P.length)i.dataServices=P;if(r.scheduler!=="off"&&p?.kind==="php")try{let n=await ge(e,t,"schedule:list"),u=[];for(let l of(n||"").split(`
|
|
1
|
+
import{Hd as he}from"./chunk-d7ke90zt.js";import{Sd as ge,Xd as pe}from"./chunk-kg61p5hw.js";import{_d as de}from"./chunk-c0bdafbx.js";import{ig as ye}from"./chunk-xhwqpgwq.js";import{jg as le}from"./chunk-a7w13qfm.js";import{pg as V,qg as Z}from"./chunk-btsyjhk7.js";import{dh as N,eh as te}from"./chunk-ja1vjdn1.js";import{$h as ce,no as ue}from"./chunk-4q6tad44.js";class j{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new N(V(t))}async query(e){let t=new URLSearchParams(te({Version:"2010-08-01",...e})).toString();return this.client.request({service:"monitoring",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t})}async getMetricStatistics(e){let t={Action:"GetMetricStatistics",Namespace:e.Namespace,MetricName:e.MetricName,StartTime:e.StartTime.toISOString(),EndTime:e.EndTime.toISOString(),Period:e.Period};(e.Statistics??[]).forEach((o,h)=>{t[`Statistics.member.${h+1}`]=o}),(e.ExtendedStatistics??[]).forEach((o,h)=>{t[`ExtendedStatistics.member.${h+1}`]=o}),(e.Dimensions??[]).forEach((o,h)=>{t[`Dimensions.member.${h+1}.Name`]=o.Name,t[`Dimensions.member.${h+1}.Value`]=o.Value});let r=await this.query(t),s=(r.GetMetricStatisticsResult||r)?.Datapoints?.member??[];if(!Array.isArray(s))s=s?[s]:[];return s.map((o)=>{let h={},m=o.ExtendedStatistics?.entry;if(m){if(!Array.isArray(m))m=[m];for(let d of m)if(d?.key!=null)h[d.key]=Number(d.value)}return{Timestamp:o.Timestamp,Sum:o.Sum!=null?Number(o.Sum):void 0,Average:o.Average!=null?Number(o.Average):void 0,Maximum:o.Maximum!=null?Number(o.Maximum):void 0,Minimum:o.Minimum!=null?Number(o.Minimum):void 0,Percentiles:Object.keys(h).length?h:void 0,Unit:o.Unit}})}async getMetricSeries(e){let t=/^p\d/.test(e.Stat);return(await this.getMetricStatistics({Namespace:e.Namespace,MetricName:e.MetricName,Dimensions:e.Dimensions,StartTime:e.StartTime,EndTime:e.EndTime,Period:e.Period,Statistics:t?[]:[e.Stat],ExtendedStatistics:t?[e.Stat]:[]})).slice().sort((a,s)=>new Date(a.Timestamp??0).getTime()-new Date(s.Timestamp??0).getTime()).map((a)=>t?a.Percentiles?.[e.Stat]??0:a[e.Stat]??0)}async describeAlarms(e){let t={Action:"DescribeAlarms"};if(e?.AlarmNamePrefix)t.AlarmNamePrefix=e.AlarmNamePrefix;if(e?.MaxRecords)t.MaxRecords=e.MaxRecords;let r=await this.query(t),s=(r.DescribeAlarmsResult||r)?.MetricAlarms?.member??[];if(!Array.isArray(s))s=s?[s]:[];return s.map((o)=>({AlarmName:o.AlarmName,StateValue:o.StateValue,MetricName:o.MetricName,ComparisonOperator:o.ComparisonOperator,Threshold:o.Threshold!=null?Number(o.Threshold):void 0,Namespace:o.Namespace}))}async putMetricAlarm(e){let t={Action:"PutMetricAlarm",AlarmName:e.AlarmName,Namespace:e.Namespace,MetricName:e.MetricName,ComparisonOperator:e.ComparisonOperator,Threshold:e.Threshold,EvaluationPeriods:e.EvaluationPeriods,Period:e.Period,Statistic:e.Statistic};if(e.AlarmDescription)t.AlarmDescription=e.AlarmDescription;(e.Dimensions??[]).forEach((r,a)=>{t[`Dimensions.member.${a+1}.Name`]=r.Name,t[`Dimensions.member.${a+1}.Value`]=r.Value}),(e.AlarmActions??[]).forEach((r,a)=>{t[`AlarmActions.member.${a+1}`]=r}),await this.query(t)}async deleteAlarms(e){if(!e.length)return;let t={Action:"DeleteAlarms"};e.forEach((r,a)=>{t[`AlarmNames.member.${a+1}`]=r}),await this.query(t)}}class K{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new N(void 0,{profile:t})}async createLogGroup(e,t){await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.CreateLogGroup","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({logGroupName:e,...t?{tags:t}:{}})})}async putRetentionPolicy(e,t){if(![1,3,5,7,14,30,60,90,120,150,180,365,400,545,731,1096,1827,2192,2557,2922,3288,3653].includes(t))throw Error("Unsupported CloudWatch Logs retention period");await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.PutRetentionPolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({logGroupName:e,retentionInDays:t})})}async describeLogStreams(e){let t={logGroupName:e.logGroupName};if(e.logStreamNamePrefix)t.logStreamNamePrefix=e.logStreamNamePrefix;if(e.orderBy)t.orderBy=e.orderBy;if(e.descending!==void 0)t.descending=e.descending;if(e.limit)t.limit=e.limit;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.DescribeLogStreams","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async getLogEvents(e){let t={logGroupName:e.logGroupName,logStreamName:e.logStreamName};if(e.startTime)t.startTime=e.startTime;if(e.endTime)t.endTime=e.endTime;if(e.limit)t.limit=e.limit;if(e.startFromHead!==void 0)t.startFromHead=e.startFromHead;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.GetLogEvents","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async describeLogGroups(e){let t={};if(e?.logGroupNamePrefix)t.logGroupNamePrefix=e.logGroupNamePrefix;if(e?.limit)t.limit=e.limit;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.DescribeLogGroups","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async deleteLogGroup(e){await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.DeleteLogGroup","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({logGroupName:e})})}async filterLogEvents(e){let t={logGroupName:e.logGroupName};if(e.logStreamNames)t.logStreamNames=e.logStreamNames;if(e.startTime)t.startTime=e.startTime;if(e.endTime)t.endTime=e.endTime;if(e.filterPattern)t.filterPattern=e.filterPattern;if(e.limit)t.limit=e.limit;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.FilterLogEvents","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}}import{createHash as fe}from"node:crypto";import{existsSync as re,mkdirSync as Se,readdirSync as Ce,readFileSync as Te,rmSync as be,writeFileSync as Ne}from"node:fs";import{homedir as Ae}from"node:os";import{join as I}from"node:path";var se=1,ie=3600000,Me=24*ie,ve=ie,xe=30*Me;function H(){let e=process.env.XDG_CACHE_HOME;return I(e&&e.trim()?e:I(Ae(),".cache"),"ts-cloud","cost-explorer")}function B(e){return I(H(),e??"__default__")}function ae(e){let t={s:e.start,e:e.end,g:e.granularity,m:[...e.metrics].sort(),gb:[...e.groupBy].map((r)=>`${r.Type}:${r.Key}`).sort(),f:e.filter??null};return fe("sha256").update(JSON.stringify(t)).digest("hex").slice(0,24)}function De(e,t){let r=Date.parse(`${t}T00:00:00Z`);if(Number.isNaN(r))return!1;let a=new Date,s=Date.UTC(a.getUTCFullYear(),a.getUTCMonth(),1);return r<=s}function Pe(e){return De(e.start,e.end)?xe:ve}function ne(e,t){let r=I(B(e),`${ae(t)}.json`);if(!re(r))return null;let a;try{a=JSON.parse(Te(r,"utf-8"))}catch{return null}if(a.schema!==se)return null;let s=Date.now()-a.savedAt;if(s<0||s>Pe(t))return null;return{response:a.response,ageSeconds:Math.floor(s/1000)}}function oe(e,t,r){let a=B(e);Se(a,{recursive:!0});let s={schema:se,savedAt:Date.now(),key:t,response:r};Ne(I(a,`${ae(t)}.json`),JSON.stringify(s))}function We(e){let t=e===void 0?H():B(e);if(!re(t))return{deletedFiles:0,scope:e??"all profiles"};let r=0;function a(s){for(let o of Ce(s,{withFileTypes:!0})){let h=I(s,o.name);if(o.isDirectory())a(h);else if(o.isFile()&&o.name.endsWith(".json"))r++}}return a(t),be(t,{recursive:!0,force:!0}),{deletedFiles:r,scope:e??"all profiles"}}function Ge(e){return e===void 0?H():B(e)}class Y{client;profile;useCache;lastCacheAgeSeconds=null;constructor(e,t){this.profile=e,this.useCache=t?.useCache??!0,this.client=new N(V(e))}async getCostByService(e){return(await this.getCostByDimension({...e,dimension:"SERVICE"})).map((r)=>({service:r.key,amount:r.amount,unit:r.unit}))}async getCostByDimension(e){let{start:t,end:r,dimension:a,granularity:s="MONTHLY",filter:o}=e,h=["UnblendedCost"],m=[{Type:"DIMENSION",Key:a}],d={start:t,end:r,granularity:s,metrics:h,groupBy:m,filter:o};if(this.useCache){let C=ne(this.profile,d);if(C)return this.lastCacheAgeSeconds=C.ageSeconds,C.response}this.lastCacheAgeSeconds=null;let p=new Map,i;do{let C={TimePeriod:{Start:t,End:r},Granularity:s,Metrics:h,GroupBy:m};if(o)C.Filter=o;if(i)C.NextPageToken=i;let D=await this.client.request({service:"ce",region:"us-east-1",method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"AWSInsightsIndexService.GetCostAndUsage"},body:JSON.stringify(C)});for(let G of D?.ResultsByTime??[])for(let T of G?.Groups??[]){let O=T.Keys?.[0]??"Unknown",_=Number.parseFloat(T.Metrics?.UnblendedCost?.Amount??"0"),q=T.Metrics?.UnblendedCost?.Unit??"USD",P=p.get(O);p.set(O,{key:O,amount:(P?.amount??0)+_,unit:q})}i=D?.NextPageToken||void 0}while(i);let E=[...p.values()].filter((C)=>C.amount>0).sort((C,D)=>D.amount-C.amount);if(this.useCache)oe(this.profile,d,E);return E}async getDailyTotals(e){return((await this.client.request({service:"ce",region:"us-east-1",method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"AWSInsightsIndexService.GetCostAndUsage"},body:JSON.stringify({TimePeriod:{Start:e.start,End:e.end},Granularity:"DAILY",Metrics:["UnblendedCost"]})}))?.ResultsByTime??[]).map((a)=>Number.parseFloat(a.Total?.UnblendedCost?.Amount??"0"))}}class J{client;region;constructor(e="us-east-1"){this.region=e,this.client=new N}async describeFileSystems(e){let t=[];if(e?.FileSystemId)t.push(`FileSystemId=${encodeURIComponent(e.FileSystemId)}`);if(e?.CreationToken)t.push(`CreationToken=${encodeURIComponent(e.CreationToken)}`);let r=`/2015-02-01/file-systems${t.length>0?`?${t.join("&")}`:""}`;return{FileSystems:((await this.client.request({service:"elasticfilesystem",region:this.region,method:"GET",path:r,headers:{"Content-Type":"application/json"}})).FileSystems||[]).map((s)=>({FileSystemId:s.FileSystemId,Name:s.Name,CreationTime:s.CreationTime,LifeCycleState:s.LifeCycleState,NumberOfMountTargets:s.NumberOfMountTargets,SizeInBytes:s.SizeInBytes?{Value:s.SizeInBytes.Value,Timestamp:s.SizeInBytes.Timestamp}:void 0,PerformanceMode:s.PerformanceMode,Encrypted:s.Encrypted,ThroughputMode:s.ThroughputMode,Tags:s.Tags}))}}}class Q{client;region;constructor(e="us-east-1"){this.region=e,this.client=new N}async call(e,t){return this.client.request({service:"wafv2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`AWSWAF_20190729.${e}`},body:JSON.stringify(t)})}async listWebACLs(e="REGIONAL"){return(await this.call("ListWebACLs",{Scope:e,Limit:100}))?.WebACLs??[]}async getWebACLRules(e,t,r="REGIONAL"){return((await this.call("GetWebACL",{Name:e,Id:t,Scope:r}))?.WebACL?.Rules??[]).map((o)=>({Name:o.Name,Priority:o.Priority,Action:o.Action?Object.keys(o.Action)[0]:o.OverrideAction?Object.keys(o.OverrideAction)[0]:"count"}))}}function me(e){return String(e).padStart(2,"0")}function F(e){return`${e.getUTCFullYear()}-${me(e.getUTCMonth()+1)}-${me(e.getUTCDate())}`}function we(e){let t=Math.max(0,Math.round((Date.now()-e)/1000));if(t<60)return`${t}s ago`;let r=Math.round(t/60);if(r<60)return`${r}m ago`;let a=Math.round(r/60);if(a<48)return`${a}h ago`;return`${Math.round(a/24)}d ago`}async function k(e,t,r,a,s,o){let h=await e.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:r,Dimensions:[{Name:"FunctionName",Value:t}],StartTime:s,EndTime:o,Period:86400,Statistics:[a]}).catch(()=>[]);if(!h.length)return 0;if(a==="Sum")return h.reduce((m,d)=>m+(d.Sum??0),0);if(a==="Maximum")return Math.max(...h.map((m)=>m.Maximum??0));return h.reduce((m,d)=>m+(d.Average??0),0)/h.length}async function W(e,t,r,a,s,o,h){let m=await e.getMetricStatistics({Namespace:t,MetricName:r,Dimensions:a,StartTime:o,EndTime:h,Period:86400,Statistics:[s]}).catch(()=>[]);if(!m.length)return 0;if(s==="Sum")return m.reduce((d,p)=>d+(p.Sum??0),0);if(s==="Maximum")return Math.max(...m.map((d)=>d.Maximum??0));return m.reduce((d,p)=>d+(p.Average??0),0)/m.length}async function X(e,t,r,a,s){let o=await e.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"Duration",Dimensions:[{Name:"FunctionName",Value:t}],StartTime:a,EndTime:s,Period:86400,ExtendedStatistics:[r]}).catch(()=>[]);return Math.round(o.reduce((h,m)=>h+(m.Percentiles?.[r]??0),0))}async function mt(e,t){let r=await pe(e,t),a=r.region,s=new j(a),o=new de(a),h=new K(a),m=new Date,d=new Date(m.getTime()-86400000),p=e.environments?.[t]?.app,i={};i.app={name:r.slug,env:t,region:a,runtime:p?.kind==="php"?`php-${p?.phpVersion??"8.3"} (fpm)`:p?.kind??"node",url:r.endpoint??"",build:r.lastRelease?.sha?.slice(0,7)??"—",deployedAt:r.lastRelease?.timestamp??"—"},i.maintenance={enabled:!1},i.scheduler={enabled:r.scheduler!=="off",expression:r.scheduler==="sub-minute"?"rate(1 minute) · sub-minute":"rate(1 minute)",lastRun:"—"};let E=0,C=0,D=0,G=[],T=[],O=[];for(let n of r.functions){let[u,l,c,f,g,S,b,A,w]=await Promise.all([k(s,n.name,"Invocations","Sum",d,m),k(s,n.name,"Errors","Sum",d,m),k(s,n.name,"Throttles","Sum",d,m),k(s,n.name,"Duration","Average",d,m),o.getFunction(n.name).catch(()=>null),X(s,n.name,"p50",d,m),X(s,n.name,"p95",d,m),X(s,n.name,"p99",d,m),s.getMetricSeries({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:[{Name:"FunctionName",Value:n.name}],StartTime:new Date(m.getTime()-43200000),EndTime:m,Period:3600,Stat:"Sum"}).catch(()=>[])]);E+=u,C+=l,D=Math.max(D,f);let R=g?.Configuration?.MemorySize??0,M=Object.keys(g?.Configuration?.Environment?.Variables??{}),U=[],y=0;try{let{events:z=[]}=await h.filterLogEvents({logGroupName:`/aws/lambda/${n.name}`,startTime:d.getTime(),limit:120});for(let x of z){let L=(x.message??"").trim(),ee=/Max Memory Used:\s*(\d+)\s*MB/.exec(L);if(ee)y=Math.max(y,Number(ee[1]));if(L&&!/^(?:START|END|REPORT|INIT_START)/.test(L))O.push({source:n.mode||n.name,timestamp:new Date(x.timestamp??0).toISOString(),when:we(x.timestamp??0),message:L.slice(0,400),level:/error|exception|fatal|panic|traceback/i.test(L)?"error":/warn|warning|timeout|retr(?:y|ies)|throttl/i.test(L)?"warn":"info"})}U=z.filter((x)=>!/^(?:START|END|REPORT|INIT_START)/.test((x.message??"").trim())).slice(-6).map((x)=>({ts:new Date(x.timestamp??0).toISOString().slice(11,19),msg:(x.message??"").trim().slice(0,120),err:/error|exception|fatal/i.test(x.message??"")}))}catch{}let v=Math.max(1,...w);G.push({key:n.mode,name:n.name,version:n.version,memory:R,timeout:g?.Configuration?.Timeout??0,runtime:g?.Configuration?.Runtime??"provided.al2023",invocations:Math.round(u),errors:Math.round(l),p95:b||Math.round(f),status:"active",provisioned:n.provisioned?`${n.provisioned.allocated}/${n.provisioned.requested}`:void 0}),T.push({key:n.mode,name:n.name,runtime:g?.Configuration?.Runtime??"provided.al2023",arch:g?.Configuration?.Architectures?.[0]??"x86_64",memory:R,timeout:g?.Configuration?.Timeout??0,ephemeral:g?.Configuration?.EphemeralStorage?.Size??512,version:n.version,concurrency:p?.concurrency??"—",invocations:Math.round(u),errors:Math.round(l),throttles:Math.round(c),p50:S||Math.round(f),p95:b||Math.round(f),p99:A||Math.round(f),maxMem:y,spark:w.length?w.map((z)=>Math.round(z/v*100)):[0],env:M.length?M:["(none)"],recent:U.length?U:[{ts:"—",msg:"no recent events",err:!1}]})}i.functions=G,i.functionsDetail=T,i.serverlessLogs=O.sort((n,u)=>String(u.timestamp).localeCompare(String(n.timestamp))).slice(0,600),i.serverlessLogsEmptyReason=O.length?void 0:"No recent function logs were found in CloudWatch for this environment.";let _=E?Number((C/E*100).toFixed(2)):0,q=Math.round(await k(s,r.functions[0]?.name??"","ConcurrentExecutions","Maximum",d,m));i.metrics={invocations:Math.round(E),errorRatePct:_,p95Ms:Math.round(D),coldStartPct:void 0,concurrency:q,estCostUsd:void 0};try{let n=new he(a),u=[],l=[],c=0;try{let{QueueUrl:g}=await n.getQueueUrl(`${r.slug}-${t}-dlq`),{Attributes:S}=await n.getQueueAttributes(g);c=Number(S.ApproximateNumberOfMessages??0)}catch{}let f=p?ue(p,r.slug,t):[];for(let g of f){let S=g.name.replace(`${r.slug}-${t}-`,""),b=0,A=0;try{let{QueueUrl:R}=await n.getQueueUrl(g.name),{Attributes:M}=await n.getQueueAttributes(R);b=Number(M.ApproximateNumberOfMessages??0),A=Number(M.ApproximateNumberOfMessagesNotVisible??0)}catch{}let w=Math.round(await W(s,"AWS/SQS","NumberOfMessagesDeleted",[{Name:"QueueName",Value:g.name}],"Sum",d,m));u.push({name:S,visible:b,inFlight:A,processed:w,dlq:c}),l.push({name:g.name,short:S,visible:b,inFlight:A,delayed:0,processed:w,oldestSec:0,concurrency:g.concurrency??p?.queueConcurrency??"—",tries:p?.queueTries??3,visTimeout:(p?.queueTimeout??120)*6,dlq:c})}if(u.length)i.queues=u;if(l.length)i.queuesDetail=l;i.dlqItems=[]}catch{}try{let n=new le(a),{Stacks:u}=await n.describeStacks({stackName:ce(e,t)}),l={};for(let c of u?.[0]?.Outputs??[])if(c.OutputKey)l[c.OutputKey]=c.OutputValue??"";if(p?.database?.connection==="aurora-serverless"){let c=`${r.slug}-${t}-db`,f=[{Name:"DBClusterIdentifier",Value:c}],[g,S]=await Promise.all([W(s,"AWS/RDS","ServerlessDatabaseCapacity",f,"Average",d,m),W(s,"AWS/RDS","DatabaseConnections",f,"Maximum",d,m)]);if(i.aurora={id:c,engine:"aurora-mysql",minAcu:p?.database?.minCapacity??0.5,maxAcu:p?.database?.maxCapacity??4,currentAcu:g?Number(g.toFixed(1)):p?.database?.minCapacity??0.5,database:"app",connections:Math.round(S),status:l.DbEndpoint?"available":"creating"},p?.rdsProxy)i.proxy={name:`${r.slug}-${t}-proxy`,endpoint:l.DbProxyEndpoint??"—",pooledConns:Math.round(S),status:"available"}}if(p?.cache?.driver==="elasticache"){let c=`${r.slug}-${t}-cache`,f=[{Name:"CacheClusterId",Value:`${c}-001`}],[g,S]=await Promise.all([W(s,"AWS/ElastiCache","CacheHits",f,"Sum",d,m),W(s,"AWS/ElastiCache","CacheMisses",f,"Sum",d,m)]),b=g+S>0?Number((g/(g+S)*100).toFixed(1)):0;i.redis={id:c,node:"cache.t4g.micro",engine:"redis",hitRate:b,status:l.CacheEndpoint?"available":"creating"}}if(p?.efs){let c=0;try{if(l.EfsFileSystemId){let f=new J(a),{FileSystems:g}=await f.describeFileSystems({FileSystemId:l.EfsFileSystemId});c=Number(((g?.[0]?.SizeInBytes?.Value??0)/1048576).toFixed(1))}}catch{}i.efs={id:l.EfsFileSystemId??"efs",mount:"/mnt/local",sizeMb:c,status:"available"}}i.assetsInfo=l.AssetsCdnDomain?{bucket:l.AssetsBucketName??`${r.slug}-${t}-assets`,cdn:l.AssetsCdnDomain,customDomain:p?.assetDomain??"—",assetUrl:r.assetUrl??"—",files:0,sizeMb:0,cacheHitPct:0,build:i.app.build}:void 0}catch{}if(i.assetsInfo)try{let u=await new Z(a).list({bucket:i.assetsInfo.bucket,maxKeys:1000});i.assetsInfo.files=u.length,i.assetsInfo.sizeMb=Number((u.reduce((l,c)=>l+(c.Size??0),0)/1048576).toFixed(1)),i.assetsRecent=u.slice(0,8).map((l)=>({path:`/${l.Key}`,size:`${Math.max(1,Math.round((l.Size??0)/1024))} KB`,type:l.Key.split(".").pop()??""}))}catch{}try{if(p?.secrets){let n=Array.isArray(p.secrets)?p.secrets.map((u)=>({key:u.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),source:u})):Object.entries(p.secrets).map(([u,l])=>({key:u,source:String(l)}));i.secretsList=n.map((u)=>({...u,updated:"—"}))}}catch{}try{let n=new Z(a),u=`${r.slug}-${t}-deployments`,l=await n.getObjectJson(u,`deployments/${r.slug}/${t}/history.json`).catch(()=>null);if(l?.records?.length)i.deploymentsDetail=l.records.slice(-12).reverse().map((c)=>({sha:(c.sha??"").slice(0,7),status:c.status??"success",when:c.timestamp??"—",took:c.took??"—",by:c.by??"—",version:c.version??"—",hooks:c.hooks??[]}))}catch{}i.metricsTotals={invocations:i.metrics.invocations,errors:Math.round(C),errorRatePct:_,p95Ms:i.metrics.p95Ms,throttles:T.reduce((n,u)=>n+u.throttles,0),coldStartPct:void 0,estCostUsd:void 0,concurrency:q},i.metricsPerFn=T.map((n)=>({key:n.key,invocations:n.invocations,errors:n.errors,throttles:n.throttles,avgMs:n.p50,maxMs:n.p99,costUsd:void 0}));try{i.invSpark=await s.getMetricSeries({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:[{Name:"FunctionName",Value:r.functions.find((n)=>n.mode==="http")?.name??""}],StartTime:new Date(m.getTime()-86400000),EndTime:m,Period:3600,Stat:"Sum"})}catch{}try{let n=new Y,u=m,l=new Date(Date.UTC(u.getUTCFullYear(),u.getUTCMonth(),1)),c=new Date(Date.UTC(u.getUTCFullYear(),u.getUTCMonth()-1,1)),[f,g]=await Promise.all([n.getCostByService({start:F(l),end:F(u),granularity:"MONTHLY"}).catch(()=>[]),n.getCostByService({start:F(c),end:F(l),granularity:"MONTHLY"}).catch(()=>[])]);if(f.length){let S=f.reduce((y,v)=>y+v.amount,0),b=g.reduce((y,v)=>y+v.amount,0),A=u.getUTCDate(),w=new Date(Date.UTC(u.getUTCFullYear(),u.getUTCMonth()+1,0)).getUTCDate();i.costSummary={monthToDateUsd:Number(S.toFixed(2)),projectedUsd:Number((S/A*w).toFixed(2)),lastMonthUsd:Number(b.toFixed(2)),dailyAvgUsd:Number((S/A).toFixed(2))},i.costServices=f.filter((y)=>y.amount>0).sort((y,v)=>v.amount-y.amount).slice(0,12).map((y)=>({name:y.service,usd:Number(y.amount.toFixed(2)),note:""})),i.metrics.estCostUsd=Number((S/A).toFixed(2)),i.metricsTotals.estCostUsd=i.metrics.estCostUsd,i.costTrend=await n.getDailyTotals({start:F(l),end:F(u)}).catch(()=>[]);let R=f.find((y)=>/lambda/i.test(y.service))?.amount??0,M=(y)=>y.invocations*(y.p50/1000)*(y.memory/1024),U=T.reduce((y,v)=>y+M(v),0)||1;i.costPerFn=T.map((y)=>({key:y.key,requests:y.invocations,gbSec:Math.round(M(y)),usd:Number((R*(M(y)/U)).toFixed(2))}))}}catch{}if(p?.firewall)try{let n=await s.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"BlockedRequests",StartTime:d,EndTime:m,Period:86400,Statistics:["Sum"]}).catch(()=>[]),u=await s.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"AllowedRequests",StartTime:d,EndTime:m,Period:86400,Statistics:["Sum"]}).catch(()=>[]);i.waf={enabled:!0,scope:"REGIONAL",acl:`${r.slug}-${t}-waf`,allowed24h:Math.round(u.reduce((l,c)=>l+(c.Sum??0),0)),blocked24h:Math.round(n.reduce((l,c)=>l+(c.Sum??0),0))};try{let l=new Q(a),c=await l.listWebACLs("REGIONAL"),f=c.find((g)=>g.Name?.includes(`${r.slug}-${t}`))??c[0];if(f?.Name&&f.Id){i.waf.acl=f.Name;let g=await l.getWebACLRules(f.Name,f.Id,"REGIONAL");if(g.length)i.wafRules=g.map((S)=>({name:S.Name??"—",detail:`priority ${S.Priority??0}`,action:S.Action??"count",blocked24h:0}))}}catch{}}catch{}let P=[];if(i.aurora)P.push({name:"Aurora Serverless v2",detail:`${i.aurora.id} · ${i.aurora.minAcu}-${i.aurora.maxAcu} ACU`,status:i.aurora.status});if(i.proxy)P.push({name:"RDS Proxy",detail:i.proxy.name,status:i.proxy.status});if(i.redis)P.push({name:`ElastiCache (${i.redis.engine})`,detail:`${i.redis.node} · ${i.redis.hitRate}% hit rate`,status:i.redis.status});if(i.efs)P.push({name:"EFS",detail:`${i.efs.mount} · ${i.efs.sizeMb} MB`,status:i.efs.status});if(P.length)i.dataServices=P;if(r.scheduler!=="off"&&p?.kind==="php")try{let n=await ge(e,t,"schedule:list"),u=[];for(let l of(n||"").split(`
|
|
2
2
|
`)){let c=/^\s*([\d*/,\-\s]+?)\s{2,}(.+?)(?:\s{2,}Next Due.*)?$/.exec(l);if(c&&/[*\d]/.test(c[1])&&c[1].trim().split(/\s+/).length===5)u.push({command:c[2].trim().replace(/^php artisan /,""),cron:c[1].trim(),desc:"",lastRun:"—",lastStatus:"ok"})}if(u.length)i.schedulerTasks=u}catch{}return i.topology=ye(i,{project:e.project.name,environment:t}),i}
|
|
3
|
-
export{K as
|
|
3
|
+
export{K as Bd,j as Cd,We as Dd,Ge as Ed,Y as Fd,mt as Gd};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{dh as a}from"./chunk-ja1vjdn1.js";class d{client;region;constructor(e="us-east-1"){this.region=e,this.client=new a}async createHostedZone(e){let t=e.CallerReference||`${Date.now()}-${Math.random().toString(36).slice(2)}`,o=`<?xml version="1.0" encoding="UTF-8"?>
|
|
2
2
|
<CreateHostedZoneRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
|
|
3
3
|
<Name>${e.Name}</Name>
|
|
4
4
|
<CallerReference>${t}</CallerReference>`;if(e.HostedZoneConfig){if(o+=`
|
|
@@ -47,4 +47,4 @@ import{ch as a}from"./chunk-0y89hs67.js";class d{client;region;constructor(e="us
|
|
|
47
47
|
</Changes>
|
|
48
48
|
</ChangeBatch>
|
|
49
49
|
</ChangeResourceRecordSetsRequest>`;let n=await this.client.request({service:"route53",region:this.region,method:"POST",path:`/2013-04-01/hostedzone/${t}/rrset`,headers:{"content-type":"application/xml"},body:o});return this.parseChangeResourceRecordSetsResponse(n)}escapeXml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}parseCreateHostedZoneResponse(e){let t=e.CreateHostedZoneResponse||e;return{HostedZone:this.parseHostedZone(t.HostedZone),ChangeInfo:{Id:t.ChangeInfo?.Id||"",Status:t.ChangeInfo?.Status||"",SubmittedAt:t.ChangeInfo?.SubmittedAt||""},DelegationSet:this.parseDelegationSet(t.DelegationSet),Location:t.Location||""}}parseListHostedZonesResponse(e){let t=e.ListHostedZonesResponse||e.ListHostedZonesByNameResponse||e,o=t.HostedZones?.HostedZone||t.HostedZones||[];if(!Array.isArray(o))o=o?[o]:[];return{HostedZones:o.map((n)=>this.parseHostedZone(n)),IsTruncated:t.IsTruncated==="true"||t.IsTruncated===!0,MaxItems:t.MaxItems||"100",Marker:t.Marker,NextMarker:t.NextMarker}}parseGetHostedZoneResponse(e){let t=e.GetHostedZoneResponse||e;return{HostedZone:this.parseHostedZone(t.HostedZone),DelegationSet:this.parseDelegationSet(t.DelegationSet),VPCs:t.VPCs?.VPC?Array.isArray(t.VPCs.VPC)?t.VPCs.VPC:[t.VPCs.VPC]:void 0}}parseListResourceRecordSetsResponse(e){let t=e.ListResourceRecordSetsResponse||e,o=t.ResourceRecordSets?.ResourceRecordSet||t.ResourceRecordSets||[];if(!Array.isArray(o))o=o?[o]:[];return{ResourceRecordSets:o.map((n)=>this.parseResourceRecordSet(n)),IsTruncated:t.IsTruncated==="true"||t.IsTruncated===!0,MaxItems:t.MaxItems||"100",NextRecordName:t.NextRecordName,NextRecordType:t.NextRecordType,NextRecordIdentifier:t.NextRecordIdentifier}}parseChangeResourceRecordSetsResponse(e){let t=e.ChangeResourceRecordSetsResponse||e;return{ChangeInfo:{Id:t.ChangeInfo?.Id||"",Status:t.ChangeInfo?.Status||"",SubmittedAt:t.ChangeInfo?.SubmittedAt||"",Comment:t.ChangeInfo?.Comment}}}parseHostedZone(e){if(!e)return{Id:"",Name:""};return{Id:e.Id||"",Name:e.Name||"",CallerReference:e.CallerReference,Config:e.Config?{Comment:e.Config.Comment,PrivateZone:e.Config.PrivateZone==="true"||e.Config.PrivateZone===!0}:void 0,ResourceRecordSetCount:e.ResourceRecordSetCount?Number(e.ResourceRecordSetCount):void 0}}parseDelegationSet(e){if(!e)return{NameServers:[]};let t=e.NameServers?.NameServer||e.NameServers||[];if(!Array.isArray(t))t=t?[t]:[];return{Id:e.Id,CallerReference:e.CallerReference,NameServers:t}}parseResourceRecordSet(e){if(!e)return{Name:"",Type:""};let t=e.ResourceRecords?.ResourceRecord||e.ResourceRecords||[];if(!Array.isArray(t))t=t?[t]:[];return{Name:e.Name||"",Type:e.Type||"",TTL:e.TTL?Number(e.TTL):void 0,ResourceRecords:t.map((o)=>({Value:o.Value||o})),AliasTarget:e.AliasTarget?{HostedZoneId:e.AliasTarget.HostedZoneId,DNSName:e.AliasTarget.DNSName,EvaluateTargetHealth:e.AliasTarget.EvaluateTargetHealth==="true"||e.AliasTarget.EvaluateTargetHealth===!0}:void 0,SetIdentifier:e.SetIdentifier,Weight:e.Weight?Number(e.Weight):void 0,Region:e.Region,GeoLocation:e.GeoLocation,Failover:e.Failover,HealthCheckId:e.HealthCheckId}}async findHostedZoneByName(e){let t=e.endsWith(".")?e:`${e}.`;return(await this.listHostedZonesByName({DNSName:t})).HostedZones.find((s)=>s.Name===t)||null}async createARecord(e){let t=Array.isArray(e.Value)?e.Value:[e.Value];return this.changeResourceRecordSets({HostedZoneId:e.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:e.Name,Type:"A",TTL:e.TTL||300,ResourceRecords:t.map((o)=>({Value:o}))}}]}})}async createCnameRecord(e){return this.changeResourceRecordSets({HostedZoneId:e.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:e.Name,Type:"CNAME",TTL:e.TTL||300,ResourceRecords:[{Value:e.Value}]}}]}})}async createAliasRecord(e){return this.changeResourceRecordSets({HostedZoneId:e.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:e.Name,Type:e.Type||"A",AliasTarget:{HostedZoneId:e.TargetHostedZoneId,DNSName:e.TargetDNSName,EvaluateTargetHealth:e.EvaluateTargetHealth??!1}}}]}})}async createTxtRecord(e){let o=(Array.isArray(e.Value)?e.Value:[e.Value]).map((n)=>{if(!n.startsWith('"'))return`"${n}"`;return n});return this.changeResourceRecordSets({HostedZoneId:e.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:e.Name,Type:"TXT",TTL:e.TTL||300,ResourceRecords:o.map((n)=>({Value:n}))}}]}})}async createMxRecord(e){return this.changeResourceRecordSets({HostedZoneId:e.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:e.Name,Type:"MX",TTL:e.TTL||300,ResourceRecords:e.Values.map((t)=>({Value:`${t.priority} ${t.mailServer}`}))}}]}})}async deleteRecord(e){return this.changeResourceRecordSets({HostedZoneId:e.HostedZoneId,ChangeBatch:{Changes:[{Action:"DELETE",ResourceRecordSet:e.RecordSet}]}})}async waitForChange(e,t=60,o=5000){let n=e.replace("/change/","");for(let s=0;s<t;s++){let r=await this.client.request({service:"route53",region:this.region,method:"GET",path:`/2013-04-01/change/${n}`});if((r.GetChangeResponse?.ChangeInfo?.Status||r.ChangeInfo?.Status)==="INSYNC")return!0;await new Promise((i)=>setTimeout(i,o))}return!1}async findOrCreateHostedZone(e){let t=e.domainName.endsWith(".")?e.domainName:`${e.domainName}.`,o=await this.findHostedZoneByName(t);if(o){let s=await this.getHostedZone({Id:o.Id});return{hostedZone:o,nameServers:s.DelegationSet.NameServers,isNew:!1}}let n=await this.createHostedZone({Name:t,HostedZoneConfig:{Comment:e.comment||`Hosted zone for ${e.domainName}`,PrivateZone:e.privateZone},VPC:e.vpc});return{hostedZone:n.HostedZone,nameServers:n.DelegationSet.NameServers,isNew:!0}}static getRootDomain(e){let t=e.replace(/\.$/,"").split(".");if(t.length<=2)return e;return t.slice(-2).join(".")}async findHostedZoneForDomain(e){let o=e.replace(/\.$/,"").split(".");for(let n=0;n<o.length-1;n++){let s=o.slice(n).join("."),r=await this.findHostedZoneByName(s);if(r)return r}return null}async ensureHostedZone(e){let t=await this.findOrCreateHostedZone({domainName:e.domainName,comment:e.comment});return{hostedZoneId:t.hostedZone.Id.replace("/hostedzone/",""),nameServers:t.nameServers,isNew:t.isNew,action:t.isNew?"created":"found"}}async setupDomainDns(e){let{domain:t,createIfNotExists:o=!0}=e,n=await this.findHostedZoneByName(t);if(n){let r=await this.getHostedZone({Id:n.Id});return{success:!0,hostedZoneId:n.Id.replace("/hostedzone/",""),nameServers:r.DelegationSet.NameServers,isNew:!1,message:`Found existing hosted zone for ${t}`}}if(!o)return{success:!1,hostedZoneId:null,nameServers:[],isNew:!1,message:`No hosted zone found for ${t} and createIfNotExists is false`};let s=await this.createHostedZone({Name:t,HostedZoneConfig:{Comment:`Created automatically by ts-cloud for ${t}`}});return{success:!0,hostedZoneId:s.HostedZone.Id.replace("/hostedzone/",""),nameServers:s.DelegationSet.NameServers,isNew:!0,message:`Created new hosted zone for ${t}. Please update your domain registrar with these name servers: ${s.DelegationSet.NameServers.join(", ")}`}}static CloudFrontHostedZoneId="Z2FDTNDATAQYW2";static S3WebsiteHostedZoneIds={"us-east-1":"Z3AQBSTGFYJSTF","us-east-2":"Z2O1EMRO9K5GLX","us-west-1":"Z2F56UZL2M1ACD","us-west-2":"Z3BJ6K6RIION7M","ap-east-1":"ZNB98KWMFR0R6","ap-south-1":"Z11RGJOFQNVJUP","ap-northeast-1":"Z2M4EHUR26P7ZW","ap-northeast-2":"Z3W03O7B5YMIYP","ap-northeast-3":"Z2YQB5RD63NC85","ap-southeast-1":"Z3O0J2DXBE1FTB","ap-southeast-2":"Z1WCIGYICN2BYD","ca-central-1":"Z1QDHH18159H29","eu-central-1":"Z21DNDUVLTQW6Q","eu-west-1":"Z1BKCTXD74EZPE","eu-west-2":"Z3GKZC51ZF0DB4","eu-west-3":"Z3R1K369G5AVDG","eu-north-1":"Z3BAZG2TWCNX0D","sa-east-1":"Z7KQH4QJS55SO"};static ALBHostedZoneIds={"us-east-1":"Z35SXDOTRQ7X7K","us-east-2":"Z3AADJGX6KTTL2","us-west-1":"Z368ELLRRE2KJ0","us-west-2":"Z1H1FL5HABSF5","ap-east-1":"Z3DQVH9N71FHZ0","ap-south-1":"ZP97RAFLXTNZK","ap-northeast-1":"Z14GRHDCWA56QT","ap-northeast-2":"ZWKZPGTI48KDX","ap-northeast-3":"Z5LXEBD8Y73MNV","ap-southeast-1":"Z1LMS91P8CMLE5","ap-southeast-2":"Z1GM3OXH4ZPM65","ca-central-1":"ZQSVJUPU6J1EY","eu-central-1":"Z215JYRZR1TBD5","eu-west-1":"Z32O12XQLNTSW2","eu-west-2":"ZHURV8PSTC4K8","eu-west-3":"Z3Q77PNBQS71R4","eu-north-1":"Z23TAZ6LKFMNIO","sa-east-1":"Z2P70J7HTTTPLU"};static APIGatewayHostedZoneIds={"us-east-1":"Z1UJRXOUMOOFQ8","us-east-2":"ZOJJZC49E0EPZ","us-west-1":"Z2MUQ32089INYE","us-west-2":"Z2OJLYMUO9EFXC","ap-east-1":"Z3FD1VL90ND7K5","ap-south-1":"Z3VO1THU9YC4UR","ap-northeast-1":"Z1YSHQZHG15GKL","ap-northeast-2":"Z20JF4UZKIW1U8","ap-northeast-3":"Z2YQB5RD63NC85","ap-southeast-1":"ZL327KTPIQFUL","ap-southeast-2":"Z2RPCDW04V8134","ca-central-1":"Z19DQILCV0OWEC","eu-central-1":"Z1U9ULNL0V5AJ3","eu-west-1":"ZLY8HYME6SFDD","eu-west-2":"ZJ5UAJN8Y3Z2Q","eu-west-3":"Z3KY65QIEKYHQQ","eu-north-1":"Z3UWIKFBOOGXPP","sa-east-1":"ZCMLWB8V5SYIT"}}
|
|
50
|
-
export{d as
|
|
50
|
+
export{d as og};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{ch as a,dh as b,eh as c,fh as d}from"./chunk-ja1vjdn1.js";import"./chunk-ehc63fvs.js";export{b as AWSClient,c as buildQueryParams,d as detectCredentialSource,a as resolveS3Endpoint};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{createRequire as g}from"node:module";var d=Object.defineProperty;var e=(a)=>a;function f(a,b){this[a]=e.bind(null,b)}var h=(a,b)=>{for(var c in b)d(a,c,{get:b[c],enumerable:!0,configurable:!0,set:f.bind(b,c)})};var j=g(import.meta.url);
|
|
2
|
-
export{h as
|
|
2
|
+
export{h as np,j as op};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Gd as a}from"./chunk-e2bybahr.js";import"./chunk-d7ke90zt.js";import"./chunk-kg61p5hw.js";import"./chunk-c0bdafbx.js";import"./chunk-xhwqpgwq.js";import"./chunk-a7w13qfm.js";import"./chunk-btsyjhk7.js";import"./chunk-6tfwm33r.js";import"./chunk-ja1vjdn1.js";import"./chunk-4q6tad44.js";import"./chunk-ehc63fvs.js";export{a as resolveDashboardData};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{df as w}from"./chunk-8khgprf6.js";var L="\x00";function k(t,i){if(t==="*"||t==="**")return!0;let e=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*");return new RegExp(`^${e}$`).test(i)}function y(t,i){if(t.startsWith("*.")){let e=t.slice(1);return i.endsWith(e)&&i.length>e.length}return t===i}function d(t,i){if(t.enabled===!1)return!1;if(t.methods?.length&&!t.methods.some((e)=>e.toUpperCase()===i.method.toUpperCase()))return!1;if(t.path&&!k(t.path,i.path))return!1;if(t.host&&!y(t.host,i.host??""))return!1;return!0}function m(t,i){let e=t.key??{source:"ip"},o=e.fallbackToIp!==!1,r;if(e.source==="ip")r=i.ip;else if(e.source==="global")r="global";else if(e.source==="host")r=i.host??"";else if(e.source==="path")r=i.path;else if(e.source==="header")r=e.name?i.headers?.[e.name.toLowerCase()]:void 0;else if(e.source==="cookie")r=e.name?i.cookies?.[e.name]:void 0;if(!r&&e.source!=="global")r=o?i.ip:"__missing__";return`${t.id}\x00${r}`}class A{clock;maxTrackedKeys;buckets=new Map;windows=new Map;rules;constructor(t,i=()=>Date.now(),e=1e5){this.clock=i;this.maxTrackedKeys=e;this.rules=[...t].sort((o,r)=>(o.priority??0)-(r.priority??0))}check(t){let i=this.clock(),e=this.rules.filter((n)=>d(n,t)),o;for(let n of e){let s=this.test(n,t,i);if(s.allowed)continue;if(!o||p(s.action)>p(o.action))o=s}if(o)return o;let r={action:"allow",allowed:!0};for(let n of e){let s=this.consume(n,t,i);if(s.remaining!=null&&(r.remaining??1/0)>s.remaining)r=s}return r}test(t,i,e){let o=m(t,i);if((t.algorithm??"token_bucket")==="token_bucket"){let n=t.burst??t.limit,s=this.buckets.get(o),a=s?Math.min(n,s.tokens+this.refill(t,e-s.updatedAt)):n;if(a>=1)return{action:"allow",allowed:!0};return this.blocked(t,o,0,this.msPerToken(t)*(1-a),e)}let r=(this.windows.get(o)?.hits??[]).filter((n)=>n>e-t.windowMs);if(r.length<t.limit)return{action:"allow",allowed:!0};return this.blocked(t,o,0,r[0]+t.windowMs-e,e)}peek(t){let i=this.clock();for(let e of this.rules){if(!d(e,t))continue;let o=this.test(e,t,i);if(!o.allowed)return o}return{action:"allow",allowed:!0}}msPerToken(t){return t.windowMs/Math.max(1,t.limit)}refill(t,i){return Math.max(0,i)/this.msPerToken(t)}blocked(t,i,e,o,r){let n=t.action??"deny";return{action:n,allowed:n==="allow"||n==="log",ruleId:t.id,limit:t.limit,remaining:e,retryAfterMs:Math.max(0,Math.ceil(o)),resetAt:r+Math.max(0,o),key:i}}consume(t,i,e){let o=m(t,i);if((t.algorithm??"token_bucket")==="token_bucket"){let l=t.burst??t.limit,u=this.buckets.get(o)??{tokens:l,updatedAt:e},c=Math.min(l,u.tokens+this.refill(t,e-u.updatedAt));if(c<1)return this.buckets.set(o,{tokens:c,updatedAt:e}),this.blocked(t,o,0,this.msPerToken(t)*(1-c),e);return this.evictIfNeeded(this.buckets),this.buckets.set(o,{tokens:c-1,updatedAt:e}),{action:"allow",allowed:!0,ruleId:t.id,limit:l,remaining:Math.floor(c-1),resetAt:e+this.msPerToken(t)*(l-(c-1)),key:o}}let n=this.windows.get(o)??{hits:[]},s=e-t.windowMs,a=n.hits.filter((l)=>l>s);if(a.length>=t.limit)return this.windows.set(o,{hits:a}),this.blocked(t,o,0,a[0]+t.windowMs-e,e);return a.push(e),this.evictIfNeeded(this.windows),this.windows.set(o,{hits:a}),{action:"allow",allowed:!0,ruleId:t.id,limit:t.limit,remaining:t.limit-a.length,resetAt:a[0]+t.windowMs,key:o}}evictIfNeeded(t){if(t.size<this.maxTrackedKeys)return;let i=t.size-this.maxTrackedKeys+1,e=0;for(let o of t.keys())if(t.delete(o),++e>=i)break}sweep(){let t=this.clock(),i=0;for(let[e,o]of this.windows){let r=e.split("\x00")[0],n=this.rules.find((s)=>s.id===r);if(!n){this.windows.delete(e),i++;continue}if(o.hits.every((s)=>s<=t-n.windowMs))this.windows.delete(e),i++}for(let[e,o]of this.buckets){let r=e.split("\x00")[0],n=this.rules.find((s)=>s.id===r);if(!n||t-o.updatedAt>n.windowMs*2)this.buckets.delete(e),i++}return i}get trackedKeys(){return this.buckets.size+this.windows.size}}function p(t){return{allow:0,log:1,throttle:2,challenge:3,deny:4}[t]}function I(t){let i={};if(t.limit!=null)i["ratelimit-limit"]=String(t.limit);if(t.remaining!=null)i["ratelimit-remaining"]=String(t.remaining);if(t.resetAt!=null)i["ratelimit-reset"]=String(Math.max(0,Math.ceil((t.resetAt-Date.now())/1000)));if(!t.allowed&&t.retryAfterMs!=null)i["retry-after"]=String(Math.max(1,Math.ceil(t.retryAfterMs/1000)));return i}function C(){return[{id:"global-ip",limit:600,windowMs:60000,burst:100,key:{source:"ip"},action:"deny",priority:100},{id:"api-ip",limit:120,windowMs:60000,burst:30,path:"/api/**",key:{source:"ip"},action:"deny",priority:50},{id:"auth-ip",limit:10,windowMs:60000,algorithm:"sliding_window",path:"/auth/**",methods:["POST"],key:{source:"ip"},action:"challenge",priority:10}]}var h="protection.controls",b=24,x=4,M={ipRules:{allow:[],block:[]}};function f(t,i){if(!t?.enabled)return;return new Date(t.expiresAt).getTime()>i.getTime()?t:void 0}function g(t,i){let e=Number.isFinite(t)?Number(t):i;return Math.min(b,Math.max(0.25,e))}var R=500;class P{controlPlane;options;constructor(t,i={}){this.controlPlane=t;this.options=i}now(){return this.options.now?.()??new Date}read(){let t=this.controlPlane.getSetting(h);if(!t||typeof t!=="object"||Array.isArray(t))return{...M,ipRules:{allow:[],block:[]}};let i=t;return{attackMode:i.attackMode,mitigationPause:i.mitigationPause,ipRules:{allow:Array.isArray(i.ipRules?.allow)?i.ipRules.allow:[],block:Array.isArray(i.ipRules?.block)?i.ipRules.block:[]},updatedAt:i.updatedAt}}write(t){let i={...t,updatedAt:this.now().toISOString()};return this.controlPlane.setSetting(h,i),i}raw(){return this.read()}current(){let t=this.now(),i=this.read();return{attackMode:f(i.attackMode,t),mitigationPause:f(i.mitigationPause,t),ipRules:i.ipRules}}enableAttackMode(t){let i=this.now(),e={enabled:!0,startedAt:i.toISOString(),expiresAt:new Date(i.getTime()+g(t.hours,x)*3600000).toISOString(),reason:t.reason.trim()||"Attack mode enabled by an operator.",actorId:t.actorId};return this.write({...this.read(),attackMode:e}),e}disableAttackMode(){let t=this.read();if(!t.attackMode?.enabled)return!1;return this.write({...t,attackMode:{...t.attackMode,enabled:!1}}),!0}pauseMitigations(t){let i=t.reason.trim();if(!i)throw Error("Pausing mitigations requires a reason: you are liable for the traffic it admits.");let e=this.now(),o={enabled:!0,startedAt:e.toISOString(),expiresAt:new Date(e.getTime()+g(t.hours,b)*3600000).toISOString(),reason:i,actorId:t.actorId};return this.write({...this.read(),mitigationPause:o}),o}resumeMitigations(){let t=this.read();if(!t.mitigationPause?.enabled)return!1;return this.write({...t,mitigationPause:{...t.mitigationPause,enabled:!1}}),!0}addIpRule(t,i){let e=i.trim();if(!w(e))throw Error(`Not a valid IP or CIDR: ${i}`);let o=this.read(),r={...o.ipRules,[t]:[...new Set([...o.ipRules[t],e])]};if(r[t].length>R)throw Error(`At most ${R} ${t} rules are supported.`);let n=t==="allow"?"block":"allow";return r[n]=r[n].filter((s)=>s!==e),this.write({...o,ipRules:r}),r}removeIpRule(t,i){let e=this.read(),o={...e.ipRules,[t]:e.ipRules[t].filter((r)=>r!==i.trim())};return this.write({...e,ipRules:o}),o}}function D(t){if(t.mitigationPause)return{attackMode:!!t.attackMode,mitigationPaused:!0,summary:`Automatic mitigation is paused until ${t.mitigationPause.expiresAt}. All traffic is being served and billed.`,expiresAt:t.mitigationPause.expiresAt};if(t.attackMode)return{attackMode:!0,mitigationPaused:!1,summary:`Attack mode is on until ${t.attackMode.expiresAt}. Every visitor is being challenged.`,expiresAt:t.attackMode.expiresAt};return{attackMode:!1,mitigationPaused:!1,summary:"Protection is in its normal posture."}}function E(t,i){if(i.mitigationPause)return t.map((e)=>({...e,enabled:!1}));if(!i.attackMode)return[...t];return t.map((e)=>({...e,action:e.action==="deny"?"deny":"challenge",burst:Math.max(1,Math.min(e.burst??e.limit,5))}))}function T(t,i){let e=[...new Set([...t.allowlist??[],...i.ipRules.allow])],o=[...new Set([...t.blocklist??[],...i.ipRules.block])];if(i.mitigationPause)return{...t,allowlist:e,blocklist:o,monitorOnly:!0};if(!i.attackMode)return{...t,allowlist:e,blocklist:o};let r=t.thresholds??{};return{...t,allowlist:e,blocklist:o,thresholds:{...r,newConnectionsPerSecond:Math.max(1,Math.floor((r.newConnectionsPerSecond??50)/5)),concurrentPerSource:Math.max(1,Math.floor((r.concurrentPerSource??100)/5))}}}function v(t,i){let e=t?.infrastructure?.compute;if(!e||e.ddos===!1)return t;let o=typeof e.ddos==="object"&&e.ddos!==null?e.ddos:{};return{...t,infrastructure:{...t.infrastructure,compute:{...e,ddos:T(o,i)}}}}export{L as a,k as b,d as c,m as d,A as e,I as f,C as g,h,b as i,x as j,P as k,D as l,E as m,T as n,v as o};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{rd as a,sd as b}from"./chunk-mfrf9q4b.js";import"./chunk-e5ab5twy.js";import"./chunk-ja1vjdn1.js";import"./chunk-ehc63fvs.js";export{a as ACMClient,b as ACMDnsValidator};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Lh as d}from"./chunk-4q6tad44.js";import"./chunk-ehc63fvs.js";function E(t){let e=t.sites||{};for(let r of Object.values(e))if(r?.repository?.url)return{provider:r.repository.provider,branch:r.repository.branch};return}function v(t){let e=t.trim().toLowerCase();if(e.includes("github.com"))return"github";if(e.includes("gitlab.com"))return"gitlab";if(e.includes("bitbucket.org"))return"bitbucket";return}function a(t){return`'${t.replace(/'/g,"'\\''")}'`}function _(t){return t.replace(/'/g,"''")}function S(t,e){let r=["bunx --bun @stacksjs/ts-cloud deploy","--env",a(t)];if(e.site)r.push("--site",a(e.site));if(e.skipDnsVerification)r.push("--skip-dns-verification");return r.push("--yes"),r.join(" ")}function k(t,e="production",r={}){let l=E(t),n=r.provider||l?.provider;if(n!=="github"&&n!=="gitlab"&&n!=="bitbucket")return null;let i=t.environments?.[e],s=i?.deployBranch||l?.branch||"main",u=S(e,r),c=JSON.stringify(s),f=JSON.stringify(e),p=i?.domain?i.domain.startsWith("http")?i.domain:`https://${i.domain}`:void 0,h=p?`
|
|
2
2
|
url: ${JSON.stringify(p)}`:"",y=r.setup==="pantry"?` - name: Setup Pantry
|
|
3
3
|
uses: home-lang/pantry/packages/action@main`:` - uses: oven-sh/setup-bun@v2
|
|
4
4
|
- run: bun install --frozen-lockfile`,b=d(t)==="hetzner"&&!!t.infrastructure?.compute,o=r.sshPrivateKeySecret||"SSH_PRIVATE_KEY";if(!/^[A-Z_][A-Z0-9_]*$/i.test(o))throw Error(`Invalid SSH private key secret name '${o}'`);let g=b?`
|
|
@@ -3,4 +3,4 @@ import*as _ from"node:crypto";import{existsSync as V,readFileSync as Y}from"node
|
|
|
3
3
|
`).join(""),l=u.map((E)=>E.toLowerCase()).join(";"),C=[s,A,b,c,l,f].join(`
|
|
4
4
|
`),y="AWS4-HMAC-SHA256",S=r;if(r==="email")S="ses";let x=`${g}/${i}/${S}/aws4_request`,K=[y,p,x,this.sha256(C)].join(`
|
|
5
5
|
`),F=this.getSignatureKey(e.secretAccessKey,g,i,S),q=this.hmac(F,K),U=`${y} Credential=${e.accessKeyId}/${x}, SignedHeaders=${l}, Signature=${q}`;return{...m,Authorization:U}}getAmzDate(t){return t.toISOString().replace(/[:-]|\.\d{3}/g,"")}getDateStamp(t){return t.toISOString().slice(0,10).replace(/-/g,"")}uriEncode(t){return encodeURIComponent(t).replace(/[!'()*]/g,(e)=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}sha256(t){return _.createHash("sha256").update(t,"utf8").digest("hex")}hmac(t,e){return _.createHmac("sha256",t).update(e,"utf8").digest("hex")}getSignatureKey(t,e,r,i){let s=_.createHmac("sha256",`AWS4${t}`).update(e).digest(),n=_.createHmac("sha256",s).update(r).digest(),a=_.createHmac("sha256",n).update(i).digest();return _.createHmac("sha256",a).update("aws4_request").digest()}parseXmlResponse(t){try{let e=this.xmlParser.parse(t);if(e.ErrorResponse)throw this.createErrorFromXml(e.ErrorResponse.Error);let r=Object.keys(e);if(r.length===1)return e[r[0]];return e}catch(e){if(e.code||e.statusCode)throw e;return{}}}parseError(t,e,r){let i=Error();if(i.statusCode=e,i.requestId=r.get("x-amzn-requestid")||r.get("x-amz-request-id")||void 0,t.startsWith("<"))try{let s=this.xmlParser.parse(t);if(s.ErrorResponse?.Error){let n=s.ErrorResponse.Error;return i.code=n.Code,i.message=`AWS Error [${n.Code}]: ${n.Message||"Unknown error"}`,i.type=n.Type,i}if(s.Error)return i.code=s.Error.Code,i.message=`AWS Error [${s.Error.Code}]: ${s.Error.Message||"Unknown error"}`,i}catch{}try{let s=JSON.parse(t);if(s.__type||s.code)return i.code=s.__type||s.code,i.message=`AWS Error [${i.code}]: ${s.message||s.Message||"Unknown error"}`,i}catch{}return i.message=`AWS API Error (${e}): ${t}`,i}createErrorFromXml(t){let e=Error();return e.code=t.Code,e.message=`AWS Error [${t.Code}]: ${t.Message||"Unknown error"}`,e.type=t.Type,e}isRetryableError(t){return["RequestTimeout","RequestTimeoutException","PriorRequestNotComplete","ConnectionError","ThrottlingException","Throttling","TooManyRequestsException","ProvisionedThroughputExceededException","RequestLimitExceeded","BandwidthLimitExceeded","SlowDown","ServiceUnavailable","ServiceUnavailableException","InternalError","InternalFailure","InternalServerError","InternalServiceException","TransientError","TransientFailure","IDPCommunicationErrorException","NetworkError","ConnectionRefusedException","EC2ThrottledException","503 Slow Down","500 InternalError"].includes(t)}isRetryableStatusCode(t){return t>=500||t===429}shouldRetry(t){if(t.name==="FetchError"||t.name==="TypeError"||t.code==="ECONNRESET")return!0;if(t.code&&this.isRetryableError(t.code))return!0;if(t.statusCode&&this.isRetryableStatusCode(t.statusCode))return!0;if(t.statusCode&&t.statusCode>=400&&t.statusCode<500&&t.statusCode!==429)return!1;if(t.statusCode)return!1;return!0}calculateRetryDelay(t){let e=this.config.retryDelay??1000,r=30000,i=Math.min(e*2**t,30000),s=Math.random()*0.3*i;return i+s}sleep(t){return new Promise((e)=>setTimeout(e,t))}getFromCache(t){let e=this.cache.get(t);if(!e)return null;if(Date.now()>e.expires)return this.cache.delete(t),null;return e.data}setInCache(t,e,r){this.cache.set(t,{data:e,expires:Date.now()+r})}clearCache(){this.cache.clear()}clearExpiredCache(){let t=Date.now();for(let[e,r]of this.cache.entries())if(t>r.expires)this.cache.delete(e)}}function ie(t){let e={};for(let[r,i]of Object.entries(t)){if(i===void 0||i===null)continue;if(Array.isArray(i))i.forEach((s,n)=>{e[`${r}.${n+1}`]=String(s)});else if(typeof i==="object")for(let[s,n]of Object.entries(i))e[`${r}.${s}`]=String(n);else e[r]=String(i)}return e}function se(){let t=process.env.AWS_ACCESS_KEY_ID,e=process.env.AWS_SECRET_ACCESS_KEY,r=t==="",i=e==="";if(t&&e)return{source:"env",emptyEnvKey:r,emptyEnvSecret:i,description:"environment variables (AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY)"};let s=process.env.AWS_PROFILE||"default",n=process.env.AWS_SHARED_CREDENTIALS_FILE||B(W(),".aws","credentials");if(V(n))return{source:"file",profile:s,emptyEnvKey:r,emptyEnvSecret:i,description:`~/.aws/credentials (profile: ${s})`};return{source:"ec2",emptyEnvKey:r,emptyEnvSecret:i,description:"EC2 instance metadata service (IMDSv2)"}}
|
|
6
|
-
export{R as
|
|
6
|
+
export{R as ch,J as dh,ie as eh,se as fh};
|