@stacksjs/ts-cloud 0.9.3 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/aws/index.js +1 -269
- package/dist/bin/chunk-08c0pzkb.js +1 -0
- package/dist/bin/chunk-12210qvj.js +1 -0
- package/dist/bin/chunk-1v6bt68w.js +6 -0
- package/dist/bin/chunk-35ttwn26.js +70 -0
- package/dist/bin/chunk-3r3be05z.js +1 -0
- package/dist/bin/chunk-41yqpdv7.js +2 -0
- package/dist/bin/chunk-5rv31chh.js +1 -0
- package/dist/bin/chunk-6eat8ezk.js +2 -0
- package/dist/bin/chunk-6gktf2m2.js +1 -0
- package/dist/bin/chunk-6zjy949y.js +141 -0
- package/dist/bin/chunk-7wzdaqh6.js +2 -0
- package/dist/bin/chunk-80ar3aty.js +1 -0
- package/dist/bin/chunk-8rwhsp5b.js +2 -0
- package/dist/bin/chunk-936vp7dx.js +44 -0
- package/dist/bin/chunk-9px3rg4a.js +4 -0
- package/dist/bin/chunk-anm3ae6z.js +7364 -0
- package/dist/bin/{chunk-ynjvbphf.js → chunk-axvr7dwa.js} +6 -6
- package/dist/bin/chunk-b0hj9m5e.js +2 -0
- package/dist/bin/{chunk-mh0kdzqp.js → chunk-b2ymh8k0.js} +1 -1
- package/dist/bin/chunk-b35989e3.js +50 -0
- package/dist/bin/chunk-c2b6nk0q.js +37 -0
- package/dist/bin/chunk-ckxpgwxw.js +3 -0
- package/dist/bin/chunk-d6zzgvtn.js +92 -0
- package/dist/bin/chunk-da8zpf82.js +1 -0
- package/dist/bin/chunk-ddmjjstg.js +1 -0
- package/dist/bin/chunk-dhhz4zyj.js +1 -0
- package/dist/bin/chunk-dj9a67c3.js +9 -0
- package/dist/bin/chunk-ds1z880f.js +1 -0
- package/dist/bin/chunk-dvkj4k6h.js +111 -0
- package/dist/bin/chunk-eh40fpvj.js +1 -0
- package/dist/bin/chunk-ey9fagrr.js +6 -0
- package/dist/bin/chunk-ezftw2q4.js +1 -0
- package/dist/bin/chunk-g6a4n3rh.js +1 -0
- package/dist/bin/chunk-g90nqfgv.js +585 -0
- package/dist/bin/chunk-gs40j75w.js +1 -0
- package/dist/bin/chunk-jjjts1vt.js +1 -0
- package/dist/bin/{chunk-ry030a6b.js → chunk-jnsbzqzz.js} +30 -30
- package/dist/bin/chunk-jnx4jgw8.js +1 -0
- package/dist/bin/chunk-jt1tndm2.js +3 -0
- package/dist/bin/chunk-kybdb0ws.js +2 -0
- package/dist/bin/chunk-m3nqw76h.js +3 -0
- package/dist/bin/chunk-mn6j22zn.js +6 -0
- package/dist/bin/chunk-nb0yjkv5.js +2 -0
- package/dist/bin/chunk-pjpa4x52.js +2 -0
- package/dist/bin/chunk-pkgkfe6s.js +2 -0
- package/dist/bin/chunk-pnz5hk8n.js +60 -0
- package/dist/bin/chunk-q46zr2tv.js +1 -0
- package/dist/bin/chunk-qtdngvs8.js +1 -0
- package/dist/bin/chunk-sbejksrh.js +2 -0
- package/dist/bin/chunk-svyd4v6c.js +34 -0
- package/dist/bin/chunk-tna7ay8d.js +1 -0
- package/dist/bin/chunk-tp4c2mv1.js +1 -0
- package/dist/bin/chunk-w5d6tr2x.js +1 -0
- package/dist/bin/chunk-wewcjam5.js +1 -0
- package/dist/bin/chunk-xv4bscrm.js +1 -0
- package/dist/bin/chunk-y9eyc5pw.js +1 -0
- package/dist/bin/chunk-y9f8649w.js +512 -0
- package/dist/bin/cli.js +428 -418
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/chunk-06jk7ba9.js +7355 -0
- package/dist/chunk-0e16qt6k.js +5 -0
- package/dist/chunk-13hxhzaz.js +34 -0
- package/dist/chunk-2p89vt3b.js +2 -0
- package/dist/chunk-77t2ctwn.js +2 -0
- package/dist/chunk-88z37ey4.js +114 -0
- package/dist/chunk-8c4715hz.js +2 -0
- package/dist/chunk-9a22225r.js +60 -0
- package/dist/chunk-as6by62d.js +1 -0
- package/dist/chunk-cd0zpxhf.js +44 -0
- package/dist/chunk-cp54a0qn.js +6 -0
- package/dist/chunk-d67xbk4v.js +141 -0
- package/dist/chunk-dckz9xve.js +2 -0
- package/dist/chunk-e1666vjv.js +2 -0
- package/dist/chunk-hhdx5k96.js +442 -0
- package/dist/chunk-kv2ztkp4.js +1617 -0
- package/dist/chunk-nrz6zypg.js +1 -0
- package/dist/chunk-q816js1y.js +1 -0
- package/dist/chunk-qh9ep11z.js +704 -0
- package/dist/chunk-rg720cqg.js +1 -0
- package/dist/chunk-snak8s7m.js +92 -0
- package/dist/chunk-vq737g82.js +1 -0
- package/dist/chunk-xd6w0c11.js +50 -0
- package/dist/chunk-xtwjt370.js +37 -0
- package/dist/chunk-y26yh5zp.js +1 -0
- package/dist/chunk-zmxffmmq.js +4 -0
- package/dist/deploy/attach-credentials.d.ts +4 -8
- package/dist/deploy/index.js +1 -168
- package/dist/dns/cloudflare.d.ts +27 -0
- package/dist/dns/godaddy.d.ts +18 -1
- package/dist/dns/index.d.ts +2 -0
- package/dist/dns/index.js +1 -41
- package/dist/dns/zone-migration.d.ts +92 -0
- package/dist/dns/zone-migration.test.d.ts +1 -0
- package/dist/drivers/hetzner/driver.d.ts +8 -1
- package/dist/drivers/index.js +1 -154
- package/dist/drivers/shared/compute-provision.d.ts +14 -2
- package/dist/drivers/shared/db-provision.d.ts +3 -2
- package/dist/drivers/shared/mail-provision.d.ts +116 -0
- package/dist/drivers/shared/mail-provision.test.d.ts +1 -0
- package/dist/drivers/shared/managed-services-probe.d.ts +47 -0
- package/dist/drivers/shared/managed-services-probe.test.d.ts +1 -0
- package/dist/drivers/shared/package-manager.d.ts +1 -0
- package/dist/drivers/shared/remote-failure.d.ts +21 -0
- package/dist/drivers/shared/remote-failure.test.d.ts +1 -0
- package/dist/drivers/shared/sqlite-shared-path.d.ts +50 -0
- package/dist/drivers/shared/sqlite-shared-path.test.d.ts +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +100 -6129
- package/dist/operations/plan.d.ts +136 -0
- package/dist/operations/plan.test.d.ts +1 -0
- package/dist/operations/server-rename.d.ts +84 -0
- package/dist/operations/server-rename.test.d.ts +1 -0
- package/dist/operations/site-move.d.ts +263 -0
- package/dist/operations/site-move.test.d.ts +1 -0
- package/dist/protection/index.js +1 -89
- package/dist/push/index.js +1 -509
- package/dist/spend/index.js +1 -173
- package/dist/ui/404.html +1 -1
- package/dist/ui/accept-invitation.html +1 -1
- package/dist/ui/access-denied.html +1 -1
- package/dist/ui/account/automation.html +5 -5
- package/dist/ui/account/security.html +2 -2
- package/dist/ui/applications/compose.html +6 -6
- package/dist/ui/applications/new.html +2 -2
- package/dist/ui/data/backups.html +80 -80
- package/dist/ui/data/services.html +78 -78
- package/dist/ui/data/volumes.html +50 -50
- package/dist/ui/index.html +50 -50
- package/dist/ui/infrastructure/topology.html +118 -118
- package/dist/ui/integrations.html +1 -1
- package/dist/ui/operations/alerts.html +47 -47
- package/dist/ui/operations/configuration.html +5 -5
- package/dist/ui/operations/jobs.html +76 -76
- package/dist/ui/operations/maintenance.html +6 -6
- package/dist/ui/operations/observability.html +82 -82
- package/dist/ui/operations/previews.html +5 -5
- package/dist/ui/operations/queue.html +6 -6
- package/dist/ui/operations/regions.html +6 -6
- package/dist/ui/operations/releases.html +6 -6
- package/dist/ui/operations/spend.html +54 -54
- package/dist/ui/operations/workloads.html +104 -104
- package/dist/ui/security.html +2 -2
- package/dist/ui/server/actions.html +56 -56
- package/dist/ui/server/activity.html +1 -1
- package/dist/ui/server/capacity.html +6 -6
- package/dist/ui/server/database.html +106 -106
- package/dist/ui/server/deployments.html +50 -50
- package/dist/ui/server/diagnostics.html +2 -2
- package/dist/ui/server/firewall.html +76 -76
- package/dist/ui/server/fleet.html +34 -34
- package/dist/ui/server/logs.html +24 -24
- package/dist/ui/server/metrics.html +112 -112
- package/dist/ui/server/security.html +1 -1
- package/dist/ui/server/services.html +27 -27
- package/dist/ui/server/sites.html +120 -120
- package/dist/ui/server/ssh-keys.html +51 -51
- package/dist/ui/server/team.html +144 -144
- package/dist/ui/server/terminal.html +15 -15
- package/dist/ui/serverless/alarms.html +52 -52
- package/dist/ui/serverless/assets.html +27 -27
- package/dist/ui/serverless/cost.html +2 -2
- package/dist/ui/serverless/data.html +36 -36
- package/dist/ui/serverless/deployments.html +27 -27
- package/dist/ui/serverless/firewall.html +1 -1
- package/dist/ui/serverless/functions.html +40 -40
- package/dist/ui/serverless/logs.html +24 -24
- package/dist/ui/serverless/metrics.html +2 -2
- package/dist/ui/serverless/queues.html +47 -47
- package/dist/ui/serverless/secrets.html +52 -52
- package/dist/ui/serverless/traces.html +6 -6
- package/dist/ui/serverless.html +54 -54
- package/dist/ui-src/src/charts.ts +17499 -12662
- package/dist/ui-src/src/topology.ts +2 -2
- package/package.json +3 -3
- package/dist/bin/chunk-09nwf2gy.js +0 -34
- package/dist/bin/chunk-14cwr6eh.js +0 -70
- package/dist/bin/chunk-271gk1n2.js +0 -6
- package/dist/bin/chunk-38pq971s.js +0 -2
- package/dist/bin/chunk-3gykfyq4.js +0 -37
- package/dist/bin/chunk-3r4fb59r.js +0 -3
- package/dist/bin/chunk-41x17hw1.js +0 -1
- package/dist/bin/chunk-4vrqm9h0.js +0 -2
- package/dist/bin/chunk-57y1zxbf.js +0 -3
- package/dist/bin/chunk-598yf4bs.js +0 -1
- package/dist/bin/chunk-8v7ddyvf.js +0 -1
- package/dist/bin/chunk-92mea34a.js +0 -1
- package/dist/bin/chunk-9pvsff8g.js +0 -1
- package/dist/bin/chunk-9v39615t.js +0 -1
- package/dist/bin/chunk-avm7tnwe.js +0 -1
- package/dist/bin/chunk-ax9mr6wm.js +0 -44
- package/dist/bin/chunk-axhnkn5g.js +0 -2
- package/dist/bin/chunk-b5gd39s8.js +0 -512
- package/dist/bin/chunk-b9qbp8j1.js +0 -1
- package/dist/bin/chunk-bz828v8q.js +0 -3
- package/dist/bin/chunk-c1vcdgvr.js +0 -1
- package/dist/bin/chunk-ctd2vg9w.js +0 -2
- package/dist/bin/chunk-dbgffky8.js +0 -1
- package/dist/bin/chunk-dwr30vbv.js +0 -1
- package/dist/bin/chunk-e3xrwh9z.js +0 -1
- package/dist/bin/chunk-fhc6ntvd.js +0 -2
- package/dist/bin/chunk-fpm59y25.js +0 -6
- package/dist/bin/chunk-fvbxvq6b.js +0 -1
- package/dist/bin/chunk-fy8j3y8p.js +0 -92
- package/dist/bin/chunk-fz21b57w.js +0 -1
- package/dist/bin/chunk-gavvf0pg.js +0 -141
- package/dist/bin/chunk-ggn7ax8p.js +0 -4
- package/dist/bin/chunk-gpe2prkm.js +0 -1
- package/dist/bin/chunk-gqf6jsmy.js +0 -1
- package/dist/bin/chunk-h5pa5men.js +0 -2
- package/dist/bin/chunk-hm08xdxf.js +0 -2
- package/dist/bin/chunk-hzgz13nf.js +0 -1
- package/dist/bin/chunk-hzqw8xm5.js +0 -111
- package/dist/bin/chunk-j703btc5.js +0 -50
- package/dist/bin/chunk-jpjamjey.js +0 -6935
- package/dist/bin/chunk-m2zwtapr.js +0 -1
- package/dist/bin/chunk-m669wtgr.js +0 -1
- package/dist/bin/chunk-mr0atd2s.js +0 -2
- package/dist/bin/chunk-ngcyftm2.js +0 -1
- package/dist/bin/chunk-p66ptpmr.js +0 -2
- package/dist/bin/chunk-p8q9bq9g.js +0 -1
- package/dist/bin/chunk-r3kv0vm9.js +0 -6
- package/dist/bin/chunk-r9hjwcj9.js +0 -6
- package/dist/bin/chunk-rtczra13.js +0 -1
- package/dist/bin/chunk-rytk89az.js +0 -60
- package/dist/bin/chunk-sgyffpgm.js +0 -581
- package/dist/bin/chunk-vek8a0w6.js +0 -1
- package/dist/bin/chunk-waayf9ay.js +0 -2
- package/dist/bin/chunk-yv9sth30.js +0 -1
- package/dist/chunk-01d86gt1.js +0 -1324
- package/dist/chunk-050r7ycy.js +0 -46516
- package/dist/chunk-1c8dbv57.js +0 -7278
- package/dist/chunk-29rse4p1.js +0 -12203
- package/dist/chunk-32e7ya18.js +0 -642
- package/dist/chunk-4cjrg98a.js +0 -597
- package/dist/chunk-50jpda9q.js +0 -371
- package/dist/chunk-6a1t7fnq.js +0 -12121
- package/dist/chunk-728jvrr0.js +0 -1701
- package/dist/chunk-7m60qnc8.js +0 -1762
- package/dist/chunk-aa2dkn7b.js +0 -205
- package/dist/chunk-d48vtdj4.js +0 -433
- package/dist/chunk-f55nkpvb.js +0 -8
- package/dist/chunk-fgk8cqew.js +0 -152
- package/dist/chunk-he9a874b.js +0 -769
- package/dist/chunk-k2yyatfw.js +0 -10
- package/dist/chunk-k4px0bnv.js +0 -23
- package/dist/chunk-nsgqsmrh.js +0 -1779
- package/dist/chunk-q0st3se8.js +0 -42033
- package/dist/chunk-qr803fye.js +0 -2122
- package/dist/chunk-rds0sy87.js +0 -1771
- package/dist/chunk-ttz2ra5j.js +0 -12
- package/dist/chunk-v0bahtg2.js +0 -4
- package/dist/chunk-va2yd85b.js +0 -200
- package/dist/chunk-x9s0cqfx.js +0 -13
- package/dist/chunk-zqtpg06c.js +0 -1752
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stacksjs/ts-cloud",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.10.0",
|
|
5
5
|
"description": "A lightweight, performant infrastructure-as-code library and CLI for deploying both server-based (EC2) and serverless applications.",
|
|
6
6
|
"author": "Chris Breuer <chris@stacksjs.com>",
|
|
7
7
|
"license": "MIT",
|
|
@@ -98,8 +98,8 @@
|
|
|
98
98
|
},
|
|
99
99
|
"dependencies": {
|
|
100
100
|
"@stacksjs/ts-xml": "^0.1.0",
|
|
101
|
-
"@ts-cloud/aws-types": "0.
|
|
102
|
-
"@ts-cloud/core": "0.
|
|
101
|
+
"@ts-cloud/aws-types": "0.10.0",
|
|
102
|
+
"@ts-cloud/core": "0.10.0"
|
|
103
103
|
},
|
|
104
104
|
"devDependencies": {
|
|
105
105
|
"better-dx": "^0.2.16",
|
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
import{Zf as j}from"./chunk-j703btc5.js";import{$f as E}from"./chunk-fy8j3y8p.js";import{Og as L}from"./chunk-fpm59y25.js";import{Vo as W}from"./chunk-mh0kdzqp.js";function h(z,D){let F=[`Action=${z}`,"Version=2010-05-08"];for(let[J,H]of Object.entries(D)){if(H===void 0||H===null)continue;if(Array.isArray(H))H.forEach((O,Z)=>{if(typeof O==="object"&&O!==null)for(let[$,_]of Object.entries(O))F.push(`${J}.member.${Z+1}.${$}=${encodeURIComponent(String(_))}`);else F.push(`${J}.member.${Z+1}=${encodeURIComponent(String(O))}`)});else if(typeof H==="object"){for(let[O,Z]of Object.entries(H))if(Z!==void 0&&Z!==null)F.push(`${J}.${O}=${encodeURIComponent(String(Z))}`)}else F.push(`${J}=${encodeURIComponent(String(H))}`)}return F.join("&")}function G(z,D){let F=new RegExp(`<${D}>([^<]*)</${D}>`),J=z.match(F);return J?J[1]:void 0}function Y(z,D,F){let J=new RegExp(`<${D}>([\\s\\S]*?)</${D}>`),H=z.match(J);if(!H)return[];let O=[],Z=new RegExp(`<${F}>([\\s\\S]*?)</${F}>`,"g"),$;while(($=Z.exec(H[1]))!==null)O.push($[1]);return O}class w{client;region;constructor(z="us-east-1",D){this.client=new L(void 0,{profile:D}),this.region=z}async request(z,D={}){let F=h(z,D);return await this.client.request({service:"iam",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:F})}async createUser(z){let D=await this.request("CreateUser",z);return this.parseUser(D)}async getUser(z={}){let D=await this.request("GetUser",z);return this.parseUser(D)}async listUsers(z={}){let D=await this.request("ListUsers",z),F=this.parseUsers(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{Users:F,IsTruncated:J,Marker:H}}async updateUser(z){await this.request("UpdateUser",z)}async deleteUser(z){await this.request("DeleteUser",z)}parseUser(z){return{UserName:G(z,"UserName")||"",UserId:G(z,"UserId")||"",Arn:G(z,"Arn")||"",Path:G(z,"Path"),CreateDate:G(z,"CreateDate"),PasswordLastUsed:G(z,"PasswordLastUsed")}}parseUsers(z){return Y(z,"Users","member").map((F)=>({UserName:G(F,"UserName")||"",UserId:G(F,"UserId")||"",Arn:G(F,"Arn")||"",Path:G(F,"Path"),CreateDate:G(F,"CreateDate"),PasswordLastUsed:G(F,"PasswordLastUsed")}))}async createGroup(z){let D=await this.request("CreateGroup",z);return this.parseGroup(D)}async getGroup(z){let D=await this.request("GetGroup",z),F=this.parseGroup(D),J=this.parseUsers(D),H=G(D,"IsTruncated")==="true",O=G(D,"Marker");return{Group:F,Users:J,IsTruncated:H,Marker:O}}async listGroups(z={}){let D=await this.request("ListGroups",z),F=this.parseGroups(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{Groups:F,IsTruncated:J,Marker:H}}async updateGroup(z){await this.request("UpdateGroup",z)}async deleteGroup(z){await this.request("DeleteGroup",z)}async addUserToGroup(z){await this.request("AddUserToGroup",z)}async removeUserFromGroup(z){await this.request("RemoveUserFromGroup",z)}async listGroupsForUser(z){let D=await this.request("ListGroupsForUser",z),F=this.parseGroups(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{Groups:F,IsTruncated:J,Marker:H}}parseGroup(z){return{GroupName:G(z,"GroupName")||"",GroupId:G(z,"GroupId")||"",Arn:G(z,"Arn")||"",Path:G(z,"Path"),CreateDate:G(z,"CreateDate")}}parseGroups(z){return Y(z,"Groups","member").map((F)=>({GroupName:G(F,"GroupName")||"",GroupId:G(F,"GroupId")||"",Arn:G(F,"Arn")||"",Path:G(F,"Path"),CreateDate:G(F,"CreateDate")}))}async createRole(z){let D=await this.request("CreateRole",z);return this.parseRole(D)}async getRole(z){let D=await this.request("GetRole",z);return this.parseRole(D)}async listRoles(z={}){let D=await this.request("ListRoles",z),F=this.parseRoles(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{Roles:F,IsTruncated:J,Marker:H}}async updateRole(z){await this.request("UpdateRole",z)}async updateRoleDescription(z){let D=await this.request("UpdateRoleDescription",z);return this.parseRole(D)}async updateAssumeRolePolicy(z){await this.request("UpdateAssumeRolePolicy",z)}async deleteRole(z){await this.request("DeleteRole",z)}async tagRole(z){await this.request("TagRole",z)}async untagRole(z){await this.request("UntagRole",z)}async listRoleTags(z){let D=await this.request("ListRoleTags",z),F=this.parseTags(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{Tags:F,IsTruncated:J,Marker:H}}parseRole(z){return{RoleName:G(z,"RoleName")||"",RoleId:G(z,"RoleId")||"",Arn:G(z,"Arn")||"",Path:G(z,"Path"),CreateDate:G(z,"CreateDate"),AssumeRolePolicyDocument:G(z,"AssumeRolePolicyDocument"),Description:G(z,"Description"),MaxSessionDuration:G(z,"MaxSessionDuration")?Number.parseInt(G(z,"MaxSessionDuration"),10):void 0}}parseRoles(z){return Y(z,"Roles","member").map((F)=>({RoleName:G(F,"RoleName")||"",RoleId:G(F,"RoleId")||"",Arn:G(F,"Arn")||"",Path:G(F,"Path"),CreateDate:G(F,"CreateDate"),AssumeRolePolicyDocument:G(F,"AssumeRolePolicyDocument"),Description:G(F,"Description"),MaxSessionDuration:G(F,"MaxSessionDuration")?Number.parseInt(G(F,"MaxSessionDuration"),10):void 0}))}parseTags(z){return Y(z,"Tags","member").map((F)=>({Key:G(F,"Key")||"",Value:G(F,"Value")||""}))}async createPolicy(z){let D=await this.request("CreatePolicy",z);return this.parsePolicy(D)}async getPolicy(z){let D=await this.request("GetPolicy",z);return this.parsePolicy(D)}async getPolicyVersion(z){let D=await this.request("GetPolicyVersion",z);return{VersionId:G(D,"VersionId")||"",IsDefaultVersion:G(D,"IsDefaultVersion")==="true",CreateDate:G(D,"CreateDate"),Document:G(D,"Document")}}async listPolicies(z={}){let D=await this.request("ListPolicies",z),F=this.parsePolicies(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{Policies:F,IsTruncated:J,Marker:H}}async listPolicyVersions(z){let D=await this.request("ListPolicyVersions",z),F=this.parsePolicyVersions(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{Versions:F,IsTruncated:J,Marker:H}}async createPolicyVersion(z){let D=await this.request("CreatePolicyVersion",z);return{VersionId:G(D,"VersionId")||"",IsDefaultVersion:G(D,"IsDefaultVersion")==="true",CreateDate:G(D,"CreateDate")}}async deletePolicyVersion(z){await this.request("DeletePolicyVersion",z)}async setDefaultPolicyVersion(z){await this.request("SetDefaultPolicyVersion",z)}async deletePolicy(z){await this.request("DeletePolicy",z)}async attachUserPolicy(z){await this.request("AttachUserPolicy",z)}async detachUserPolicy(z){await this.request("DetachUserPolicy",z)}async attachGroupPolicy(z){await this.request("AttachGroupPolicy",z)}async detachGroupPolicy(z){await this.request("DetachGroupPolicy",z)}async attachRolePolicy(z){await this.request("AttachRolePolicy",z)}async detachRolePolicy(z){await this.request("DetachRolePolicy",z)}async listAttachedUserPolicies(z){let D=await this.request("ListAttachedUserPolicies",z),F=this.parseAttachedPolicies(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{AttachedPolicies:F,IsTruncated:J,Marker:H}}async listAttachedGroupPolicies(z){let D=await this.request("ListAttachedGroupPolicies",z),F=this.parseAttachedPolicies(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{AttachedPolicies:F,IsTruncated:J,Marker:H}}async listAttachedRolePolicies(z){let D=await this.request("ListAttachedRolePolicies",z),F=this.parseAttachedPolicies(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{AttachedPolicies:F,IsTruncated:J,Marker:H}}parsePolicy(z){return{PolicyName:G(z,"PolicyName")||"",PolicyId:G(z,"PolicyId")||"",Arn:G(z,"Arn")||"",Path:G(z,"Path"),DefaultVersionId:G(z,"DefaultVersionId"),AttachmentCount:G(z,"AttachmentCount")?Number.parseInt(G(z,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:G(z,"PermissionsBoundaryUsageCount")?Number.parseInt(G(z,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:G(z,"IsAttachable")==="true",Description:G(z,"Description"),CreateDate:G(z,"CreateDate"),UpdateDate:G(z,"UpdateDate")}}parsePolicies(z){return Y(z,"Policies","member").map((F)=>({PolicyName:G(F,"PolicyName")||"",PolicyId:G(F,"PolicyId")||"",Arn:G(F,"Arn")||"",Path:G(F,"Path"),DefaultVersionId:G(F,"DefaultVersionId"),AttachmentCount:G(F,"AttachmentCount")?Number.parseInt(G(F,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:G(F,"PermissionsBoundaryUsageCount")?Number.parseInt(G(F,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:G(F,"IsAttachable")==="true",Description:G(F,"Description"),CreateDate:G(F,"CreateDate"),UpdateDate:G(F,"UpdateDate")}))}parsePolicyVersions(z){return Y(z,"Versions","member").map((F)=>({VersionId:G(F,"VersionId")||"",IsDefaultVersion:G(F,"IsDefaultVersion")==="true",CreateDate:G(F,"CreateDate")}))}parseAttachedPolicies(z){return Y(z,"AttachedPolicies","member").map((F)=>({PolicyName:G(F,"PolicyName")||"",PolicyArn:G(F,"PolicyArn")||""}))}async putUserPolicy(z){await this.request("PutUserPolicy",z)}async getUserPolicy(z){let D=await this.request("GetUserPolicy",z);return{UserName:G(D,"UserName")||"",PolicyName:G(D,"PolicyName")||"",PolicyDocument:decodeURIComponent(G(D,"PolicyDocument")||"")}}async deleteUserPolicy(z){await this.request("DeleteUserPolicy",z)}async listUserPolicies(z){let D=await this.request("ListUserPolicies",z),F=Y(D,"PolicyNames","member"),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{PolicyNames:F,IsTruncated:J,Marker:H}}async putGroupPolicy(z){await this.request("PutGroupPolicy",z)}async getGroupPolicy(z){let D=await this.request("GetGroupPolicy",z);return{GroupName:G(D,"GroupName")||"",PolicyName:G(D,"PolicyName")||"",PolicyDocument:decodeURIComponent(G(D,"PolicyDocument")||"")}}async deleteGroupPolicy(z){await this.request("DeleteGroupPolicy",z)}async listGroupPolicies(z){let D=await this.request("ListGroupPolicies",z),F=Y(D,"PolicyNames","member"),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{PolicyNames:F,IsTruncated:J,Marker:H}}async putRolePolicy(z){await this.request("PutRolePolicy",z)}async getRolePolicy(z){let D=await this.request("GetRolePolicy",z);return{RoleName:G(D,"RoleName")||"",PolicyName:G(D,"PolicyName")||"",PolicyDocument:decodeURIComponent(G(D,"PolicyDocument")||"")}}async deleteRolePolicy(z){await this.request("DeleteRolePolicy",z)}async listRolePolicies(z){let D=await this.request("ListRolePolicies",z),F=Y(D,"PolicyNames","member"),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{PolicyNames:F,IsTruncated:J,Marker:H}}async createAccessKey(z={}){let D=await this.request("CreateAccessKey",z);if(typeof D==="object"){let F=D?.CreateAccessKeyResult?.AccessKey||D?.AccessKey;if(F)return{AccessKey:{UserName:F.UserName||"",AccessKeyId:F.AccessKeyId||"",Status:F.Status||"Active",SecretAccessKey:F.SecretAccessKey||"",CreateDate:F.CreateDate}}}return{AccessKey:{UserName:G(D,"UserName")||"",AccessKeyId:G(D,"AccessKeyId")||"",Status:G(D,"Status")||"Active",SecretAccessKey:G(D,"SecretAccessKey")||"",CreateDate:G(D,"CreateDate")}}}async listAccessKeys(z={}){let D=await this.request("ListAccessKeys",z),F=this.parseAccessKeys(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{AccessKeyMetadata:F,IsTruncated:J,Marker:H}}async updateAccessKey(z){await this.request("UpdateAccessKey",z)}async deleteAccessKey(z){await this.request("DeleteAccessKey",z)}async getAccessKeyLastUsed(z){let D=await this.request("GetAccessKeyLastUsed",z);return{UserName:G(D,"UserName")||"",AccessKeyLastUsed:{LastUsedDate:G(D,"LastUsedDate"),ServiceName:G(D,"ServiceName"),Region:G(D,"Region")}}}parseAccessKeys(z){return Y(z,"AccessKeyMetadata","member").map((F)=>({UserName:G(F,"UserName"),AccessKeyId:G(F,"AccessKeyId")||"",Status:G(F,"Status")||"Active",CreateDate:G(F,"CreateDate")}))}async createInstanceProfile(z){let D=await this.request("CreateInstanceProfile",z);return this.parseInstanceProfile(D)}async getInstanceProfile(z){let D=await this.request("GetInstanceProfile",z);return this.parseInstanceProfile(D)}async listInstanceProfiles(z={}){let D=await this.request("ListInstanceProfiles",z),F=this.parseInstanceProfiles(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{InstanceProfiles:F,IsTruncated:J,Marker:H}}async listInstanceProfilesForRole(z){let D=await this.request("ListInstanceProfilesForRole",z),F=this.parseInstanceProfiles(D),J=G(D,"IsTruncated")==="true",H=G(D,"Marker");return{InstanceProfiles:F,IsTruncated:J,Marker:H}}async addRoleToInstanceProfile(z){await this.request("AddRoleToInstanceProfile",z)}async removeRoleFromInstanceProfile(z){await this.request("RemoveRoleFromInstanceProfile",z)}async deleteInstanceProfile(z){await this.request("DeleteInstanceProfile",z)}parseInstanceProfile(z){return{InstanceProfileName:G(z,"InstanceProfileName")||"",InstanceProfileId:G(z,"InstanceProfileId")||"",Arn:G(z,"Arn")||"",Path:G(z,"Path"),CreateDate:G(z,"CreateDate")}}parseInstanceProfiles(z){return Y(z,"InstanceProfiles","member").map((F)=>({InstanceProfileName:G(F,"InstanceProfileName")||"",InstanceProfileId:G(F,"InstanceProfileId")||"",Arn:G(F,"Arn")||"",Path:G(F,"Path"),CreateDate:G(F,"CreateDate")}))}async getAccountPasswordPolicy(){let z=await this.request("GetAccountPasswordPolicy");return{MinimumPasswordLength:G(z,"MinimumPasswordLength")?Number.parseInt(G(z,"MinimumPasswordLength"),10):void 0,RequireSymbols:G(z,"RequireSymbols")==="true",RequireNumbers:G(z,"RequireNumbers")==="true",RequireUppercaseCharacters:G(z,"RequireUppercaseCharacters")==="true",RequireLowercaseCharacters:G(z,"RequireLowercaseCharacters")==="true",AllowUsersToChangePassword:G(z,"AllowUsersToChangePassword")==="true",ExpirePasswords:G(z,"ExpirePasswords")==="true",MaxPasswordAge:G(z,"MaxPasswordAge")?Number.parseInt(G(z,"MaxPasswordAge"),10):void 0,PasswordReusePrevention:G(z,"PasswordReusePrevention")?Number.parseInt(G(z,"PasswordReusePrevention"),10):void 0,HardExpiry:G(z,"HardExpiry")==="true"}}async updateAccountPasswordPolicy(z){await this.request("UpdateAccountPasswordPolicy",z)}async deleteAccountPasswordPolicy(){await this.request("DeleteAccountPasswordPolicy")}async getAccountSummary(){let z=await this.request("GetAccountSummary"),D={},F=Y(z,"SummaryMap","entry");for(let J of F){let H=G(J,"key"),O=G(J,"value");if(H&&O)D[H]=Number.parseInt(O,10)}return D}async listAccountAliases(){let z=await this.request("ListAccountAliases"),D=Y(z,"AccountAliases","member"),F=G(z,"IsTruncated")==="true",J=G(z,"Marker");return{AccountAliases:D,IsTruncated:F,Marker:J}}async createAccountAlias(z){await this.request("CreateAccountAlias",z)}async deleteAccountAlias(z){await this.request("DeleteAccountAlias",z)}async simulatePrincipalPolicy(z){let D=await this.request("SimulatePrincipalPolicy",z);return this.parseSimulationResults(D)}parseSimulationResults(z){let F=Y(z,"EvaluationResults","member").map((O)=>{let $=Y(O,"MatchedStatements","member").map((_)=>({SourcePolicyId:G(_,"SourcePolicyId"),SourcePolicyType:G(_,"SourcePolicyType")}));return{EvalActionName:G(O,"EvalActionName")||"",EvalResourceName:G(O,"EvalResourceName"),EvalDecision:G(O,"EvalDecision")||"",MatchedStatements:$.length>0?$:void 0}}),J=G(z,"IsTruncated")==="true",H=G(z,"Marker");return{EvaluationResults:F,IsTruncated:J,Marker:H}}}class U{client;region;constructor(z="us-east-1",D){this.region=z,this.client=new L(D)}async createEmailIdentity(z){return await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/identities",headers:{"Content-Type":"application/json"},body:JSON.stringify(z)})}async getEmailIdentity(z){let D=await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/identities/${encodeURIComponent(z)}`,headers:{"Content-Type":"application/json"}});return{IdentityType:D.IdentityType,IdentityName:z,SendingEnabled:D.VerifiedForSendingStatus,VerificationStatus:D.VerificationStatus,DkimAttributes:D.DkimAttributes,MailFromAttributes:D.MailFromAttributes}}async putEmailIdentityMailFromAttributes(z,D){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(z)}/mail-from`,headers:{"Content-Type":"application/json"},body:JSON.stringify(D)})}async listEmailIdentities(z){let D="/v2/email/identities",F=[];if(z?.PageSize)F.push(`PageSize=${z.PageSize}`);if(z?.NextToken)F.push(`NextToken=${encodeURIComponent(z.NextToken)}`);if(F.length>0)D+=`?${F.join("&")}`;let J=await this.client.request({service:"email",region:this.region,method:"GET",path:D,headers:{"Content-Type":"application/json"}});return{EmailIdentities:J.EmailIdentities,NextToken:J.NextToken}}async deleteEmailIdentity(z){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/identities/${encodeURIComponent(z)}`,headers:{"Content-Type":"application/json"}})}async putEmailIdentityDkimAttributes(z){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(z.EmailIdentity)}/dkim`,headers:{"Content-Type":"application/json"},body:JSON.stringify({SigningEnabled:z.SigningEnabled})})}async sendEmail(z){return{MessageId:(await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/outbound-emails",headers:{"Content-Type":"application/json"},body:JSON.stringify(z)})).MessageId}}async sendBulkEmail(z){return{BulkEmailEntryResults:(await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/outbound-bulk-emails",headers:{"Content-Type":"application/json"},body:JSON.stringify(z)})).BulkEmailEntryResults}}async createEmailTemplate(z){await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/templates",headers:{"Content-Type":"application/json"},body:JSON.stringify(z)})}async getEmailTemplate(z){return await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/templates/${encodeURIComponent(z)}`,headers:{"Content-Type":"application/json"}})}async deleteEmailTemplate(z){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/templates/${encodeURIComponent(z)}`,headers:{"Content-Type":"application/json"}})}async listEmailTemplates(z){let D="/v2/email/templates",F=[];if(z?.PageSize)F.push(`PageSize=${z.PageSize}`);if(z?.NextToken)F.push(`NextToken=${encodeURIComponent(z.NextToken)}`);if(F.length>0)D+=`?${F.join("&")}`;return await this.client.request({service:"email",region:this.region,method:"GET",path:D,headers:{"Content-Type":"application/json"}})}async getSendStatistics(){return{SendDataPoints:(await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendStatistics&Version=2010-12-01"})).GetSendStatisticsResponse?.GetSendStatisticsResult?.SendDataPoints?.member}}async getSendQuota(){let D=(await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendQuota&Version=2010-12-01"})).GetSendQuotaResponse?.GetSendQuotaResult;return{Max24HourSend:D?.Max24HourSend?Number(D.Max24HourSend):void 0,MaxSendRate:D?.MaxSendRate?Number(D.MaxSendRate):void 0,SentLast24Hours:D?.SentLast24Hours?Number(D.SentLast24Hours):void 0}}async verifyDomain(z){let D=await this.createEmailIdentity({EmailIdentity:z});return{dkimTokens:D.DkimAttributes?.Tokens,verificationStatus:D.DkimAttributes?.Status}}async sendSimpleEmail(z){let D=Array.isArray(z.to)?z.to:[z.to],F=z.replyTo?Array.isArray(z.replyTo)?z.replyTo:[z.replyTo]:void 0,J={};if(z.text)J.Text={Data:z.text};if(z.html)J.Html={Data:z.html};return this.sendEmail({FromEmailAddress:z.from,Destination:{ToAddresses:D},Content:{Simple:{Subject:{Data:z.subject},Body:J}},ReplyToAddresses:F})}async sendTemplatedEmail(z){let D=Array.isArray(z.to)?z.to:[z.to],F=z.replyTo?Array.isArray(z.replyTo)?z.replyTo:[z.replyTo]:void 0;return this.sendEmail({FromEmailAddress:z.from,Destination:{ToAddresses:D},Content:{Template:{TemplateName:z.templateName,TemplateData:JSON.stringify(z.templateData)}},ReplyToAddresses:F})}async getDkimRecords(z){let D=await this.getEmailIdentity(z);if(!D.DkimAttributes?.Tokens)return[];return D.DkimAttributes.Tokens.map((F)=>({name:`${F}._domainkey.${z}`,type:"CNAME",value:`${F}.dkim.amazonses.com`}))}async isDomainVerified(z){try{let D=await this.getEmailIdentity(z);return D.VerificationStatus==="SUCCESS"&&D.SendingEnabled===!0}catch{return!1}}async waitForDomainVerification(z,D=60,F=30000){for(let J=0;J<D;J++){if(await this.isDomainVerified(z))return!0;await new Promise((O)=>setTimeout(O,F))}return!1}buildFormBody(z){return Object.entries(z).filter(([,F])=>F!==void 0).map(([F,J])=>`${encodeURIComponent(F)}=${encodeURIComponent(J)}`).join("&")}async createReceiptRuleSet(z){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"CreateReceiptRuleSet",Version:"2010-12-01",RuleSetName:z})})}async deleteReceiptRuleSet(z){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteReceiptRuleSet",Version:"2010-12-01",RuleSetName:z})})}async setActiveReceiptRuleSet(z){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"SetActiveReceiptRuleSet",Version:"2010-12-01",RuleSetName:z})})}async listReceiptRuleSets(z){let D={Action:"ListReceiptRuleSets",Version:"2010-12-01"};if(z)D.NextToken=z;let F=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(D)}),J=F?.ListReceiptRuleSetsResponse?.ListReceiptRuleSetsResult||F?.ListReceiptRuleSetsResult,H=J?.RuleSets?.member;return{RuleSets:Array.isArray(H)?H:H?[H]:[],NextToken:J?.NextToken}}async describeReceiptRuleSet(z){let D=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DescribeReceiptRuleSet",Version:"2010-12-01",RuleSetName:z})}),F=D?.DescribeReceiptRuleSetResponse?.DescribeReceiptRuleSetResult||D?.DescribeReceiptRuleSetResult,J=F?.Rules?.member;return{Metadata:F?.Metadata,Rules:Array.isArray(J)?J:J?[J]:[]}}async createReceiptRule(z){let D={Action:"CreateReceiptRule",Version:"2010-12-01",RuleSetName:z.RuleSetName,"Rule.Name":z.Rule.Name,"Rule.Enabled":z.Rule.Enabled!==!1?"true":"false"};if(z.Rule.TlsPolicy)D["Rule.TlsPolicy"]=z.Rule.TlsPolicy;if(z.Rule.ScanEnabled!==void 0)D["Rule.ScanEnabled"]=z.Rule.ScanEnabled?"true":"false";if(z.After)D.After=z.After;if(z.Rule.Recipients)z.Rule.Recipients.forEach((F,J)=>{D[`Rule.Recipients.member.${J+1}`]=F});z.Rule.Actions.forEach((F,J)=>{let H=J+1;if(F.S3Action){if(D[`Rule.Actions.member.${H}.S3Action.BucketName`]=F.S3Action.BucketName,F.S3Action.ObjectKeyPrefix)D[`Rule.Actions.member.${H}.S3Action.ObjectKeyPrefix`]=F.S3Action.ObjectKeyPrefix;if(F.S3Action.KmsKeyArn)D[`Rule.Actions.member.${H}.S3Action.KmsKeyArn`]=F.S3Action.KmsKeyArn}if(F.LambdaAction)D[`Rule.Actions.member.${H}.LambdaAction.FunctionArn`]=F.LambdaAction.FunctionArn,D[`Rule.Actions.member.${H}.LambdaAction.InvocationType`]=F.LambdaAction.InvocationType||"Event";if(F.SNSAction){if(D[`Rule.Actions.member.${H}.SNSAction.TopicArn`]=F.SNSAction.TopicArn,F.SNSAction.Encoding)D[`Rule.Actions.member.${H}.SNSAction.Encoding`]=F.SNSAction.Encoding}if(F.StopAction){if(D[`Rule.Actions.member.${H}.StopAction.Scope`]=F.StopAction.Scope,F.StopAction.TopicArn)D[`Rule.Actions.member.${H}.StopAction.TopicArn`]=F.StopAction.TopicArn}}),await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(D)})}async deleteReceiptRule(z,D){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteReceiptRule",Version:"2010-12-01",RuleSetName:z,RuleName:D})})}async receiptRuleSetExists(z){try{return await this.describeReceiptRuleSet(z),!0}catch(D){if(D.code==="RuleSetDoesNotExist"||D.statusCode===400)return!1;throw D}}async getActiveReceiptRuleSet(){let z=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DescribeActiveReceiptRuleSet",Version:"2010-12-01"})}),D=z?.DescribeActiveReceiptRuleSetResponse?.DescribeActiveReceiptRuleSetResult||z?.DescribeActiveReceiptRuleSetResult;if(!D?.Metadata)return null;let F=D?.Rules?.member;return{Metadata:D?.Metadata,Rules:Array.isArray(F)?F:F?[F]:[]}}async updateReceiptRule(z){let D={Action:"UpdateReceiptRule",Version:"2010-12-01",RuleSetName:z.RuleSetName,"Rule.Name":z.Rule.Name};if(z.Rule.Enabled!==void 0)D["Rule.Enabled"]=z.Rule.Enabled?"true":"false";if(z.Rule.TlsPolicy)D["Rule.TlsPolicy"]=z.Rule.TlsPolicy;if(z.Rule.ScanEnabled!==void 0)D["Rule.ScanEnabled"]=z.Rule.ScanEnabled?"true":"false";if(z.Rule.Recipients)z.Rule.Recipients.forEach((F,J)=>{D[`Rule.Recipients.member.${J+1}`]=F});z.Rule.Actions.forEach((F,J)=>{let H=J+1;if(F.S3Action){if(D[`Rule.Actions.member.${H}.S3Action.BucketName`]=F.S3Action.BucketName,F.S3Action.ObjectKeyPrefix)D[`Rule.Actions.member.${H}.S3Action.ObjectKeyPrefix`]=F.S3Action.ObjectKeyPrefix;if(F.S3Action.KmsKeyArn)D[`Rule.Actions.member.${H}.S3Action.KmsKeyArn`]=F.S3Action.KmsKeyArn}if(F.LambdaAction)D[`Rule.Actions.member.${H}.LambdaAction.FunctionArn`]=F.LambdaAction.FunctionArn,D[`Rule.Actions.member.${H}.LambdaAction.InvocationType`]=F.LambdaAction.InvocationType||"Event";if(F.SNSAction){if(D[`Rule.Actions.member.${H}.SNSAction.TopicArn`]=F.SNSAction.TopicArn,F.SNSAction.Encoding)D[`Rule.Actions.member.${H}.SNSAction.Encoding`]=F.SNSAction.Encoding}if(F.StopAction){if(D[`Rule.Actions.member.${H}.StopAction.Scope`]=F.StopAction.Scope,F.StopAction.TopicArn)D[`Rule.Actions.member.${H}.StopAction.TopicArn`]=F.StopAction.TopicArn}}),await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(D)})}async sendRawEmail(z){let D=Buffer.from(z.rawMessage).toString("base64"),F={Action:"SendRawEmail",Version:"2010-12-01",Source:z.source,"RawMessage.Data":D};z.destinations.forEach((O,Z)=>{F[`Destinations.member.${Z+1}`]=O});let J=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(F)});return{MessageId:(J?.SendRawEmailResponse?.SendRawEmailResult||J?.SendRawEmailResult)?.MessageId}}async getSuppressedDestination(z){try{return(await this.client.request({service:"ses",region:this.region,method:"GET",path:`/v2/email/suppression/addresses/${encodeURIComponent(z)}`}))?.SuppressedDestination||null}catch(D){if(D.message?.includes("404")||D.message?.includes("NotFoundException"))return null;throw D}}async deleteSuppressedDestination(z){await this.client.request({service:"ses",region:this.region,method:"DELETE",path:`/v2/email/suppression/addresses/${encodeURIComponent(z)}`})}}class M{ses;s3;iam;route53;region;domain;defaultFrom;constructor(z={}){this.region=z.region||"us-east-1",this.domain=z.domain,this.defaultFrom=z.defaultFrom,this.ses=new U(this.region),this.s3=new E(this.region),this.iam=new w(this.region),this.route53=new j(this.region)}async send(z){let D=z.from||this.defaultFrom;if(!D)throw Error("From address is required. Set defaultFrom in constructor or provide from in options.");let F=z.fromName?`${z.fromName} <${D}>`:D,J=Array.isArray(z.to)?z.to:[z.to];if(!z.attachments||z.attachments.length===0)return{messageId:(await this.ses.sendSimpleEmail({from:F,to:J,subject:z.subject,text:z.text,html:z.html,replyTo:z.replyTo})).MessageId||""};let H=this.buildRawEmail(z,F,J);return{messageId:(await this.ses.sendEmail({FromEmailAddress:F,Destination:{ToAddresses:J,CcAddresses:z.cc?Array.isArray(z.cc)?z.cc:[z.cc]:void 0,BccAddresses:z.bcc?Array.isArray(z.bcc)?z.bcc:[z.bcc]:void 0},Content:{Raw:{Data:Buffer.from(H).toString("base64")}}})).MessageId||""}}async sendTemplate(z){let D=z.from||this.defaultFrom;if(!D)throw Error("From address is required");let F=z.fromName?`${z.fromName} <${D}>`:D;return{messageId:(await this.ses.sendTemplatedEmail({from:F,to:z.to,templateName:z.templateName,templateData:z.templateData,replyTo:z.replyTo})).MessageId||""}}async sendBulk(z){let D=z.from||this.defaultFrom;if(!D)throw Error("From address is required");let F=z.recipients.map((H)=>({Destination:{ToAddresses:Array.isArray(H.to)?H.to:[H.to]},ReplacementEmailContent:H.templateData?{ReplacementTemplate:{ReplacementTemplateData:JSON.stringify(H.templateData)}}:void 0}));return{results:(await this.ses.sendBulkEmail({FromEmailAddress:D,BulkEmailEntries:F,DefaultContent:{Template:{TemplateName:z.templateName,TemplateData:JSON.stringify(z.defaultTemplateData)}}})).BulkEmailEntryResults?.map((H)=>({status:H.Status||"UNKNOWN",messageId:H.MessageId,error:H.Error}))||[]}}async setupDomain(z){let D;try{D=await this.ses.getEmailIdentity(z)}catch{let J=await this.ses.createEmailIdentity({EmailIdentity:z});D={VerificationStatus:J.DkimAttributes?.Status,DkimAttributes:J.DkimAttributes,SendingEnabled:J.VerifiedForSendingStatus}}try{await this.ses.putEmailIdentityDkimAttributes({EmailIdentity:z,SigningEnabled:!0})}catch{}try{await this.ses.putEmailIdentityMailFromAttributes(z,{MailFromDomain:`mail.${z}`,BehaviorOnMxFailure:"USE_DEFAULT_VALUE"})}catch{}let F=await this.ses.getDkimRecords(z);return{domainVerified:D.SendingEnabled===!0,dkimStatus:D.DkimAttributes?.Status||"UNKNOWN",dkimTokens:D.DkimAttributes?.Tokens,mailFromStatus:D.MailFromAttributes?.MailFromDomainStatus}}async getDnsRecords(z){let D=[],F=await this.ses.getDkimRecords(z);for(let J of F)D.push({type:J.type,name:J.name,value:J.value,ttl:1800});return D.push({type:"MX",name:z,value:`inbound-smtp.${this.region}.amazonaws.com`,priority:10,ttl:3600}),D.push({type:"MX",name:`mail.${z}`,value:`feedback-smtp.${this.region}.amazonses.com`,priority:10,ttl:3600}),D.push({type:"TXT",name:`mail.${z}`,value:"v=spf1 include:amazonses.com ~all",ttl:3600}),D.push({type:"TXT",name:`_dmarc.${z}`,value:`v=DMARC1;p=quarantine;pct=25;rua=mailto:dmarcreports@${z}`,ttl:3600}),D}async isDomainReady(z){try{let D=await this.ses.getEmailIdentity(z);return D.SendingEnabled===!0&&D.DkimAttributes?.Status==="SUCCESS"}catch{return!1}}async setupReceiving(z){let D={Version:"2012-10-17",Statement:[{Sid:"AllowSESPuts",Effect:"Allow",Principal:{Service:"ses.amazonaws.com"},Action:"s3:PutObject",Resource:`arn:aws:s3:::${z.bucketName}/*`,Condition:{StringEquals:{"AWS:SourceAccount":z.accountId}}}]};await this.s3.putBucketPolicy(z.bucketName,D);try{await this.ses.createReceiptRuleSet(z.ruleSetName)}catch(J){if(!J.message?.includes("already exists")&&J.code!=="AlreadyExists")throw J}let F=[{S3Action:{BucketName:z.bucketName,ObjectKeyPrefix:z.prefix||"inbox/"}}];if(z.lambdaArn)F.push({LambdaAction:{FunctionArn:z.lambdaArn,InvocationType:"Event"}});try{await this.ses.createReceiptRule({RuleSetName:z.ruleSetName,Rule:{Name:z.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:z.recipients||[z.domain],ScanEnabled:z.scanEnabled!==!1,Actions:F}})}catch(J){if(J.message?.includes("already exists"))await this.ses.deleteReceiptRule(z.ruleSetName,z.ruleName),await this.ses.createReceiptRule({RuleSetName:z.ruleSetName,Rule:{Name:z.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:z.recipients||[z.domain],ScanEnabled:z.scanEnabled!==!1,Actions:F}});else throw J}await this.ses.setActiveReceiptRuleSet(z.ruleSetName)}async getIncomingEmails(z){return(await this.s3.list({bucket:z.bucket,prefix:z.prefix||"incoming/",maxKeys:z.maxResults||100})).map((F)=>({key:F.Key||"",lastModified:F.LastModified||"",size:F.Size||0}))}async readEmail(z){return await this.s3.getObject(z.bucket,z.key)}async createSmtpCredentials(z){let D=`ses-smtp-${z.username.replace(/[^a-zA-Z0-9]/g,"-")}`,{AWSClient:F}=await import("./chunk-dbgffky8.js"),J=new F,H=(Q,C)=>{let I={Action:Q,Version:"2010-05-08",...C};return Object.entries(I).map(([R,K])=>`${encodeURIComponent(R)}=${encodeURIComponent(K)}`).join("&")};try{await J.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:H("CreateUser",{UserName:D})})}catch(Q){if(!Q.message?.includes("EntityAlreadyExists"))throw Q}let O={Version:"2012-10-17",Statement:[{Effect:"Allow",Action:"ses:SendRawEmail",Resource:"*",Condition:{StringLike:{"ses:FromAddress":`*@${z.domain}`}}}]},Z=`ses-smtp-policy-${z.domain.replace(/\./g,"-")}`;try{await J.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:H("PutUserPolicy",{UserName:D,PolicyName:Z,PolicyDocument:JSON.stringify(O)})})}catch{}let _=(await J.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:H("CreateAccessKey",{UserName:D})}))?.CreateAccessKeyResult?.AccessKey;if(!_?.AccessKeyId||!_?.SecretAccessKey)throw Error("Failed to create access key");let B=this.deriveSmtpPassword(_.SecretAccessKey);return{username:_.AccessKeyId,password:B,server:`email-smtp.${this.region}.amazonaws.com`,port:587}}deriveSmtpPassword(z){let D=W("node:crypto"),F="SendRawEmail",J=Buffer.from([4]),H=D.createHmac("sha256",`AWS4${z}`).update("11111111").digest();return H=D.createHmac("sha256",H).update(this.region).digest(),H=D.createHmac("sha256",H).update("ses").digest(),H=D.createHmac("sha256",H).update("aws4_request").digest(),H=D.createHmac("sha256",H).update("SendRawEmail").digest(),Buffer.concat([J,H]).toString("base64")}async createTemplate(z){await this.ses.createEmailTemplate({TemplateName:z.name,TemplateContent:{Subject:z.subject,Text:z.text,Html:z.html}})}async getTemplate(z){try{let D=await this.ses.getEmailTemplate(z);return{name:D.TemplateName||z,subject:D.TemplateContent?.Subject,text:D.TemplateContent?.Text,html:D.TemplateContent?.Html}}catch{return null}}async deleteTemplate(z){await this.ses.deleteEmailTemplate(z)}async listTemplates(){return(await this.ses.listEmailTemplates()).TemplatesMetadata?.map((D)=>({name:D.TemplateName||"",createdAt:D.CreatedTimestamp}))||[]}async deploy(z){let D=`${z.appName}-${z.environment}-email-rules`,F=`${z.appName}-inbound-email`,J=z.storage?.bucketName||`${z.appName}-${z.environment}-email`,H=await this.setupDomain(z.domain);if(!(await this.s3.listBuckets()).Buckets?.some((_)=>_.Name===J))await this.s3.createBucket(J);await this.setupReceiving({domain:z.domain,ruleSetName:D,ruleName:F,bucketName:J,prefix:z.storage?.prefix||"inbox/",accountId:z.accountId,recipients:z.catchAll?[z.domain]:z.mailboxes,scanEnabled:!0});let $=await this.getDnsRecords(z.domain);return{success:!0,domainVerified:H.domainVerified,dkimStatus:H.dkimStatus,receiptRuleSet:D,storageBucket:J,dnsRecords:$}}async undeploy(z){let D=`${z.appName}-${z.environment}-email-rules`,F=`${z.appName}-inbound-email`,J=`${z.appName}-${z.environment}-email`;try{await this.ses.deleteReceiptRule(D,F)}catch{}try{await this.ses.deleteReceiptRuleSet(D)}catch{}if(z.deleteBucket)try{await this.s3.emptyAndDeleteBucket(J)}catch{}}async getSendingStats(){let z=await this.ses.getSendQuota();return{sentLast24Hours:z.SentLast24Hours||0,maxSendRate:z.MaxSendRate||0,max24HourSend:z.Max24HourSend||0}}buildRawEmail(z,D,F){let J=`----=_Part_${Date.now()}_${Math.random().toString(36).substring(2)}`,H="";if(H+=`From: ${D}\r
|
|
2
|
-
`,H+=`To: ${F.join(", ")}\r
|
|
3
|
-
`,z.cc){let O=Array.isArray(z.cc)?z.cc:[z.cc];H+=`Cc: ${O.join(", ")}\r
|
|
4
|
-
`}if(H+=`Subject: ${z.subject}\r
|
|
5
|
-
`,H+=`MIME-Version: 1.0\r
|
|
6
|
-
`,H+=`Content-Type: multipart/mixed; boundary="${J}"\r
|
|
7
|
-
`,H+=`\r
|
|
8
|
-
`,z.text||z.html)if(H+=`--${J}\r
|
|
9
|
-
`,z.html&&z.text){let O=`----=_Alt_${Date.now()}`;H+=`Content-Type: multipart/alternative; boundary="${O}"\r
|
|
10
|
-
`,H+=`\r
|
|
11
|
-
`,H+=`--${O}\r
|
|
12
|
-
`,H+=`Content-Type: text/plain; charset="UTF-8"\r
|
|
13
|
-
`,H+=`\r
|
|
14
|
-
`,H+=`${z.text}\r
|
|
15
|
-
`,H+=`--${O}\r
|
|
16
|
-
`,H+=`Content-Type: text/html; charset="UTF-8"\r
|
|
17
|
-
`,H+=`\r
|
|
18
|
-
`,H+=`${z.html}\r
|
|
19
|
-
`,H+=`--${O}--\r
|
|
20
|
-
`}else if(z.html)H+=`Content-Type: text/html; charset="UTF-8"\r
|
|
21
|
-
`,H+=`\r
|
|
22
|
-
`,H+=`${z.html}\r
|
|
23
|
-
`;else H+=`Content-Type: text/plain; charset="UTF-8"\r
|
|
24
|
-
`,H+=`\r
|
|
25
|
-
`,H+=`${z.text}\r
|
|
26
|
-
`;if(z.attachments)for(let O of z.attachments)H+=`--${J}\r
|
|
27
|
-
`,H+=`Content-Type: ${O.contentType||"application/octet-stream"}; name="${O.filename}"\r
|
|
28
|
-
`,H+=`Content-Transfer-Encoding: base64\r
|
|
29
|
-
`,H+=`Content-Disposition: attachment; filename="${O.filename}"\r
|
|
30
|
-
`,H+=`\r
|
|
31
|
-
`,H+=`${O.content}\r
|
|
32
|
-
`;return H+=`--${J}--\r
|
|
33
|
-
`,H}}var y=new M;
|
|
34
|
-
export{w as Vf,U as Wf,M as Xf,y as Yf};
|
|
@@ -1,70 +0,0 @@
|
|
|
1
|
-
import{qh as T}from"./chunk-jpjamjey.js";import"./chunk-mh0kdzqp.js";function _(q){let j=q.sites||{};for(let D of Object.values(j))if(D?.repository?.url)return{provider:D.repository.provider,branch:D.repository.branch};return}function x(q){let j=q.trim().toLowerCase();if(j.includes("github.com"))return"github";if(j.includes("gitlab.com"))return"gitlab";if(j.includes("bitbucket.org"))return"bitbucket";return}function Q(q){return`'${q.replace(/'/g,"'\\''")}'`}function $(q){return q.replace(/'/g,"''")}function k(q,j){let D=["bunx --bun @stacksjs/ts-cloud deploy","--env",Q(q)];if(j.site)D.push("--site",Q(j.site));if(j.skipDnsVerification)D.push("--skip-dns-verification");return D.push("--yes"),D.join(" ")}function I(q,j="production",D={}){let N=_(q),F=D.provider||N?.provider;if(F!=="github"&&F!=="gitlab"&&F!=="bitbucket")return null;let G=q.environments?.[j],H=G?.deployBranch||N?.branch||"main",L=k(j,D),M=JSON.stringify(H),V=JSON.stringify(j),O=G?.domain?G.domain.startsWith("http")?G.domain:`https://${G.domain}`:void 0,W=O?`
|
|
2
|
-
url: ${JSON.stringify(O)}`:"",X=D.setup==="pantry"?` - name: Setup Pantry
|
|
3
|
-
uses: home-lang/pantry/packages/action@main`:` - uses: oven-sh/setup-bun@v2
|
|
4
|
-
- run: bun install --frozen-lockfile`,Y=T(q)==="hetzner"&&!!q.infrastructure?.compute,J=D.sshPrivateKeySecret||"SSH_PRIVATE_KEY";if(!/^[A-Z_][A-Z0-9_]*$/i.test(J))throw Error(`Invalid SSH private key secret name '${J}'`);let Z=Y?`
|
|
5
|
-
- name: Configure deployment SSH key
|
|
6
|
-
env:
|
|
7
|
-
SSH_PRIVATE_KEY: \${{ secrets.${J} }}
|
|
8
|
-
run: |
|
|
9
|
-
if [ -z "$SSH_PRIVATE_KEY" ]; then
|
|
10
|
-
echo "::error::${J} is required for Hetzner compute deployments"
|
|
11
|
-
exit 1
|
|
12
|
-
fi
|
|
13
|
-
install -d -m 700 "$HOME/.ssh"
|
|
14
|
-
printf '%s\\n' "$SSH_PRIVATE_KEY" | tr -d '\\r' > "$HOME/.ssh/id_ed25519"
|
|
15
|
-
chmod 600 "$HOME/.ssh/id_ed25519"
|
|
16
|
-
ssh-keygen -y -f "$HOME/.ssh/id_ed25519" > "$HOME/.ssh/id_ed25519.pub"
|
|
17
|
-
`:"";if(F==="github")return{provider:F,branch:H,path:".github/workflows/deploy.yml",content:`name: Deploy ${j}
|
|
18
|
-
run-name: Deploy ${j} from \${{ github.ref_name }}
|
|
19
|
-
|
|
20
|
-
on:
|
|
21
|
-
push:
|
|
22
|
-
branches: [${M}]
|
|
23
|
-
workflow_dispatch:
|
|
24
|
-
|
|
25
|
-
permissions:
|
|
26
|
-
contents: read
|
|
27
|
-
|
|
28
|
-
concurrency:
|
|
29
|
-
group: ts-cloud-${j}
|
|
30
|
-
cancel-in-progress: false
|
|
31
|
-
|
|
32
|
-
jobs:
|
|
33
|
-
deploy:
|
|
34
|
-
if: github.ref_name == '${$(H)}'
|
|
35
|
-
runs-on: ubuntu-latest
|
|
36
|
-
environment:
|
|
37
|
-
name: ${V}${W}
|
|
38
|
-
steps:
|
|
39
|
-
- uses: actions/checkout@v6
|
|
40
|
-
${X}
|
|
41
|
-
${Z}
|
|
42
|
-
# Provide the provider credentials your config needs as repo secrets.
|
|
43
|
-
- run: ${L}
|
|
44
|
-
env:
|
|
45
|
-
HCLOUD_TOKEN: \${{ secrets.HCLOUD_TOKEN }}
|
|
46
|
-
HETZNER_API_TOKEN: \${{ secrets.HETZNER_API_TOKEN }}
|
|
47
|
-
AWS_ACCESS_KEY_ID: \${{ secrets.AWS_ACCESS_KEY_ID }}
|
|
48
|
-
AWS_SECRET_ACCESS_KEY: \${{ secrets.AWS_SECRET_ACCESS_KEY }}
|
|
49
|
-
TS_CLOUD_UI_DISABLE: '1'
|
|
50
|
-
`};if(F==="gitlab")return{provider:F,branch:H,path:".gitlab-ci.yml",content:`deploy:
|
|
51
|
-
image: oven/bun:latest
|
|
52
|
-
rules:
|
|
53
|
-
- if: '$CI_COMMIT_BRANCH == ${M}'
|
|
54
|
-
environment: ${j}
|
|
55
|
-
script:
|
|
56
|
-
- bun install --frozen-lockfile
|
|
57
|
-
- ${L}
|
|
58
|
-
# Set HCLOUD_TOKEN / HETZNER_API_TOKEN / AWS credentials as CI variables.
|
|
59
|
-
`};return{provider:F,branch:H,path:"bitbucket-pipelines.yml",content:`pipelines:
|
|
60
|
-
branches:
|
|
61
|
-
${M}:
|
|
62
|
-
- step:
|
|
63
|
-
name: Deploy ${j}
|
|
64
|
-
deployment: ${j}
|
|
65
|
-
image: oven/bun:latest
|
|
66
|
-
script:
|
|
67
|
-
- bun install --frozen-lockfile
|
|
68
|
-
- ${L}
|
|
69
|
-
# Set HCLOUD_TOKEN / HETZNER_API_TOKEN / AWS credentials as repo variables.
|
|
70
|
-
`}}export{x as inferQuickDeployProvider,I as buildQuickDeployCi};
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{Uo as M,Vo as O}from"./chunk-mh0kdzqp.js";var b={};M(b,{warning:()=>$,warn:()=>_,table:()=>W,success:()=>Y,step:()=>L,select:()=>S,prompt:()=>U,info:()=>T,header:()=>k,getAwsRegions:()=>V,getAwsAccountId:()=>C,formatDuration:()=>z,formatBytes:()=>v,error:()=>Z,confirm:()=>I,colors:()=>B,colorize:()=>K,checkAwsCredentials:()=>y,checkAwsCli:()=>R,box:()=>A,Spinner:()=>D,ProgressBar:()=>G});var B={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m"};function K(j,q){return`${B[q]}${j}${B.reset}`}function Y(j){console.log(`${B.green}✓${B.reset} ${j}`)}function Z(j){console.error(`${B.red}✗${B.reset} ${j}`)}function _(j){console.warn(`${B.yellow}⚠${B.reset} ${j}`)}var $=_;function T(j){console.log(`${B.blue}ℹ${B.reset} ${j}`)}function L(j){console.log(`${B.cyan}→${B.reset} ${j}`)}function k(j){console.log(`
|
|
2
|
-
${B.bright}${B.cyan}${j}${B.reset}
|
|
3
|
-
`)}var Q=!!(process.env.CI||process.env.GITHUB_ACTIONS||process.env.BUILDKITE||process.env.CIRCLECI||process.env.GITLAB_CI);class D{frames=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];interval=null;currentFrame=0;message;constructor(j){this.message=j}get text(){return this.message}set text(j){if(this.message=j,Q&&this.interval)console.log(` ${j}`)}start(){if(Q){console.log(` ${this.message}`),this.interval=!0;return}this.interval=setInterval(()=>{process.stdout.write(`\r${B.cyan}${this.frames[this.currentFrame]}${B.reset} ${this.message}`),this.currentFrame=(this.currentFrame+1)%this.frames.length},80)}succeed(j){this.stop(),Y(j||this.message)}fail(j){this.stop(),Z(j||this.message)}warn(j){this.stop(),$(j||this.message)}stop(){if(this.interval){if(!Q)process.stdout.write("\r");if(typeof this.interval==="object")clearInterval(this.interval);this.interval=null}}}class G{total;current=0;width=40;constructor(j){this.total=j}update(j){this.current=j,this.render()}increment(){this.current++,this.render()}render(){let j=Math.floor(this.current/this.total*100),q=Math.floor(this.current/this.total*this.width),E=this.width-q,F=`${"█".repeat(q)}${"░".repeat(E)}`;if(process.stdout.write(`\r${B.cyan}${F}${B.reset} ${j}% (${this.current}/${this.total})`),this.current>=this.total)process.stdout.write(`
|
|
4
|
-
`)}}async function U(j,q){let F=(await import("node:readline")).createInterface({input:process.stdin,output:process.stdout});return new Promise((J)=>{let H=q?`${B.cyan}?${B.reset} ${j} ${B.gray}(${q})${B.reset}: `:`${B.cyan}?${B.reset} ${j}: `;F.question(H,(N)=>{F.close(),J(N||q||"")})})}async function I(j,q=!1){let E=await U(`${j} (y/n)`,q?"y":"n");return E.toLowerCase()==="y"||E.toLowerCase()==="yes"}async function S(j,q){console.log(`${B.cyan}?${B.reset} ${j}`),q.forEach((J,H)=>{console.log(` ${B.gray}${H+1}.${B.reset} ${J}`)});let E=await U("Select","1"),F=Number.parseInt(E)-1;if(F>=0&&F<q.length)return q[F];return q[0]}function W(j,q){let E=j.map((J,H)=>{let N=Math.max(...q.map((P)=>(P[H]||"").length));return Math.max(J.length,N)}),F=j.map((J,H)=>J.padEnd(E[H])).join(" ");console.log(K(F,"bright")),console.log(K("─".repeat(F.length),"gray")),q.forEach((J)=>{let H=J.map((N,P)=>(N||"").padEnd(E[P])).join(" ");console.log(H)})}function v(j){if(j===0)return"0 B";let q=1024,E=["B","KB","MB","GB","TB"],F=Math.floor(Math.log(j)/Math.log(q));return`${Number.parseFloat((j/q**F).toFixed(2))} ${E[F]}`}function z(j){if(j<1000)return`${j}ms`;let q=Math.floor(j/1000);if(q<60)return`${q}s`;let E=Math.floor(q/60),F=q%60;if(E<60)return`${E}m ${F}s`;let J=Math.floor(E/60),H=E%60;return`${J}h ${H}m`}function A(j,q="cyan"){let E=j.split(`
|
|
5
|
-
`),F=Math.max(...E.map((H)=>H.length)),J="─".repeat(F+2);console.log(K(`┌${J}┐`,q)),E.forEach((H)=>{console.log(K(`│ ${H.padEnd(F)} │`,q))}),console.log(K(`└${J}┘`,q))}async function R(){return!0}async function y(){try{let{AWSClient:j}=await import("./chunk-dbgffky8.js");return await new j().request({service:"sts",region:"us-east-1",method:"POST",path:"/",body:new URLSearchParams({Action:"GetCallerIdentity",Version:"2011-06-15"}).toString()}),!0}catch{return!1}}async function C(){try{let{AWSClient:j}=await import("./chunk-dbgffky8.js"),E=await new j().request({service:"sts",region:"us-east-1",method:"POST",path:"/",body:new URLSearchParams({Action:"GetCallerIdentity",Version:"2011-06-15"}).toString()});return E.Account||E.GetCallerIdentityResult?.Account||null}catch{return null}}async function V(){try{let{AWSClient:j}=await import("./chunk-dbgffky8.js"),E=await new j().request({service:"ec2",region:"us-east-1",method:"POST",path:"/",body:new URLSearchParams({Action:"DescribeRegions",Version:"2016-11-15"}).toString()}),F=[];if(E.regionInfo){let J=Array.isArray(E.regionInfo)?E.regionInfo:[E.regionInfo];F.push(...J.map((H)=>H.regionName))}return F.length>0?F:X()}catch{return X()}}function X(){return["us-east-1","us-east-2","us-west-1","us-west-2","eu-west-1","eu-central-1","ap-southeast-1","ap-northeast-1"]}
|
|
6
|
-
export{B as sg,K as tg,Y as ug,Z as vg,_ as wg,$ as xg,T as yg,L as zg,k as Ag,D as Bg,U as Cg,I as Dg,S as Eg,W as Fg,v as Gg,A as Hg,R as Ig,y as Jg,C as Kg,V as Lg,b as Mg};
|
|
@@ -1,37 +0,0 @@
|
|
|
1
|
-
var Y={mode:"detection",paranoiaLevel:1,inboundThreshold:5,outboundThreshold:4,maxBodyBytes:13107200,rejectOversizedBody:!0,auditLogPath:"/var/log/ts-cloud/waf-audit.log",blockStatus:403},C={bypassBase:1e5,exclusionBase:101000,rateLimitBase:102000,customBase:109000};function X(q){return q.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/[\r\n]+/g," ")}function W(q){if(q.length>1000)return!1;if(/\([^)]*[+*]\)[+*]/.test(q))return!1;if(/\[[^\]]*\][+*]\{/.test(q))return!1;try{return new RegExp(q),!0}catch{return!1}}function R(q,V){let G=[],K=[],J=V;for(let H of q){if(H.enabled===!1)continue;if(H.key&&(H.key.source==="cookie"||H.key.source==="header")&&!H.key.name){K.push({ruleId:H.id,reason:"The rule keys on a header or cookie but names none."});continue}let $=H.path?_(H.path):".*";if(!W($)){K.push({ruleId:H.id,reason:"The path pattern compiles to an unsafe regular expression."});continue}let Z=[`SecRule REQUEST_URI "@rx ${X($)}"`];if(H.methods?.length)Z.push(` "chain,id:${J},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${X(H.id)}'"`);else Z.push(` "id:${J},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${X(H.id)}'"`);if(G.push(`# Marks requests governed by the ts-cloud rate limit "${X(H.id)}".`),G.push(Z.join(" \\\n")),H.methods?.length)G.push(` SecRule REQUEST_METHOD "@within ${X(H.methods.join(" ").toUpperCase())}" "t:none"`);G.push(""),J++}return{lines:G,unmapped:K}}function _(q){return`^${q.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*")}$`}function y(q={},V=[]){let G=q.mode??Y.mode,K=[],J=q.paranoiaLevel??Y.paranoiaLevel,H=q.inboundThreshold??Y.inboundThreshold,$=q.outboundThreshold??Y.outboundThreshold,Z=q.maxBodyBytes??Y.maxBodyBytes,j=q.rejectOversizedBody!==!1;if(G==="blocking"&&J>=3)K.push(`Paranoia level ${J} blocks legitimate traffic on most applications until it is tuned. Run it in detection mode first.`);if(G==="blocking")K.push("zig-waf is pre-alpha. Blocking mode makes it a failure path for every request.");if(!j)K.push("Oversized bodies are passed through uninspected, so padding a request bypasses every rule.");if(q.bypassPaths?.length)K.push(`${q.bypassPaths.length} path(s) bypass inspection entirely.`);let Q=["# Managed by ts-cloud. Edits are overwritten on the next deploy.",`# Mode: ${G}. Paranoia level: ${J}.`,""];if(G==="off")return Q.push("SecRuleEngine Off",""),{config:`${Q.join(`
|
|
2
|
-
`)}
|
|
3
|
-
`,unmappedRateLimits:[],warnings:K,mode:G};Q.push(`SecRuleEngine ${G==="blocking"?"On":"DetectionOnly"}`,"SecRequestBodyAccess On","SecResponseBodyAccess Off",`SecRequestBodyLimit ${Z}`,`SecRequestBodyNoFilesLimit ${Math.min(Z,131072)}`,`SecRequestBodyLimitAction ${j?"Reject":"ProcessPartial"}`,"SecRequestBodyInMemoryLimit 131072",`SecAuditEngine ${G==="blocking"?"RelevantOnly":"On"}`,"SecAuditLogParts ABIJDEFHZ",`SecAuditLog ${X(q.auditLogPath??Y.auditLogPath)}`,"SecAuditLogType Serial",`SecDefaultAction "phase:1,log,auditlog,${G==="blocking"?`deny,status:${q.blockStatus??Y.blockStatus}`:"pass"}"`,"","# CRS anomaly scoring setup.",`SecAction "id:900000,phase:1,pass,nolog,t:none,setvar:tx.paranoia_level=${J}"`,`SecAction "id:900001,phase:1,pass,nolog,t:none,setvar:tx.inbound_anomaly_score_threshold=${H}"`,`SecAction "id:900002,phase:1,pass,nolog,t:none,setvar:tx.outbound_anomaly_score_threshold=${$}"`,'SecAction "id:900003,phase:1,pass,nolog,t:none,setvar:tx.critical_anomaly_score=5,setvar:tx.error_anomaly_score=4,setvar:tx.warning_anomaly_score=3,setvar:tx.notice_anomaly_score=2"','SecAction "id:900004,phase:1,pass,nolog,t:none,setvar:tx.anomaly_score=0"',"");let z=C.bypassBase;for(let N of q.bypassPaths??[]){let k=_(N);if(!W(k)){K.push(`Bypass path "${N}" was dropped: it compiles to an unsafe regular expression.`);continue}Q.push(`# Inspection bypass for ${X(N)}. Every bypass is an unguarded route.`,`SecRule REQUEST_URI "@rx ${X(k)}" "id:${z},phase:1,pass,nolog,ctl:ruleEngine=Off"`,""),z++}let B=C.exclusionBase;for(let N of q.exclusions??[]){if(!Number.isInteger(N.ruleId)||N.ruleId<=0){K.push(`Exclusion with rule id "${N.ruleId}" was dropped: the id is not a positive integer.`);continue}if(Q.push(`# ${X(N.reason)}`),N.pathPattern){if(!W(N.pathPattern)){K.push(`Exclusion for rule ${N.ruleId} was dropped: its path pattern is unsafe.`);continue}Q.push(`SecRule REQUEST_URI "@rx ${X(N.pathPattern)}" "id:${B},phase:1,pass,nolog,ctl:ruleRemoveById=${N.ruleId}"`),B++}else Q.push(`SecRuleRemoveById ${N.ruleId}`);Q.push("")}let M=R(V,C.rateLimitBase);if(M.lines.length>0)Q.push("# Rate-limit route markers. SecLang has no counters, so the tag is set","# here and the counting stays in the ts-cloud limiter.",...M.lines);let O=C.customBase;for(let N of q.customRules??[])Q.push(`# Operator-supplied rule ${O}.`,N.trim(),""),O++;if(G==="blocking")Q.push("# Blocking decision: one rule, at the end, on the accumulated score.",`SecRule TX:ANOMALY_SCORE "@ge %{tx.inbound_anomaly_score_threshold}" "id:949110,phase:2,deny,status:${q.blockStatus??Y.blockStatus},log,msg:'Inbound anomaly score exceeded (total: %{tx.anomaly_score})'"`,"");return{config:`${Q.join(`
|
|
4
|
-
`)}
|
|
5
|
-
`,unmappedRateLimits:M.unmapped,warnings:K,mode:G}}function A(q={},V=[],G={}){let K=G.binary??"/usr/local/bin/zig-waf",J=G.configPath??"/etc/ts-cloud/waf.conf",H=y(q,V);return`#!/usr/bin/env bash
|
|
6
|
-
# Managed by ts-cloud. Installs the zig-waf ruleset.
|
|
7
|
-
set -euo pipefail
|
|
8
|
-
|
|
9
|
-
if [ ! -x "${K}" ]; then
|
|
10
|
-
echo "ts-cloud: ${K} is not installed; skipping WAF configuration" >&2
|
|
11
|
-
exit 0
|
|
12
|
-
fi
|
|
13
|
-
|
|
14
|
-
install -d -m 0755 "$(dirname "${J}")"
|
|
15
|
-
install -d -m 0750 /var/log/ts-cloud
|
|
16
|
-
|
|
17
|
-
cat > "${J}.new" <<'WAF_EOF'
|
|
18
|
-
${H.config}WAF_EOF
|
|
19
|
-
|
|
20
|
-
# Compile the config before it goes live. A config that does not validate
|
|
21
|
-
# would leave the engine with no rules while still reporting itself enabled.
|
|
22
|
-
if ! "${K}" validate "${J}.new"; then
|
|
23
|
-
echo "ts-cloud: generated WAF config failed validation, keeping the previous one" >&2
|
|
24
|
-
rm -f "${J}.new"
|
|
25
|
-
exit 1
|
|
26
|
-
fi
|
|
27
|
-
|
|
28
|
-
if [ -f "${J}" ] && cmp -s "${J}.new" "${J}"; then
|
|
29
|
-
rm -f "${J}.new"
|
|
30
|
-
echo "ts-cloud: WAF config unchanged"
|
|
31
|
-
exit 0
|
|
32
|
-
fi
|
|
33
|
-
|
|
34
|
-
mv "${J}.new" "${J}"
|
|
35
|
-
echo "ts-cloud: WAF config installed (mode: ${H.mode})"
|
|
36
|
-
`}function F(q,V){return q.map((G)=>({projectId:V.projectId,environmentId:V.environmentId,resourceId:V.resourceId,kind:"event",source:"zig-waf",name:G.action==="blocked"?"waf.blocked":"waf.matched",timestamp:G.timestamp,value:1,host:G.host,pathTemplate:G.path,method:G.method,attributes:{ruleId:G.ruleId??null,anomalyScore:G.anomalyScore,action:G.action,messages:G.messages.slice(0,5)}}))}
|
|
37
|
-
export{X as Je,W as Ke,_ as Le,y as Me,A as Ne,F as Oe};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{Rd as E}from"./chunk-p66ptpmr.js";import{Uf as n}from"./chunk-h5pa5men.js";import{$f as C}from"./chunk-fy8j3y8p.js";import{Ag as m,Hg as Zz,ug as k,vg as Xz,wg as l,yg as F,zg as Y}from"./chunk-271gk1n2.js";import{Og as Jz}from"./chunk-fpm59y25.js";import{Do as Yz,Gh as $z,Hh as Wz,Ih as Mz,Jo as Hz,Qn as Oz,Rn as _z,Tn as Kz,Vn as Qz,Wn as jz}from"./chunk-jpjamjey.js";import{Vo as t}from"./chunk-mh0kdzqp.js";import{existsSync as Lz,readdirSync as Uz,readFileSync as Bz,statSync as Ez}from"node:fs";import{join as Pz,relative as Rz}from"node:path";class d{client;region;constructor(z="us-east-1",G){this.region=z,this.client=new Jz}async createSecret(z){let G={Name:z.Name};if(z.Description)G.Description=z.Description;if(z.KmsKeyId)G.KmsKeyId=z.KmsKeyId;if(z.SecretBinary)G.SecretBinary=z.SecretBinary;if(z.SecretString)G.SecretString=z.SecretString;if(z.Tags&&z.Tags.length>0)G.Tags=z.Tags;if(z.AddReplicaRegions&&z.AddReplicaRegions.length>0)G.AddReplicaRegions=z.AddReplicaRegions;if(z.ForceOverwriteReplicaSecret!==void 0)G.ForceOverwriteReplicaSecret=z.ForceOverwriteReplicaSecret;G.ClientRequestToken=z.ClientRequestToken||crypto.randomUUID();let J=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.CreateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(G)});return{ARN:J.ARN,Name:J.Name,VersionId:J.VersionId,ReplicationStatus:J.ReplicationStatus}}async updateSecret(z){let G={SecretId:z.SecretId};if(z.Description)G.Description=z.Description;if(z.KmsKeyId)G.KmsKeyId=z.KmsKeyId;if(z.SecretBinary)G.SecretBinary=z.SecretBinary;if(z.SecretString)G.SecretString=z.SecretString;let J=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.UpdateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(G)});return{ARN:J.ARN,Name:J.Name,VersionId:J.VersionId}}async putSecretValue(z){let G={SecretId:z.SecretId};if(z.SecretBinary)G.SecretBinary=z.SecretBinary;if(z.SecretString)G.SecretString=z.SecretString;if(z.VersionStages&&z.VersionStages.length>0)G.VersionStages=z.VersionStages;if(z.ClientRequestToken)G.ClientRequestToken=z.ClientRequestToken;let J=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.PutSecretValue","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(G)});return{ARN:J.ARN,Name:J.Name,VersionId:J.VersionId,VersionStages:J.VersionStages}}async getSecretValue(z){let G={SecretId:z.SecretId};if(z.VersionId)G.VersionId=z.VersionId;if(z.VersionStage)G.VersionStage=z.VersionStage;let J=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.GetSecretValue","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(G)});return{ARN:J.ARN,Name:J.Name,VersionId:J.VersionId,SecretBinary:J.SecretBinary,SecretString:J.SecretString,VersionStages:J.VersionStages,CreatedDate:J.CreatedDate}}async describeSecret(z){let G={SecretId:z},J=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.DescribeSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(G)});return this.parseSecret(J)}async listSecrets(z){let G={};if(z?.MaxResults)G.MaxResults=z.MaxResults;if(z?.NextToken)G.NextToken=z.NextToken;if(z?.Filters&&z.Filters.length>0)G.Filters=z.Filters;if(z?.SortOrder)G.SortOrder=z.SortOrder;let J=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.ListSecrets","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(G)});return{SecretList:J.SecretList?.map((X)=>this.parseSecret(X)),NextToken:J.NextToken}}async deleteSecret(z){let G={SecretId:z.SecretId};if(z.RecoveryWindowInDays!==void 0)G.RecoveryWindowInDays=z.RecoveryWindowInDays;if(z.ForceDeleteWithoutRecovery!==void 0)G.ForceDeleteWithoutRecovery=z.ForceDeleteWithoutRecovery;let J=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.DeleteSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(G)});return{ARN:J.ARN,Name:J.Name,DeletionDate:J.DeletionDate}}async restoreSecret(z){let G={SecretId:z},J=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.RestoreSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(G)});return{ARN:J.ARN,Name:J.Name}}async rotateSecret(z){let G={SecretId:z.SecretId};if(z.ClientRequestToken)G.ClientRequestToken=z.ClientRequestToken;if(z.RotationLambdaARN)G.RotationLambdaARN=z.RotationLambdaARN;if(z.RotationRules)G.RotationRules=z.RotationRules;if(z.RotateImmediately!==void 0)G.RotateImmediately=z.RotateImmediately;let J=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.RotateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(G)});return{ARN:J.ARN,Name:J.Name,VersionId:J.VersionId}}async cancelRotateSecret(z){let G={SecretId:z},J=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.CancelRotateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(G)});return{ARN:J.ARN,Name:J.Name}}async getResourcePolicy(z){let G={SecretId:z},J=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.GetResourcePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(G)});return{ARN:J.ARN,Name:J.Name,ResourcePolicy:J.ResourcePolicy}}async putResourcePolicy(z){let G={SecretId:z.SecretId,ResourcePolicy:z.ResourcePolicy};if(z.BlockPublicPolicy!==void 0)G.BlockPublicPolicy=z.BlockPublicPolicy;let J=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.PutResourcePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(G)});return{ARN:J.ARN,Name:J.Name}}async deleteResourcePolicy(z){let G={SecretId:z},J=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.DeleteResourcePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(G)});return{ARN:J.ARN,Name:J.Name}}async tagResource(z){let G={SecretId:z.SecretId,Tags:z.Tags};await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.TagResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(G)})}async untagResource(z){let G={SecretId:z.SecretId,TagKeys:z.TagKeys};await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.UntagResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(G)})}async setString(z,G,J){try{let X=await this.putSecretValue({SecretId:z,SecretString:G});return{ARN:X.ARN,VersionId:X.VersionId}}catch(X){if(X.code==="ResourceNotFoundException"){let Z=await this.createSecret({Name:z,SecretString:G,Description:J?.description,KmsKeyId:J?.kmsKeyId,Tags:J?.tags});return{ARN:Z.ARN,VersionId:Z.VersionId}}throw X}}async setJson(z,G,J){return this.setString(z,JSON.stringify(G),J)}async getString(z){return(await this.getSecretValue({SecretId:z})).SecretString}async getJson(z){let G=await this.getString(z);if(G)return JSON.parse(G);return}async listAll(){let z=[],G;do{let J=await this.listSecrets({NextToken:G});if(J.SecretList)z.push(...J.SecretList);G=J.NextToken}while(G);return z}parseSecret(z){return{ARN:z.ARN,Name:z.Name,Description:z.Description,KmsKeyId:z.KmsKeyId,RotationEnabled:z.RotationEnabled,RotationLambdaARN:z.RotationLambdaARN,RotationRules:z.RotationRules,LastRotatedDate:z.LastRotatedDate,LastChangedDate:z.LastChangedDate,LastAccessedDate:z.LastAccessedDate,DeletedDate:z.DeletedDate,NextRotationDate:z.NextRotationDate,Tags:z.Tags,SecretVersionsToStages:z.SecretVersionsToStages,CreatedDate:z.CreatedDate,PrimaryRegion:z.PrimaryRegion}}}function q(z,G){let J=z.environments?.[G]?.app;if(!J)throw Error(`No serverless app configured for environment '${G}'. Add environments.${G}.app to your config.`);let X=z.project.slug,Z=z.environments?.[G]?.region||z.project.region||"us-east-1";return{app:J,slug:X,region:Z,stackName:$z(z,G),artifactBucket:Wz(X,G),assetsBucket:Mz(X,G)}}function iz(z,G){let J=q(z,G),X=`${J.slug}-${G}`;return{region:J.region,slug:J.slug,stackName:J.stackName,functions:{http:`${X}-http`,queue:`${X}-queue`,cli:`${X}-cli`}}}async function N(z,G=8){let J;for(let X=0;X<G;X++)try{return await z()}catch(Z){let $=Z?.code||Z?.name||"",W=String(Z?.message||"");if($==="ResourceConflictException"||/update is in progress|currently in the following state/i.test(W)){J=Z,await new Promise((M)=>setTimeout(M,3000));continue}throw Z}throw J}var Tz=(z,G)=>`releases/${z}/${G}/current.json`;async function p(z,G,J,X){try{return await z.getObjectJson(G,Tz(J,X))}catch{return null}}async function Vz(z,G,J,X,Z){await z.putObjectJson(G,Tz(J,X),Z)}async function hz(z,G){if(!z.secrets)return{};let J=new d(G),X={},Z=Array.isArray(z.secrets)?z.secrets.map(($)=>({envName:$.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),secretId:$})):Object.entries(z.secrets).map(([$,W])=>({envName:$,secretId:W}));if(Array.isArray(z.secrets)){let $=new Map;for(let{envName:M,secretId:O}of Z)$.set(M,[...$.get(M)??[],O]);let W=[...$.entries()].filter(([,M])=>M.length>1);if(W.length){let M=W.map(([O,K])=>`${O} ← ${K.join(", ")}`).join("; ");throw Error(`serverless secrets: multiple secrets map to the same env var (${M}). Use the map form { ENV_NAME: 'secret/id' } to disambiguate.`)}}for(let{envName:$,secretId:W}of Z){let O=(await J.getSecretValue({SecretId:W})).SecretString??"";try{let K=JSON.parse(O);if(K&&typeof K==="object"&&!Array.isArray(K)){for(let[H,j]of Object.entries(K))X[H]=String(j);continue}}catch{}X[$]=O}return X}function Iz(z,G){let J={},X=G.DbProxyEndpoint||G.DbEndpoint;if(X)J.DB_CONNECTION="mysql",J.DB_HOST=X,J.DB_PORT="3306",J.DB_DATABASE=J.DB_DATABASE||"app";if(G.CacheEndpoint){if(J.REDIS_HOST=G.CacheEndpoint,J.REDIS_PORT="6379",z.cache?.driver==="elasticache")J.CACHE_STORE="redis",J.CACHE_DRIVER="redis",J.SESSION_DRIVER="redis"}return J}function o(z,G,J,X,Z,$,W,M={}){let O=z.kind==="php"?Yz({cacheDriver:z.cache?.driver==="elasticache"?"redis":"dynamodb"}):{};return{TSCLOUD_LAMBDA_MODE:X,TSCLOUD_ENV:J,MAINTENANCE_MODE:"0",...z.octane?{TSCLOUD_OCTANE:"1"}:{},...z.serveAssets?{TSCLOUD_SERVE_ASSETS:"1"}:{},...z.redirectRobotsTxt===!1?{TSCLOUD_REDIRECT_ROBOTS_TXT:"0"}:{},...O,...M,...G.app.cache?.driver!=="elasticache"?{TSCLOUD_CACHE_TABLE:`${G.slug}-${J}-cache`}:{},...W?{TSCLOUD_QUEUE:W,SQS_QUEUE:W}:{},...$?{ASSET_URL:$}:{},...z.env??{},...Z}}function Nz(z){let G=z.slice(z.lastIndexOf(".")).toLowerCase();return{".html":"text/html",".css":"text/css",".js":"text/javascript",".mjs":"text/javascript",".json":"application/json",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".txt":"text/plain",".map":"application/json"}[G]??"application/octet-stream"}function*Fz(z){for(let G of Uz(z)){let J=Pz(z,G);if(Ez(J).isDirectory())yield*Fz(J);else yield J}}async function Cz(z,G,J,X,Z=!1){let $=0;for(let W of Fz(J)){let M=Rz(J,W).replace(/\\/g,"/");if(!Z&&M.split("/").some((O)=>O.startsWith(".")))continue;await z.putObject({bucket:G,key:`${X}/${M}`,body:Bz(W),contentType:Nz(W),cacheControl:"public, max-age=31536000, immutable"}),$++}return $}function Sz(z,G){let J=Object.entries(G).reduce((X,[Z,$])=>X+Buffer.byteLength(`${Z}=${$}`,"utf8"),0);if(J>4096){let X=Object.entries(G).map(([Z,$])=>[Z,Buffer.byteLength(`${Z}=${$}`,"utf8")]).sort((Z,$)=>$[1]-Z[1]).slice(0,5).map(([Z,$])=>`${Z} (${$}B)`).join(", ");throw Error(`${z}: environment variables total ${J}B, over AWS's 4096B limit (${J-4096}B too large). Largest: ${X}. Move large/secret values out of env — store them in Secrets Manager and fetch at cold start.`)}}async function b(z,G,J,X){Sz(G,J),await N(()=>z.updateFunctionConfiguration({FunctionName:G,Environment:{Variables:J}})),await z.waitForFunctionActive(G,120);let Z=X.kind==="image"?{FunctionName:G,ImageUri:X.imageUri}:{FunctionName:G,S3Bucket:X.bucket,S3Key:X.key};await N(()=>z.updateFunctionCode(Z)),await z.waitForFunctionActive(G,120)}async function c(z,G){let X=(await N(()=>z.publishVersion({FunctionName:G}))).Version;if(!X)throw Error(`publishVersion returned no version for ${G}`);return await N(()=>z.updateAlias({FunctionName:G,Name:"live",FunctionVersion:X})),X}async function rz(z,G,J={}){let X=q(z,G),{app:Z,slug:$,region:W,stackName:M,artifactBucket:O}=X,K=J.projectRoot??process.cwd();m(`Deploying serverless app: ${$} (${G})`),F(`Stack: ${M}`),F(`Region: ${W}`);let H=new C(W),j=new n(W),V=new E(W),L=Z.kind==="php",U=Z.packaging==="image",Q=Kz(Z),R,A,w,i,g=[];if(U&&Q.usesLayer&&Q.layerKind!=="php")throw Error(`packaging: 'image' currently supports PHP and managed Node runtimes. ${Q.kind}${Q.kind==="node"?` ${Q.version}`:""} uses a custom runtime — `+"use the default zip packaging (the runtime layer is built + attached automatically).");if(U){Y("Building + pushing container image");let{buildAndPushServerlessImage:_}=await import("./chunk-m2zwtapr.js"),P=await _({app:Z,projectRoot:K,region:W,repository:`${$}-${G}`,skipBuild:J.skipBuild,onStep:(D)=>F(` ${D}`)});R=P.handlers,A={kind:"image",imageUri:P.imageUri},w=P.tag,g.push({ParameterKey:"ImageUri",ParameterValue:P.imageUri})}else{Y("Packaging application");let _=L?Hz({projectRoot:K,app:Z,skipBuild:J.skipBuild,onStep:(B)=>F(` ${B}`)}):await _z({projectRoot:K,app:Z,skipBuild:J.skipBuild,onStep:(B)=>F(` ${B}`)}),P=Oz($,G,_.sha256);if(F(`Artifact: ${_.sha256.slice(0,12)} (${(_.zip.length/1024).toFixed(0)} KB)`),R=_.handlers,w=_.sha256,Q.usesLayer){let B=Q.layerEnvVar?process.env[Q.layerEnvVar]:void 0;if(i=Z.layers??(B?[B]:void 0),!i?.length){let Dz=Q.layerKind==="php"?"serverless:build-php-layer":Q.layerKind==="bun"?"serverless:build-bun-layer":"serverless:build-node-layer";throw Error(`${Q.kind} apps on provided.al2023 need a runtime layer. Set environments.<env>.app.layers or the ${Q.layerEnvVar} env var (build one with \`cloud ${Dz}\`)${Q.kind==="node"?", or use a managed Node version (18/20/22)":""}.`)}}if(!await H.bucketExists(O))Y(`Creating artifact bucket ${O}`),await H.createBucket(O);if(await H.headObject(O,P).then((B)=>B!==null).catch(()=>!1))F("Artifact already uploaded — reusing");else Y("Uploading artifact"),await H.putObject({bucket:O,key:P,body:_.zip,contentType:"application/zip"});A={kind:"zip",bucket:O,key:P},g.push({ParameterKey:"ArtifactBucket",ParameterValue:O},{ParameterKey:"ArtifactKey",ParameterValue:P})}let T=jz({config:z,environment:G,app:Z,handlers:R,runtimeLayers:i}),e=JSON.stringify(T.template),zz=["CAPABILITY_NAMED_IAM"],S=await j.describeStacks({stackName:M}).then((_)=>_.Stacks[0]?.StackStatus).catch(()=>{return}),f=S!==void 0;if(S&&/DELETE_IN_PROGRESS/.test(S))Y("Waiting for an in-progress stack delete to finish"),await j.waitForStack(M,"stack-delete-complete").catch(()=>{}),f=!1;else if(S&&/(?:ROLLBACK_COMPLETE|REVIEW_IN_PROGRESS|CREATE_FAILED)/.test(S))Y(`Deleting unusable stack (status ${S}) before recreate`),await j.deleteStack(M),await j.waitForStack(M,"stack-delete-complete").catch(()=>{}),f=!1;Y(f?"Updating infrastructure stack":"Creating infrastructure stack");try{if(f)await j.updateStack({stackName:M,templateBody:e,parameters:g,capabilities:zz}),await j.waitForStack(M,"stack-update-complete");else await j.createStack({stackName:M,templateBody:e,parameters:g,capabilities:zz,onFailure:"DELETE"}),await j.waitForStack(M,"stack-create-complete")}catch(_){if(/No updates are to be performed/i.test(String(_?.message)))F("No infrastructure changes");else throw _}let r=await j.getStackOutputs(M).catch(()=>({})),h;if(Z.assets){let _=Pz(K,Z.assets);if(Lz(_)){let P=Z.assetDomain||r.AssetsCdnDomain;h=P?`https://${P}/${w}`:void 0,Y(`Syncing assets from ${Z.assets}`);let D=await Cz(H,X.assetsBucket,_,w,Z.dotFilesAsAssets);F(`Uploaded ${D} asset(s)${h?` → ${h}`:""}`)}else l(`Assets directory not found: ${_}`)}Y("Resolving secrets");let x=await hz(Z,W);if(Z.database?.connection==="aurora-serverless")try{let P=await new d(W).getSecretValue({SecretId:`${$}/${G}/db`}),D=JSON.parse(P.SecretString??"{}");if(D.username)x.DB_USERNAME=D.username;if(D.password)x.DB_PASSWORD=D.password}catch(_){l(`Could not resolve Aurora DB credentials: ${_.message}`)}if(!await H.bucketExists(O))await H.createBucket(O);let v=await p(H,O,$,G),I={},a=T.queueNames[0],s=Iz(Z,r);if(Y("Activating functions"),I.http=o(Z,X,G,"http",x,h,a,s),await b(V,T.functionNames.http,I.http,A),I.cli=o(Z,X,G,"cli",x,h,a,s),await b(V,T.functionNames.cli,I.cli,A),T.queueNames.length)I.queue=o(Z,X,G,"queue",x,h,a,s),await b(V,T.functionNames.queue,I.queue,A);let Gz=(Z.provisionedConcurrency??0)>0,u={};if(Gz){if(Y("Publishing versions + flipping live alias"),u.http=await c(V,T.functionNames.http),u.cli=await c(V,T.functionNames.cli),T.queueNames.length)u.queue=await c(V,T.functionNames.queue)}if(await Vz(H,O,$,G,{sha:w,code:A,previousSha:v?.sha,previousCode:v?.code,previousFunctionEnv:v?.functionEnv,...Gz?{functionVersions:u,previousFunctionVersions:v?.functionVersions}:{},functionEnv:I,functionNames:{http:T.functionNames.http,cli:T.functionNames.cli,...T.queueNames.length?{queue:T.functionNames.queue}:{}},assetUrl:h,timestamp:new Date().toISOString()}),!J.skipDeployHooks&&Z.deploy?.length){Y("Running deploy hooks");for(let _ of Z.deploy){F(` deploy: ${_}`);let P=await V.invoke({FunctionName:T.functionNames.cli,InvocationType:"RequestResponse",Payload:{command:_},LogType:"Tail"});if(P.FunctionError)throw Xz("Deploy hook failed — the new build is ALREADY LIVE."),F(` Roll back with: cloud serverless:rollback --env ${G}`),Error(`Deploy hook failed (${_}): ${P.Payload}`)}}let y=r.HttpApiEndpoint;if(!J.skipHealthCheck&&y){Y("Health check");try{let _=await fetch(y,{method:"GET"});F(`GET ${y} → ${_.status}`)}catch(_){l(`Health check could not reach ${y}: ${_.message}`)}}Zz(["Serverless deploy complete","",y?`URL: ${y}`:"",`Stack: ${M}`,`Build: ${w.slice(0,12)}`].filter(Boolean).join(`
|
|
2
|
-
`),"green")}async function az(z,G){let J=q(z,G),X=new C(J.region),Z=new E(J.region),$=await p(X,J.artifactBucket,J.slug,G);if(!$)throw Error("No previous release to redeploy. Run a full deploy first.");m(`Redeploying ${J.slug} (${G}) — build ${$.sha.slice(0,12)}`);for(let[W,M]of Object.entries($.functionNames)){if(!M)continue;Y(`Re-activating ${W} (${M})`),await b(Z,M,$.functionEnv[W]??{},$.code);let O=$.functionVersions?.[W];if(O)await N(()=>Z.updateAlias({FunctionName:M,Name:"live",FunctionVersion:O}))}k("Redeploy complete")}async function sz(z,G){let J=q(z,G),X=new C(J.region),Z=new E(J.region),$=await p(X,J.artifactBucket,J.slug,G);if(!$?.previousCode)throw Error("No previous release to roll back to.");m(`Rolling back ${J.slug} (${G}) → ${$.previousSha?.slice(0,12)}`);for(let[W,M]of Object.entries($.functionNames)){if(!M)continue;Y(`Restoring ${W} (${M})`);let O=$.previousFunctionEnv?.[W]??$.functionEnv[W]??{};await b(Z,M,O,$.previousCode);let K=$.previousFunctionVersions?.[W];if(K)await N(()=>Z.updateAlias({FunctionName:M,Name:"live",FunctionVersion:K}))}await Vz(X,J.artifactBucket,J.slug,G,{...$,sha:$.previousSha??$.sha,code:$.previousCode,functionEnv:$.previousFunctionEnv??$.functionEnv,functionVersions:$.previousFunctionVersions??$.functionVersions,previousSha:void 0,previousCode:void 0,previousFunctionEnv:void 0,previousFunctionVersions:void 0,timestamp:new Date().toISOString()}),k("Rollback complete")}async function oz(z,G,J,X){let Z=q(z,G),$=new E(Z.region),W=`${Z.slug}-${G}-http`,O={...(await $.getFunction(W)).Configuration?.Environment?.Variables??{}};if(O.MAINTENANCE_MODE=J?"1":"0",J&&X)O.MAINTENANCE_BYPASS_SECRET=X;if(!J)delete O.MAINTENANCE_BYPASS_SECRET;if(await N(()=>$.updateFunctionConfiguration({FunctionName:W,Environment:{Variables:O}})),(Z.app.provisionedConcurrency??0)>0)await $.waitForFunctionActive(W,120),await c($,W);k(J?"Application is now in maintenance mode (503)":"Application is live")}async function yz(z,G,J){let X=q(z,G),Z=new E(X.region),$=`${X.slug}-${G}-cli`,W=await Z.invoke({FunctionName:$,InvocationType:"RequestResponse",Payload:{command:J},LogType:"Tail"});if(W.FunctionError)throw Error(`Command failed: ${W.Payload}`);return W.Payload??""}var wz=(z,G)=>`commands/${z}/${G}/history.json`,kz=50;async function qz(z,G,J,X){try{return(await z.getObjectJson(G,wz(J,X)))?.records??[]}catch{return[]}}async function tz(z,G,J){let X=q(z,G),Z=new E(X.region),$=`${X.slug}-${G}-cli`,W=await Z.invoke({FunctionName:$,InvocationType:"RequestResponse",Payload:{command:J},LogType:"Tail"}),M=W.Payload??"",O=W.FunctionError?"error":"ok",K=-1;try{let H=new C(X.region);if(await H.bucketExists(X.artifactBucket)){let j=await qz(H,X.artifactBucket,X.slug,G);K=j.reduce((V,L)=>Math.max(V,L.id),0)+1,j.push({id:K,command:J,timestamp:new Date().toISOString(),status:O,output:M.slice(0,4000)}),await H.putObjectJson(X.artifactBucket,wz(X.slug,G),{records:j.slice(-kz)})}}catch{}if(W.FunctionError)throw Error(`Command failed${K>0?` (#${K})`:""}: ${M}`);return{id:K,status:O,output:M}}async function xz(z,G){let J=q(z,G),X=new C(J.region);return qz(X,J.artifactBucket,J.slug,G)}async function nz(z,G,J){let X=await xz(z,G);if(!X.length)return;return J==null?X[X.length-1]:X.find((Z)=>Z.id===J)}async function ez(z,G,J){let X=Buffer.from(J,"utf-8").toString("base64");return yz(z,G,`tscloud:db-query --sql-base64=${X}`)}async function zG(z,G){let J=q(z,G),X=new n(J.region),Z=new E(J.region),$=new C(J.region),W="not deployed",M={};try{let{Stacks:U}=await X.describeStacks({stackName:J.stackName});W=U?.[0]?.StackStatus??W;for(let Q of U?.[0]?.Outputs??[])if(Q.OutputKey)M[Q.OutputKey]=Q.OutputValue??""}catch{}let O=Qz(J.app,J.slug,G),K=J.app.provisionedConcurrency??0,H=["http","cli",...O.length?["queue"]:[]],j=`${J.slug}-${G}`,V=[];for(let U of H){let Q=`${j}-${U}`,R={mode:U,name:Q,version:"$LATEST"};if(K>0){let A=await Z.getAlias(Q,"live").catch(()=>null);if(A?.FunctionVersion){R.version=A.FunctionVersion;let w=await Z.getProvisionedConcurrencyConfig(Q,"live").catch(()=>null);if(w)R.provisioned={status:w.Status??"-",allocated:w.AllocatedProvisionedConcurrentExecutions??0,requested:w.RequestedProvisionedConcurrentExecutions??0}}}V.push(R)}let L=await p($,J.artifactBucket,J.slug,G).catch(()=>null);return{slug:J.slug,environment:G,region:J.region,stackStatus:W,endpoint:M.HttpApiEndpoint,assetUrl:L?.assetUrl,scheduler:J.app.scheduler??"on",queues:O,provisionedConcurrency:K,functions:V,lastRelease:L?{sha:L.sha,timestamp:L.timestamp}:void 0}}function Az(z,G){return`${z}-${G}-db`}async function GG(z,G,J,X){let Z=q(z,G);if(Z.app.database?.connection!=="aurora-serverless")throw Error("No Aurora Serverless v2 database is configured for this environment.");let{RDSClient:$}=await import("./chunk-yv9sth30.js"),W=new $(Z.region),M=Az(Z.slug,G);Y(`Scaling ${M} → ${J}–${X} ACUs`),await W.modifyDBCluster({DBClusterIdentifier:M,ServerlessV2ScalingConfiguration:{MinCapacity:J,MaxCapacity:X},ApplyImmediately:!0}),k(`Scaling applied to ${M} (takes effect shortly).`)}async function JG(z,G,J){let X=q(z,G);if(X.app.database?.connection!=="aurora-serverless")throw Error("No Aurora Serverless v2 database is configured for this environment.");if(!J.toTime&&!J.latest)throw Error("Specify a restore point: --to <ISO timestamp> or --latest.");let{RDSClient:Z}=await import("./chunk-yv9sth30.js"),$=new Z(X.region),W=Az(X.slug,G),M=J.latest?"latest":J.toTime.toISOString().replace(/[^0-9]/g,"").slice(0,14),O=J.target??`${W}-restore-${M}`;Y(`Restoring ${W} → new cluster ${O} (${J.latest?"latest restorable time":J.toTime.toISOString()})`),await $.restoreDBClusterToPointInTime({DBClusterIdentifier:O,SourceDBClusterIdentifier:W,RestoreToTime:J.toTime,UseLatestRestorableTime:J.latest}),Y("Waiting for the restored cluster to be ready");for(let K=0;K<120;K++){let{DBClusters:H}=await $.describeDBClusters({DBClusterIdentifier:O}),j=H?.[0]?.Status;if(j&&j!=="creating")break;await new Promise((V)=>setTimeout(V,15000))}return Y("Adding a writer instance"),await $.createDBInstance({DBInstanceIdentifier:`${O}-1`,DBClusterIdentifier:O,Engine:"aurora-mysql",DBInstanceClass:"db.serverless"}),k(`Restore complete → cluster ${O} with writer ${O}-1. Point an env's database at it once available.`),O}
|
|
3
|
-
export{d as zd,iz as Ad,hz as Bd,Iz as Cd,o as Dd,Sz as Ed,rz as Fd,az as Gd,sz as Hd,oz as Id,yz as Jd,tz as Kd,xz as Ld,nz as Md,ez as Nd,zG as Od,GG as Pd,JG as Qd};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Ad as a,Bd as b,Cd as c,Dd as d,Ed as e,Fd as f,Gd as g,Hd as h,Id as i,Jd as j,Kd as k,Ld as l,Md as m,Nd as n,Od as o,Pd as p,Qd as q}from"./chunk-3r4fb59r.js";import"./chunk-p66ptpmr.js";import"./chunk-h5pa5men.js";import"./chunk-fy8j3y8p.js";import"./chunk-271gk1n2.js";import"./chunk-fpm59y25.js";import"./chunk-jpjamjey.js";import"./chunk-mh0kdzqp.js";export{i as setMaintenance,o as serverlessInfo,p as scaleServerlessDatabase,j as runRemoteCommand,n as runDbQuery,k as runAndRecordCommand,h as rollbackServerlessApp,q as restoreServerlessDatabase,a as resolveServerlessFunctions,b as resolveSecrets,g as redeployServerlessApp,l as listCommandHistory,c as infraEnvFromOutputs,m as getCommandRecord,f as deployServerlessApp,d as buildFunctionEnv,e as assertEnvWithinLimit};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{Og as E}from"./chunk-fpm59y25.js";class J{client;region;constructor(b="us-east-1",w){this.region=b,this.client=new E}async createQueue(b){let h={Action:"CreateQueue",QueueName:b.fifo&&!b.queueName.endsWith(".fifo")?`${b.queueName}.fifo`:b.queueName,Version:"2012-11-05"},j=1;if(b.visibilityTimeout!==void 0)h[`Attribute.${j}.Name`]="VisibilityTimeout",h[`Attribute.${j}.Value`]=b.visibilityTimeout.toString(),j++;if(b.messageRetentionPeriod!==void 0)h[`Attribute.${j}.Name`]="MessageRetentionPeriod",h[`Attribute.${j}.Value`]=b.messageRetentionPeriod.toString(),j++;if(b.delaySeconds!==void 0)h[`Attribute.${j}.Name`]="DelaySeconds",h[`Attribute.${j}.Value`]=b.delaySeconds.toString(),j++;if(b.maxMessageSize!==void 0)h[`Attribute.${j}.Name`]="MaximumMessageSize",h[`Attribute.${j}.Value`]=b.maxMessageSize.toString(),j++;if(b.receiveMessageWaitTime!==void 0)h[`Attribute.${j}.Name`]="ReceiveMessageWaitTimeSeconds",h[`Attribute.${j}.Value`]=b.receiveMessageWaitTime.toString(),j++;if(b.fifo){if(h[`Attribute.${j}.Name`]="FifoQueue",h[`Attribute.${j}.Value`]="true",j++,b.contentBasedDeduplication)h[`Attribute.${j}.Name`]="ContentBasedDeduplication",h[`Attribute.${j}.Value`]="true",j++}if(b.deadLetterTargetArn&&b.maxReceiveCount)h[`Attribute.${j}.Name`]="RedrivePolicy",h[`Attribute.${j}.Value`]=JSON.stringify({deadLetterTargetArn:b.deadLetterTargetArn,maxReceiveCount:b.maxReceiveCount}),j++;if(b.tags&&Object.keys(b.tags).length>0){let B=1;for(let[F,G]of Object.entries(b.tags))h[`Tag.${B}.Key`]=F,h[`Tag.${B}.Value`]=G,B++}let z=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(h).toString()});return{QueueUrl:z.QueueUrl||z.CreateQueueResult?.QueueUrl}}async listQueues(b){let w={Action:"ListQueues",Version:"2012-11-05"};if(b)w.QueueNamePrefix=b;let h=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(w).toString()}),j=[];if(h.QueueUrl)j.push(h.QueueUrl);else if(h.ListQueuesResult?.QueueUrl)if(Array.isArray(h.ListQueuesResult.QueueUrl))j.push(...h.ListQueuesResult.QueueUrl);else j.push(h.ListQueuesResult.QueueUrl);return{QueueUrls:j}}async getQueueAttributes(b){let w={Action:"GetQueueAttributes",QueueUrl:b,Version:"2012-11-05","AttributeName.1":"All"},h=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(w).toString()});return{Attributes:h.Attributes||h.GetQueueAttributesResult?.Attributes||{}}}async getQueueUrl(b){let w={Action:"GetQueueUrl",QueueName:b,Version:"2012-11-05"},h=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(w).toString()});return{QueueUrl:h.QueueUrl||h.GetQueueUrlResult?.QueueUrl}}async deleteQueue(b){let w={Action:"DeleteQueue",QueueUrl:b,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(w).toString()})}async purgeQueue(b){let w={Action:"PurgeQueue",QueueUrl:b,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(w).toString()})}async sendMessage(b){let w={Action:"SendMessage",QueueUrl:b.queueUrl,MessageBody:b.messageBody,Version:"2012-11-05"};if(b.delaySeconds!==void 0)w.DelaySeconds=b.delaySeconds;if(b.messageGroupId)w.MessageGroupId=b.messageGroupId;if(b.messageDeduplicationId)w.MessageDeduplicationId=b.messageDeduplicationId;let h=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(w).toString()});return{MessageId:h.MessageId||h.SendMessageResult?.MessageId}}async receiveMessages(b){let w={Action:"ReceiveMessage",QueueUrl:b.queueUrl,Version:"2012-11-05"};if(b.maxMessages!==void 0)w.MaxNumberOfMessages=b.maxMessages;if(b.visibilityTimeout!==void 0)w.VisibilityTimeout=b.visibilityTimeout;if(b.waitTimeSeconds!==void 0)w.WaitTimeSeconds=b.waitTimeSeconds;let h=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(w).toString()}),j=[],z=h.Message||h.ReceiveMessageResult?.Message;if(z)if(Array.isArray(z))j.push(...z.map((B)=>({MessageId:B.MessageId,ReceiptHandle:B.ReceiptHandle,Body:B.Body})));else j.push({MessageId:z.MessageId,ReceiptHandle:z.ReceiptHandle,Body:z.Body});return{Messages:j}}async deleteMessage(b,w){let h={Action:"DeleteMessage",QueueUrl:b,ReceiptHandle:w,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(h).toString()})}}
|
|
2
|
-
export{J as yd};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{yd as Wg}from"./chunk-4vrqm9h0.js";import{Jd as Zg,Od as $g}from"./chunk-3r4fb59r.js";import{Rd as xg}from"./chunk-p66ptpmr.js";import{Tf as Yg}from"./chunk-axhnkn5g.js";import{Uf as Og}from"./chunk-h5pa5men.js";import{$f as s,_f as c}from"./chunk-fy8j3y8p.js";import{Og as Q,Pg as gg}from"./chunk-fpm59y25.js";import{Gh as Xg,Un as Bg}from"./chunk-jpjamjey.js";class r{client;region;constructor(g="us-east-1",T){this.region=g,this.client=new Q(c(T))}async query(g){let T=new URLSearchParams(gg({Version:"2010-08-01",...g})).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(g){let T={Action:"GetMetricStatistics",Namespace:g.Namespace,MetricName:g.MetricName,StartTime:g.StartTime.toISOString(),EndTime:g.EndTime.toISOString(),Period:g.Period};(g.Statistics??[]).forEach((P,Y)=>{T[`Statistics.member.${Y+1}`]=P}),(g.ExtendedStatistics??[]).forEach((P,Y)=>{T[`ExtendedStatistics.member.${Y+1}`]=P}),(g.Dimensions??[]).forEach((P,Y)=>{T[`Dimensions.member.${Y+1}.Name`]=P.Name,T[`Dimensions.member.${Y+1}.Value`]=P.Value});let N=await this.query(T),L=(N.GetMetricStatisticsResult||N)?.Datapoints?.member??[];if(!Array.isArray(L))L=L?[L]:[];return L.map((P)=>{let Y={},X=P.ExtendedStatistics?.entry;if(X){if(!Array.isArray(X))X=[X];for(let Z of X)if(Z?.key!=null)Y[Z.key]=Number(Z.value)}return{Timestamp:P.Timestamp,Sum:P.Sum!=null?Number(P.Sum):void 0,Average:P.Average!=null?Number(P.Average):void 0,Maximum:P.Maximum!=null?Number(P.Maximum):void 0,Minimum:P.Minimum!=null?Number(P.Minimum):void 0,Percentiles:Object.keys(Y).length?Y:void 0,Unit:P.Unit}})}async getMetricSeries(g){let T=/^p\d/.test(g.Stat);return(await this.getMetricStatistics({Namespace:g.Namespace,MetricName:g.MetricName,Dimensions:g.Dimensions,StartTime:g.StartTime,EndTime:g.EndTime,Period:g.Period,Statistics:T?[]:[g.Stat],ExtendedStatistics:T?[g.Stat]:[]})).slice().sort((z,L)=>new Date(z.Timestamp??0).getTime()-new Date(L.Timestamp??0).getTime()).map((z)=>T?z.Percentiles?.[g.Stat]??0:z[g.Stat]??0)}async describeAlarms(g){let T={Action:"DescribeAlarms"};if(g?.AlarmNamePrefix)T.AlarmNamePrefix=g.AlarmNamePrefix;if(g?.MaxRecords)T.MaxRecords=g.MaxRecords;let N=await this.query(T),L=(N.DescribeAlarmsResult||N)?.MetricAlarms?.member??[];if(!Array.isArray(L))L=L?[L]:[];return L.map((P)=>({AlarmName:P.AlarmName,StateValue:P.StateValue,MetricName:P.MetricName,ComparisonOperator:P.ComparisonOperator,Threshold:P.Threshold!=null?Number(P.Threshold):void 0,Namespace:P.Namespace}))}async putMetricAlarm(g){let T={Action:"PutMetricAlarm",AlarmName:g.AlarmName,Namespace:g.Namespace,MetricName:g.MetricName,ComparisonOperator:g.ComparisonOperator,Threshold:g.Threshold,EvaluationPeriods:g.EvaluationPeriods,Period:g.Period,Statistic:g.Statistic};if(g.AlarmDescription)T.AlarmDescription=g.AlarmDescription;(g.Dimensions??[]).forEach((N,z)=>{T[`Dimensions.member.${z+1}.Name`]=N.Name,T[`Dimensions.member.${z+1}.Value`]=N.Value}),(g.AlarmActions??[]).forEach((N,z)=>{T[`AlarmActions.member.${z+1}`]=N}),await this.query(T)}async deleteAlarms(g){if(!g.length)return;let T={Action:"DeleteAlarms"};g.forEach((N,z)=>{T[`AlarmNames.member.${z+1}`]=N}),await this.query(T)}}class a{client;region;constructor(g="us-east-1",T){this.region=g,this.client=new Q(void 0,{profile:T})}async createLogGroup(g,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:g,...T?{tags:T}:{}})})}async putRetentionPolicy(g,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:g,retentionInDays:T})})}async describeLogStreams(g){let T={logGroupName:g.logGroupName};if(g.logStreamNamePrefix)T.logStreamNamePrefix=g.logStreamNamePrefix;if(g.orderBy)T.orderBy=g.orderBy;if(g.descending!==void 0)T.descending=g.descending;if(g.limit)T.limit=g.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(g){let T={logGroupName:g.logGroupName,logStreamName:g.logStreamName};if(g.startTime)T.startTime=g.startTime;if(g.endTime)T.endTime=g.endTime;if(g.limit)T.limit=g.limit;if(g.startFromHead!==void 0)T.startFromHead=g.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(g){let T={};if(g?.logGroupNamePrefix)T.logGroupNamePrefix=g.logGroupNamePrefix;if(g?.limit)T.limit=g.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(g){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:g})})}async filterLogEvents(g){let T={logGroupName:g.logGroupName};if(g.logStreamNames)T.logStreamNames=g.logStreamNames;if(g.startTime)T.startTime=g.startTime;if(g.endTime)T.endTime=g.endTime;if(g.filterPattern)T.filterPattern=g.filterPattern;if(g.limit)T.limit=g.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 jg}from"node:crypto";import{existsSync as Tg,mkdirSync as Vg,readdirSync as Hg,readFileSync as Ug,rmSync as Kg,writeFileSync as Eg}from"node:fs";import{homedir as Qg}from"node:os";import{join as m}from"node:path";var Ng=1,Lg=3600000,Rg=24*Lg,Fg=Lg,qg=30*Rg;function i(){let g=process.env.XDG_CACHE_HOME;return m(g&&g.trim()?g:m(Qg(),".cache"),"ts-cloud","cost-explorer")}function f(g){return m(i(),g??"__default__")}function Gg(g){let T={s:g.start,e:g.end,g:g.granularity,m:[...g.metrics].sort(),gb:[...g.groupBy].map((N)=>`${N.Type}:${N.Key}`).sort(),f:g.filter??null};return jg("sha256").update(JSON.stringify(T)).digest("hex").slice(0,24)}function Ag(g,T){let N=Date.parse(`${T}T00:00:00Z`);if(Number.isNaN(N))return!1;let z=new Date,L=Date.UTC(z.getUTCFullYear(),z.getUTCMonth(),1);return N<=L}function Sg(g){return Ag(g.start,g.end)?qg:Fg}function zg(g,T){let N=m(f(g),`${Gg(T)}.json`);if(!Tg(N))return null;let z;try{z=JSON.parse(Ug(N,"utf-8"))}catch{return null}if(z.schema!==Ng)return null;let L=Date.now()-z.savedAt;if(L<0||L>Sg(T))return null;return{response:z.response,ageSeconds:Math.floor(L/1000)}}function Jg(g,T,N){let z=f(g);Vg(z,{recursive:!0});let L={schema:Ng,savedAt:Date.now(),key:T,response:N};Eg(m(z,`${Gg(T)}.json`),JSON.stringify(L))}function wg(g){let T=g===void 0?i():f(g);if(!Tg(T))return{deletedFiles:0,scope:g??"all profiles"};let N=0;function z(L){for(let P of Hg(L,{withFileTypes:!0})){let Y=m(L,P.name);if(P.isDirectory())z(Y);else if(P.isFile()&&P.name.endsWith(".json"))N++}}return z(T),Kg(T,{recursive:!0,force:!0}),{deletedFiles:N,scope:g??"all profiles"}}function vg(g){return g===void 0?i():f(g)}class e{client;profile;useCache;lastCacheAgeSeconds=null;constructor(g,T){this.profile=g,this.useCache=T?.useCache??!0,this.client=new Q(c(g))}async getCostByService(g){return(await this.getCostByDimension({...g,dimension:"SERVICE"})).map((N)=>({service:N.key,amount:N.amount,unit:N.unit}))}async getCostByDimension(g){let{start:T,end:N,dimension:z,granularity:L="MONTHLY",filter:P}=g,Y=["UnblendedCost"],X=[{Type:"DIMENSION",Key:z}],Z={start:T,end:N,granularity:L,metrics:Y,groupBy:X,filter:P};if(this.useCache){let U=zg(this.profile,Z);if(U)return this.lastCacheAgeSeconds=U.ageSeconds,U.response}this.lastCacheAgeSeconds=null;let W=new Map,G;do{let U={TimePeriod:{Start:T,End:N},Granularity:L,Metrics:Y,GroupBy:X};if(P)U.Filter=P;if(G)U.NextPageToken=G;let S=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(U)});for(let v of S?.ResultsByTime??[])for(let K of v?.Groups??[]){let C=K.Keys?.[0]??"Unknown",u=Number.parseFloat(K.Metrics?.UnblendedCost?.Amount??"0"),l=K.Metrics?.UnblendedCost?.Unit??"USD",_=W.get(C);W.set(C,{key:C,amount:(_?.amount??0)+u,unit:l})}G=S?.NextPageToken||void 0}while(G);let b=[...W.values()].filter((U)=>U.amount>0).sort((U,S)=>S.amount-U.amount);if(this.useCache)Jg(this.profile,Z,b);return b}async getDailyTotals(g){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:g.start,End:g.end},Granularity:"DAILY",Metrics:["UnblendedCost"]})}))?.ResultsByTime??[]).map((z)=>Number.parseFloat(z.Total?.UnblendedCost?.Amount??"0"))}}class p{client;region;constructor(g="us-east-1"){this.region=g,this.client=new Q}async describeFileSystems(g){let T=[];if(g?.FileSystemId)T.push(`FileSystemId=${encodeURIComponent(g.FileSystemId)}`);if(g?.CreationToken)T.push(`CreationToken=${encodeURIComponent(g.CreationToken)}`);let N=`/2015-02-01/file-systems${T.length>0?`?${T.join("&")}`:""}`;return{FileSystems:((await this.client.request({service:"elasticfilesystem",region:this.region,method:"GET",path:N,headers:{"Content-Type":"application/json"}})).FileSystems||[]).map((L)=>({FileSystemId:L.FileSystemId,Name:L.Name,CreationTime:L.CreationTime,LifeCycleState:L.LifeCycleState,NumberOfMountTargets:L.NumberOfMountTargets,SizeInBytes:L.SizeInBytes?{Value:L.SizeInBytes.Value,Timestamp:L.SizeInBytes.Timestamp}:void 0,PerformanceMode:L.PerformanceMode,Encrypted:L.Encrypted,ThroughputMode:L.ThroughputMode,Tags:L.Tags}))}}}class t{client;region;constructor(g="us-east-1"){this.region=g,this.client=new Q}async call(g,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.${g}`},body:JSON.stringify(T)})}async listWebACLs(g="REGIONAL"){return(await this.call("ListWebACLs",{Scope:g,Limit:100}))?.WebACLs??[]}async getWebACLRules(g,T,N="REGIONAL"){return((await this.call("GetWebACL",{Name:g,Id:T,Scope:N}))?.WebACL?.Rules??[]).map((P)=>({Name:P.Name,Priority:P.Priority,Action:P.Action?Object.keys(P.Action)[0]:P.OverrideAction?Object.keys(P.OverrideAction)[0]:"count"}))}}function Pg(g){return String(g).padStart(2,"0")}function y(g){return`${g.getUTCFullYear()}-${Pg(g.getUTCMonth()+1)}-${Pg(g.getUTCDate())}`}function _g(g){let T=Math.max(0,Math.round((Date.now()-g)/1000));if(T<60)return`${T}s ago`;let N=Math.round(T/60);if(N<60)return`${N}m ago`;let z=Math.round(N/60);if(z<48)return`${z}h ago`;return`${Math.round(z/24)}d ago`}async function k(g,T,N,z,L,P){let Y=await g.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:N,Dimensions:[{Name:"FunctionName",Value:T}],StartTime:L,EndTime:P,Period:86400,Statistics:[z]}).catch(()=>[]);if(!Y.length)return 0;if(z==="Sum")return Y.reduce((X,Z)=>X+(Z.Sum??0),0);if(z==="Maximum")return Math.max(...Y.map((X)=>X.Maximum??0));return Y.reduce((X,Z)=>X+(Z.Average??0),0)/Y.length}async function w(g,T,N,z,L,P,Y){let X=await g.getMetricStatistics({Namespace:T,MetricName:N,Dimensions:z,StartTime:P,EndTime:Y,Period:86400,Statistics:[L]}).catch(()=>[]);if(!X.length)return 0;if(L==="Sum")return X.reduce((Z,W)=>Z+(W.Sum??0),0);if(L==="Maximum")return Math.max(...X.map((Z)=>Z.Maximum??0));return X.reduce((Z,W)=>Z+(W.Average??0),0)/X.length}async function n(g,T,N,z,L){let P=await g.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"Duration",Dimensions:[{Name:"FunctionName",Value:T}],StartTime:z,EndTime:L,Period:86400,ExtendedStatistics:[N]}).catch(()=>[]);return Math.round(P.reduce((Y,X)=>Y+(X.Percentiles?.[N]??0),0))}async function PT(g,T){let N=await $g(g,T),z=N.region,L=new r(z),P=new xg(z),Y=new a(z),X=new Date,Z=new Date(X.getTime()-86400000),W=g.environments?.[T]?.app,G={};G.app={name:N.slug,env:T,region:z,runtime:W?.kind==="php"?`php-${W?.phpVersion??"8.3"} (fpm)`:W?.kind??"node",url:N.endpoint??"",build:N.lastRelease?.sha?.slice(0,7)??"—",deployedAt:N.lastRelease?.timestamp??"—"},G.maintenance={enabled:!1},G.scheduler={enabled:N.scheduler!=="off",expression:N.scheduler==="sub-minute"?"rate(1 minute) · sub-minute":"rate(1 minute)",lastRun:"—"};let b=0,U=0,S=0,v=[],K=[],C=[];for(let J of N.functions){let[O,x,B,V,$,H,E,R,I]=await Promise.all([k(L,J.name,"Invocations","Sum",Z,X),k(L,J.name,"Errors","Sum",Z,X),k(L,J.name,"Throttles","Sum",Z,X),k(L,J.name,"Duration","Average",Z,X),P.getFunction(J.name).catch(()=>null),n(L,J.name,"p50",Z,X),n(L,J.name,"p95",Z,X),n(L,J.name,"p99",Z,X),L.getMetricSeries({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:[{Name:"FunctionName",Value:J.name}],StartTime:new Date(X.getTime()-43200000),EndTime:X,Period:3600,Stat:"Sum"}).catch(()=>[])]);b+=O,U+=x,S=Math.max(S,V);let D=$?.Configuration?.MemorySize??0,F=Object.keys($?.Configuration?.Environment?.Variables??{}),M=[],j=0;try{let{events:d=[]}=await Y.filterLogEvents({logGroupName:`/aws/lambda/${J.name}`,startTime:Z.getTime(),limit:120});for(let A of d){let h=(A.message??"").trim(),o=/Max Memory Used:\s*(\d+)\s*MB/.exec(h);if(o)j=Math.max(j,Number(o[1]));if(h&&!/^(?:START|END|REPORT|INIT_START)/.test(h))C.push({source:J.mode||J.name,timestamp:new Date(A.timestamp??0).toISOString(),when:_g(A.timestamp??0),message:h.slice(0,400),level:/error|exception|fatal|panic|traceback/i.test(h)?"error":/warn|warning|timeout|retr(?:y|ies)|throttl/i.test(h)?"warn":"info"})}M=d.filter((A)=>!/^(?:START|END|REPORT|INIT_START)/.test((A.message??"").trim())).slice(-6).map((A)=>({ts:new Date(A.timestamp??0).toISOString().slice(11,19),msg:(A.message??"").trim().slice(0,120),err:/error|exception|fatal/i.test(A.message??"")}))}catch{}let q=Math.max(1,...I);v.push({key:J.mode,name:J.name,version:J.version,memory:D,timeout:$?.Configuration?.Timeout??0,runtime:$?.Configuration?.Runtime??"provided.al2023",invocations:Math.round(O),errors:Math.round(x),p95:E||Math.round(V),status:"active",provisioned:J.provisioned?`${J.provisioned.allocated}/${J.provisioned.requested}`:void 0}),K.push({key:J.mode,name:J.name,runtime:$?.Configuration?.Runtime??"provided.al2023",arch:$?.Configuration?.Architectures?.[0]??"x86_64",memory:D,timeout:$?.Configuration?.Timeout??0,ephemeral:$?.Configuration?.EphemeralStorage?.Size??512,version:J.version,concurrency:W?.concurrency??"—",invocations:Math.round(O),errors:Math.round(x),throttles:Math.round(B),p50:H||Math.round(V),p95:E||Math.round(V),p99:R||Math.round(V),maxMem:j,spark:I.length?I.map((d)=>Math.round(d/q*100)):[0],env:F.length?F:["(none)"],recent:M.length?M:[{ts:"—",msg:"no recent events",err:!1}]})}G.functions=v,G.functionsDetail=K,G.serverlessLogs=C.sort((J,O)=>String(O.timestamp).localeCompare(String(J.timestamp))).slice(0,600),G.serverlessLogsEmptyReason=C.length?void 0:"No recent function logs were found in CloudWatch for this environment.";let u=b?Number((U/b*100).toFixed(2)):0,l=Math.round(await k(L,N.functions[0]?.name??"","ConcurrentExecutions","Maximum",Z,X));G.metrics={invocations:Math.round(b),errorRatePct:u,p95Ms:Math.round(S),coldStartPct:void 0,concurrency:l,estCostUsd:void 0};try{let J=new Wg(z),O=[],x=[],B=0;try{let{QueueUrl:$}=await J.getQueueUrl(`${N.slug}-${T}-dlq`),{Attributes:H}=await J.getQueueAttributes($);B=Number(H.ApproximateNumberOfMessages??0)}catch{}let V=W?Bg(W,N.slug,T):[];for(let $ of V){let H=$.name.replace(`${N.slug}-${T}-`,""),E=0,R=0;try{let{QueueUrl:D}=await J.getQueueUrl($.name),{Attributes:F}=await J.getQueueAttributes(D);E=Number(F.ApproximateNumberOfMessages??0),R=Number(F.ApproximateNumberOfMessagesNotVisible??0)}catch{}let I=Math.round(await w(L,"AWS/SQS","NumberOfMessagesDeleted",[{Name:"QueueName",Value:$.name}],"Sum",Z,X));O.push({name:H,visible:E,inFlight:R,processed:I,dlq:B}),x.push({name:$.name,short:H,visible:E,inFlight:R,delayed:0,processed:I,oldestSec:0,concurrency:$.concurrency??W?.queueConcurrency??"—",tries:W?.queueTries??3,visTimeout:(W?.queueTimeout??120)*6,dlq:B})}if(O.length)G.queues=O;if(x.length)G.queuesDetail=x;G.dlqItems=[]}catch{}try{let J=new Og(z),{Stacks:O}=await J.describeStacks({stackName:Xg(g,T)}),x={};for(let B of O?.[0]?.Outputs??[])if(B.OutputKey)x[B.OutputKey]=B.OutputValue??"";if(W?.database?.connection==="aurora-serverless"){let B=`${N.slug}-${T}-db`,V=[{Name:"DBClusterIdentifier",Value:B}],[$,H]=await Promise.all([w(L,"AWS/RDS","ServerlessDatabaseCapacity",V,"Average",Z,X),w(L,"AWS/RDS","DatabaseConnections",V,"Maximum",Z,X)]);if(G.aurora={id:B,engine:"aurora-mysql",minAcu:W?.database?.minCapacity??0.5,maxAcu:W?.database?.maxCapacity??4,currentAcu:$?Number($.toFixed(1)):W?.database?.minCapacity??0.5,database:"app",connections:Math.round(H),status:x.DbEndpoint?"available":"creating"},W?.rdsProxy)G.proxy={name:`${N.slug}-${T}-proxy`,endpoint:x.DbProxyEndpoint??"—",pooledConns:Math.round(H),status:"available"}}if(W?.cache?.driver==="elasticache"){let B=`${N.slug}-${T}-cache`,V=[{Name:"CacheClusterId",Value:`${B}-001`}],[$,H]=await Promise.all([w(L,"AWS/ElastiCache","CacheHits",V,"Sum",Z,X),w(L,"AWS/ElastiCache","CacheMisses",V,"Sum",Z,X)]),E=$+H>0?Number(($/($+H)*100).toFixed(1)):0;G.redis={id:B,node:"cache.t4g.micro",engine:"redis",hitRate:E,status:x.CacheEndpoint?"available":"creating"}}if(W?.efs){let B=0;try{if(x.EfsFileSystemId){let V=new p(z),{FileSystems:$}=await V.describeFileSystems({FileSystemId:x.EfsFileSystemId});B=Number((($?.[0]?.SizeInBytes?.Value??0)/1048576).toFixed(1))}}catch{}G.efs={id:x.EfsFileSystemId??"efs",mount:"/mnt/local",sizeMb:B,status:"available"}}G.assetsInfo=x.AssetsCdnDomain?{bucket:x.AssetsBucketName??`${N.slug}-${T}-assets`,cdn:x.AssetsCdnDomain,customDomain:W?.assetDomain??"—",assetUrl:N.assetUrl??"—",files:0,sizeMb:0,cacheHitPct:0,build:G.app.build}:void 0}catch{}if(G.assetsInfo)try{let O=await new s(z).list({bucket:G.assetsInfo.bucket,maxKeys:1000});G.assetsInfo.files=O.length,G.assetsInfo.sizeMb=Number((O.reduce((x,B)=>x+(B.Size??0),0)/1048576).toFixed(1)),G.assetsRecent=O.slice(0,8).map((x)=>({path:`/${x.Key}`,size:`${Math.max(1,Math.round((x.Size??0)/1024))} KB`,type:x.Key.split(".").pop()??""}))}catch{}try{if(W?.secrets){let J=Array.isArray(W.secrets)?W.secrets.map((O)=>({key:O.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),source:O})):Object.entries(W.secrets).map(([O,x])=>({key:O,source:String(x)}));G.secretsList=J.map((O)=>({...O,updated:"—"}))}}catch{}try{let J=new s(z),O=`${N.slug}-${T}-deployments`,x=await J.getObjectJson(O,`deployments/${N.slug}/${T}/history.json`).catch(()=>null);if(x?.records?.length)G.deploymentsDetail=x.records.slice(-12).reverse().map((B)=>({sha:(B.sha??"").slice(0,7),status:B.status??"success",when:B.timestamp??"—",took:B.took??"—",by:B.by??"—",version:B.version??"—",hooks:B.hooks??[]}))}catch{}G.metricsTotals={invocations:G.metrics.invocations,errors:Math.round(U),errorRatePct:u,p95Ms:G.metrics.p95Ms,throttles:K.reduce((J,O)=>J+O.throttles,0),coldStartPct:void 0,estCostUsd:void 0,concurrency:l},G.metricsPerFn=K.map((J)=>({key:J.key,invocations:J.invocations,errors:J.errors,throttles:J.throttles,avgMs:J.p50,maxMs:J.p99,costUsd:void 0}));try{G.invSpark=await L.getMetricSeries({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:[{Name:"FunctionName",Value:N.functions.find((J)=>J.mode==="http")?.name??""}],StartTime:new Date(X.getTime()-86400000),EndTime:X,Period:3600,Stat:"Sum"})}catch{}try{let J=new e,O=X,x=new Date(Date.UTC(O.getUTCFullYear(),O.getUTCMonth(),1)),B=new Date(Date.UTC(O.getUTCFullYear(),O.getUTCMonth()-1,1)),[V,$]=await Promise.all([J.getCostByService({start:y(x),end:y(O),granularity:"MONTHLY"}).catch(()=>[]),J.getCostByService({start:y(B),end:y(x),granularity:"MONTHLY"}).catch(()=>[])]);if(V.length){let H=V.reduce((j,q)=>j+q.amount,0),E=$.reduce((j,q)=>j+q.amount,0),R=O.getUTCDate(),I=new Date(Date.UTC(O.getUTCFullYear(),O.getUTCMonth()+1,0)).getUTCDate();G.costSummary={monthToDateUsd:Number(H.toFixed(2)),projectedUsd:Number((H/R*I).toFixed(2)),lastMonthUsd:Number(E.toFixed(2)),dailyAvgUsd:Number((H/R).toFixed(2))},G.costServices=V.filter((j)=>j.amount>0).sort((j,q)=>q.amount-j.amount).slice(0,12).map((j)=>({name:j.service,usd:Number(j.amount.toFixed(2)),note:""})),G.metrics.estCostUsd=Number((H/R).toFixed(2)),G.metricsTotals.estCostUsd=G.metrics.estCostUsd,G.costTrend=await J.getDailyTotals({start:y(x),end:y(O)}).catch(()=>[]);let D=V.find((j)=>/lambda/i.test(j.service))?.amount??0,F=(j)=>j.invocations*(j.p50/1000)*(j.memory/1024),M=K.reduce((j,q)=>j+F(q),0)||1;G.costPerFn=K.map((j)=>({key:j.key,requests:j.invocations,gbSec:Math.round(F(j)),usd:Number((D*(F(j)/M)).toFixed(2))}))}}catch{}if(W?.firewall)try{let J=await L.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"BlockedRequests",StartTime:Z,EndTime:X,Period:86400,Statistics:["Sum"]}).catch(()=>[]),O=await L.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"AllowedRequests",StartTime:Z,EndTime:X,Period:86400,Statistics:["Sum"]}).catch(()=>[]);G.waf={enabled:!0,scope:"REGIONAL",acl:`${N.slug}-${T}-waf`,allowed24h:Math.round(O.reduce((x,B)=>x+(B.Sum??0),0)),blocked24h:Math.round(J.reduce((x,B)=>x+(B.Sum??0),0))};try{let x=new t(z),B=await x.listWebACLs("REGIONAL"),V=B.find(($)=>$.Name?.includes(`${N.slug}-${T}`))??B[0];if(V?.Name&&V.Id){G.waf.acl=V.Name;let $=await x.getWebACLRules(V.Name,V.Id,"REGIONAL");if($.length)G.wafRules=$.map((H)=>({name:H.Name??"—",detail:`priority ${H.Priority??0}`,action:H.Action??"count",blocked24h:0}))}}catch{}}catch{}let _=[];if(G.aurora)_.push({name:"Aurora Serverless v2",detail:`${G.aurora.id} · ${G.aurora.minAcu}-${G.aurora.maxAcu} ACU`,status:G.aurora.status});if(G.proxy)_.push({name:"RDS Proxy",detail:G.proxy.name,status:G.proxy.status});if(G.redis)_.push({name:`ElastiCache (${G.redis.engine})`,detail:`${G.redis.node} · ${G.redis.hitRate}% hit rate`,status:G.redis.status});if(G.efs)_.push({name:"EFS",detail:`${G.efs.mount} · ${G.efs.sizeMb} MB`,status:G.efs.status});if(_.length)G.dataServices=_;if(N.scheduler!=="off"&&W?.kind==="php")try{let J=await Zg(g,T,"schedule:list"),O=[];for(let x of(J||"").split(`
|
|
2
|
-
`)){let B=/^\s*([\d*/,\-\s]+?)\s{2,}(.+?)(?:\s{2,}Next Due.*)?$/.exec(x);if(B&&/[*\d]/.test(B[1])&&B[1].trim().split(/\s+/).length===5)O.push({command:B[2].trim().replace(/^php artisan /,""),cron:B[1].trim(),desc:"",lastRun:"—",lastStatus:"ok"})}if(O.length)G.schedulerTasks=O}catch{}return G.topology=Yg(G,{project:g.project.name,environment:T}),G}
|
|
3
|
-
export{a as sd,r as td,wg as ud,vg as vd,e as wd,PT as xd};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{$f as a}from"./chunk-fy8j3y8p.js";import"./chunk-fpm59y25.js";import"./chunk-mh0kdzqp.js";export{a as S3Client};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Ae as b,Be as c,Ce as d,De as e,Ee as f,Fe as g,Ge as h,He as i,Ie as j,ze as a}from"./chunk-sgyffpgm.js";import"./chunk-3gykfyq4.js";import"./chunk-ax9mr6wm.js";import"./chunk-ggn7ax8p.js";import"./chunk-r3kv0vm9.js";import"./chunk-r9hjwcj9.js";import"./chunk-axhnkn5g.js";import"./chunk-h5pa5men.js";import"./chunk-fy8j3y8p.js";import"./chunk-fpm59y25.js";import"./chunk-jpjamjey.js";import"./chunk-mh0kdzqp.js";export{a as sharedBoxProbeScript,e as serverLogSources,j as resolveServerDashboardData,i as resolveConfigOnlyServerDashboardData,g as parseServerSecurity,f as parseServerLogs,h as parseDeployHistory,c as parseBlock,b as metricsScript,d as mergeDiscoveredSites};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{od as a,pd as b,qd as c,rd as d}from"./chunk-bz828v8q.js";import"./chunk-r9hjwcj9.js";import"./chunk-jpjamjey.js";import"./chunk-mh0kdzqp.js";export{c as runComputeRecipe,a as rollbackComputeSite,d as restoreDatabaseBackup,b as getComputeDeployHistory};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Rd as a}from"./chunk-p66ptpmr.js";import"./chunk-fpm59y25.js";import"./chunk-mh0kdzqp.js";export{a as LambdaClient};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as k,b as l,c as m,d as n,e as o,f as p,g as q,h as z,i as A,j as B,k as C,l as D,m as E,n as F,o as G}from"./chunk-hzgz13nf.js";import{Je as H,Ke as I,Le as J,Me as K,Ne as L,Oe as M}from"./chunk-3gykfyq4.js";import{Pe as r,Qe as s,Re as t,Se as u,Te as v,Ue as w,Ve as x,We as y}from"./chunk-ax9mr6wm.js";import{do as a,eo as b,fo as c,go as d,ho as e,io as f,jo as g,ko as h,lo as i,mo as j}from"./chunk-jpjamjey.js";import"./chunk-mh0kdzqp.js";export{M as wafEventTelemetry,t as sysctlHardening,m as ruleMatches,L as renderWafInstallScript,K as renderWafConfig,u as renderSysctlFile,v as renderNftablesRuleset,w as renderDdosInstallScript,j as recursionBlockedResponse,n as rateLimitKey,p as rateLimitHeaders,i as propagationHeaders,x as planMitigation,f as parseChain,G as mergeControlsIntoConfig,s as isValidCidr,I as isSafePattern,g as inspectInvocation,J as globToRegex,l as globMatches,d as functionFingerprint,H as escapeSecLang,D as describePosture,q as defaultRateLimitRules,y as applyMitigationFactor,E as applyControlsToRateLimits,F as applyControlsToDdos,c as TRACE_HEADER,h as RecursionGuard,o as RateLimiter,k as RATE_LIMIT_KEY_SEPARATOR,C as ProtectionControlStore,z as PROTECTION_SETTING,A as MAX_CONTROL_HOURS,a as DEPTH_HEADER,e as DEFAULT_RECURSION_LIMITS,r as DEFAULT_DDOS_THRESHOLDS,B as DEFAULT_ATTACK_MODE_HOURS,b as CHAIN_HEADER};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{$e as d,Ye as a,Ze as b,_e as c,af as e,bf as f,cf as g,df as h,ef as i,ff as j}from"./chunk-r3kv0vm9.js";import"./chunk-jpjamjey.js";import"./chunk-mh0kdzqp.js";export{f as stageLiveDashboardRoot,g as resolveUiSource,e as resolveDashboardVersion,c as resolveDashboardAuth,i as managementDashboardSiteNames,d as liveStageDir,h as ensureManagementDashboard,b as dashboardCredentialsFile,j as buildManagementDashboardArtifact,a as MANAGEMENT_DASHBOARD_SITE};
|
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
var V={newConnectionsPerSecond:50,concurrentPerSource:100,synPerSecond:2000,burst:100,icmpPerSecond:5,banSeconds:600};function N(j){return{...V,...j.thresholds}}var m=/^(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{1,2})?$|^[0-9a-f:]+(?:\/\d{1,3})?$/i;function I(j){if(!m.test(j))return!1;let[q,z]=j.split("/");if(q.includes(":"))return z==null||Number(z)>=0&&Number(z)<=128;let K=q.split(".");if(K.length!==4||K.some((W)=>Number(W)>255||W===""))return!1;return z==null||Number(z)>=0&&Number(z)<=32}function U(j){return[...new Set((j??[]).map((q)=>q.trim()).filter(I))]}function O(j){let q=(j??[80,443]).filter((z)=>Number.isInteger(z)&&z>=1&&z<=65535);return[...new Set(q)].sort((z,K)=>z-K)}function k(j={}){let q=N(j);return{"net.ipv4.tcp_syncookies":"1","net.ipv4.tcp_max_syn_backlog":String(Math.max(4096,q.synPerSecond*4)),"net.ipv4.tcp_synack_retries":"2","net.ipv4.tcp_abort_on_overflow":"1","net.ipv4.tcp_fin_timeout":"15","net.ipv4.tcp_keepalive_time":"300","net.ipv4.tcp_keepalive_intvl":"30","net.ipv4.tcp_keepalive_probes":"3","net.core.somaxconn":"4096","net.core.netdev_max_backlog":"16384","net.ipv4.conf.all.rp_filter":"1","net.ipv4.conf.default.rp_filter":"1","net.ipv4.conf.all.accept_source_route":"0","net.ipv4.conf.all.accept_redirects":"0","net.ipv4.conf.all.send_redirects":"0","net.ipv6.conf.all.accept_redirects":"0","net.ipv6.conf.all.accept_source_route":"0","net.ipv4.icmp_echo_ignore_broadcasts":"1","net.ipv4.icmp_ignore_bogus_error_responses":"1","net.netfilter.nf_conntrack_max":"262144","net.netfilter.nf_conntrack_tcp_timeout_established":"3600"}}function _(j={}){let q=["# Managed by ts-cloud. Edits are overwritten on the next deploy.","# Network hardening against L3/L4 floods.",""];for(let[z,K]of Object.entries(k(j)))q.push(`${z} = ${K}`);return`${q.join(`
|
|
2
|
-
`)}
|
|
3
|
-
`}function y(j={}){let q=N(j),z=O(j.ports),K=U(j.allowlist),W=U(j.blocklist),X=j.monitorOnly?"counter":"counter drop",M=j.originProtection?.enabled?U(j.originProtection.cdnRanges):[],Q=K.filter((J)=>!J.includes(":")),Z=K.filter((J)=>J.includes(":")),$=W.filter((J)=>!J.includes(":")),G=["#!/usr/sbin/nft -f","# Managed by ts-cloud. Edits are overwritten on the next deploy.","","table inet ts_cloud_ddos","delete table inet ts_cloud_ddos","","table inet ts_cloud_ddos {"," # Sources that tripped a limit, with a timeout so a ban self-expires.",` set banned4 { type ipv4_addr; flags timeout; timeout ${q.banSeconds}s; }`,` set banned6 { type ipv6_addr; flags timeout; timeout ${q.banSeconds}s; }`];if(Q.length>0)G.push(` set allow4 { type ipv4_addr; flags interval; elements = { ${Q.join(", ")} } }`);if(Z.length>0)G.push(` set allow6 { type ipv6_addr; flags interval; elements = { ${Z.join(", ")} } }`);if($.length>0)G.push(` set block4 { type ipv4_addr; flags interval; elements = { ${$.join(", ")} } }`);if(M.length>0)G.push(` set cdn4 { type ipv4_addr; flags interval; elements = { ${M.filter((J)=>!J.includes(":")).join(", ")} } }`);if(G.push(""," chain input {"," type filter hook input priority -150; policy accept;",""," # Established traffic is already paid for; never re-inspect it."," ct state established,related accept"," iif lo accept",""," # Invalid packets are never legitimate and are cheap to drop early."," ct state invalid counter drop"),Q.length>0)G.push(" ip saddr @allow4 accept");if(Z.length>0)G.push(" ip6 saddr @allow6 accept");if($.length>0)G.push(" ip saddr @block4 counter drop");if(G.push(" ip saddr @banned4 counter drop"," ip6 saddr @banned6 counter drop",""),G.push(" # Nonsense TCP flag combinations: scanners and stack fingerprinting."," tcp flags & (fin|syn) == (fin|syn) counter drop"," tcp flags & (syn|rst) == (syn|rst) counter drop"," tcp flags & (fin|rst) == (fin|rst) counter drop"," tcp flags & (fin|ack) == fin counter drop"," tcp flags & (syn|fin|ack|rst|psh|urg) == 0x0 counter drop",""," # Ping stays usable, ping floods do not.",` ip protocol icmp icmp type echo-request limit rate ${q.icmpPerSecond}/second burst ${q.burst} packets accept`," ip protocol icmp icmp type echo-request counter drop",""),z.length>0){let J=z.join(", ");if(G.push(" # Platform-wide SYN ceiling. Above it the kernel falls back to cookies.",` tcp dport { ${J} } ct state new limit rate ${q.synPerSecond}/second burst ${q.burst} packets accept`,""," # Per-source new-connection rate. This is what stops one host hammering.",` tcp dport { ${J} } ct state new meter conn_rate4 { ip saddr limit rate over ${q.newConnectionsPerSecond}/second burst ${q.burst} packets } add @banned4 { ip saddr } ${X}`,` tcp dport { ${J} } ct state new meter conn_rate6 { ip6 saddr limit rate over ${q.newConnectionsPerSecond}/second burst ${q.burst} packets } add @banned6 { ip6 saddr } ${X}`,""," # Concurrency ceiling per source: the slow-loris defence.",` tcp dport { ${J} } ct state new meter conn_count4 { ip saddr ct count over ${q.concurrentPerSource} } ${X}`,` tcp dport { ${J} } ct state new meter conn_count6 { ip6 saddr ct count over ${q.concurrentPerSource} } ${X}`,""),M.length>0)G.push(" # Origin protection: reject traffic that skipped the CDN and came"," # straight to the box, which is how an attacker bypasses the edge.",` tcp dport { ${J} } ip saddr != @cdn4 counter drop`,"")}return G.push(" }","}",""),G.join(`
|
|
4
|
-
`)}function C(j={}){return`#!/usr/bin/env bash
|
|
5
|
-
# Managed by ts-cloud. Installs L3/L4 flood mitigation.
|
|
6
|
-
set -euo pipefail
|
|
7
|
-
|
|
8
|
-
if ! command -v nft >/dev/null 2>&1; then
|
|
9
|
-
export DEBIAN_FRONTEND=noninteractive
|
|
10
|
-
apt-get update -qq
|
|
11
|
-
apt-get install -y -qq nftables
|
|
12
|
-
fi
|
|
13
|
-
|
|
14
|
-
install -d -m 0755 /etc/ts-cloud /etc/nftables.d
|
|
15
|
-
cat > /etc/sysctl.d/90-ts-cloud-ddos.conf <<'SYSCTL_EOF'
|
|
16
|
-
${_(j)}SYSCTL_EOF
|
|
17
|
-
sysctl --system >/dev/null
|
|
18
|
-
|
|
19
|
-
cat > /etc/nftables.d/ts-cloud-ddos.nft.new <<'NFT_EOF'
|
|
20
|
-
${y(j)}NFT_EOF
|
|
21
|
-
|
|
22
|
-
# Syntax-check before applying: a bad ruleset would leave the box unprotected.
|
|
23
|
-
if ! nft -c -f /etc/nftables.d/ts-cloud-ddos.nft.new; then
|
|
24
|
-
echo "ts-cloud: generated nftables ruleset failed validation, keeping the previous one" >&2
|
|
25
|
-
rm -f /etc/nftables.d/ts-cloud-ddos.nft.new
|
|
26
|
-
exit 1
|
|
27
|
-
fi
|
|
28
|
-
|
|
29
|
-
mv /etc/nftables.d/ts-cloud-ddos.nft.new /etc/nftables.d/ts-cloud-ddos.nft
|
|
30
|
-
nft -f /etc/nftables.d/ts-cloud-ddos.nft
|
|
31
|
-
|
|
32
|
-
# Applying the ruleset does not survive a reboot on its own: nftables.service
|
|
33
|
-
# loads /etc/nftables.conf, so the file has to be included from there or the box
|
|
34
|
-
# comes back up unprotected and nothing says so.
|
|
35
|
-
touch /etc/nftables.conf
|
|
36
|
-
if ! grep -q 'ts-cloud-ddos.nft' /etc/nftables.conf; then
|
|
37
|
-
printf '
|
|
38
|
-
include "/etc/nftables.d/ts-cloud-ddos.nft"
|
|
39
|
-
' >> /etc/nftables.conf
|
|
40
|
-
fi
|
|
41
|
-
systemctl enable nftables >/dev/null 2>&1 || true
|
|
42
|
-
echo "ts-cloud: L3/L4 mitigation active"
|
|
43
|
-
`}var F=["off","monitor","rate_limit","challenge","lockdown"];function L(j,q=[]){let z=[],K=Math.max(1,j.baselineRequestsPerSecond),W=j.requestsPerSecond/K,X=0,M=(B,H)=>{z.push(H),X=Math.max(X,F.indexOf(B))},Q=W>=3;if(Q)M("monitor",`Traffic is ${W.toFixed(1)}x the baseline.`);let Z=j.topSourceShare>=0.25,$=j.errorRate>=0.25,G=(j.suspiciousAgentShare??0)>=0.5,J=j.uniqueSources>0&&j.requestsPerSecond/j.uniqueSources>=50;if(Q&&Z)M("rate_limit",`One source accounts for ${(j.topSourceShare*100).toFixed(0)}% of traffic.`);if(Q&&J)M("rate_limit","Request rate per unique source is far above what a browser produces.");if(Q&&$)M("challenge",`Error rate is ${(j.errorRate*100).toFixed(0)}% under load.`);if(Q&&G)M("challenge","Most requests carry no recognisable browser agent.");if(W>=20&&(Z||$||G||J))M("lockdown",`Traffic is ${W.toFixed(0)}x the baseline with attack-shaped characteristics.`);if(!Q&&j.topSourceShare>=0.6&&j.requestsPerSecond>K)M("rate_limit","A single source dominates traffic without an overall surge.");let Y=F[X],P={off:1,monitor:1,rate_limit:0.5,challenge:0.25,lockdown:0.1}[Y];return{level:Y,reasons:z,rateLimitFactor:P,challengeEnabled:Y==="challenge"||Y==="lockdown",staticOnly:Y==="lockdown",banCandidates:Y==="off"||Y==="monitor"?[]:U(q)}}function T(j,q){return Math.max(1,Math.floor(j*q.rateLimitFactor))}
|
|
44
|
-
export{V as Pe,I as Qe,k as Re,_ as Se,y as Te,C as Ue,L as Ve,T as We};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var L=[{index:0,id:"clients",label:"Clients"},{index:1,id:"dns",label:"DNS & TLS"},{index:2,id:"edge",label:"Edge"},{index:3,id:"routing",label:"Routing"},{index:4,id:"apps",label:"Applications"},{index:5,id:"runtime",label:"Background runtime"},{index:6,id:"data",label:"Data services"},{index:7,id:"durability",label:"Durability"}],m=[{index:0,id:"clients",label:"Clients"},{index:1,id:"dns",label:"DNS & TLS"},{index:2,id:"edge",label:"Edge"},{index:3,id:"entry",label:"Entry points"},{index:4,id:"compute",label:"Compute"},{index:5,id:"messaging",label:"Messaging & pooling"},{index:6,id:"data",label:"Data services"},{index:7,id:"durability",label:"Durability"}],w=[{match:/^redis/,kind:"cache",label:"Redis"},{match:/^(?:mysql|mariadb)/,kind:"database",label:"MySQL"},{match:/^postgres/,kind:"database",label:"PostgreSQL"},{match:/^meilisearch/,kind:"database",label:"Meilisearch"},{match:/^vitess|^vtgate/,kind:"database",label:"Vitess"},{match:/^memcached/,kind:"cache",label:"Memcached"}],y=/^(?:rpx-gateway|nginx|caddy|traefik|haproxy)$/;function j(H,Z=""){let J=H==null?"":String(H).trim();return J&&J!=="-"&&J!=="—"?J:Z}function h(H){return Array.isArray(H)?H.length:0}function D(H){let Z=j(H).toLowerCase();if(!Z)return"unknown";if(["running","live","active","available","success","ok","healthy","enabled"].includes(Z))return"ok";if(["failed","stopped","unreachable","error","critical","disabled"].includes(Z))return"bad";if(["configured","creating","pending","degraded","shadowed","warn","unknown"].includes(Z))return"warn";return"warn"}function Q(H,Z,J){if(J.has(Z.source)&&J.has(Z.target))H.push(Z)}function v(H,Z={}){let J=[],M=[],E=[],P=H.server??{},$=Array.isArray(H.sites)?H.sites:[],O=Array.isArray(H.services)?H.services:[],Y=Array.isArray(H.workers)?H.workers:[],I=H.security??{},b=!!H._serverReachable&&!H.metricsUnavailable,_="box";if(!b)E.push("The compute box could not be probed, so live service state is missing; the shape comes from your cloud config.");J.push({id:"internet",label:"Internet",kind:"internet",layer:0,status:"ok",sub:"Public traffic",facts:[],external:!0});let W=[...new Set($.map((z)=>j(z.domain)||j(z.route).split("/")[0]).filter((z)=>z&&z!=="internal"&&z!=="loopback"))],q=Array.isArray(I.tlsCertificates)?I.tlsCertificates:[],X=q.filter((z)=>Number(z?.daysRemaining??999)<21).length;J.push({id:"dns",label:W.length===1?W[0]:"Public domains",kind:"dns",layer:1,status:X?"warn":W.length?"ok":"unknown",sub:W.length>1?`${W.length} domains`:"DNS & certificates",facts:[{label:"Domains",value:W.length?W.slice(0,6).join(", "):"none resolved"},{label:"Certificates",value:q.length?`${q.length} issued`:"none reported"},...X?[{label:"Expiring",value:`${X} within 21 days`}]:[]],href:"/server/security",external:!0});let T=I.firewall??{},A=Array.isArray(I.ports)?I.ports:[];J.push({id:"firewall",label:"Host firewall",kind:"firewall",layer:2,status:D(T.status),sub:j(T.summary,"Inbound filtering"),facts:[{label:"State",value:j(T.status,"unknown")},{label:"Open ports",value:A.length?A.map((z)=>j(z.listen)).join(", "):"not reported"}],href:"/server/firewall",group:"box"});let C=O.find((z)=>y.test(j(z.name)));J.push({id:"proxy",label:j(C?.name,"Reverse proxy"),kind:"proxy",layer:3,status:C?D(C.status):"unknown",sub:"TLS termination & routing",facts:[{label:"Service",value:j(C?.name,"not detected")},{label:"State",value:j(C?.status,b?"not running":"not probed")},{label:"Routes",value:`${$.length} site${$.length===1?"":"s"}`}],href:"/server/services",group:"box"});for(let z of $){let B=`site:${j(z.name)}`;if(!j(z.name))continue;J.push({id:B,label:j(z.name),kind:"site",layer:4,status:D(z.status),sub:j(z.runtime,"runtime"),facts:[{label:"Route",value:j(z.route,"internal")},{label:"Runtime",value:j(z.runtime,"unknown")},{label:"Delivery",value:j(z.deploy,"unknown")},{label:"TLS",value:j(z.tls,"unknown")},...z.responseMs!=null?[{label:"Response",value:`${Math.round(Number(z.responseMs))} ms`}]:[],...z.httpStatus!=null?[{label:"HTTP",value:String(z.httpStatus)}]:[]],href:"/server/sites",group:"box"})}for(let z of Y){let B=`worker:${j(z.name)}`;if(!j(z.name))continue;J.push({id:B,label:j(z.name),kind:"worker",layer:5,status:D(z.status),sub:`${Number(z.processes??1)} process${Number(z.processes??1)===1?"":"es"}`,facts:[{label:"Processes",value:String(z.processes??1)},{label:"State",value:j(z.status,"unknown")},...j(z.site)?[{label:"Site",value:j(z.site)}]:[]],href:"/operations/jobs",group:"box"})}let g=H.serverScheduler??{};if(g.enabled)J.push({id:"scheduler",label:"Scheduler",kind:"scheduler",layer:5,status:"ok",sub:"Cron dispatch",facts:[{label:"Last run",value:j(g.lastRun,"unknown")}],href:"/operations/jobs",group:"box"});let U=O.map((z)=>{let B=j(z.name),G=w.find((N)=>N.match.test(B));return G?{service:z,name:B,...G}:null}).filter((z)=>!!z);for(let z of U)J.push({id:`data:${z.name}`,label:z.label,kind:z.kind,layer:6,status:D(z.service.status),sub:z.name,facts:[{label:"Unit",value:z.name},{label:"State",value:j(z.service.status,"unknown")}],href:"/data/services",group:"box"});let V=H.backup??{};if(V.enabled)J.push({id:"backup",label:"Backups",kind:"backup",layer:7,status:"ok",sub:j(V.destination,"destination"),facts:[{label:"Destination",value:j(V.destination,"unknown")},{label:"Schedule",value:j(V.schedule,"unknown")},{label:"Retention",value:`${V.retention??0} copies`},{label:"Last run",value:j(V.last,"unknown")}],href:"/data/backups"});let K=new Set(J.map((z)=>z.id));Q(M,{source:"internet",target:"dns",flow:"request",label:"https"},K),Q(M,{source:"dns",target:"firewall",flow:"request",label:"443/80"},K),Q(M,{source:"firewall",target:"proxy",flow:"request"},K);for(let z of $){let B=`site:${j(z.name)}`;Q(M,{source:"proxy",target:B,flow:"request",label:j(z.path)||void 0,status:D(z.status)},K)}for(let z of Y){let B=`worker:${j(z.name)}`,G=`site:${j(z.site)}`;if(K.has(G))Q(M,{source:G,target:B,flow:"async",label:"queue"},K);else Q(M,{source:"proxy",target:B,flow:"async",label:"queue"},K)}for(let z of Y)Q(M,{source:"scheduler",target:`worker:${j(z.name)}`,flow:"async",label:"dispatch"},K);let S=[...$.map((z)=>`site:${j(z.name)}`),...Y.map((z)=>`worker:${j(z.name)}`)];for(let z of U)for(let B of S)Q(M,{source:B,target:`data:${z.name}`,flow:"data",label:"localhost"},K);if(U.length&&S.length)E.push("Data-service edges show co-location on the box: every process on it can reach localhost. They are not a declared per-site binding.");for(let z of U)Q(M,{source:`data:${z.name}`,target:"backup",flow:"backup",label:"snapshot"},K);for(let z of $)Q(M,{source:`site:${j(z.name)}`,target:"backup",flow:"backup"},K);return{mode:"server",project:j(Z.project)||j(H.project?.name)||j(P.name,"project"),environment:j(Z.environment)||j(H.environment,"production"),provider:j(P.provider,"unknown"),region:j(P.region,"unknown"),generatedAt:new Date().toISOString(),layers:L,groups:[{id:"box",label:j(P.name,"App server"),sub:[j(P.provider),j(P.region),j(P.ip)].filter(Boolean).join(" · ")}],nodes:J,links:M,notes:E}}function p(H,Z={}){let J=[],M=[],E=[],P=H.app??{},$=Array.isArray(H.functions)?H.functions:[],O=Array.isArray(H.queues)?H.queues:[],Y=H.metrics??{};if(!$.length)E.push("No Lambda functions were read for this environment, so the compute layer is empty rather than assumed.");J.push({id:"internet",label:"Internet",kind:"internet",layer:0,status:"ok",sub:"Public traffic",facts:[],external:!0});let I=j(P.url),b=I.replace(/^https?:\/\//,"").split("/")[0];J.push({id:"dns",label:b||"Application domain",kind:"dns",layer:1,status:b?"ok":"unknown",sub:"DNS & certificates",facts:[{label:"Endpoint",value:I||"not resolved"}],external:!0});let _=H.waf;if(_)J.push({id:"waf",label:"WAF",kind:"waf",layer:2,status:D(_.status??"active"),sub:j(_.scope,"Managed rules"),facts:[{label:"Web ACL",value:j(_.name,"unnamed")},..._.blocked!=null?[{label:"Blocked (24h)",value:String(_.blocked)}]:[],{label:"Rules",value:String(h(H.wafRules))}],href:"/serverless/firewall"});let W=H.assetsInfo;if(W)J.push({id:"cdn",label:"Asset CDN",kind:"cdn",layer:2,status:"ok",sub:j(W.cdn,"CloudFront"),facts:[{label:"Distribution",value:j(W.cdn,"unknown")},{label:"Custom domain",value:j(W.customDomain,"none")}],href:"/serverless/assets"}),J.push({id:"assets",label:"Asset bucket",kind:"storage",layer:6,status:"ok",sub:j(W.bucket,"S3"),facts:[{label:"Bucket",value:j(W.bucket,"unknown")},...W.files?[{label:"Objects",value:String(W.files)}]:[],...W.sizeMb?[{label:"Size",value:`${W.sizeMb} MB`}]:[]],href:"/serverless/assets"});let q=$.find((G)=>j(G.key).startsWith("http"));J.push({id:"gateway",label:"HTTP entry point",kind:"gateway",layer:3,status:q?"ok":"unknown",sub:"Function URL / API Gateway",facts:[{label:"Endpoint",value:I||"not resolved"},{label:"Invocations (24h)",value:String(Y.invocations??0)},...Y.errorRatePct!=null?[{label:"Error rate",value:`${Y.errorRatePct}%`}]:[]],href:"/serverless/metrics"});for(let G of $){let N=`fn:${j(G.name)}`;if(!j(G.name))continue;let F=Number(G.errors??0),R=Number(G.invocations??0);J.push({id:N,label:j(G.key,j(G.name)),kind:"function",layer:4,status:F>0?R&&F/R>0.02?"bad":"warn":R?"ok":"idle",sub:j(G.runtime,"lambda"),facts:[{label:"Function",value:j(G.name)},{label:"Memory",value:`${G.memory??0} MB`},{label:"Timeout",value:`${G.timeout??0}s`},{label:"Invocations (24h)",value:String(R)},{label:"Errors (24h)",value:String(F)},{label:"p95",value:`${G.p95??0} ms`},...G.provisioned?[{label:"Provisioned",value:j(G.provisioned)}]:[]],href:"/serverless/functions"})}for(let G of O){let N=`queue:${j(G.name)}`;if(!j(G.name))continue;let F=Number(G.dlq??0);J.push({id:N,label:j(G.name),kind:"queue",layer:5,status:F>0?"bad":Number(G.visible??0)>0?"warn":"ok",sub:"SQS",facts:[{label:"Visible",value:String(G.visible??0)},{label:"In flight",value:String(G.inFlight??0)},{label:"Processed (24h)",value:String(G.processed??0)},{label:"Dead letter",value:String(F)}],href:"/serverless/queues"})}let X=H.aurora;if(X)J.push({id:"database",label:"Aurora Serverless",kind:"database",layer:6,status:D(X.status),sub:j(X.engine,"aurora"),facts:[{label:"Cluster",value:j(X.id,"unknown")},{label:"Capacity",value:`${X.currentAcu??0} ACU (${X.minAcu??0}–${X.maxAcu??0})`},{label:"Connections",value:String(X.connections??0)}],href:"/serverless/data"});let T=H.proxy;if(T)J.push({id:"rds-proxy",label:"RDS Proxy",kind:"database",layer:5,status:D(T.status),sub:"Connection pooling",facts:[{label:"Proxy",value:j(T.name,"unknown")},{label:"Endpoint",value:j(T.endpoint,"unknown")},{label:"Pooled",value:String(T.pooledConns??0)}],href:"/serverless/data"});let A=H.redis;if(A)J.push({id:"cache",label:"ElastiCache",kind:"cache",layer:6,status:D(A.status),sub:j(A.node,"redis"),facts:[{label:"Group",value:j(A.id,"unknown")},{label:"Hit rate",value:`${A.hitRate??0}%`}],href:"/serverless/data"});let C=H.efs;if(C)J.push({id:"efs",label:"EFS",kind:"filesystem",layer:6,status:D(C.status),sub:j(C.mount,"/mnt/local"),facts:[{label:"File system",value:j(C.id,"unknown")},{label:"Mount",value:j(C.mount,"unknown")},{label:"Size",value:`${C.sizeMb??0} MB`}],href:"/data/volumes"});let g=H.scheduler??{};if(g.enabled)J.push({id:"scheduler",label:"Scheduler",kind:"scheduler",layer:3,status:"ok",sub:j(g.expression,"rate(1 minute)"),facts:[{label:"Expression",value:j(g.expression,"unknown")},{label:"Last run",value:j(g.lastRun,"unknown")}],href:"/operations/jobs"});let U=new Set(J.map((G)=>G.id)),V=U.has("waf")?"waf":"gateway";Q(M,{source:"internet",target:"dns",flow:"request",label:"https"},U),Q(M,{source:"dns",target:V,flow:"request"},U),Q(M,{source:"dns",target:"cdn",flow:"request",label:"assets"},U),Q(M,{source:"waf",target:"gateway",flow:"request",label:"allowed"},U),Q(M,{source:"cdn",target:"assets",flow:"data",label:"origin"},U);let K=$.filter((G)=>j(G.key).startsWith("http")),S=$.filter((G)=>j(G.key).startsWith("queue")),z=$.filter((G)=>j(G.key).startsWith("cli"));for(let G of K)Q(M,{source:"gateway",target:`fn:${j(G.name)}`,flow:"request",label:"invoke"},U);for(let G of z)Q(M,{source:"scheduler",target:`fn:${j(G.name)}`,flow:"async",label:"schedule"},U);for(let G of O){for(let N of K)Q(M,{source:`fn:${j(N.name)}`,target:`queue:${j(G.name)}`,flow:"async",label:"publish"},U);for(let N of S)Q(M,{source:`queue:${j(G.name)}`,target:`fn:${j(N.name)}`,flow:"async",label:"consume"},U)}let B=["rds-proxy","database","cache","efs","assets"];for(let G of $){let N=`fn:${j(G.name)}`;if(U.has("rds-proxy"))Q(M,{source:N,target:"rds-proxy",flow:"data",label:"pooled"},U);else Q(M,{source:N,target:"database",flow:"data",label:"sql"},U);for(let F of B.filter((R)=>R!=="rds-proxy"&&R!=="database"))Q(M,{source:N,target:F,flow:"data"},U)}return Q(M,{source:"rds-proxy",target:"database",flow:"data",label:"sql"},U),{mode:"serverless",project:j(Z.project)||j(P.name,"application"),environment:j(Z.environment)||j(P.env,"production"),provider:"aws",region:j(P.region,"unknown"),generatedAt:new Date().toISOString(),layers:m,groups:[],nodes:J,links:M,notes:E}}
|
|
2
|
-
export{v as Sf,p as Tf};
|