@stacksjs/ts-cloud 0.16.34 → 0.16.35
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/aws/index.js +1 -1
- package/dist/bin/{chunk-qay67r71.js → chunk-16kx70x7.js} +112 -112
- package/dist/bin/chunk-1k9sw5y7.js +1 -0
- package/dist/bin/{chunk-47q37egd.js → chunk-27mfrb34.js} +3 -3
- package/dist/bin/chunk-2cx4k97r.js +1 -0
- package/dist/bin/{chunk-wef81maa.js → chunk-2qdktx9h.js} +2 -2
- package/dist/bin/chunk-2rcwhdx9.js +1 -0
- package/dist/bin/chunk-3gg55dkc.js +1 -0
- package/dist/bin/chunk-3pbbc03q.js +1 -0
- package/dist/bin/{chunk-a3vraghd.js → chunk-4mt7rspg.js} +2 -2
- package/dist/bin/{chunk-s38txg38.js → chunk-5yv95sqs.js} +2 -2
- package/dist/bin/chunk-683zr91n.js +1 -0
- package/dist/bin/chunk-691k55nw.js +1 -0
- package/dist/bin/{chunk-7x727gt5.js → chunk-71jh460j.js} +7 -7
- package/dist/bin/chunk-7n84q4np.js +1 -0
- package/dist/bin/{chunk-s6qnx8a8.js → chunk-7rwc5bvv.js} +6 -6
- package/dist/bin/chunk-8pnm151y.js +1 -0
- package/dist/bin/{chunk-szpqbbyr.js → chunk-9n3wmdd6.js} +5 -5
- package/dist/bin/{chunk-66g6jdgy.js → chunk-a0cvd2ez.js} +3 -3
- package/dist/bin/{chunk-8za3y7q3.js → chunk-ar6bxdv4.js} +3 -3
- package/dist/bin/{chunk-5tfxp3d9.js → chunk-bfzdbe4g.js} +7 -7
- package/dist/bin/{chunk-8ba9t3hv.js → chunk-bqcqzc30.js} +3 -3
- package/dist/bin/{chunk-v0va4547.js → chunk-c8439azc.js} +2 -2
- package/dist/bin/{chunk-3kyny1x7.js → chunk-cm1dsffd.js} +6 -6
- package/dist/bin/{chunk-wq4hkbgj.js → chunk-cn5tfp7t.js} +69 -69
- package/dist/bin/{chunk-hs5a6dhm.js → chunk-cnwncp50.js} +5 -5
- package/dist/bin/{chunk-59f6mqkj.js → chunk-d5q09rxb.js} +3 -3
- package/dist/bin/chunk-dd567z84.js +1 -0
- package/dist/bin/chunk-dgxzk04r.js +1 -0
- package/dist/bin/chunk-e7h2j23x.js +1 -0
- package/dist/bin/chunk-e9mkg5dn.js +1 -0
- package/dist/bin/{chunk-dgad3hwh.js → chunk-exc2mqcc.js} +16 -16
- package/dist/bin/{chunk-4c4s5yph.js → chunk-gbpmgae9.js} +2 -2
- package/dist/bin/chunk-h5darb19.js +1 -0
- package/dist/bin/{chunk-hpzbvc4a.js → chunk-haqap7d1.js} +2 -2
- package/dist/bin/chunk-hc4s84v1.js +1 -0
- package/dist/bin/chunk-hfswzdzj.js +1 -0
- package/dist/bin/{chunk-rkd3x7fw.js → chunk-j01jx36v.js} +2 -2
- package/dist/bin/chunk-p5k5z7gm.js +1 -0
- package/dist/bin/{chunk-sfb9q18c.js → chunk-qbagghsb.js} +283 -295
- package/dist/bin/chunk-qfkfhg84.js +1 -0
- package/dist/bin/chunk-qxg95ndf.js +2 -0
- package/dist/bin/{chunk-a1zagtx1.js → chunk-r3gxhy1k.js} +6 -6
- package/dist/bin/{chunk-7kjy2hng.js → chunk-r8e263ne.js} +5 -5
- package/dist/bin/chunk-s4x1pb7n.js +1 -0
- package/dist/bin/{chunk-70w9nss5.js → chunk-s7f24j6k.js} +1 -1
- package/dist/bin/chunk-svrgx20b.js +14 -0
- package/dist/bin/chunk-tcstvf11.js +1 -0
- package/dist/bin/chunk-th86qyty.js +1 -0
- package/dist/bin/chunk-tj589nbw.js +1 -0
- package/dist/bin/chunk-tv0rtc0s.js +2 -0
- package/dist/bin/{chunk-7k52s3qm.js → chunk-twmeg17s.js} +6 -6
- package/dist/bin/{chunk-nnxkw5pn.js → chunk-v3dck0e4.js} +2 -2
- package/dist/bin/{chunk-mzzrnkk5.js → chunk-v3prk467.js} +5 -5
- package/dist/bin/{chunk-4vbnagyd.js → chunk-v4gpkkzh.js} +1 -1
- package/dist/bin/{chunk-49y286vw.js → chunk-vkdw6sxn.js} +1 -1
- package/dist/bin/chunk-x8wvsf1k.js +1 -0
- package/dist/bin/chunk-y1qk3df2.js +1 -0
- package/dist/bin/{chunk-hbrb314y.js → chunk-y2qz4vw1.js} +1 -1
- package/dist/bin/{chunk-wc5swv1a.js → chunk-ymfnqae6.js} +2 -2
- package/dist/bin/{chunk-0wtnhxdt.js → chunk-yt95wsqg.js} +1 -1
- package/dist/bin/chunk-zjw9sdr5.js +1 -0
- package/dist/bin/{chunk-mb2fh91q.js → chunk-zmp0mksb.js} +2 -2
- package/dist/bin/cli.js +347 -347
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/{chunk-pkpmz35j.js → chunk-0kddm2mt.js} +7 -7
- package/dist/chunk-0my5jwq8.js +1 -0
- package/dist/chunk-3nqtbyfp.js +14 -0
- package/dist/{chunk-v9t4751b.js → chunk-50m6sq01.js} +5 -5
- package/dist/{chunk-g3f3ccdw.js → chunk-7gvnrx46.js} +4 -4
- package/dist/{chunk-444h366b.js → chunk-906prq6g.js} +6 -6
- package/dist/{chunk-0pe1dfy0.js → chunk-9aaj9a0s.js} +520 -533
- package/dist/{chunk-pqm7fz1d.js → chunk-abadztwc.js} +165 -165
- package/dist/{chunk-jp57js5y.js → chunk-ajn6xp8v.js} +3 -3
- package/dist/{chunk-29dcfx1g.js → chunk-annmzhbb.js} +81 -81
- package/dist/{chunk-qad1mjmc.js → chunk-c97wwdtk.js} +9 -9
- package/dist/{chunk-6n72pe9x.js → chunk-ctkzxq0d.js} +2 -2
- package/dist/chunk-f2xqeers.js +1 -0
- package/dist/chunk-f4m9k2q6.js +1 -0
- package/dist/{chunk-9r32w840.js → chunk-fszn9rnn.js} +43 -43
- package/dist/chunk-fxk29btr.js +1 -0
- package/dist/chunk-fz62nas4.js +1 -0
- package/dist/{chunk-wctam3r1.js → chunk-hvwqct5q.js} +2 -2
- package/dist/{chunk-45116tdd.js → chunk-jch6ks7a.js} +3 -3
- package/dist/chunk-kcj92xx7.js +2 -0
- package/dist/chunk-kzjvasjs.js +2 -0
- package/dist/{chunk-v1wqxgra.js → chunk-mxw5gkd8.js} +2 -2
- package/dist/{chunk-n4gkyye3.js → chunk-my6yn5sd.js} +2 -2
- package/dist/{chunk-y3dj8xwk.js → chunk-n4z75mk8.js} +4 -4
- package/dist/{chunk-nmm287ym.js → chunk-nr6z3e1p.js} +4 -4
- package/dist/{chunk-s958jt49.js → chunk-p0ksat08.js} +1 -1
- package/dist/{chunk-m1jp1abp.js → chunk-pdjap529.js} +2 -2
- package/dist/{chunk-e08h4q50.js → chunk-pfav9qnt.js} +7 -7
- package/dist/{chunk-y3h0ybmn.js → chunk-sekw1nyx.js} +19 -19
- package/dist/{chunk-tzvtq055.js → chunk-tez0qfv9.js} +1 -1
- package/dist/{chunk-k3azr9e3.js → chunk-tsaffke7.js} +3 -3
- package/dist/chunk-yhjagaff.js +1 -0
- package/dist/{chunk-c6nw88s3.js → chunk-yzns0k2b.js} +2 -2
- package/dist/deploy/index.js +1 -1
- package/dist/dns/index.js +1 -1
- package/dist/drivers/index.js +1 -1
- package/dist/index.js +87 -87
- package/dist/operations/index.js +1 -1
- package/dist/protection/index.js +1 -1
- package/dist/spend/index.js +1 -1
- 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 +6 -6
- package/dist/ui/account/security.html +2 -2
- package/dist/ui/applications/compose.html +5 -5
- package/dist/ui/applications/new.html +2 -2
- package/dist/ui/data/backups.html +5 -5
- package/dist/ui/data/services.html +6 -6
- package/dist/ui/data/volumes.html +6 -6
- package/dist/ui/index.html +5 -5
- package/dist/ui/infrastructure/topology.html +6 -6
- package/dist/ui/integrations.html +2 -2
- package/dist/ui/operations/alerts.html +6 -6
- package/dist/ui/operations/configuration.html +5 -5
- package/dist/ui/operations/jobs.html +6 -6
- package/dist/ui/operations/maintenance.html +6 -6
- package/dist/ui/operations/observability.html +5 -5
- package/dist/ui/operations/previews.html +6 -6
- package/dist/ui/operations/queue.html +5 -5
- package/dist/ui/operations/regions.html +6 -6
- package/dist/ui/operations/releases.html +5 -5
- package/dist/ui/operations/spend.html +5 -5
- package/dist/ui/operations/workloads.html +6 -6
- package/dist/ui/security.html +2 -2
- package/dist/ui/server/actions.html +6 -6
- package/dist/ui/server/activity.html +1 -1
- package/dist/ui/server/capacity.html +6 -6
- package/dist/ui/server/database.html +6 -6
- package/dist/ui/server/deployments.html +6 -6
- package/dist/ui/server/diagnostics.html +2 -2
- package/dist/ui/server/firewall.html +6 -6
- package/dist/ui/server/fleet.html +6 -6
- package/dist/ui/server/logs.html +6 -6
- package/dist/ui/server/metrics.html +6 -6
- package/dist/ui/server/security.html +1 -1
- package/dist/ui/server/services.html +2 -2
- package/dist/ui/server/sites.html +6 -6
- package/dist/ui/server/ssh-keys.html +6 -6
- package/dist/ui/server/team.html +6 -6
- package/dist/ui/server/terminal.html +2 -2
- package/dist/ui/serverless/alarms.html +6 -6
- package/dist/ui/serverless/assets.html +2 -2
- package/dist/ui/serverless/cost.html +2 -2
- package/dist/ui/serverless/data.html +6 -6
- package/dist/ui/serverless/deployments.html +2 -2
- package/dist/ui/serverless/firewall.html +2 -2
- package/dist/ui/serverless/functions.html +6 -6
- package/dist/ui/serverless/logs.html +6 -6
- package/dist/ui/serverless/metrics.html +2 -2
- package/dist/ui/serverless/queues.html +6 -6
- package/dist/ui/serverless/secrets.html +6 -6
- package/dist/ui/serverless/traces.html +6 -6
- package/dist/ui/serverless.html +6 -6
- package/package.json +3 -3
- package/dist/bin/chunk-1ye6ky7s.js +0 -1
- package/dist/bin/chunk-2njcbs0c.js +0 -1
- package/dist/bin/chunk-35ct309x.js +0 -1
- package/dist/bin/chunk-3ybxaehy.js +0 -1
- package/dist/bin/chunk-5p9jnpg2.js +0 -1
- package/dist/bin/chunk-9aram0sm.js +0 -1
- package/dist/bin/chunk-9jmt42fx.js +0 -1
- package/dist/bin/chunk-axwpxssn.js +0 -1
- package/dist/bin/chunk-cqc4pc2h.js +0 -1
- package/dist/bin/chunk-cxde3tbf.js +0 -1
- package/dist/bin/chunk-d0xz1vh3.js +0 -1
- package/dist/bin/chunk-d2wm1zy3.js +0 -1
- package/dist/bin/chunk-hnwdjkrt.js +0 -1
- package/dist/bin/chunk-hrvfz72e.js +0 -1
- package/dist/bin/chunk-j4d7h8rh.js +0 -1
- package/dist/bin/chunk-jsncf48k.js +0 -2
- package/dist/bin/chunk-k178k5re.js +0 -1
- package/dist/bin/chunk-k5h2a7a8.js +0 -1
- package/dist/bin/chunk-nw8wmbmq.js +0 -2
- package/dist/bin/chunk-prz0w9pq.js +0 -1
- package/dist/bin/chunk-rhjjdhhq.js +0 -1
- package/dist/bin/chunk-rv7epkg1.js +0 -1
- package/dist/bin/chunk-tftcv9rt.js +0 -1
- package/dist/bin/chunk-yd2155bj.js +0 -1
- package/dist/bin/chunk-yqefsck4.js +0 -1
- package/dist/bin/chunk-yzyt35ys.js +0 -1
- package/dist/chunk-4nfjkggt.js +0 -1
- package/dist/chunk-7r2qc39k.js +0 -2
- package/dist/chunk-8nafnyax.js +0 -1
- package/dist/chunk-e3831mvy.js +0 -1
- package/dist/chunk-rqe0sfqw.js +0 -2
- package/dist/chunk-xask9f1n.js +0 -1
- package/dist/chunk-xrr334m5.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ft,u}from"./chunk-s6qnx8a8.js";import{g}from"./chunk-59f6mqkj.js";import{B}from"./chunk-wc5swv1a.js";import{x}from"./chunk-jsncf48k.js";import{gi}from"./chunk-nw8wmbmq.js";function R(e,t){let r=[`Action=${e}`,"Version=2010-05-08"];for(let[a,i]of Object.entries(t)){if(i===void 0||i===null)continue;if(Array.isArray(i))i.forEach((n,o)=>{if(typeof n==="object"&&n!==null)for(let[m,l]of Object.entries(n))r.push(`${a}.member.${o+1}.${m}=${encodeURIComponent(String(l))}`);else r.push(`${a}.member.${o+1}=${encodeURIComponent(String(n))}`)});else if(typeof i==="object"){for(let[n,o]of Object.entries(i))if(o!==void 0&&o!==null)r.push(`${a}.${n}=${encodeURIComponent(String(o))}`)}else r.push(`${a}=${encodeURIComponent(String(i))}`)}return r.join("&")}var f=new Ft({ignoreAttributes:!0,parseTagValue:!1,trimValues:!0});function S(e){if(typeof e!=="string"||!e.trim())return{};return f.parse(e)}function s(e,t){let r=[e];while(r.length>0){let a=[];for(let i of r){if(!i||typeof i!=="object")continue;if(Array.isArray(i)){a.push(...i);continue}if(t in i){let n=i[t];return typeof n==="string"?n:void 0}a.push(...Object.values(i))}r=a}return}function c(e,t,r){let a=[e];while(a.length>0){let i=[];for(let n of a){if(!n||typeof n!=="object")continue;if(Array.isArray(n)){i.push(...n);continue}if(t in n){let o=n[t]?.[r];return o===void 0||o===null?[]:Array.isArray(o)?o:[o]}i.push(...Object.values(n))}a=i}return[]}class ee{client;region;constructor(e="us-east-1",t){this.client=new u(void 0,{profile:t}),this.region=e}async request(e,t={}){let r=R(e,t),a=await this.client.request({service:"iam",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r,rawResponse:!0});return S(a)}async createUser(e){let t=await this.request("CreateUser",e);return this.parseUser(t)}async getUser(e={}){let t=await this.request("GetUser",e);return this.parseUser(t)}async listUsers(e={}){let t=await this.request("ListUsers",e),r=this.parseUsers(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Users:r,IsTruncated:a,Marker:i}}async updateUser(e){await this.request("UpdateUser",e)}async deleteUser(e){await this.request("DeleteUser",e)}parseUser(e){return{UserName:s(e,"UserName")||"",UserId:s(e,"UserId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),CreateDate:s(e,"CreateDate"),PasswordLastUsed:s(e,"PasswordLastUsed")}}parseUsers(e){return c(e,"Users","member").map((r)=>({UserName:s(r,"UserName")||"",UserId:s(r,"UserId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),CreateDate:s(r,"CreateDate"),PasswordLastUsed:s(r,"PasswordLastUsed")}))}async createGroup(e){let t=await this.request("CreateGroup",e);return this.parseGroup(t)}async getGroup(e){let t=await this.request("GetGroup",e),r=this.parseGroup(t),a=this.parseUsers(t),i=s(t,"IsTruncated")==="true",n=s(t,"Marker");return{Group:r,Users:a,IsTruncated:i,Marker:n}}async listGroups(e={}){let t=await this.request("ListGroups",e),r=this.parseGroups(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Groups:r,IsTruncated:a,Marker:i}}async updateGroup(e){await this.request("UpdateGroup",e)}async deleteGroup(e){await this.request("DeleteGroup",e)}async addUserToGroup(e){await this.request("AddUserToGroup",e)}async removeUserFromGroup(e){await this.request("RemoveUserFromGroup",e)}async listGroupsForUser(e){let t=await this.request("ListGroupsForUser",e),r=this.parseGroups(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Groups:r,IsTruncated:a,Marker:i}}parseGroup(e){return{GroupName:s(e,"GroupName")||"",GroupId:s(e,"GroupId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),CreateDate:s(e,"CreateDate")}}parseGroups(e){return c(e,"Groups","member").map((r)=>({GroupName:s(r,"GroupName")||"",GroupId:s(r,"GroupId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),CreateDate:s(r,"CreateDate")}))}async createRole(e){let t=await this.request("CreateRole",e);return this.parseRole(t)}async getRole(e){let t=await this.request("GetRole",e);return this.parseRole(t)}async listRoles(e={}){let t=await this.request("ListRoles",e),r=this.parseRoles(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Roles:r,IsTruncated:a,Marker:i}}async updateRole(e){await this.request("UpdateRole",e)}async updateRoleDescription(e){let t=await this.request("UpdateRoleDescription",e);return this.parseRole(t)}async updateAssumeRolePolicy(e){await this.request("UpdateAssumeRolePolicy",e)}async deleteRole(e){await this.request("DeleteRole",e)}async tagRole(e){await this.request("TagRole",e)}async untagRole(e){await this.request("UntagRole",e)}async listRoleTags(e){let t=await this.request("ListRoleTags",e),r=this.parseTags(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Tags:r,IsTruncated:a,Marker:i}}parseRole(e){return{RoleName:s(e,"RoleName")||"",RoleId:s(e,"RoleId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),CreateDate:s(e,"CreateDate"),AssumeRolePolicyDocument:s(e,"AssumeRolePolicyDocument"),Description:s(e,"Description"),MaxSessionDuration:s(e,"MaxSessionDuration")?Number.parseInt(s(e,"MaxSessionDuration"),10):void 0}}parseRoles(e){return c(e,"Roles","member").map((r)=>({RoleName:s(r,"RoleName")||"",RoleId:s(r,"RoleId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),CreateDate:s(r,"CreateDate"),AssumeRolePolicyDocument:s(r,"AssumeRolePolicyDocument"),Description:s(r,"Description"),MaxSessionDuration:s(r,"MaxSessionDuration")?Number.parseInt(s(r,"MaxSessionDuration"),10):void 0}))}parseTags(e){return c(e,"Tags","member").map((r)=>({Key:s(r,"Key")||"",Value:s(r,"Value")||""}))}async createPolicy(e){let t=await this.request("CreatePolicy",e);return this.parsePolicy(t)}async getPolicy(e){let t=await this.request("GetPolicy",e);return this.parsePolicy(t)}async getPolicyVersion(e){let t=await this.request("GetPolicyVersion",e);return{VersionId:s(t,"VersionId")||"",IsDefaultVersion:s(t,"IsDefaultVersion")==="true",CreateDate:s(t,"CreateDate"),Document:s(t,"Document")}}async listPolicies(e={}){let t=await this.request("ListPolicies",e),r=this.parsePolicies(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Policies:r,IsTruncated:a,Marker:i}}async listPolicyVersions(e){let t=await this.request("ListPolicyVersions",e),r=this.parsePolicyVersions(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Versions:r,IsTruncated:a,Marker:i}}async createPolicyVersion(e){let t=await this.request("CreatePolicyVersion",e);return{VersionId:s(t,"VersionId")||"",IsDefaultVersion:s(t,"IsDefaultVersion")==="true",CreateDate:s(t,"CreateDate")}}async deletePolicyVersion(e){await this.request("DeletePolicyVersion",e)}async setDefaultPolicyVersion(e){await this.request("SetDefaultPolicyVersion",e)}async deletePolicy(e){await this.request("DeletePolicy",e)}async attachUserPolicy(e){await this.request("AttachUserPolicy",e)}async detachUserPolicy(e){await this.request("DetachUserPolicy",e)}async attachGroupPolicy(e){await this.request("AttachGroupPolicy",e)}async detachGroupPolicy(e){await this.request("DetachGroupPolicy",e)}async attachRolePolicy(e){await this.request("AttachRolePolicy",e)}async detachRolePolicy(e){await this.request("DetachRolePolicy",e)}async listAttachedUserPolicies(e){let t=await this.request("ListAttachedUserPolicies",e),r=this.parseAttachedPolicies(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{AttachedPolicies:r,IsTruncated:a,Marker:i}}async listAttachedGroupPolicies(e){let t=await this.request("ListAttachedGroupPolicies",e),r=this.parseAttachedPolicies(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{AttachedPolicies:r,IsTruncated:a,Marker:i}}async listAttachedRolePolicies(e){let t=await this.request("ListAttachedRolePolicies",e),r=this.parseAttachedPolicies(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{AttachedPolicies:r,IsTruncated:a,Marker:i}}parsePolicy(e){return{PolicyName:s(e,"PolicyName")||"",PolicyId:s(e,"PolicyId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),DefaultVersionId:s(e,"DefaultVersionId"),AttachmentCount:s(e,"AttachmentCount")?Number.parseInt(s(e,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:s(e,"PermissionsBoundaryUsageCount")?Number.parseInt(s(e,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:s(e,"IsAttachable")==="true",Description:s(e,"Description"),CreateDate:s(e,"CreateDate"),UpdateDate:s(e,"UpdateDate")}}parsePolicies(e){return c(e,"Policies","member").map((r)=>({PolicyName:s(r,"PolicyName")||"",PolicyId:s(r,"PolicyId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),DefaultVersionId:s(r,"DefaultVersionId"),AttachmentCount:s(r,"AttachmentCount")?Number.parseInt(s(r,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:s(r,"PermissionsBoundaryUsageCount")?Number.parseInt(s(r,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:s(r,"IsAttachable")==="true",Description:s(r,"Description"),CreateDate:s(r,"CreateDate"),UpdateDate:s(r,"UpdateDate")}))}parsePolicyVersions(e){return c(e,"Versions","member").map((r)=>({VersionId:s(r,"VersionId")||"",IsDefaultVersion:s(r,"IsDefaultVersion")==="true",CreateDate:s(r,"CreateDate")}))}parseAttachedPolicies(e){return c(e,"AttachedPolicies","member").map((r)=>({PolicyName:s(r,"PolicyName")||"",PolicyArn:s(r,"PolicyArn")||""}))}async putUserPolicy(e){await this.request("PutUserPolicy",e)}async getUserPolicy(e){let t=await this.request("GetUserPolicy",e);return{UserName:s(t,"UserName")||"",PolicyName:s(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(s(t,"PolicyDocument")||"")}}async deleteUserPolicy(e){await this.request("DeleteUserPolicy",e)}async listUserPolicies(e){let t=await this.request("ListUserPolicies",e),r=c(t,"PolicyNames","member"),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{PolicyNames:r,IsTruncated:a,Marker:i}}async putGroupPolicy(e){await this.request("PutGroupPolicy",e)}async getGroupPolicy(e){let t=await this.request("GetGroupPolicy",e);return{GroupName:s(t,"GroupName")||"",PolicyName:s(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(s(t,"PolicyDocument")||"")}}async deleteGroupPolicy(e){await this.request("DeleteGroupPolicy",e)}async listGroupPolicies(e){let t=await this.request("ListGroupPolicies",e),r=c(t,"PolicyNames","member"),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{PolicyNames:r,IsTruncated:a,Marker:i}}async putRolePolicy(e){await this.request("PutRolePolicy",e)}async getRolePolicy(e){let t=await this.request("GetRolePolicy",e);return{RoleName:s(t,"RoleName")||"",PolicyName:s(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(s(t,"PolicyDocument")||"")}}async deleteRolePolicy(e){await this.request("DeleteRolePolicy",e)}async listRolePolicies(e){let t=await this.request("ListRolePolicies",e),r=c(t,"PolicyNames","member"),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{PolicyNames:r,IsTruncated:a,Marker:i}}async createAccessKey(e={}){let t=await this.request("CreateAccessKey",e);if(typeof t==="object"){let r=t?.CreateAccessKeyResult?.AccessKey||t?.AccessKey;if(r)return{AccessKey:{UserName:r.UserName||"",AccessKeyId:r.AccessKeyId||"",Status:r.Status||"Active",SecretAccessKey:r.SecretAccessKey||"",CreateDate:r.CreateDate}}}return{AccessKey:{UserName:s(t,"UserName")||"",AccessKeyId:s(t,"AccessKeyId")||"",Status:s(t,"Status")||"Active",SecretAccessKey:s(t,"SecretAccessKey")||"",CreateDate:s(t,"CreateDate")}}}async listAccessKeys(e={}){let t=await this.request("ListAccessKeys",e),r=this.parseAccessKeys(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{AccessKeyMetadata:r,IsTruncated:a,Marker:i}}async updateAccessKey(e){await this.request("UpdateAccessKey",e)}async deleteAccessKey(e){await this.request("DeleteAccessKey",e)}async getAccessKeyLastUsed(e){let t=await this.request("GetAccessKeyLastUsed",e);return{UserName:s(t,"UserName")||"",AccessKeyLastUsed:{LastUsedDate:s(t,"LastUsedDate"),ServiceName:s(t,"ServiceName"),Region:s(t,"Region")}}}parseAccessKeys(e){return c(e,"AccessKeyMetadata","member").map((r)=>({UserName:s(r,"UserName"),AccessKeyId:s(r,"AccessKeyId")||"",Status:s(r,"Status")||"Active",CreateDate:s(r,"CreateDate")}))}async createInstanceProfile(e){let t=await this.request("CreateInstanceProfile",e);return this.parseInstanceProfile(t)}async getInstanceProfile(e){let t=await this.request("GetInstanceProfile",e);return this.parseInstanceProfile(t)}async listInstanceProfiles(e={}){let t=await this.request("ListInstanceProfiles",e),r=this.parseInstanceProfiles(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{InstanceProfiles:r,IsTruncated:a,Marker:i}}async listInstanceProfilesForRole(e){let t=await this.request("ListInstanceProfilesForRole",e),r=this.parseInstanceProfiles(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{InstanceProfiles:r,IsTruncated:a,Marker:i}}async addRoleToInstanceProfile(e){await this.request("AddRoleToInstanceProfile",e)}async removeRoleFromInstanceProfile(e){await this.request("RemoveRoleFromInstanceProfile",e)}async deleteInstanceProfile(e){await this.request("DeleteInstanceProfile",e)}parseInstanceProfile(e){return{InstanceProfileName:s(e,"InstanceProfileName")||"",InstanceProfileId:s(e,"InstanceProfileId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),CreateDate:s(e,"CreateDate")}}parseInstanceProfiles(e){return c(e,"InstanceProfiles","member").map((r)=>({InstanceProfileName:s(r,"InstanceProfileName")||"",InstanceProfileId:s(r,"InstanceProfileId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),CreateDate:s(r,"CreateDate")}))}async getAccountPasswordPolicy(){let e=await this.request("GetAccountPasswordPolicy");return{MinimumPasswordLength:s(e,"MinimumPasswordLength")?Number.parseInt(s(e,"MinimumPasswordLength"),10):void 0,RequireSymbols:s(e,"RequireSymbols")==="true",RequireNumbers:s(e,"RequireNumbers")==="true",RequireUppercaseCharacters:s(e,"RequireUppercaseCharacters")==="true",RequireLowercaseCharacters:s(e,"RequireLowercaseCharacters")==="true",AllowUsersToChangePassword:s(e,"AllowUsersToChangePassword")==="true",ExpirePasswords:s(e,"ExpirePasswords")==="true",MaxPasswordAge:s(e,"MaxPasswordAge")?Number.parseInt(s(e,"MaxPasswordAge"),10):void 0,PasswordReusePrevention:s(e,"PasswordReusePrevention")?Number.parseInt(s(e,"PasswordReusePrevention"),10):void 0,HardExpiry:s(e,"HardExpiry")==="true"}}async updateAccountPasswordPolicy(e){await this.request("UpdateAccountPasswordPolicy",e)}async deleteAccountPasswordPolicy(){await this.request("DeleteAccountPasswordPolicy")}async getAccountSummary(){let e=await this.request("GetAccountSummary"),t={},r=c(e,"SummaryMap","entry");for(let a of r){let i=s(a,"key"),n=s(a,"value");if(i&&n)t[i]=Number.parseInt(n,10)}return t}async listAccountAliases(){let e=await this.request("ListAccountAliases"),t=c(e,"AccountAliases","member"),r=s(e,"IsTruncated")==="true",a=s(e,"Marker");return{AccountAliases:t,IsTruncated:r,Marker:a}}async createAccountAlias(e){await this.request("CreateAccountAlias",e)}async deleteAccountAlias(e){await this.request("DeleteAccountAlias",e)}async simulatePrincipalPolicy(e){let t=await this.request("SimulatePrincipalPolicy",e);return this.parseSimulationResults(t)}parseSimulationResults(e){let r=c(e,"EvaluationResults","member").map((n)=>{let m=c(n,"MatchedStatements","member").map((l)=>({SourcePolicyId:s(l,"SourcePolicyId"),SourcePolicyType:s(l,"SourcePolicyType")}));return{EvalActionName:s(n,"EvalActionName")||"",EvalResourceName:s(n,"EvalResourceName"),EvalDecision:s(n,"EvalDecision")||"",MatchedStatements:m.length>0?m:void 0}}),a=s(e,"IsTruncated")==="true",i=s(e,"Marker");return{EvaluationResults:r,IsTruncated:a,Marker:i}}}class be{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new u(t)}async createEmailIdentity(e){return await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/identities",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async getEmailIdentity(e){let t=await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/identities/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}});return{IdentityType:t.IdentityType,IdentityName:e,SendingEnabled:t.VerifiedForSendingStatus,VerificationStatus:t.VerificationStatus,DkimAttributes:t.DkimAttributes,MailFromAttributes:t.MailFromAttributes}}async putEmailIdentityMailFromAttributes(e,t){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(e)}/mail-from`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async listEmailIdentities(e){let t="/v2/email/identities",r=[];if(e?.PageSize)r.push(`PageSize=${e.PageSize}`);if(e?.NextToken)r.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(r.length>0)t+=`?${r.join("&")}`;let a=await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}});return{EmailIdentities:a.EmailIdentities,NextToken:a.NextToken}}async deleteEmailIdentity(e){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/identities/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async putEmailIdentityDkimAttributes(e){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(e.EmailIdentity)}/dkim`,headers:{"Content-Type":"application/json"},body:JSON.stringify({SigningEnabled:e.SigningEnabled})})}async sendEmail(e){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(e)})).MessageId}}async sendBulkEmail(e){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(e)})).BulkEmailEntryResults}}async createEmailTemplate(e){await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/templates",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async getEmailTemplate(e){return await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/templates/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async deleteEmailTemplate(e){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/templates/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async listEmailTemplates(e){let t="/v2/email/templates",r=[];if(e?.PageSize)r.push(`PageSize=${e.PageSize}`);if(e?.NextToken)r.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(r.length>0)t+=`?${r.join("&")}`;return await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}})}async getSendStatistics(){let e=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"}),t=x(e,"GetSendStatistics")?.SendDataPoints?.member;return{SendDataPoints:t==null?[]:Array.isArray(t)?t:[t]}}async getSendQuota(){let e=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"}),t=x(e,"GetSendQuota"),r=(a)=>a==null||a===""?void 0:Number(a);return{Max24HourSend:r(t?.Max24HourSend),MaxSendRate:r(t?.MaxSendRate),SentLast24Hours:r(t?.SentLast24Hours)}}async verifyDomain(e){let t=await this.createEmailIdentity({EmailIdentity:e});return{dkimTokens:t.DkimAttributes?.Tokens,verificationStatus:t.DkimAttributes?.Status}}async sendSimpleEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],r=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0,a={};if(e.text)a.Text={Data:e.text};if(e.html)a.Html={Data:e.html};return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Simple:{Subject:{Data:e.subject},Body:a}},ReplyToAddresses:r})}async sendTemplatedEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],r=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0;return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Template:{TemplateName:e.templateName,TemplateData:JSON.stringify(e.templateData)}},ReplyToAddresses:r})}async getDkimRecords(e){let t=await this.getEmailIdentity(e);if(!t.DkimAttributes?.Tokens)return[];return t.DkimAttributes.Tokens.map((r)=>({name:`${r}._domainkey.${e}`,type:"CNAME",value:`${r}.dkim.amazonses.com`}))}async isDomainVerified(e){try{let t=await this.getEmailIdentity(e);return t.VerificationStatus==="SUCCESS"&&t.SendingEnabled===!0}catch{return!1}}async waitForDomainVerification(e,t=60,r=30000){for(let a=0;a<t;a++){if(await this.isDomainVerified(e))return!0;await new Promise((n)=>setTimeout(n,r))}return!1}buildFormBody(e){return Object.entries(e).filter(([,r])=>r!==void 0).map(([r,a])=>`${encodeURIComponent(r)}=${encodeURIComponent(a)}`).join("&")}async createReceiptRuleSet(e){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:e})})}async deleteReceiptRuleSet(e){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:e})})}async setActiveReceiptRuleSet(e){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:e})})}async listReceiptRuleSets(e){let t={Action:"ListReceiptRuleSets",Version:"2010-12-01"};if(e)t.NextToken=e;let r=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)}),a=r?.ListReceiptRuleSetsResponse?.ListReceiptRuleSetsResult||r?.ListReceiptRuleSetsResult,i=a?.RuleSets?.member;return{RuleSets:Array.isArray(i)?i:i?[i]:[],NextToken:a?.NextToken}}async describeReceiptRuleSet(e){let t=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:e})}),r=t?.DescribeReceiptRuleSetResponse?.DescribeReceiptRuleSetResult||t?.DescribeReceiptRuleSetResult,a=r?.Rules?.member;return{Metadata:r?.Metadata,Rules:Array.isArray(a)?a:a?[a]:[]}}async createReceiptRule(e){let t={Action:"CreateReceiptRule",Version:"2010-12-01",RuleSetName:e.RuleSetName,"Rule.Name":e.Rule.Name,"Rule.Enabled":e.Rule.Enabled!==!1?"true":"false"};if(e.Rule.TlsPolicy)t["Rule.TlsPolicy"]=e.Rule.TlsPolicy;if(e.Rule.ScanEnabled!==void 0)t["Rule.ScanEnabled"]=e.Rule.ScanEnabled?"true":"false";if(e.After)t.After=e.After;if(e.Rule.Recipients)e.Rule.Recipients.forEach((r,a)=>{t[`Rule.Recipients.member.${a+1}`]=r});e.Rule.Actions.forEach((r,a)=>{let i=a+1;if(r.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=r.S3Action.BucketName,r.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=r.S3Action.ObjectKeyPrefix;if(r.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=r.S3Action.KmsKeyArn}if(r.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=r.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=r.LambdaAction.InvocationType||"Event";if(r.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=r.SNSAction.TopicArn,r.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=r.SNSAction.Encoding}if(r.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=r.StopAction.Scope,r.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=r.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(t)})}async deleteReceiptRule(e,t){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:e,RuleName:t})})}async receiptRuleSetExists(e){try{return await this.describeReceiptRuleSet(e),!0}catch(t){if(t.code==="RuleSetDoesNotExist"||t.statusCode===400)return!1;throw t}}async getActiveReceiptRuleSet(){let e=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"})}),t=e?.DescribeActiveReceiptRuleSetResponse?.DescribeActiveReceiptRuleSetResult||e?.DescribeActiveReceiptRuleSetResult;if(!t?.Metadata)return null;let r=t?.Rules?.member;return{Metadata:t?.Metadata,Rules:Array.isArray(r)?r:r?[r]:[]}}async updateReceiptRule(e){let t={Action:"UpdateReceiptRule",Version:"2010-12-01",RuleSetName:e.RuleSetName,"Rule.Name":e.Rule.Name};if(e.Rule.Enabled!==void 0)t["Rule.Enabled"]=e.Rule.Enabled?"true":"false";if(e.Rule.TlsPolicy)t["Rule.TlsPolicy"]=e.Rule.TlsPolicy;if(e.Rule.ScanEnabled!==void 0)t["Rule.ScanEnabled"]=e.Rule.ScanEnabled?"true":"false";if(e.Rule.Recipients)e.Rule.Recipients.forEach((r,a)=>{t[`Rule.Recipients.member.${a+1}`]=r});e.Rule.Actions.forEach((r,a)=>{let i=a+1;if(r.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=r.S3Action.BucketName,r.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=r.S3Action.ObjectKeyPrefix;if(r.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=r.S3Action.KmsKeyArn}if(r.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=r.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=r.LambdaAction.InvocationType||"Event";if(r.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=r.SNSAction.TopicArn,r.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=r.SNSAction.Encoding}if(r.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=r.StopAction.Scope,r.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=r.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(t)})}async sendRawEmail(e){let t=Buffer.from(e.rawMessage).toString("base64"),r={Action:"SendRawEmail",Version:"2010-12-01",Source:e.source,"RawMessage.Data":t};e.destinations.forEach((n,o)=>{r[`Destinations.member.${o+1}`]=n});let a=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(r)});return{MessageId:(a?.SendRawEmailResponse?.SendRawEmailResult||a?.SendRawEmailResult)?.MessageId}}async getSuppressedDestination(e){try{return(await this.client.request({service:"ses",region:this.region,method:"GET",path:`/v2/email/suppression/addresses/${encodeURIComponent(e)}`}))?.SuppressedDestination||null}catch(t){if(t.message?.includes("404")||t.message?.includes("NotFoundException"))return null;throw t}}async deleteSuppressedDestination(e){await this.client.request({service:"ses",region:this.region,method:"DELETE",path:`/v2/email/suppression/addresses/${encodeURIComponent(e)}`})}}class fc{ses;s3;iam;route53;region;domain;defaultFrom;constructor(e={}){this.region=e.region||"us-east-1",this.domain=e.domain,this.defaultFrom=e.defaultFrom,this.ses=new be(this.region),this.s3=new g(this.region),this.iam=new ee(this.region),this.route53=new B(this.region)}async send(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required. Set defaultFrom in constructor or provide from in options.");let r=e.fromName?`${e.fromName} <${t}>`:t,a=Array.isArray(e.to)?e.to:[e.to];if(!e.attachments||e.attachments.length===0)return{messageId:(await this.ses.sendSimpleEmail({from:r,to:a,subject:e.subject,text:e.text,html:e.html,replyTo:e.replyTo})).MessageId||""};let i=this.buildRawEmail(e,r,a);return{messageId:(await this.ses.sendEmail({FromEmailAddress:r,Destination:{ToAddresses:a,CcAddresses:e.cc?Array.isArray(e.cc)?e.cc:[e.cc]:void 0,BccAddresses:e.bcc?Array.isArray(e.bcc)?e.bcc:[e.bcc]:void 0},Content:{Raw:{Data:Buffer.from(i).toString("base64")}}})).MessageId||""}}async sendTemplate(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required");let r=e.fromName?`${e.fromName} <${t}>`:t;return{messageId:(await this.ses.sendTemplatedEmail({from:r,to:e.to,templateName:e.templateName,templateData:e.templateData,replyTo:e.replyTo})).MessageId||""}}async sendBulk(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required");let r=e.recipients.map((i)=>({Destination:{ToAddresses:Array.isArray(i.to)?i.to:[i.to]},ReplacementEmailContent:i.templateData?{ReplacementTemplate:{ReplacementTemplateData:JSON.stringify(i.templateData)}}:void 0}));return{results:(await this.ses.sendBulkEmail({FromEmailAddress:t,BulkEmailEntries:r,DefaultContent:{Template:{TemplateName:e.templateName,TemplateData:JSON.stringify(e.defaultTemplateData)}}})).BulkEmailEntryResults?.map((i)=>({status:i.Status||"UNKNOWN",messageId:i.MessageId,error:i.Error}))||[]}}async setupDomain(e){let t;try{t=await this.ses.getEmailIdentity(e)}catch{let a=await this.ses.createEmailIdentity({EmailIdentity:e});t={VerificationStatus:a.DkimAttributes?.Status,DkimAttributes:a.DkimAttributes,SendingEnabled:a.VerifiedForSendingStatus}}try{await this.ses.putEmailIdentityDkimAttributes({EmailIdentity:e,SigningEnabled:!0})}catch{}try{await this.ses.putEmailIdentityMailFromAttributes(e,{MailFromDomain:`mail.${e}`,BehaviorOnMxFailure:"USE_DEFAULT_VALUE"})}catch{}let r=await this.ses.getDkimRecords(e);return{domainVerified:t.SendingEnabled===!0,dkimStatus:t.DkimAttributes?.Status||"UNKNOWN",dkimTokens:t.DkimAttributes?.Tokens,mailFromStatus:t.MailFromAttributes?.MailFromDomainStatus}}async getDnsRecords(e){let t=[],r=await this.ses.getDkimRecords(e);for(let a of r)t.push({type:a.type,name:a.name,value:a.value,ttl:1800});return t.push({type:"MX",name:e,value:`inbound-smtp.${this.region}.amazonaws.com`,priority:10,ttl:3600}),t.push({type:"MX",name:`mail.${e}`,value:`feedback-smtp.${this.region}.amazonses.com`,priority:10,ttl:3600}),t.push({type:"TXT",name:`mail.${e}`,value:"v=spf1 include:amazonses.com ~all",ttl:3600}),t.push({type:"TXT",name:`_dmarc.${e}`,value:`v=DMARC1;p=quarantine;pct=25;rua=mailto:dmarcreports@${e}`,ttl:3600}),t}async isDomainReady(e){try{let t=await this.ses.getEmailIdentity(e);return t.SendingEnabled===!0&&t.DkimAttributes?.Status==="SUCCESS"}catch{return!1}}async setupReceiving(e){let t={Version:"2012-10-17",Statement:[{Sid:"AllowSESPuts",Effect:"Allow",Principal:{Service:"ses.amazonaws.com"},Action:"s3:PutObject",Resource:`arn:aws:s3:::${e.bucketName}/*`,Condition:{StringEquals:{"AWS:SourceAccount":e.accountId}}}]};await this.s3.putBucketPolicy(e.bucketName,t);try{await this.ses.createReceiptRuleSet(e.ruleSetName)}catch(a){if(!a.message?.includes("already exists")&&a.code!=="AlreadyExists")throw a}let r=[{S3Action:{BucketName:e.bucketName,ObjectKeyPrefix:e.prefix||"inbox/"}}];if(e.lambdaArn)r.push({LambdaAction:{FunctionArn:e.lambdaArn,InvocationType:"Event"}});try{await this.ses.createReceiptRule({RuleSetName:e.ruleSetName,Rule:{Name:e.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:e.recipients||[e.domain],ScanEnabled:e.scanEnabled!==!1,Actions:r}})}catch(a){if(a.message?.includes("already exists"))await this.ses.deleteReceiptRule(e.ruleSetName,e.ruleName),await this.ses.createReceiptRule({RuleSetName:e.ruleSetName,Rule:{Name:e.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:e.recipients||[e.domain],ScanEnabled:e.scanEnabled!==!1,Actions:r}});else throw a}await this.ses.setActiveReceiptRuleSet(e.ruleSetName)}async getIncomingEmails(e){return(await this.s3.list({bucket:e.bucket,prefix:e.prefix||"incoming/",maxKeys:e.maxResults||100})).map((r)=>({key:r.Key||"",lastModified:r.LastModified||"",size:r.Size||0}))}async readEmail(e){return await this.s3.getObject(e.bucket,e.key)}async createSmtpCredentials(e){let t=`ses-smtp-${e.username.replace(/[^a-zA-Z0-9]/g,"-")}`,{AWSClient:r}=await import("./chunk-2njcbs0c.js"),a=new r,i=(d,y)=>{let P={Action:d,Version:"2010-05-08",...y};return Object.entries(P).map(([A,h])=>`${encodeURIComponent(A)}=${encodeURIComponent(h)}`).join("&")};try{await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateUser",{UserName:t})})}catch(d){if(!d.message?.includes("EntityAlreadyExists"))throw d}let n={Version:"2012-10-17",Statement:[{Effect:"Allow",Action:"ses:SendRawEmail",Resource:"*",Condition:{StringLike:{"ses:FromAddress":`*@${e.domain}`}}}]},o=`ses-smtp-policy-${e.domain.replace(/\./g,"-")}`;try{await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("PutUserPolicy",{UserName:t,PolicyName:o,PolicyDocument:JSON.stringify(n)})})}catch{}let l=(await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateAccessKey",{UserName:t})}))?.CreateAccessKeyResult?.AccessKey;if(!l?.AccessKeyId||!l?.SecretAccessKey)throw Error("Failed to create access key");let p=this.deriveSmtpPassword(l.SecretAccessKey);return{username:l.AccessKeyId,password:p,server:`email-smtp.${this.region}.amazonaws.com`,port:587}}deriveSmtpPassword(e){let t=gi("node:crypto"),r="SendRawEmail",a=Buffer.from([4]),i=t.createHmac("sha256",`AWS4${e}`).update("11111111").digest();return i=t.createHmac("sha256",i).update(this.region).digest(),i=t.createHmac("sha256",i).update("ses").digest(),i=t.createHmac("sha256",i).update("aws4_request").digest(),i=t.createHmac("sha256",i).update("SendRawEmail").digest(),Buffer.concat([a,i]).toString("base64")}async createTemplate(e){await this.ses.createEmailTemplate({TemplateName:e.name,TemplateContent:{Subject:e.subject,Text:e.text,Html:e.html}})}async getTemplate(e){try{let t=await this.ses.getEmailTemplate(e);return{name:t.TemplateName||e,subject:t.TemplateContent?.Subject,text:t.TemplateContent?.Text,html:t.TemplateContent?.Html}}catch{return null}}async deleteTemplate(e){await this.ses.deleteEmailTemplate(e)}async listTemplates(){return(await this.ses.listEmailTemplates()).TemplatesMetadata?.map((t)=>({name:t.TemplateName||"",createdAt:t.CreatedTimestamp}))||[]}async deploy(e){let t=`${e.appName}-${e.environment}-email-rules`,r=`${e.appName}-inbound-email`,a=e.storage?.bucketName||`${e.appName}-${e.environment}-email`,i=await this.setupDomain(e.domain);if(!(await this.s3.listBuckets()).Buckets?.some((l)=>l.Name===a))await this.s3.createBucket(a);await this.setupReceiving({domain:e.domain,ruleSetName:t,ruleName:r,bucketName:a,prefix:e.storage?.prefix||"inbox/",accountId:e.accountId,recipients:e.catchAll?[e.domain]:e.mailboxes,scanEnabled:!0});let m=await this.getDnsRecords(e.domain);return{success:!0,domainVerified:i.domainVerified,dkimStatus:i.dkimStatus,receiptRuleSet:t,storageBucket:a,dnsRecords:m}}async undeploy(e){let t=`${e.appName}-${e.environment}-email-rules`,r=`${e.appName}-inbound-email`,a=`${e.appName}-${e.environment}-email`;try{await this.ses.deleteReceiptRule(t,r)}catch{}try{await this.ses.deleteReceiptRuleSet(t)}catch{}if(e.deleteBucket)try{await this.s3.emptyAndDeleteBucket(a)}catch{}}async getSendingStats(){let e=await this.ses.getSendQuota();return{sentLast24Hours:e.SentLast24Hours||0,maxSendRate:e.MaxSendRate||0,max24HourSend:e.Max24HourSend||0}}buildRawEmail(e,t,r){let a=`----=_Part_${Date.now()}_${Math.random().toString(36).substring(2)}`,i="";if(i+=`From: ${t}\r
|
|
1
|
+
import{zt,u}from"./chunk-7rwc5bvv.js";import{g}from"./chunk-d5q09rxb.js";import{F}from"./chunk-ymfnqae6.js";import{_}from"./chunk-tv0rtc0s.js";import{Lr}from"./chunk-qxg95ndf.js";function R(e,t){let r=[`Action=${e}`,"Version=2010-05-08"];for(let[a,i]of Object.entries(t)){if(i===void 0||i===null)continue;if(Array.isArray(i))i.forEach((n,o)=>{if(typeof n==="object"&&n!==null)for(let[m,l]of Object.entries(n))r.push(`${a}.member.${o+1}.${m}=${encodeURIComponent(String(l))}`);else r.push(`${a}.member.${o+1}=${encodeURIComponent(String(n))}`)});else if(typeof i==="object"){for(let[n,o]of Object.entries(i))if(o!==void 0&&o!==null)r.push(`${a}.${n}=${encodeURIComponent(String(o))}`)}else r.push(`${a}=${encodeURIComponent(String(i))}`)}return r.join("&")}var f=new zt({ignoreAttributes:!0,parseTagValue:!1,trimValues:!0});function S(e){if(typeof e!=="string"||!e.trim())return{};return f.parse(e)}function s(e,t){let r=[e];while(r.length>0){let a=[];for(let i of r){if(!i||typeof i!=="object")continue;if(Array.isArray(i)){a.push(...i);continue}if(t in i){let n=i[t];return typeof n==="string"?n:void 0}a.push(...Object.values(i))}r=a}return}function c(e,t,r){let a=[e];while(a.length>0){let i=[];for(let n of a){if(!n||typeof n!=="object")continue;if(Array.isArray(n)){i.push(...n);continue}if(t in n){let o=n[t]?.[r];return o===void 0||o===null?[]:Array.isArray(o)?o:[o]}i.push(...Object.values(n))}a=i}return[]}class te{client;region;constructor(e="us-east-1",t){this.client=new u(void 0,{profile:t}),this.region=e}async request(e,t={}){let r=R(e,t),a=await this.client.request({service:"iam",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r,rawResponse:!0});return S(a)}async createUser(e){let t=await this.request("CreateUser",e);return this.parseUser(t)}async getUser(e={}){let t=await this.request("GetUser",e);return this.parseUser(t)}async listUsers(e={}){let t=await this.request("ListUsers",e),r=this.parseUsers(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Users:r,IsTruncated:a,Marker:i}}async updateUser(e){await this.request("UpdateUser",e)}async deleteUser(e){await this.request("DeleteUser",e)}parseUser(e){return{UserName:s(e,"UserName")||"",UserId:s(e,"UserId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),CreateDate:s(e,"CreateDate"),PasswordLastUsed:s(e,"PasswordLastUsed")}}parseUsers(e){return c(e,"Users","member").map((r)=>({UserName:s(r,"UserName")||"",UserId:s(r,"UserId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),CreateDate:s(r,"CreateDate"),PasswordLastUsed:s(r,"PasswordLastUsed")}))}async createGroup(e){let t=await this.request("CreateGroup",e);return this.parseGroup(t)}async getGroup(e){let t=await this.request("GetGroup",e),r=this.parseGroup(t),a=this.parseUsers(t),i=s(t,"IsTruncated")==="true",n=s(t,"Marker");return{Group:r,Users:a,IsTruncated:i,Marker:n}}async listGroups(e={}){let t=await this.request("ListGroups",e),r=this.parseGroups(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Groups:r,IsTruncated:a,Marker:i}}async updateGroup(e){await this.request("UpdateGroup",e)}async deleteGroup(e){await this.request("DeleteGroup",e)}async addUserToGroup(e){await this.request("AddUserToGroup",e)}async removeUserFromGroup(e){await this.request("RemoveUserFromGroup",e)}async listGroupsForUser(e){let t=await this.request("ListGroupsForUser",e),r=this.parseGroups(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Groups:r,IsTruncated:a,Marker:i}}parseGroup(e){return{GroupName:s(e,"GroupName")||"",GroupId:s(e,"GroupId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),CreateDate:s(e,"CreateDate")}}parseGroups(e){return c(e,"Groups","member").map((r)=>({GroupName:s(r,"GroupName")||"",GroupId:s(r,"GroupId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),CreateDate:s(r,"CreateDate")}))}async createRole(e){let t=await this.request("CreateRole",e);return this.parseRole(t)}async getRole(e){let t=await this.request("GetRole",e);return this.parseRole(t)}async listRoles(e={}){let t=await this.request("ListRoles",e),r=this.parseRoles(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Roles:r,IsTruncated:a,Marker:i}}async updateRole(e){await this.request("UpdateRole",e)}async updateRoleDescription(e){let t=await this.request("UpdateRoleDescription",e);return this.parseRole(t)}async updateAssumeRolePolicy(e){await this.request("UpdateAssumeRolePolicy",e)}async deleteRole(e){await this.request("DeleteRole",e)}async tagRole(e){await this.request("TagRole",e)}async untagRole(e){await this.request("UntagRole",e)}async listRoleTags(e){let t=await this.request("ListRoleTags",e),r=this.parseTags(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Tags:r,IsTruncated:a,Marker:i}}parseRole(e){return{RoleName:s(e,"RoleName")||"",RoleId:s(e,"RoleId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),CreateDate:s(e,"CreateDate"),AssumeRolePolicyDocument:s(e,"AssumeRolePolicyDocument"),Description:s(e,"Description"),MaxSessionDuration:s(e,"MaxSessionDuration")?Number.parseInt(s(e,"MaxSessionDuration"),10):void 0}}parseRoles(e){return c(e,"Roles","member").map((r)=>({RoleName:s(r,"RoleName")||"",RoleId:s(r,"RoleId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),CreateDate:s(r,"CreateDate"),AssumeRolePolicyDocument:s(r,"AssumeRolePolicyDocument"),Description:s(r,"Description"),MaxSessionDuration:s(r,"MaxSessionDuration")?Number.parseInt(s(r,"MaxSessionDuration"),10):void 0}))}parseTags(e){return c(e,"Tags","member").map((r)=>({Key:s(r,"Key")||"",Value:s(r,"Value")||""}))}async createPolicy(e){let t=await this.request("CreatePolicy",e);return this.parsePolicy(t)}async getPolicy(e){let t=await this.request("GetPolicy",e);return this.parsePolicy(t)}async getPolicyVersion(e){let t=await this.request("GetPolicyVersion",e);return{VersionId:s(t,"VersionId")||"",IsDefaultVersion:s(t,"IsDefaultVersion")==="true",CreateDate:s(t,"CreateDate"),Document:s(t,"Document")}}async listPolicies(e={}){let t=await this.request("ListPolicies",e),r=this.parsePolicies(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Policies:r,IsTruncated:a,Marker:i}}async listPolicyVersions(e){let t=await this.request("ListPolicyVersions",e),r=this.parsePolicyVersions(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{Versions:r,IsTruncated:a,Marker:i}}async createPolicyVersion(e){let t=await this.request("CreatePolicyVersion",e);return{VersionId:s(t,"VersionId")||"",IsDefaultVersion:s(t,"IsDefaultVersion")==="true",CreateDate:s(t,"CreateDate")}}async deletePolicyVersion(e){await this.request("DeletePolicyVersion",e)}async setDefaultPolicyVersion(e){await this.request("SetDefaultPolicyVersion",e)}async deletePolicy(e){await this.request("DeletePolicy",e)}async attachUserPolicy(e){await this.request("AttachUserPolicy",e)}async detachUserPolicy(e){await this.request("DetachUserPolicy",e)}async attachGroupPolicy(e){await this.request("AttachGroupPolicy",e)}async detachGroupPolicy(e){await this.request("DetachGroupPolicy",e)}async attachRolePolicy(e){await this.request("AttachRolePolicy",e)}async detachRolePolicy(e){await this.request("DetachRolePolicy",e)}async listAttachedUserPolicies(e){let t=await this.request("ListAttachedUserPolicies",e),r=this.parseAttachedPolicies(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{AttachedPolicies:r,IsTruncated:a,Marker:i}}async listAttachedGroupPolicies(e){let t=await this.request("ListAttachedGroupPolicies",e),r=this.parseAttachedPolicies(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{AttachedPolicies:r,IsTruncated:a,Marker:i}}async listAttachedRolePolicies(e){let t=await this.request("ListAttachedRolePolicies",e),r=this.parseAttachedPolicies(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{AttachedPolicies:r,IsTruncated:a,Marker:i}}parsePolicy(e){return{PolicyName:s(e,"PolicyName")||"",PolicyId:s(e,"PolicyId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),DefaultVersionId:s(e,"DefaultVersionId"),AttachmentCount:s(e,"AttachmentCount")?Number.parseInt(s(e,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:s(e,"PermissionsBoundaryUsageCount")?Number.parseInt(s(e,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:s(e,"IsAttachable")==="true",Description:s(e,"Description"),CreateDate:s(e,"CreateDate"),UpdateDate:s(e,"UpdateDate")}}parsePolicies(e){return c(e,"Policies","member").map((r)=>({PolicyName:s(r,"PolicyName")||"",PolicyId:s(r,"PolicyId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),DefaultVersionId:s(r,"DefaultVersionId"),AttachmentCount:s(r,"AttachmentCount")?Number.parseInt(s(r,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:s(r,"PermissionsBoundaryUsageCount")?Number.parseInt(s(r,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:s(r,"IsAttachable")==="true",Description:s(r,"Description"),CreateDate:s(r,"CreateDate"),UpdateDate:s(r,"UpdateDate")}))}parsePolicyVersions(e){return c(e,"Versions","member").map((r)=>({VersionId:s(r,"VersionId")||"",IsDefaultVersion:s(r,"IsDefaultVersion")==="true",CreateDate:s(r,"CreateDate")}))}parseAttachedPolicies(e){return c(e,"AttachedPolicies","member").map((r)=>({PolicyName:s(r,"PolicyName")||"",PolicyArn:s(r,"PolicyArn")||""}))}async putUserPolicy(e){await this.request("PutUserPolicy",e)}async getUserPolicy(e){let t=await this.request("GetUserPolicy",e);return{UserName:s(t,"UserName")||"",PolicyName:s(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(s(t,"PolicyDocument")||"")}}async deleteUserPolicy(e){await this.request("DeleteUserPolicy",e)}async listUserPolicies(e){let t=await this.request("ListUserPolicies",e),r=c(t,"PolicyNames","member"),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{PolicyNames:r,IsTruncated:a,Marker:i}}async putGroupPolicy(e){await this.request("PutGroupPolicy",e)}async getGroupPolicy(e){let t=await this.request("GetGroupPolicy",e);return{GroupName:s(t,"GroupName")||"",PolicyName:s(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(s(t,"PolicyDocument")||"")}}async deleteGroupPolicy(e){await this.request("DeleteGroupPolicy",e)}async listGroupPolicies(e){let t=await this.request("ListGroupPolicies",e),r=c(t,"PolicyNames","member"),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{PolicyNames:r,IsTruncated:a,Marker:i}}async putRolePolicy(e){await this.request("PutRolePolicy",e)}async getRolePolicy(e){let t=await this.request("GetRolePolicy",e);return{RoleName:s(t,"RoleName")||"",PolicyName:s(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(s(t,"PolicyDocument")||"")}}async deleteRolePolicy(e){await this.request("DeleteRolePolicy",e)}async listRolePolicies(e){let t=await this.request("ListRolePolicies",e),r=c(t,"PolicyNames","member"),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{PolicyNames:r,IsTruncated:a,Marker:i}}async createAccessKey(e={}){let t=await this.request("CreateAccessKey",e);if(typeof t==="object"){let r=t?.CreateAccessKeyResult?.AccessKey||t?.AccessKey;if(r)return{AccessKey:{UserName:r.UserName||"",AccessKeyId:r.AccessKeyId||"",Status:r.Status||"Active",SecretAccessKey:r.SecretAccessKey||"",CreateDate:r.CreateDate}}}return{AccessKey:{UserName:s(t,"UserName")||"",AccessKeyId:s(t,"AccessKeyId")||"",Status:s(t,"Status")||"Active",SecretAccessKey:s(t,"SecretAccessKey")||"",CreateDate:s(t,"CreateDate")}}}async listAccessKeys(e={}){let t=await this.request("ListAccessKeys",e),r=this.parseAccessKeys(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{AccessKeyMetadata:r,IsTruncated:a,Marker:i}}async updateAccessKey(e){await this.request("UpdateAccessKey",e)}async deleteAccessKey(e){await this.request("DeleteAccessKey",e)}async getAccessKeyLastUsed(e){let t=await this.request("GetAccessKeyLastUsed",e);return{UserName:s(t,"UserName")||"",AccessKeyLastUsed:{LastUsedDate:s(t,"LastUsedDate"),ServiceName:s(t,"ServiceName"),Region:s(t,"Region")}}}parseAccessKeys(e){return c(e,"AccessKeyMetadata","member").map((r)=>({UserName:s(r,"UserName"),AccessKeyId:s(r,"AccessKeyId")||"",Status:s(r,"Status")||"Active",CreateDate:s(r,"CreateDate")}))}async createInstanceProfile(e){let t=await this.request("CreateInstanceProfile",e);return this.parseInstanceProfile(t)}async getInstanceProfile(e){let t=await this.request("GetInstanceProfile",e);return this.parseInstanceProfile(t)}async listInstanceProfiles(e={}){let t=await this.request("ListInstanceProfiles",e),r=this.parseInstanceProfiles(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{InstanceProfiles:r,IsTruncated:a,Marker:i}}async listInstanceProfilesForRole(e){let t=await this.request("ListInstanceProfilesForRole",e),r=this.parseInstanceProfiles(t),a=s(t,"IsTruncated")==="true",i=s(t,"Marker");return{InstanceProfiles:r,IsTruncated:a,Marker:i}}async addRoleToInstanceProfile(e){await this.request("AddRoleToInstanceProfile",e)}async removeRoleFromInstanceProfile(e){await this.request("RemoveRoleFromInstanceProfile",e)}async deleteInstanceProfile(e){await this.request("DeleteInstanceProfile",e)}parseInstanceProfile(e){return{InstanceProfileName:s(e,"InstanceProfileName")||"",InstanceProfileId:s(e,"InstanceProfileId")||"",Arn:s(e,"Arn")||"",Path:s(e,"Path"),CreateDate:s(e,"CreateDate")}}parseInstanceProfiles(e){return c(e,"InstanceProfiles","member").map((r)=>({InstanceProfileName:s(r,"InstanceProfileName")||"",InstanceProfileId:s(r,"InstanceProfileId")||"",Arn:s(r,"Arn")||"",Path:s(r,"Path"),CreateDate:s(r,"CreateDate")}))}async getAccountPasswordPolicy(){let e=await this.request("GetAccountPasswordPolicy");return{MinimumPasswordLength:s(e,"MinimumPasswordLength")?Number.parseInt(s(e,"MinimumPasswordLength"),10):void 0,RequireSymbols:s(e,"RequireSymbols")==="true",RequireNumbers:s(e,"RequireNumbers")==="true",RequireUppercaseCharacters:s(e,"RequireUppercaseCharacters")==="true",RequireLowercaseCharacters:s(e,"RequireLowercaseCharacters")==="true",AllowUsersToChangePassword:s(e,"AllowUsersToChangePassword")==="true",ExpirePasswords:s(e,"ExpirePasswords")==="true",MaxPasswordAge:s(e,"MaxPasswordAge")?Number.parseInt(s(e,"MaxPasswordAge"),10):void 0,PasswordReusePrevention:s(e,"PasswordReusePrevention")?Number.parseInt(s(e,"PasswordReusePrevention"),10):void 0,HardExpiry:s(e,"HardExpiry")==="true"}}async updateAccountPasswordPolicy(e){await this.request("UpdateAccountPasswordPolicy",e)}async deleteAccountPasswordPolicy(){await this.request("DeleteAccountPasswordPolicy")}async getAccountSummary(){let e=await this.request("GetAccountSummary"),t={},r=c(e,"SummaryMap","entry");for(let a of r){let i=s(a,"key"),n=s(a,"value");if(i&&n)t[i]=Number.parseInt(n,10)}return t}async listAccountAliases(){let e=await this.request("ListAccountAliases"),t=c(e,"AccountAliases","member"),r=s(e,"IsTruncated")==="true",a=s(e,"Marker");return{AccountAliases:t,IsTruncated:r,Marker:a}}async createAccountAlias(e){await this.request("CreateAccountAlias",e)}async deleteAccountAlias(e){await this.request("DeleteAccountAlias",e)}async simulatePrincipalPolicy(e){let t=await this.request("SimulatePrincipalPolicy",e);return this.parseSimulationResults(t)}parseSimulationResults(e){let r=c(e,"EvaluationResults","member").map((n)=>{let m=c(n,"MatchedStatements","member").map((l)=>({SourcePolicyId:s(l,"SourcePolicyId"),SourcePolicyType:s(l,"SourcePolicyType")}));return{EvalActionName:s(n,"EvalActionName")||"",EvalResourceName:s(n,"EvalResourceName"),EvalDecision:s(n,"EvalDecision")||"",MatchedStatements:m.length>0?m:void 0}}),a=s(e,"IsTruncated")==="true",i=s(e,"Marker");return{EvaluationResults:r,IsTruncated:a,Marker:i}}}class Ce{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new u(t)}async createEmailIdentity(e){return await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/identities",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async getEmailIdentity(e){let t=await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/identities/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}});return{IdentityType:t.IdentityType,IdentityName:e,SendingEnabled:t.VerifiedForSendingStatus,VerificationStatus:t.VerificationStatus,DkimAttributes:t.DkimAttributes,MailFromAttributes:t.MailFromAttributes}}async putEmailIdentityMailFromAttributes(e,t){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(e)}/mail-from`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async listEmailIdentities(e){let t="/v2/email/identities",r=[];if(e?.PageSize)r.push(`PageSize=${e.PageSize}`);if(e?.NextToken)r.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(r.length>0)t+=`?${r.join("&")}`;let a=await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}});return{EmailIdentities:a.EmailIdentities,NextToken:a.NextToken}}async deleteEmailIdentity(e){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/identities/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async putEmailIdentityDkimAttributes(e){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(e.EmailIdentity)}/dkim`,headers:{"Content-Type":"application/json"},body:JSON.stringify({SigningEnabled:e.SigningEnabled})})}async sendEmail(e){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(e)})).MessageId}}async sendBulkEmail(e){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(e)})).BulkEmailEntryResults}}async createEmailTemplate(e){await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/templates",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async getEmailTemplate(e){return await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/templates/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async deleteEmailTemplate(e){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/templates/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async listEmailTemplates(e){let t="/v2/email/templates",r=[];if(e?.PageSize)r.push(`PageSize=${e.PageSize}`);if(e?.NextToken)r.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(r.length>0)t+=`?${r.join("&")}`;return await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}})}async getSendStatistics(){let e=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"}),t=_(e,"GetSendStatistics")?.SendDataPoints?.member;return{SendDataPoints:t==null?[]:Array.isArray(t)?t:[t]}}async getSendQuota(){let e=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"}),t=_(e,"GetSendQuota"),r=(a)=>a==null||a===""?void 0:Number(a);return{Max24HourSend:r(t?.Max24HourSend),MaxSendRate:r(t?.MaxSendRate),SentLast24Hours:r(t?.SentLast24Hours)}}async verifyDomain(e){let t=await this.createEmailIdentity({EmailIdentity:e});return{dkimTokens:t.DkimAttributes?.Tokens,verificationStatus:t.DkimAttributes?.Status}}async sendSimpleEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],r=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0,a={};if(e.text)a.Text={Data:e.text};if(e.html)a.Html={Data:e.html};return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Simple:{Subject:{Data:e.subject},Body:a}},ReplyToAddresses:r})}async sendTemplatedEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],r=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0;return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Template:{TemplateName:e.templateName,TemplateData:JSON.stringify(e.templateData)}},ReplyToAddresses:r})}async getDkimRecords(e){let t=await this.getEmailIdentity(e);if(!t.DkimAttributes?.Tokens)return[];return t.DkimAttributes.Tokens.map((r)=>({name:`${r}._domainkey.${e}`,type:"CNAME",value:`${r}.dkim.amazonses.com`}))}async isDomainVerified(e){try{let t=await this.getEmailIdentity(e);return t.VerificationStatus==="SUCCESS"&&t.SendingEnabled===!0}catch{return!1}}async waitForDomainVerification(e,t=60,r=30000){for(let a=0;a<t;a++){if(await this.isDomainVerified(e))return!0;await new Promise((n)=>setTimeout(n,r))}return!1}buildFormBody(e){return Object.entries(e).filter(([,r])=>r!==void 0).map(([r,a])=>`${encodeURIComponent(r)}=${encodeURIComponent(a)}`).join("&")}async createReceiptRuleSet(e){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:e})})}async deleteReceiptRuleSet(e){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:e})})}async setActiveReceiptRuleSet(e){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:e})})}async listReceiptRuleSets(e){let t={Action:"ListReceiptRuleSets",Version:"2010-12-01"};if(e)t.NextToken=e;let r=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)}),a=r?.ListReceiptRuleSetsResponse?.ListReceiptRuleSetsResult||r?.ListReceiptRuleSetsResult,i=a?.RuleSets?.member;return{RuleSets:Array.isArray(i)?i:i?[i]:[],NextToken:a?.NextToken}}async describeReceiptRuleSet(e){let t=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:e})}),r=t?.DescribeReceiptRuleSetResponse?.DescribeReceiptRuleSetResult||t?.DescribeReceiptRuleSetResult,a=r?.Rules?.member;return{Metadata:r?.Metadata,Rules:Array.isArray(a)?a:a?[a]:[]}}async createReceiptRule(e){let t={Action:"CreateReceiptRule",Version:"2010-12-01",RuleSetName:e.RuleSetName,"Rule.Name":e.Rule.Name,"Rule.Enabled":e.Rule.Enabled!==!1?"true":"false"};if(e.Rule.TlsPolicy)t["Rule.TlsPolicy"]=e.Rule.TlsPolicy;if(e.Rule.ScanEnabled!==void 0)t["Rule.ScanEnabled"]=e.Rule.ScanEnabled?"true":"false";if(e.After)t.After=e.After;if(e.Rule.Recipients)e.Rule.Recipients.forEach((r,a)=>{t[`Rule.Recipients.member.${a+1}`]=r});e.Rule.Actions.forEach((r,a)=>{let i=a+1;if(r.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=r.S3Action.BucketName,r.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=r.S3Action.ObjectKeyPrefix;if(r.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=r.S3Action.KmsKeyArn}if(r.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=r.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=r.LambdaAction.InvocationType||"Event";if(r.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=r.SNSAction.TopicArn,r.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=r.SNSAction.Encoding}if(r.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=r.StopAction.Scope,r.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=r.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(t)})}async deleteReceiptRule(e,t){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:e,RuleName:t})})}async receiptRuleSetExists(e){try{return await this.describeReceiptRuleSet(e),!0}catch(t){if(t.code==="RuleSetDoesNotExist"||t.statusCode===400)return!1;throw t}}async getActiveReceiptRuleSet(){let e=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"})}),t=e?.DescribeActiveReceiptRuleSetResponse?.DescribeActiveReceiptRuleSetResult||e?.DescribeActiveReceiptRuleSetResult;if(!t?.Metadata)return null;let r=t?.Rules?.member;return{Metadata:t?.Metadata,Rules:Array.isArray(r)?r:r?[r]:[]}}async updateReceiptRule(e){let t={Action:"UpdateReceiptRule",Version:"2010-12-01",RuleSetName:e.RuleSetName,"Rule.Name":e.Rule.Name};if(e.Rule.Enabled!==void 0)t["Rule.Enabled"]=e.Rule.Enabled?"true":"false";if(e.Rule.TlsPolicy)t["Rule.TlsPolicy"]=e.Rule.TlsPolicy;if(e.Rule.ScanEnabled!==void 0)t["Rule.ScanEnabled"]=e.Rule.ScanEnabled?"true":"false";if(e.Rule.Recipients)e.Rule.Recipients.forEach((r,a)=>{t[`Rule.Recipients.member.${a+1}`]=r});e.Rule.Actions.forEach((r,a)=>{let i=a+1;if(r.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=r.S3Action.BucketName,r.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=r.S3Action.ObjectKeyPrefix;if(r.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=r.S3Action.KmsKeyArn}if(r.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=r.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=r.LambdaAction.InvocationType||"Event";if(r.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=r.SNSAction.TopicArn,r.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=r.SNSAction.Encoding}if(r.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=r.StopAction.Scope,r.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=r.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(t)})}async sendRawEmail(e){let t=Buffer.from(e.rawMessage).toString("base64"),r={Action:"SendRawEmail",Version:"2010-12-01",Source:e.source,"RawMessage.Data":t};e.destinations.forEach((n,o)=>{r[`Destinations.member.${o+1}`]=n});let a=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(r)});return{MessageId:(a?.SendRawEmailResponse?.SendRawEmailResult||a?.SendRawEmailResult)?.MessageId}}async getSuppressedDestination(e){try{return(await this.client.request({service:"ses",region:this.region,method:"GET",path:`/v2/email/suppression/addresses/${encodeURIComponent(e)}`}))?.SuppressedDestination||null}catch(t){if(t.message?.includes("404")||t.message?.includes("NotFoundException"))return null;throw t}}async deleteSuppressedDestination(e){await this.client.request({service:"ses",region:this.region,method:"DELETE",path:`/v2/email/suppression/addresses/${encodeURIComponent(e)}`})}}class Hc{ses;s3;iam;route53;region;domain;defaultFrom;constructor(e={}){this.region=e.region||"us-east-1",this.domain=e.domain,this.defaultFrom=e.defaultFrom,this.ses=new Ce(this.region),this.s3=new g(this.region),this.iam=new te(this.region),this.route53=new F(this.region)}async send(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required. Set defaultFrom in constructor or provide from in options.");let r=e.fromName?`${e.fromName} <${t}>`:t,a=Array.isArray(e.to)?e.to:[e.to];if(!e.attachments||e.attachments.length===0)return{messageId:(await this.ses.sendSimpleEmail({from:r,to:a,subject:e.subject,text:e.text,html:e.html,replyTo:e.replyTo})).MessageId||""};let i=this.buildRawEmail(e,r,a);return{messageId:(await this.ses.sendEmail({FromEmailAddress:r,Destination:{ToAddresses:a,CcAddresses:e.cc?Array.isArray(e.cc)?e.cc:[e.cc]:void 0,BccAddresses:e.bcc?Array.isArray(e.bcc)?e.bcc:[e.bcc]:void 0},Content:{Raw:{Data:Buffer.from(i).toString("base64")}}})).MessageId||""}}async sendTemplate(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required");let r=e.fromName?`${e.fromName} <${t}>`:t;return{messageId:(await this.ses.sendTemplatedEmail({from:r,to:e.to,templateName:e.templateName,templateData:e.templateData,replyTo:e.replyTo})).MessageId||""}}async sendBulk(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required");let r=e.recipients.map((i)=>({Destination:{ToAddresses:Array.isArray(i.to)?i.to:[i.to]},ReplacementEmailContent:i.templateData?{ReplacementTemplate:{ReplacementTemplateData:JSON.stringify(i.templateData)}}:void 0}));return{results:(await this.ses.sendBulkEmail({FromEmailAddress:t,BulkEmailEntries:r,DefaultContent:{Template:{TemplateName:e.templateName,TemplateData:JSON.stringify(e.defaultTemplateData)}}})).BulkEmailEntryResults?.map((i)=>({status:i.Status||"UNKNOWN",messageId:i.MessageId,error:i.Error}))||[]}}async setupDomain(e){let t;try{t=await this.ses.getEmailIdentity(e)}catch{let a=await this.ses.createEmailIdentity({EmailIdentity:e});t={VerificationStatus:a.DkimAttributes?.Status,DkimAttributes:a.DkimAttributes,SendingEnabled:a.VerifiedForSendingStatus}}try{await this.ses.putEmailIdentityDkimAttributes({EmailIdentity:e,SigningEnabled:!0})}catch{}try{await this.ses.putEmailIdentityMailFromAttributes(e,{MailFromDomain:`mail.${e}`,BehaviorOnMxFailure:"USE_DEFAULT_VALUE"})}catch{}let r=await this.ses.getDkimRecords(e);return{domainVerified:t.SendingEnabled===!0,dkimStatus:t.DkimAttributes?.Status||"UNKNOWN",dkimTokens:t.DkimAttributes?.Tokens,mailFromStatus:t.MailFromAttributes?.MailFromDomainStatus}}async getDnsRecords(e){let t=[],r=await this.ses.getDkimRecords(e);for(let a of r)t.push({type:a.type,name:a.name,value:a.value,ttl:1800});return t.push({type:"MX",name:e,value:`inbound-smtp.${this.region}.amazonaws.com`,priority:10,ttl:3600}),t.push({type:"MX",name:`mail.${e}`,value:`feedback-smtp.${this.region}.amazonses.com`,priority:10,ttl:3600}),t.push({type:"TXT",name:`mail.${e}`,value:"v=spf1 include:amazonses.com ~all",ttl:3600}),t.push({type:"TXT",name:`_dmarc.${e}`,value:`v=DMARC1;p=quarantine;pct=25;rua=mailto:dmarcreports@${e}`,ttl:3600}),t}async isDomainReady(e){try{let t=await this.ses.getEmailIdentity(e);return t.SendingEnabled===!0&&t.DkimAttributes?.Status==="SUCCESS"}catch{return!1}}async setupReceiving(e){let t={Version:"2012-10-17",Statement:[{Sid:"AllowSESPuts",Effect:"Allow",Principal:{Service:"ses.amazonaws.com"},Action:"s3:PutObject",Resource:`arn:aws:s3:::${e.bucketName}/*`,Condition:{StringEquals:{"AWS:SourceAccount":e.accountId}}}]};await this.s3.putBucketPolicy(e.bucketName,t);try{await this.ses.createReceiptRuleSet(e.ruleSetName)}catch(a){if(!a.message?.includes("already exists")&&a.code!=="AlreadyExists")throw a}let r=[{S3Action:{BucketName:e.bucketName,ObjectKeyPrefix:e.prefix||"inbox/"}}];if(e.lambdaArn)r.push({LambdaAction:{FunctionArn:e.lambdaArn,InvocationType:"Event"}});try{await this.ses.createReceiptRule({RuleSetName:e.ruleSetName,Rule:{Name:e.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:e.recipients||[e.domain],ScanEnabled:e.scanEnabled!==!1,Actions:r}})}catch(a){if(a.message?.includes("already exists"))await this.ses.deleteReceiptRule(e.ruleSetName,e.ruleName),await this.ses.createReceiptRule({RuleSetName:e.ruleSetName,Rule:{Name:e.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:e.recipients||[e.domain],ScanEnabled:e.scanEnabled!==!1,Actions:r}});else throw a}await this.ses.setActiveReceiptRuleSet(e.ruleSetName)}async getIncomingEmails(e){return(await this.s3.list({bucket:e.bucket,prefix:e.prefix||"incoming/",maxKeys:e.maxResults||100})).map((r)=>({key:r.Key||"",lastModified:r.LastModified||"",size:r.Size||0}))}async readEmail(e){return await this.s3.getObject(e.bucket,e.key)}async createSmtpCredentials(e){let t=`ses-smtp-${e.username.replace(/[^a-zA-Z0-9]/g,"-")}`,{AWSClient:r}=await import("./chunk-2cx4k97r.js"),a=new r,i=(d,y)=>{let P={Action:d,Version:"2010-05-08",...y};return Object.entries(P).map(([A,h])=>`${encodeURIComponent(A)}=${encodeURIComponent(h)}`).join("&")};try{await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateUser",{UserName:t})})}catch(d){if(!d.message?.includes("EntityAlreadyExists"))throw d}let n={Version:"2012-10-17",Statement:[{Effect:"Allow",Action:"ses:SendRawEmail",Resource:"*",Condition:{StringLike:{"ses:FromAddress":`*@${e.domain}`}}}]},o=`ses-smtp-policy-${e.domain.replace(/\./g,"-")}`;try{await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("PutUserPolicy",{UserName:t,PolicyName:o,PolicyDocument:JSON.stringify(n)})})}catch{}let l=(await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateAccessKey",{UserName:t})}))?.CreateAccessKeyResult?.AccessKey;if(!l?.AccessKeyId||!l?.SecretAccessKey)throw Error("Failed to create access key");let p=this.deriveSmtpPassword(l.SecretAccessKey);return{username:l.AccessKeyId,password:p,server:`email-smtp.${this.region}.amazonaws.com`,port:587}}deriveSmtpPassword(e){let t=Lr("node:crypto"),r="SendRawEmail",a=Buffer.from([4]),i=t.createHmac("sha256",`AWS4${e}`).update("11111111").digest();return i=t.createHmac("sha256",i).update(this.region).digest(),i=t.createHmac("sha256",i).update("ses").digest(),i=t.createHmac("sha256",i).update("aws4_request").digest(),i=t.createHmac("sha256",i).update("SendRawEmail").digest(),Buffer.concat([a,i]).toString("base64")}async createTemplate(e){await this.ses.createEmailTemplate({TemplateName:e.name,TemplateContent:{Subject:e.subject,Text:e.text,Html:e.html}})}async getTemplate(e){try{let t=await this.ses.getEmailTemplate(e);return{name:t.TemplateName||e,subject:t.TemplateContent?.Subject,text:t.TemplateContent?.Text,html:t.TemplateContent?.Html}}catch{return null}}async deleteTemplate(e){await this.ses.deleteEmailTemplate(e)}async listTemplates(){return(await this.ses.listEmailTemplates()).TemplatesMetadata?.map((t)=>({name:t.TemplateName||"",createdAt:t.CreatedTimestamp}))||[]}async deploy(e){let t=`${e.appName}-${e.environment}-email-rules`,r=`${e.appName}-inbound-email`,a=e.storage?.bucketName||`${e.appName}-${e.environment}-email`,i=await this.setupDomain(e.domain);if(!(await this.s3.listBuckets()).Buckets?.some((l)=>l.Name===a))await this.s3.createBucket(a);await this.setupReceiving({domain:e.domain,ruleSetName:t,ruleName:r,bucketName:a,prefix:e.storage?.prefix||"inbox/",accountId:e.accountId,recipients:e.catchAll?[e.domain]:e.mailboxes,scanEnabled:!0});let m=await this.getDnsRecords(e.domain);return{success:!0,domainVerified:i.domainVerified,dkimStatus:i.dkimStatus,receiptRuleSet:t,storageBucket:a,dnsRecords:m}}async undeploy(e){let t=`${e.appName}-${e.environment}-email-rules`,r=`${e.appName}-inbound-email`,a=`${e.appName}-${e.environment}-email`;try{await this.ses.deleteReceiptRule(t,r)}catch{}try{await this.ses.deleteReceiptRuleSet(t)}catch{}if(e.deleteBucket)try{await this.s3.emptyAndDeleteBucket(a)}catch{}}async getSendingStats(){let e=await this.ses.getSendQuota();return{sentLast24Hours:e.SentLast24Hours||0,maxSendRate:e.MaxSendRate||0,max24HourSend:e.Max24HourSend||0}}buildRawEmail(e,t,r){let a=`----=_Part_${Date.now()}_${Math.random().toString(36).substring(2)}`,i="";if(i+=`From: ${t}\r
|
|
2
2
|
`,i+=`To: ${r.join(", ")}\r
|
|
3
3
|
`,e.cc){let n=Array.isArray(e.cc)?e.cc:[e.cc];i+=`Cc: ${n.join(", ")}\r
|
|
4
4
|
`}if(i+=`Subject: ${e.subject}\r
|
|
@@ -30,5 +30,5 @@ import{Ft,u}from"./chunk-s6qnx8a8.js";import{g}from"./chunk-59f6mqkj.js";import{
|
|
|
30
30
|
`,i+=`\r
|
|
31
31
|
`,i+=`${n.content}\r
|
|
32
32
|
`;return i+=`--${a}--\r
|
|
33
|
-
`,i}}var
|
|
34
|
-
export{
|
|
33
|
+
`,i}}var im=new Hc;
|
|
34
|
+
export{te,Ce,Hc,im};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{J,U,
|
|
2
|
-
`),s=r==="root"?'bash -l "$TS_CLOUD_RECIPE"':`runuser -l ${g(r)} -c "bash $TS_CLOUD_RECIPE"`;return["set -uo pipefail",`echo "__TS_CLOUD_RECIPE_BEGIN__ ${e.name} (user=${r})"`,"TS_CLOUD_RECIPE=$(mktemp)",`cat > "$TS_CLOUD_RECIPE" <<'TS_CLOUD_RECIPE_EOF'`,n,"TS_CLOUD_RECIPE_EOF",'chmod +r "$TS_CLOUD_RECIPE"',s,"TS_CLOUD_RC=$?",'rm -f "$TS_CLOUD_RECIPE"',`echo "__TS_CLOUD_RECIPE_END__ ${e.name} exit=$TS_CLOUD_RC"`,"exit $TS_CLOUD_RC"]}var m={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};async function l(e){return await e.driver.findComputeTargets({slug:e.slug,environment:e.environment,role:e.role||"app"})}async function
|
|
3
|
-
export{
|
|
1
|
+
import{J,U,Ti,Vo,Vt,Vc,zc}from"./chunk-v3prk467.js";function g(e){return`'${e.split("'").join("'\\''")}'`}function c(e){let r=e.user||"root",n=e.script.join(`
|
|
2
|
+
`),s=r==="root"?'bash -l "$TS_CLOUD_RECIPE"':`runuser -l ${g(r)} -c "bash $TS_CLOUD_RECIPE"`;return["set -uo pipefail",`echo "__TS_CLOUD_RECIPE_BEGIN__ ${e.name} (user=${r})"`,"TS_CLOUD_RECIPE=$(mktemp)",`cat > "$TS_CLOUD_RECIPE" <<'TS_CLOUD_RECIPE_EOF'`,n,"TS_CLOUD_RECIPE_EOF",'chmod +r "$TS_CLOUD_RECIPE"',s,"TS_CLOUD_RC=$?",'rm -f "$TS_CLOUD_RECIPE"',`echo "__TS_CLOUD_RECIPE_END__ ${e.name} exit=$TS_CLOUD_RC"`,"exit $TS_CLOUD_RC"]}var m={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};async function l(e){return await e.driver.findComputeTargets({slug:e.slug,environment:e.environment,role:e.role||"app"})}async function Mo(e,r){let n=e.logger||m,s=await l(e);if(s.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};let t=J(e.slug,r.siteName),o=Vt(t,r.to||"unused"),a=r.onlyIfLive?f(o.current,r.siteName,r.onlyIfLive):[];if(r.dryRun){let i=await e.driver.runRemoteDeploy({targets:s,commands:["set -uo pipefail",...a,...Vc(o,r.to?{to:r.to}:{})],comment:`ts-cloud rollback plan ${e.slug}/${r.siteName}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});return{success:i.success,error:i.error,perInstance:i.perInstance}}let p=["set -uo pipefail",...a,...zc(o,{...r.to?{to:r.to}:{},unitBase:`${e.slug}-${r.siteName}`}),`(cd ${U} && pantry restart php-fpm) 2>/dev/null || true`,`(cd ${o.current} && eval "$(cd ${U} && pantry env 2>/dev/null)" && php artisan queue:restart) 2>/dev/null || true`];n.step(`Rolling back ${r.siteName}${r.to?` to ${r.to}`:" to the previous release"} on ${s.length} server(s)...`);let u=await e.driver.runRemoteDeploy({targets:s,commands:p,comment:`ts-cloud rollback ${e.slug}/${r.siteName}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});if(!u.success)n.error(`Rollback failed: ${u.error||"unknown error"}`);else n.success(`Rolled back ${r.siteName}.`);return{success:u.success,error:u.error,perInstance:u.perInstance}}function f(e,r,n){let s=n.replace(/[^0-9A-Za-z._-]/g,"");return[`TS_CLOUD_LIVE_ID=$(basename "$(readlink -f ${e} 2>/dev/null)" 2>/dev/null || true)`,`if [ -z "$TS_CLOUD_LIVE_ID" ] || [ "$TS_CLOUD_LIVE_ID" = "." ]; then echo "${r}: no live release here; left alone"; exit 0; fi`,`case "${s}" in "$TS_CLOUD_LIVE_ID"*) ;; *) echo "${r} serves $TS_CLOUD_LIVE_ID, not ${s}; left alone"; exit 0 ;; esac`]}async function rm(e,r){let n=await l(e);if(n.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};let s=Vo(J(e.slug,r.siteName)),t=Math.max(1,r.limit??20),o=[`[ -f ${s} ] && tail -n ${t} ${s} || echo "no deploy history for ${r.siteName}"`],a=await e.driver.runRemoteDeploy({targets:n,commands:o,comment:`ts-cloud deploy:history ${e.slug}/${r.siteName}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});return{success:a.success,error:a.error,perInstance:a.perInstance}}async function nm(e,r){let n=e.logger||m,s=await l(e);if(s.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};n.step(`Running recipe '${r.name}' as ${r.user||"root"} on ${s.length} server(s)...`);let t=await e.driver.runRemoteDeploy({targets:s,commands:c({name:r.name,script:r.script,user:r.user}),comment:`ts-cloud recipe ${r.name}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});if(!t.success)n.error(`Recipe '${r.name}' failed: ${t.error||"unknown error"}`);else n.success(`Recipe '${r.name}' completed.`);return{success:t.success,error:t.error,perInstance:t.perInstance}}async function Uo(e,r){let n=e.logger||m;if(!r.database?.name)return{success:!1,error:"No appDatabase configured to restore."};let s=await l(e);if(s.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};n.step(`Restoring database '${r.database.name}'${r.from?` from ${r.from}`:" from the latest backup"} on ${s.length} server(s)...`);let t=await e.driver.runRemoteDeploy({targets:s,commands:Ti(r.database,{from:r.from}),comment:`ts-cloud db:restore ${e.slug}/${r.database.name}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});if(!t.success)n.error(`Restore failed: ${t.error||"unknown error"}`);else n.success(`Restored ${r.database.name}.`);return{success:t.success,error:t.error,perInstance:t.perInstance}}
|
|
3
|
+
export{Mo,rm,nm,Uo};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Ld={newConnectionsPerSecond:50,concurrentPerSource:100,synPerSecond:2000,burst:100,icmpPerSecond:5,banSeconds:600};function h(e){return{...Ld,...e.thresholds}}var _=/^(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{1,2})?$|^[0-9a-f:]+(?:\/\d{1,3})?$/i;function ds(e){if(!_.test(e))return!1;let[t,n]=e.split("/");if(t.includes(":"))return n==null||Number(n)>=0&&Number(n)<=128;let s=t.split(".");if(s.length!==4||s.some((a)=>Number(a)>255||a===""))return!1;return n==null||Number(n)>=0&&Number(n)<=32}function f(e){return[...new Set((e??[]).map((t)=>t.trim()).filter(ds))]}function y(e){let t=(e??[80,443]).filter((n)=>Number.isInteger(n)&&n>=1&&n<=65535);return[...new Set(t)].sort((n,s)=>n-s)}function Md(e={}){let t=h(e);return{"net.ipv4.tcp_syncookies":"1","net.ipv4.tcp_max_syn_backlog":String(Math.max(4096,t.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 Ud(e={}){let t=["# Managed by ts-cloud. Edits are overwritten on the next deploy.","# Network hardening against L3/L4 floods.",""];for(let[n,s]of Object.entries(Md(e)))t.push(`${n} = ${s}`);return`${t.join(`
|
|
2
2
|
`)}
|
|
3
|
-
`}function
|
|
4
|
-
`)}function
|
|
3
|
+
`}function Fd(e={}){let t=h(e),n=y(e.ports),s=f(e.allowlist),a=f(e.blocklist),l=e.monitorOnly?"counter":"counter drop",i=e.originProtection?.enabled?f(e.originProtection.cdnRanges):[],c=s.filter((r)=>!r.includes(":")),p=s.filter((r)=>r.includes(":")),u=a.filter((r)=>!r.includes(":")),o=["#!/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 ${t.banSeconds}s; }`,` set banned6 { type ipv6_addr; flags timeout; timeout ${t.banSeconds}s; }`];if(c.length>0)o.push(` set allow4 { type ipv4_addr; flags interval; elements = { ${c.join(", ")} } }`);if(p.length>0)o.push(` set allow6 { type ipv6_addr; flags interval; elements = { ${p.join(", ")} } }`);if(u.length>0)o.push(` set block4 { type ipv4_addr; flags interval; elements = { ${u.join(", ")} } }`);if(i.length>0)o.push(` set cdn4 { type ipv4_addr; flags interval; elements = { ${i.filter((r)=>!r.includes(":")).join(", ")} } }`);if(o.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"),c.length>0)o.push(" ip saddr @allow4 accept");if(p.length>0)o.push(" ip6 saddr @allow6 accept");if(u.length>0)o.push(" ip saddr @block4 counter drop");if(o.push(" ip saddr @banned4 counter drop"," ip6 saddr @banned6 counter drop",""),o.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 ${t.icmpPerSecond}/second burst ${t.burst} packets accept`," ip protocol icmp icmp type echo-request counter drop",""),n.length>0){let r=n.join(", ");if(o.push(" # Platform-wide SYN ceiling. Above it the kernel falls back to cookies.",` tcp dport { ${r} } ct state new limit rate ${t.synPerSecond}/second burst ${t.burst} packets accept`,""," # Per-source new-connection rate. This is what stops one host hammering.",` tcp dport { ${r} } ct state new meter conn_rate4 { ip saddr limit rate over ${t.newConnectionsPerSecond}/second burst ${t.burst} packets } add @banned4 { ip saddr } ${l}`,` tcp dport { ${r} } ct state new meter conn_rate6 { ip6 saddr limit rate over ${t.newConnectionsPerSecond}/second burst ${t.burst} packets } add @banned6 { ip6 saddr } ${l}`,""," # Concurrency ceiling per source: the slow-loris defence.",` tcp dport { ${r} } ct state new meter conn_count4 { ip saddr ct count over ${t.concurrentPerSource} } ${l}`,` tcp dport { ${r} } ct state new meter conn_count6 { ip6 saddr ct count over ${t.concurrentPerSource} } ${l}`,""),i.length>0)o.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 { ${r} } ip saddr != @cdn4 counter drop`,"")}return o.push(" }","}",""),o.join(`
|
|
4
|
+
`)}function Cr(e={}){return`#!/usr/bin/env bash
|
|
5
5
|
# Managed by ts-cloud. Installs L3/L4 flood mitigation.
|
|
6
6
|
set -euo pipefail
|
|
7
7
|
|
|
@@ -13,11 +13,11 @@ fi
|
|
|
13
13
|
|
|
14
14
|
install -d -m 0755 /etc/ts-cloud /etc/nftables.d
|
|
15
15
|
cat > /etc/sysctl.d/90-ts-cloud-ddos.conf <<'SYSCTL_EOF'
|
|
16
|
-
${
|
|
16
|
+
${Ud(e)}SYSCTL_EOF
|
|
17
17
|
sysctl --system >/dev/null
|
|
18
18
|
|
|
19
19
|
cat > /etc/nftables.d/ts-cloud-ddos.nft.new <<'NFT_EOF'
|
|
20
|
-
${
|
|
20
|
+
${Fd(e)}NFT_EOF
|
|
21
21
|
|
|
22
22
|
# Syntax-check before applying: a bad ruleset would leave the box unprotected.
|
|
23
23
|
if ! nft -c -f /etc/nftables.d/ts-cloud-ddos.nft.new; then
|
|
@@ -40,5 +40,5 @@ include "/etc/nftables.d/ts-cloud-ddos.nft"
|
|
|
40
40
|
fi
|
|
41
41
|
systemctl enable nftables >/dev/null 2>&1 || true
|
|
42
42
|
echo "ts-cloud: L3/L4 mitigation active"
|
|
43
|
-
`}var b=["off","monitor","rate_limit","challenge","lockdown"];function
|
|
44
|
-
export{
|
|
43
|
+
`}var b=["off","monitor","rate_limit","challenge","lockdown"];function Xp(e,t=[]){let n=[],s=Math.max(1,e.baselineRequestsPerSecond),a=e.requestsPerSecond/s,l=0,i=(g,v)=>{n.push(v),l=Math.max(l,b.indexOf(g))},c=a>=3;if(c)i("monitor",`Traffic is ${a.toFixed(1)}x the baseline.`);let p=e.topSourceShare>=0.25,u=e.errorRate>=0.25,o=(e.suspiciousAgentShare??0)>=0.5,r=e.uniqueSources>0&&e.requestsPerSecond/e.uniqueSources>=50;if(c&&p)i("rate_limit",`One source accounts for ${(e.topSourceShare*100).toFixed(0)}% of traffic.`);if(c&&r)i("rate_limit","Request rate per unique source is far above what a browser produces.");if(c&&u)i("challenge",`Error rate is ${(e.errorRate*100).toFixed(0)}% under load.`);if(c&&o)i("challenge","Most requests carry no recognisable browser agent.");if(a>=20&&(p||u||o||r))i("lockdown",`Traffic is ${a.toFixed(0)}x the baseline with attack-shaped characteristics.`);if(!c&&e.topSourceShare>=0.6&&e.requestsPerSecond>s)i("rate_limit","A single source dominates traffic without an overall surge.");let d=b[l],m={off:1,monitor:1,rate_limit:0.5,challenge:0.25,lockdown:0.1}[d];return{level:d,reasons:n,rateLimitFactor:m,challengeEnabled:d==="challenge"||d==="lockdown",staticOnly:d==="lockdown",banCandidates:d==="off"||d==="monitor"?[]:f(t)}}function us(e,t){return Math.max(1,Math.floor(e*t.rateLimitFactor))}
|
|
44
|
+
export{Ld,ds,Md,Ud,Fd,Cr,Xp,us};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{De,ra,Ro,ha,un,Bo,ya,Sa,wa,Aa}from"./chunk-sfb9q18c.js";import{n,r,a,e,p,i,Se}from"./chunk-a1zagtx1.js";import{u}from"./chunk-s6qnx8a8.js";import{v}from"./chunk-4vbnagyd.js";import{R}from"./chunk-rkd3x7fw.js";import{g}from"./chunk-59f6mqkj.js";import{existsSync as de,readdirSync as me,readFileSync as pe,statSync as fe}from"node:fs";import{join as ne,relative as ye}from"node:path";class K{client;region;constructor(t="us-east-1",s){this.region=t,this.client=new u(void 0,{profile:s})}async createSecret(t){let s={Name:t.Name};if(t.Description)s.Description=t.Description;if(t.KmsKeyId)s.KmsKeyId=t.KmsKeyId;if(t.SecretBinary)s.SecretBinary=t.SecretBinary;if(t.SecretString)s.SecretString=t.SecretString;if(t.Tags&&t.Tags.length>0)s.Tags=t.Tags;if(t.AddReplicaRegions&&t.AddReplicaRegions.length>0)s.AddReplicaRegions=t.AddReplicaRegions;if(t.ForceOverwriteReplicaSecret!==void 0)s.ForceOverwriteReplicaSecret=t.ForceOverwriteReplicaSecret;s.ClientRequestToken=t.ClientRequestToken||crypto.randomUUID();let o=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(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId,ReplicationStatus:o.ReplicationStatus}}async updateSecret(t){let s={SecretId:t.SecretId,ClientRequestToken:t.ClientRequestToken||crypto.randomUUID()};if(t.Description)s.Description=t.Description;if(t.KmsKeyId)s.KmsKeyId=t.KmsKeyId;if(t.SecretBinary)s.SecretBinary=t.SecretBinary;if(t.SecretString)s.SecretString=t.SecretString;let o=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(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId}}async putSecretValue(t){let s={SecretId:t.SecretId};if(t.SecretBinary)s.SecretBinary=t.SecretBinary;if(t.SecretString)s.SecretString=t.SecretString;if(t.VersionStages&&t.VersionStages.length>0)s.VersionStages=t.VersionStages;s.ClientRequestToken=t.ClientRequestToken||crypto.randomUUID();let o=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(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId,VersionStages:o.VersionStages}}async getSecretValue(t){let s={SecretId:t.SecretId};if(t.VersionId)s.VersionId=t.VersionId;if(t.VersionStage)s.VersionStage=t.VersionStage;let o=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(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId,SecretBinary:o.SecretBinary,SecretString:o.SecretString,VersionStages:o.VersionStages,CreatedDate:o.CreatedDate}}async describeSecret(t){let s={SecretId:t},o=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(s)});return this.parseSecret(o)}async listSecrets(t){let s={};if(t?.MaxResults)s.MaxResults=t.MaxResults;if(t?.NextToken)s.NextToken=t.NextToken;if(t?.Filters&&t.Filters.length>0)s.Filters=t.Filters;if(t?.SortOrder)s.SortOrder=t.SortOrder;let o=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(s)});return{SecretList:o.SecretList?.map((c)=>this.parseSecret(c)),NextToken:o.NextToken}}async deleteSecret(t){let s={SecretId:t.SecretId};if(t.RecoveryWindowInDays!==void 0)s.RecoveryWindowInDays=t.RecoveryWindowInDays;if(t.ForceDeleteWithoutRecovery!==void 0)s.ForceDeleteWithoutRecovery=t.ForceDeleteWithoutRecovery;let o=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(s)});return{ARN:o.ARN,Name:o.Name,DeletionDate:o.DeletionDate}}async restoreSecret(t){let s={SecretId:t},o=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(s)});return{ARN:o.ARN,Name:o.Name}}async rotateSecret(t){let s={SecretId:t.SecretId};if(t.ClientRequestToken)s.ClientRequestToken=t.ClientRequestToken;if(t.RotationLambdaARN)s.RotationLambdaARN=t.RotationLambdaARN;if(t.RotationRules)s.RotationRules=t.RotationRules;if(t.RotateImmediately!==void 0)s.RotateImmediately=t.RotateImmediately;let o=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(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId}}async cancelRotateSecret(t){let s={SecretId:t},o=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(s)});return{ARN:o.ARN,Name:o.Name}}async getResourcePolicy(t){let s={SecretId:t},o=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(s)});return{ARN:o.ARN,Name:o.Name,ResourcePolicy:o.ResourcePolicy}}async putResourcePolicy(t){let s={SecretId:t.SecretId,ResourcePolicy:t.ResourcePolicy};if(t.BlockPublicPolicy!==void 0)s.BlockPublicPolicy=t.BlockPublicPolicy;let o=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(s)});return{ARN:o.ARN,Name:o.Name}}async deleteResourcePolicy(t){let s={SecretId:t},o=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(s)});return{ARN:o.ARN,Name:o.Name}}async tagResource(t){let s={SecretId:t.SecretId,Tags:t.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(s)})}async untagResource(t){let s={SecretId:t.SecretId,TagKeys:t.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(s)})}async setString(t,s,o){try{let c=await this.putSecretValue({SecretId:t,SecretString:s});return{ARN:c.ARN,VersionId:c.VersionId}}catch(c){if(c.code==="ResourceNotFoundException"){let l=await this.createSecret({Name:t,SecretString:s,Description:o?.description,KmsKeyId:o?.kmsKeyId,Tags:o?.tags});return{ARN:l.ARN,VersionId:l.VersionId}}throw c}}async setJson(t,s,o){return this.setString(t,JSON.stringify(s),o)}async getString(t){return(await this.getSecretValue({SecretId:t})).SecretString}async getJson(t){let s=await this.getString(t);if(s)return JSON.parse(s);return}async listAll(){let t=[],s;do{let o=await this.listSecrets({NextToken:s});if(o.SecretList)t.push(...o.SecretList);s=o.NextToken}while(s);return t}parseSecret(t){return{ARN:t.ARN,Name:t.Name,Description:t.Description,KmsKeyId:t.KmsKeyId,RotationEnabled:t.RotationEnabled,RotationLambdaARN:t.RotationLambdaARN,RotationRules:t.RotationRules,LastRotatedDate:t.LastRotatedDate,LastChangedDate:t.LastChangedDate,LastAccessedDate:t.LastAccessedDate,DeletedDate:t.DeletedDate,NextRotationDate:t.NextRotationDate,Tags:t.Tags,SecretVersionsToStages:t.SecretVersionsToStages,CreatedDate:t.CreatedDate,PrimaryRegion:t.PrimaryRegion}}}function E(t,s){let o=t.environments?.[s]?.app;if(!o)throw Error(`No serverless app configured for environment '${s}'. Add environments.${s}.app to your config.`);let c=t.project.slug,l=t.environments?.[s]?.region||t.project.region||"us-east-1";return{app:o,slug:c,region:l,stackName:De(t,s),artifactBucket:ra(c,s),assetsBucket:Ro(c,s)}}function yt(t,s){let o=E(t,s),c=`${o.slug}-${s}`;return{region:o.region,slug:o.slug,stackName:o.stackName,functions:{http:`${c}-http`,queue:`${c}-queue`,cli:`${c}-cli`}}}async function q(t,s=8){let o;for(let c=0;c<s;c++)try{return await t()}catch(l){let d=l?.code||l?.name||"",m=String(l?.message||"");if(d==="ResourceConflictException"||/update is in progress|currently in the following state/i.test(m)){o=l,await new Promise((f)=>setTimeout(f,3000));continue}throw l}throw o}var ie=(t,s)=>`releases/${t}/${s}/current.json`;async function G(t,s,o,c){try{return await t.getObjectJson(s,ie(o,c))}catch{return null}}async function ae(t,s,o,c,l){await t.putObjectJson(s,ie(o,c),l)}async function Re(t,s){if(!t.secrets)return{};let o=new K(s),c={},l=Array.isArray(t.secrets)?t.secrets.map((d)=>({envName:d.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),secretId:d})):Object.entries(t.secrets).map(([d,m])=>({envName:d,secretId:m}));if(Array.isArray(t.secrets)){let d=new Map;for(let{envName:f,secretId:S}of l)d.set(f,[...d.get(f)??[],S]);let m=[...d.entries()].filter(([,f])=>f.length>1);if(m.length){let f=m.map(([S,h])=>`${S} ← ${h.join(", ")}`).join("; ");throw Error(`serverless secrets: multiple secrets map to the same env var (${f}). Use the map form { ENV_NAME: 'secret/id' } to disambiguate.`)}}for(let{envName:d,secretId:m}of l){let S=(await o.getSecretValue({SecretId:m})).SecretString??"";try{let h=JSON.parse(S);if(h&&typeof h==="object"&&!Array.isArray(h)){for(let[C,w]of Object.entries(h))c[C]=String(w);continue}}catch{}c[d]=S}return c}function Pd(t,s){let o={},c=s.DbProxyEndpoint||s.DbEndpoint;if(c)o.DB_CONNECTION="mysql",o.DB_HOST=c,o.DB_PORT="3306",o.DB_DATABASE=o.DB_DATABASE||"app";if(s.CacheEndpoint){if(o.REDIS_HOST=s.CacheEndpoint,o.REDIS_PORT="6379",t.cache?.driver==="elasticache")o.CACHE_STORE="redis",o.CACHE_DRIVER="redis",o.SESSION_DRIVER="redis"}return o}function Cs(t,s,o,c,l,d,m,f={}){let S=t.kind==="php"?wa({cacheDriver:t.cache?.driver==="elasticache"?"redis":"dynamodb"}):{};return{TSCLOUD_LAMBDA_MODE:c,TSCLOUD_ENV:o,MAINTENANCE_MODE:"0",...t.octane?{TSCLOUD_OCTANE:"1"}:{},...t.serveAssets?{TSCLOUD_SERVE_ASSETS:"1"}:{},...t.redirectRobotsTxt===!1?{TSCLOUD_REDIRECT_ROBOTS_TXT:"0"}:{},...S,...f,...s.app.cache?.driver!=="elasticache"?{TSCLOUD_CACHE_TABLE:`${s.slug}-${o}-cache`}:{},...m?{TSCLOUD_QUEUE:m,SQS_QUEUE:m}:{},...d?{ASSET_URL:d}:{},...t.env??{},...l}}function he(t){let s=t.slice(t.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"}[s]??"application/octet-stream"}function*oe(t){for(let s of me(t)){let o=ne(t,s);if(fe(o).isDirectory())yield*oe(o);else yield o}}async function ve(t,s,o,c,l=!1){let d=0;for(let m of oe(o)){let f=ye(o,m).replace(/\\/g,"/");if(!l&&f.split("/").some((S)=>S.startsWith(".")))continue;await t.putObject({bucket:s,key:`${c}/${f}`,body:pe(m),contentType:he(m),cacheControl:"public, max-age=31536000, immutable"}),d++}return d}function po(t,s){let o=Object.entries(s).reduce((c,[l,d])=>c+Buffer.byteLength(`${l}=${d}`,"utf8"),0);if(o>4096){let c=Object.entries(s).map(([l,d])=>[l,Buffer.byteLength(`${l}=${d}`,"utf8")]).sort((l,d)=>d[1]-l[1]).slice(0,5).map(([l,d])=>`${l} (${d}B)`).join(", ");throw Error(`${t}: environment variables total ${o}B, over AWS's 4096B limit (${o-4096}B too large). Largest: ${c}. Move large/secret values out of env — store them in Secrets Manager and fetch at cold start.`)}}async function U(t,s,o,c){po(s,o),await q(()=>t.updateFunctionConfiguration({FunctionName:s,Environment:{Variables:o}})),await t.waitForFunctionActive(s,120);let l=c.kind==="image"?{FunctionName:s,ImageUri:c.imageUri}:{FunctionName:s,S3Bucket:c.bucket,S3Key:c.key};await q(()=>t.updateFunctionCode(l)),await t.waitForFunctionActive(s,120)}async function X(t,s){let c=(await q(()=>t.publishVersion({FunctionName:s}))).Version;if(!c)throw Error(`publishVersion returned no version for ${s}`);return await q(()=>t.updateAlias({FunctionName:s,Name:"live",FunctionVersion:c})),c}async function mp(t,s,o={}){let c=E(t,s),{app:l,slug:d,region:m,stackName:f,artifactBucket:S}=c,h=o.projectRoot??process.cwd();i(`Deploying serverless app: ${d} (${s})`),e(`Stack: ${f}`),e(`Region: ${m}`);let C=new g(m),w=new v(m),b=new R(m),P=l.kind==="php",O=l.packaging==="image",N=Bo(l),V,I,k,Y,M=[];if(O&&N.usesLayer&&N.layerKind!=="php")throw Error(`packaging: 'image' currently supports PHP and managed Node runtimes. ${N.kind}${N.kind==="node"?` ${N.version}`:""} uses a custom runtime — `+"use the default zip packaging (the runtime layer is built + attached automatically).");if(O){p("Building + pushing container image");let{buildAndPushServerlessImage:y}=await import("./chunk-3ybxaehy.js"),A=await y({app:l,projectRoot:h,region:m,repository:`${d}-${s}`,skipBuild:o.skipBuild,onStep:(D)=>e(` ${D}`)});V=A.handlers,I={kind:"image",imageUri:A.imageUri},k=A.tag,M.push({ParameterKey:"ImageUri",ParameterValue:A.imageUri})}else{p("Packaging application");let y=P?Aa({projectRoot:h,app:l,skipBuild:o.skipBuild,onStep:(x)=>e(` ${x}`)}):await un({projectRoot:h,app:l,skipBuild:o.skipBuild,onStep:(x)=>e(` ${x}`)}),A=ha(d,s,y.sha256);if(e(`Artifact: ${y.sha256.slice(0,12)} (${(y.zip.length/1024).toFixed(0)} KB)`),V=y.handlers,k=y.sha256,N.usesLayer){let x=N.layerEnvVar?process.env[N.layerEnvVar]:void 0;if(Y=l.layers??(x?[x]:void 0),!Y?.length){let ge=N.layerKind==="php"?"serverless:build-php-layer":N.layerKind==="bun"?"serverless:build-bun-layer":"serverless:build-node-layer";throw Error(`${N.kind} apps on provided.al2023 need a runtime layer. Set environments.<env>.app.layers or the ${N.layerEnvVar} env var (build one with \`cloud ${ge}\`)${N.kind==="node"?", or use a managed Node version (18/20/22)":""}.`)}}if(!await C.bucketExists(S))p(`Creating artifact bucket ${S}`),await C.createBucket(S);if(await C.headObject(S,A).then((x)=>x!==null).catch(()=>!1))e("Artifact already uploaded — reusing");else p("Uploading artifact"),await C.putObject({bucket:S,key:A,body:y.zip,contentType:"application/zip"});I={kind:"zip",bucket:S,key:A},M.push({ParameterKey:"ArtifactBucket",ParameterValue:S},{ParameterKey:"ArtifactKey",ParameterValue:A})}let T=Sa({config:t,environment:s,app:l,handlers:V,runtimeLayers:Y}),te=JSON.stringify(T.template),re=["CAPABILITY_NAMED_IAM"],L=await w.describeStacks({stackName:f}).then((y)=>y.Stacks[0]?.StackStatus).catch(()=>{return}),J=L!==void 0;if(L&&/DELETE_IN_PROGRESS/.test(L))p("Waiting for an in-progress stack delete to finish"),await w.waitForStack(f,"stack-delete-complete").catch(()=>{}),J=!1;else if(L&&/(?:ROLLBACK_COMPLETE|REVIEW_IN_PROGRESS|CREATE_FAILED)/.test(L))p(`Deleting unusable stack (status ${L}) before recreate`),await w.deleteStack(f),await w.waitForStack(f,"stack-delete-complete").catch(()=>{}),J=!1;p(J?"Updating infrastructure stack":"Creating infrastructure stack");try{if(J)await w.updateStack({stackName:f,templateBody:te,parameters:M,capabilities:re}),await w.waitForStack(f,"stack-update-complete");else await w.createStack({stackName:f,templateBody:te,parameters:M,capabilities:re,onFailure:"DELETE"}),await w.waitForStack(f,"stack-create-complete")}catch(y){if(/No updates are to be performed/i.test(String(y?.message)))e("No infrastructure changes");else throw y}let Q=await w.getStackOutputs(f).catch(()=>({})),B;if(l.assets){let y=ne(h,l.assets);if(de(y)){let A=l.assetDomain||Q.AssetsCdnDomain;B=A?`https://${A}/${k}`:void 0,p(`Syncing assets from ${l.assets}`);let D=await ve(C,c.assetsBucket,y,k,l.dotFilesAsAssets);e(`Uploaded ${D} asset(s)${B?` → ${B}`:""}`)}else a(`Assets directory not found: ${y}`)}p("Resolving secrets");let _=await Re(l,m);if(l.database?.connection==="aurora-serverless")try{let A=await new K(m).getSecretValue({SecretId:`${d}/${s}/db`}),D=JSON.parse(A.SecretString??"{}");if(D.username)_.DB_USERNAME=D.username;if(D.password)_.DB_PASSWORD=D.password}catch(y){a(`Could not resolve Aurora DB credentials: ${y.message}`)}if(!await C.bucketExists(S))await C.createBucket(S);let H=await G(C,S,d,s),F={},Z=T.queueNames[0],ee=Pd(l,Q);if(p("Activating functions"),F.http=Cs(l,c,s,"http",_,B,Z,ee),await U(b,T.functionNames.http,F.http,I),F.cli=Cs(l,c,s,"cli",_,B,Z,ee),await U(b,T.functionNames.cli,F.cli,I),T.queueNames.length)F.queue=Cs(l,c,s,"queue",_,B,Z,ee),await U(b,T.functionNames.queue,F.queue,I);let se=(l.provisionedConcurrency??0)>0,W={};if(se){if(p("Publishing versions + flipping live alias"),W.http=await X(b,T.functionNames.http),W.cli=await X(b,T.functionNames.cli),T.queueNames.length)W.queue=await X(b,T.functionNames.queue)}if(await ae(C,S,d,s,{sha:k,code:I,previousSha:H?.sha,previousCode:H?.code,previousFunctionEnv:H?.functionEnv,...se?{functionVersions:W,previousFunctionVersions:H?.functionVersions}:{},functionEnv:F,functionNames:{http:T.functionNames.http,cli:T.functionNames.cli,...T.queueNames.length?{queue:T.functionNames.queue}:{}},assetUrl:B,timestamp:new Date().toISOString()}),!o.skipDeployHooks&&l.deploy?.length){p("Running deploy hooks");for(let y of l.deploy){e(` deploy: ${y}`);let A=await b.invoke({FunctionName:T.functionNames.cli,InvocationType:"RequestResponse",Payload:{command:y},LogType:"Tail"});if(A.FunctionError)throw r("Deploy hook failed — the new build is ALREADY LIVE."),e(` Roll back with: cloud serverless:rollback --env ${s}`),Error(`Deploy hook failed (${y}): ${A.Payload}`)}}let j=Q.HttpApiEndpoint;if(!o.skipHealthCheck&&j){p("Health check");try{let y=await fetch(j,{method:"GET"});e(`GET ${j} → ${y.status}`)}catch(y){a(`Health check could not reach ${j}: ${y.message}`)}}Se(["Serverless deploy complete","",j?`URL: ${j}`:"",`Stack: ${f}`,`Build: ${k.slice(0,12)}`].filter(Boolean).join(`
|
|
2
|
-
`),"green")}async function
|
|
3
|
-
export{K,
|
|
1
|
+
import{ke,ca,Ii,Ba,vn,Li,ja,Va,Xa,Qa}from"./chunk-qbagghsb.js";import{n,r,a,e,p,i,ve}from"./chunk-r3gxhy1k.js";import{u}from"./chunk-7rwc5bvv.js";import{v}from"./chunk-v4gpkkzh.js";import{I}from"./chunk-j01jx36v.js";import{g}from"./chunk-d5q09rxb.js";import{existsSync as de,readdirSync as me,readFileSync as pe,statSync as fe}from"node:fs";import{join as ne,relative as Se}from"node:path";class K{client;region;constructor(t="us-east-1",s){this.region=t,this.client=new u(void 0,{profile:s})}async createSecret(t){let s={Name:t.Name};if(t.Description)s.Description=t.Description;if(t.KmsKeyId)s.KmsKeyId=t.KmsKeyId;if(t.SecretBinary)s.SecretBinary=t.SecretBinary;if(t.SecretString)s.SecretString=t.SecretString;if(t.Tags&&t.Tags.length>0)s.Tags=t.Tags;if(t.AddReplicaRegions&&t.AddReplicaRegions.length>0)s.AddReplicaRegions=t.AddReplicaRegions;if(t.ForceOverwriteReplicaSecret!==void 0)s.ForceOverwriteReplicaSecret=t.ForceOverwriteReplicaSecret;s.ClientRequestToken=t.ClientRequestToken||crypto.randomUUID();let o=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(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId,ReplicationStatus:o.ReplicationStatus}}async updateSecret(t){let s={SecretId:t.SecretId,ClientRequestToken:t.ClientRequestToken||crypto.randomUUID()};if(t.Description)s.Description=t.Description;if(t.KmsKeyId)s.KmsKeyId=t.KmsKeyId;if(t.SecretBinary)s.SecretBinary=t.SecretBinary;if(t.SecretString)s.SecretString=t.SecretString;let o=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(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId}}async putSecretValue(t){let s={SecretId:t.SecretId};if(t.SecretBinary)s.SecretBinary=t.SecretBinary;if(t.SecretString)s.SecretString=t.SecretString;if(t.VersionStages&&t.VersionStages.length>0)s.VersionStages=t.VersionStages;s.ClientRequestToken=t.ClientRequestToken||crypto.randomUUID();let o=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(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId,VersionStages:o.VersionStages}}async getSecretValue(t){let s={SecretId:t.SecretId};if(t.VersionId)s.VersionId=t.VersionId;if(t.VersionStage)s.VersionStage=t.VersionStage;let o=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(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId,SecretBinary:o.SecretBinary,SecretString:o.SecretString,VersionStages:o.VersionStages,CreatedDate:o.CreatedDate}}async describeSecret(t){let s={SecretId:t},o=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(s)});return this.parseSecret(o)}async listSecrets(t){let s={};if(t?.MaxResults)s.MaxResults=t.MaxResults;if(t?.NextToken)s.NextToken=t.NextToken;if(t?.Filters&&t.Filters.length>0)s.Filters=t.Filters;if(t?.SortOrder)s.SortOrder=t.SortOrder;let o=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(s)});return{SecretList:o.SecretList?.map((c)=>this.parseSecret(c)),NextToken:o.NextToken}}async deleteSecret(t){let s={SecretId:t.SecretId};if(t.RecoveryWindowInDays!==void 0)s.RecoveryWindowInDays=t.RecoveryWindowInDays;if(t.ForceDeleteWithoutRecovery!==void 0)s.ForceDeleteWithoutRecovery=t.ForceDeleteWithoutRecovery;let o=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(s)});return{ARN:o.ARN,Name:o.Name,DeletionDate:o.DeletionDate}}async restoreSecret(t){let s={SecretId:t},o=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(s)});return{ARN:o.ARN,Name:o.Name}}async rotateSecret(t){let s={SecretId:t.SecretId};if(t.ClientRequestToken)s.ClientRequestToken=t.ClientRequestToken;if(t.RotationLambdaARN)s.RotationLambdaARN=t.RotationLambdaARN;if(t.RotationRules)s.RotationRules=t.RotationRules;if(t.RotateImmediately!==void 0)s.RotateImmediately=t.RotateImmediately;let o=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(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId}}async cancelRotateSecret(t){let s={SecretId:t},o=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(s)});return{ARN:o.ARN,Name:o.Name}}async getResourcePolicy(t){let s={SecretId:t},o=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(s)});return{ARN:o.ARN,Name:o.Name,ResourcePolicy:o.ResourcePolicy}}async putResourcePolicy(t){let s={SecretId:t.SecretId,ResourcePolicy:t.ResourcePolicy};if(t.BlockPublicPolicy!==void 0)s.BlockPublicPolicy=t.BlockPublicPolicy;let o=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(s)});return{ARN:o.ARN,Name:o.Name}}async deleteResourcePolicy(t){let s={SecretId:t},o=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(s)});return{ARN:o.ARN,Name:o.Name}}async tagResource(t){let s={SecretId:t.SecretId,Tags:t.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(s)})}async untagResource(t){let s={SecretId:t.SecretId,TagKeys:t.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(s)})}async setString(t,s,o){try{let c=await this.putSecretValue({SecretId:t,SecretString:s});return{ARN:c.ARN,VersionId:c.VersionId}}catch(c){if(c.code==="ResourceNotFoundException"){let l=await this.createSecret({Name:t,SecretString:s,Description:o?.description,KmsKeyId:o?.kmsKeyId,Tags:o?.tags});return{ARN:l.ARN,VersionId:l.VersionId}}throw c}}async setJson(t,s,o){return this.setString(t,JSON.stringify(s),o)}async getString(t){return(await this.getSecretValue({SecretId:t})).SecretString}async getJson(t){let s=await this.getString(t);if(s)return JSON.parse(s);return}async listAll(){let t=[],s;do{let o=await this.listSecrets({NextToken:s});if(o.SecretList)t.push(...o.SecretList);s=o.NextToken}while(s);return t}parseSecret(t){return{ARN:t.ARN,Name:t.Name,Description:t.Description,KmsKeyId:t.KmsKeyId,RotationEnabled:t.RotationEnabled,RotationLambdaARN:t.RotationLambdaARN,RotationRules:t.RotationRules,LastRotatedDate:t.LastRotatedDate,LastChangedDate:t.LastChangedDate,LastAccessedDate:t.LastAccessedDate,DeletedDate:t.DeletedDate,NextRotationDate:t.NextRotationDate,Tags:t.Tags,SecretVersionsToStages:t.SecretVersionsToStages,CreatedDate:t.CreatedDate,PrimaryRegion:t.PrimaryRegion}}}function k(t,s){let o=t.environments?.[s]?.app;if(!o)throw Error(`No serverless app configured for environment '${s}'. Add environments.${s}.app to your config.`);let c=t.project.slug,l=t.environments?.[s]?.region||t.project.region||"us-east-1";return{app:o,slug:c,region:l,stackName:ke(t,s),artifactBucket:ca(c,s),assetsBucket:Ii(c,s)}}function bt(t,s){let o=k(t,s),c=`${o.slug}-${s}`;return{region:o.region,slug:o.slug,stackName:o.stackName,functions:{http:`${c}-http`,queue:`${c}-queue`,cli:`${c}-cli`}}}async function q(t,s=8){let o;for(let c=0;c<s;c++)try{return await t()}catch(l){let d=l?.code||l?.name||"",m=String(l?.message||"");if(d==="ResourceConflictException"||/update is in progress|currently in the following state/i.test(m)){o=l,await new Promise((f)=>setTimeout(f,3000));continue}throw l}throw o}var ie=(t,s)=>`releases/${t}/${s}/current.json`;async function G(t,s,o,c){try{return await t.getObjectJson(s,ie(o,c))}catch{return null}}async function ae(t,s,o,c,l){await t.putObjectJson(s,ie(o,c),l)}async function ye(t,s){if(!t.secrets)return{};let o=new K(s),c={},l=Array.isArray(t.secrets)?t.secrets.map((d)=>({envName:d.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),secretId:d})):Object.entries(t.secrets).map(([d,m])=>({envName:d,secretId:m}));if(Array.isArray(t.secrets)){let d=new Map;for(let{envName:f,secretId:S}of l)d.set(f,[...d.get(f)??[],S]);let m=[...d.entries()].filter(([,f])=>f.length>1);if(m.length){let f=m.map(([S,R])=>`${S} ← ${R.join(", ")}`).join("; ");throw Error(`serverless secrets: multiple secrets map to the same env var (${f}). Use the map form { ENV_NAME: 'secret/id' } to disambiguate.`)}}for(let{envName:d,secretId:m}of l){let S=(await o.getSecretValue({SecretId:m})).SecretString??"";try{let R=JSON.parse(S);if(R&&typeof R==="object"&&!Array.isArray(R)){for(let[w,N]of Object.entries(R))c[w]=String(N);continue}}catch{}c[d]=S}return c}function zd(t,s){let o={},c=s.DbProxyEndpoint||s.DbEndpoint;if(c)o.DB_CONNECTION="mysql",o.DB_HOST=c,o.DB_PORT="3306",o.DB_DATABASE=o.DB_DATABASE||"app";if(s.CacheEndpoint){if(o.REDIS_HOST=s.CacheEndpoint,o.REDIS_PORT="6379",t.cache?.driver==="elasticache")o.CACHE_STORE="redis",o.CACHE_DRIVER="redis",o.SESSION_DRIVER="redis"}return o}function Do(t,s,o,c,l,d,m,f={}){let S=t.kind==="php"?Xa({cacheDriver:t.cache?.driver==="elasticache"?"redis":"dynamodb"}):{};return{TSCLOUD_LAMBDA_MODE:c,TSCLOUD_ENV:o,MAINTENANCE_MODE:"0",...t.octane?{TSCLOUD_OCTANE:"1"}:{},...t.serveAssets?{TSCLOUD_SERVE_ASSETS:"1"}:{},...t.redirectRobotsTxt===!1?{TSCLOUD_REDIRECT_ROBOTS_TXT:"0"}:{},...S,...f,...s.app.cache?.driver!=="elasticache"?{TSCLOUD_CACHE_TABLE:`${s.slug}-${o}-cache`}:{},...m?{TSCLOUD_QUEUE:m,SQS_QUEUE:m}:{},...d?{ASSET_URL:d}:{},...t.env??{},...l}}function Re(t){let s=t.slice(t.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"}[s]??"application/octet-stream"}function*oe(t){for(let s of me(t)){let o=ne(t,s);if(fe(o).isDirectory())yield*oe(o);else yield o}}async function he(t,s,o,c,l=!1){let d=0;for(let m of oe(o)){let f=Se(o,m).replace(/\\/g,"/");if(!l&&f.split("/").some((S)=>S.startsWith(".")))continue;await t.putObject({bucket:s,key:`${c}/${f}`,body:pe(m),contentType:Re(m),cacheControl:"public, max-age=31536000, immutable"}),d++}return d}function Ts(t,s){let o=Object.entries(s).reduce((c,[l,d])=>c+Buffer.byteLength(`${l}=${d}`,"utf8"),0);if(o>4096){let c=Object.entries(s).map(([l,d])=>[l,Buffer.byteLength(`${l}=${d}`,"utf8")]).sort((l,d)=>d[1]-l[1]).slice(0,5).map(([l,d])=>`${l} (${d}B)`).join(", ");throw Error(`${t}: environment variables total ${o}B, over AWS's 4096B limit (${o-4096}B too large). Largest: ${c}. Move large/secret values out of env — store them in Secrets Manager and fetch at cold start.`)}}async function U(t,s,o,c){Ts(s,o),await q(()=>t.updateFunctionConfiguration({FunctionName:s,Environment:{Variables:o}})),await t.waitForFunctionActive(s,120);let l=c.kind==="image"?{FunctionName:s,ImageUri:c.imageUri}:{FunctionName:s,S3Bucket:c.bucket,S3Key:c.key};await q(()=>t.updateFunctionCode(l)),await t.waitForFunctionActive(s,120)}async function X(t,s){let c=(await q(()=>t.publishVersion({FunctionName:s}))).Version;if(!c)throw Error(`publishVersion returned no version for ${s}`);return await q(()=>t.updateAlias({FunctionName:s,Name:"live",FunctionVersion:c})),c}async function Qp(t,s,o={}){let c=k(t,s),{app:l,slug:d,region:m,stackName:f,artifactBucket:S}=c,R=o.projectRoot??process.cwd();i(`Deploying serverless app: ${d} (${s})`),e(`Stack: ${f}`),e(`Region: ${m}`);let w=new g(m),N=new v(m),T=new I(m),P=l.kind==="php",O=l.packaging==="image",h=Li(l),V,E,b,Y,M=[];if(O&&h.usesLayer&&h.layerKind!=="php")throw Error(`packaging: 'image' currently supports PHP and managed Node runtimes. ${h.kind}${h.kind==="node"?` ${h.version}`:""} uses a custom runtime — `+"use the default zip packaging (the runtime layer is built + attached automatically).");if(O){p("Building + pushing container image");let{buildAndPushServerlessImage:y}=await import("./chunk-691k55nw.js"),C=await y({app:l,projectRoot:R,region:m,repository:`${d}-${s}`,skipBuild:o.skipBuild,onStep:(D)=>e(` ${D}`)});V=C.handlers,E={kind:"image",imageUri:C.imageUri},b=C.tag,M.push({ParameterKey:"ImageUri",ParameterValue:C.imageUri})}else{p("Packaging application");let y=P?Qa({projectRoot:R,app:l,skipBuild:o.skipBuild,onStep:(x)=>e(` ${x}`)}):await vn({projectRoot:R,app:l,skipBuild:o.skipBuild,onStep:(x)=>e(` ${x}`)}),C=Ba(d,s,y.sha256);if(e(`Artifact: ${y.sha256.slice(0,12)} (${(y.zip.length/1024).toFixed(0)} KB)`),V=y.handlers,b=y.sha256,h.usesLayer){let x=h.layerEnvVar?process.env[h.layerEnvVar]:void 0;if(Y=l.layers??(x?[x]:void 0),!Y?.length){let ge=h.layerKind==="php"?"serverless:build-php-layer":h.layerKind==="bun"?"serverless:build-bun-layer":"serverless:build-node-layer";throw Error(`${h.kind} apps on provided.al2023 need a runtime layer. Set environments.<env>.app.layers or the ${h.layerEnvVar} env var (build one with \`cloud ${ge}\`)${h.kind==="node"?", or use a managed Node version (18/20/22)":""}.`)}}if(!await w.bucketExists(S))p(`Creating artifact bucket ${S}`),await w.createBucket(S);if(await w.headObject(S,C).then((x)=>x!==null).catch(()=>!1))e("Artifact already uploaded — reusing");else p("Uploading artifact"),await w.putObject({bucket:S,key:C,body:y.zip,contentType:"application/zip"});E={kind:"zip",bucket:S,key:C},M.push({ParameterKey:"ArtifactBucket",ParameterValue:S},{ParameterKey:"ArtifactKey",ParameterValue:C})}let A=Va({config:t,environment:s,app:l,handlers:V,runtimeLayers:Y}),te=JSON.stringify(A.template),re=["CAPABILITY_NAMED_IAM"],L=await N.describeStacks({stackName:f}).then((y)=>y.Stacks[0]?.StackStatus).catch(()=>{return}),J=L!==void 0;if(L&&/DELETE_IN_PROGRESS/.test(L))p("Waiting for an in-progress stack delete to finish"),await N.waitForStack(f,"stack-delete-complete").catch(()=>{}),J=!1;else if(L&&/(?:ROLLBACK_COMPLETE|REVIEW_IN_PROGRESS|CREATE_FAILED)/.test(L))p(`Deleting unusable stack (status ${L}) before recreate`),await N.deleteStack(f),await N.waitForStack(f,"stack-delete-complete").catch(()=>{}),J=!1;p(J?"Updating infrastructure stack":"Creating infrastructure stack");try{if(J)await N.updateStack({stackName:f,templateBody:te,parameters:M,capabilities:re}),await N.waitForStack(f,"stack-update-complete");else await N.createStack({stackName:f,templateBody:te,parameters:M,capabilities:re,onFailure:"DELETE"}),await N.waitForStack(f,"stack-create-complete")}catch(y){if(/No updates are to be performed/i.test(String(y?.message)))e("No infrastructure changes");else throw y}let Q=await N.getStackOutputs(f).catch(()=>({})),B;if(l.assets){let y=ne(R,l.assets);if(de(y)){let C=l.assetDomain||Q.AssetsCdnDomain;B=C?`https://${C}/${b}`:void 0,p(`Syncing assets from ${l.assets}`);let D=await he(w,c.assetsBucket,y,b,l.dotFilesAsAssets);e(`Uploaded ${D} asset(s)${B?` → ${B}`:""}`)}else a(`Assets directory not found: ${y}`)}p("Resolving secrets");let _=await ye(l,m);if(l.database?.connection==="aurora-serverless")try{let C=await new K(m).getSecretValue({SecretId:`${d}/${s}/db`}),D=JSON.parse(C.SecretString??"{}");if(D.username)_.DB_USERNAME=D.username;if(D.password)_.DB_PASSWORD=D.password}catch(y){a(`Could not resolve Aurora DB credentials: ${y.message}`)}if(!await w.bucketExists(S))await w.createBucket(S);let H=await G(w,S,d,s),F={},Z=A.queueNames[0],ee=zd(l,Q);if(p("Activating functions"),F.http=Do(l,c,s,"http",_,B,Z,ee),await U(T,A.functionNames.http,F.http,E),F.cli=Do(l,c,s,"cli",_,B,Z,ee),await U(T,A.functionNames.cli,F.cli,E),A.queueNames.length)F.queue=Do(l,c,s,"queue",_,B,Z,ee),await U(T,A.functionNames.queue,F.queue,E);let se=(l.provisionedConcurrency??0)>0,W={};if(se){if(p("Publishing versions + flipping live alias"),W.http=await X(T,A.functionNames.http),W.cli=await X(T,A.functionNames.cli),A.queueNames.length)W.queue=await X(T,A.functionNames.queue)}if(await ae(w,S,d,s,{sha:b,code:E,previousSha:H?.sha,previousCode:H?.code,previousFunctionEnv:H?.functionEnv,...se?{functionVersions:W,previousFunctionVersions:H?.functionVersions}:{},functionEnv:F,functionNames:{http:A.functionNames.http,cli:A.functionNames.cli,...A.queueNames.length?{queue:A.functionNames.queue}:{}},assetUrl:B,timestamp:new Date().toISOString()}),!o.skipDeployHooks&&l.deploy?.length){p("Running deploy hooks");for(let y of l.deploy){e(` deploy: ${y}`);let C=await T.invoke({FunctionName:A.functionNames.cli,InvocationType:"RequestResponse",Payload:{command:y},LogType:"Tail"});if(C.FunctionError)throw r("Deploy hook failed — the new build is ALREADY LIVE."),e(` Roll back with: cloud serverless:rollback --env ${s}`),Error(`Deploy hook failed (${y}): ${C.Payload}`)}}let j=Q.HttpApiEndpoint;if(!o.skipHealthCheck&&j){p("Health check");try{let y=await fetch(j,{method:"GET"});e(`GET ${j} → ${y.status}`)}catch(y){a(`Health check could not reach ${j}: ${y.message}`)}}ve(["Serverless deploy complete","",j?`URL: ${j}`:"",`Stack: ${f}`,`Build: ${b.slice(0,12)}`].filter(Boolean).join(`
|
|
2
|
+
`),"green")}async function No(t,s){let o=k(t,s),c=new g(o.region),l=new I(o.region),d=await G(c,o.artifactBucket,o.slug,s);if(!d)throw Error("No previous release to redeploy. Run a full deploy first.");i(`Redeploying ${o.slug} (${s}) — build ${d.sha.slice(0,12)}`);for(let[m,f]of Object.entries(d.functionNames)){if(!f)continue;p(`Re-activating ${m} (${f})`),await U(l,f,d.functionEnv[m]??{},d.code);let S=d.functionVersions?.[m];if(S)await q(()=>l.updateAlias({FunctionName:f,Name:"live",FunctionVersion:S}))}n("Redeploy complete")}async function ko(t,s){let o=k(t,s),c=new g(o.region),l=new I(o.region),d=await G(c,o.artifactBucket,o.slug,s);if(!d?.previousCode)throw Error("No previous release to roll back to.");i(`Rolling back ${o.slug} (${s}) → ${d.previousSha?.slice(0,12)}`);for(let[m,f]of Object.entries(d.functionNames)){if(!f)continue;p(`Restoring ${m} (${f})`);let S=d.previousFunctionEnv?.[m]??d.functionEnv[m]??{};await U(l,f,S,d.previousCode);let R=d.previousFunctionVersions?.[m];if(R)await q(()=>l.updateAlias({FunctionName:f,Name:"live",FunctionVersion:R}))}await ae(c,o.artifactBucket,o.slug,s,{...d,sha:d.previousSha??d.sha,code:d.previousCode,functionEnv:d.previousFunctionEnv??d.functionEnv,functionVersions:d.previousFunctionVersions??d.functionVersions,previousSha:void 0,previousCode:void 0,previousFunctionEnv:void 0,previousFunctionVersions:void 0,timestamp:new Date().toISOString()}),n("Rollback complete")}async function Es(t,s,o,c){let l=k(t,s),d=new I(l.region),m=`${l.slug}-${s}-http`,S={...(await d.getFunction(m)).Configuration?.Environment?.Variables??{}};if(S.MAINTENANCE_MODE=o?"1":"0",o&&c)S.MAINTENANCE_BYPASS_SECRET=c;if(!o)delete S.MAINTENANCE_BYPASS_SECRET;if(await q(()=>d.updateFunctionConfiguration({FunctionName:m,Environment:{Variables:S}})),(l.app.provisionedConcurrency??0)>0)await d.waitForFunctionActive(m,120),await X(d,m);n(o?"Application is now in maintenance mode (503)":"Application is live")}async function Bt(t,s,o){let c=k(t,s),l=new I(c.region),d=`${c.slug}-${s}-cli`,m=await l.invoke({FunctionName:d,InvocationType:"RequestResponse",Payload:{command:o},LogType:"Tail"});if(m.FunctionError)throw Error(`Command failed: ${m.Payload}`);return m.Payload??""}var ce=(t,s)=>`commands/${t}/${s}/history.json`,Ne=50;async function le(t,s,o,c){try{return(await t.getObjectJson(s,ce(o,c)))?.records??[]}catch{return[]}}async function Yp(t,s,o){let c=k(t,s),l=new I(c.region),d=`${c.slug}-${s}-cli`,m=await l.invoke({FunctionName:d,InvocationType:"RequestResponse",Payload:{command:o},LogType:"Tail"}),f=m.Payload??"",S=m.FunctionError?"error":"ok",R=-1;try{let w=new g(c.region);if(await w.bucketExists(c.artifactBucket)){let N=await le(w,c.artifactBucket,c.slug,s);R=N.reduce((T,P)=>Math.max(T,P.id),0)+1,N.push({id:R,command:o,timestamp:new Date().toISOString(),status:S,output:f.slice(0,4000)}),await w.putObjectJson(c.artifactBucket,ce(c.slug,s),{records:N.slice(-Ne)})}}catch{}if(m.FunctionError)throw Error(`Command failed${R>0?` (#${R})`:""}: ${f}`);return{id:R,status:S,output:f}}async function Hd(t,s){let o=k(t,s),c=new g(o.region);return le(c,o.artifactBucket,o.slug,s)}async function Zp(t,s,o){let c=await Hd(t,s);if(!c.length)return;return o==null?c[c.length-1]:c.find((l)=>l.id===o)}async function em(t,s,o){let c=Buffer.from(o,"utf-8").toString("base64");return Bt(t,s,`tscloud:db-query --sql-base64=${c}`)}async function z(t,s){let o=k(t,s),c=new v(o.region),l=new I(o.region),d=new g(o.region),m="not deployed",f={};try{let{Stacks:O}=await c.describeStacks({stackName:o.stackName});m=O?.[0]?.StackStatus??m;for(let h of O?.[0]?.Outputs??[])if(h.OutputKey)f[h.OutputKey]=h.OutputValue??""}catch{}let S=ja(o.app,o.slug,s),R=o.app.provisionedConcurrency??0,w=["http","cli",...S.length?["queue"]:[]],N=`${o.slug}-${s}`,T=[];for(let O of w){let h=`${N}-${O}`,V={mode:O,name:h,version:"$LATEST"};if(R>0){let E=await l.getAlias(h,"live").catch(()=>null);if(E?.FunctionVersion){V.version=E.FunctionVersion;let b=await l.getProvisionedConcurrencyConfig(h,"live").catch(()=>null);if(b)V.provisioned={status:b.Status??"-",allocated:b.AllocatedProvisionedConcurrentExecutions??0,requested:b.RequestedProvisionedConcurrentExecutions??0}}}T.push(V)}let P=await G(d,o.artifactBucket,o.slug,s).catch(()=>null);return{slug:o.slug,environment:s,region:o.region,stackStatus:m,endpoint:f.HttpApiEndpoint,assetUrl:P?.assetUrl,scheduler:o.app.scheduler??"on",queues:S,provisionedConcurrency:R,functions:T,lastRelease:P?{sha:P.sha,timestamp:P.timestamp}:void 0}}function ue(t,s){return`${t}-${s}-db`}async function xo(t,s,o,c){let l=k(t,s);if(l.app.database?.connection!=="aurora-serverless")throw Error("No Aurora Serverless v2 database is configured for this environment.");let{RDSClient:d}=await import("./chunk-tj589nbw.js"),m=new d(l.region),f=ue(l.slug,s);p(`Scaling ${f} → ${o}–${c} ACUs`),await m.modifyDBCluster({DBClusterIdentifier:f,ServerlessV2ScalingConfiguration:{MinCapacity:o,MaxCapacity:c},ApplyImmediately:!0}),n(`Scaling applied to ${f} (takes effect shortly).`)}async function tm(t,s,o){let c=k(t,s);if(c.app.database?.connection!=="aurora-serverless")throw Error("No Aurora Serverless v2 database is configured for this environment.");if(!o.toTime&&!o.latest)throw Error("Specify a restore point: --to <ISO timestamp> or --latest.");let{RDSClient:l}=await import("./chunk-tj589nbw.js"),d=new l(c.region),m=ue(c.slug,s),f=o.latest?"latest":o.toTime.toISOString().replace(/[^0-9]/g,"").slice(0,14),S=o.target??`${m}-restore-${f}`;p(`Restoring ${m} → new cluster ${S} (${o.latest?"latest restorable time":o.toTime.toISOString()})`),await d.restoreDBClusterToPointInTime({DBClusterIdentifier:S,SourceDBClusterIdentifier:m,RestoreToTime:o.toTime,UseLatestRestorableTime:o.latest}),p("Waiting for the restored cluster to be ready");for(let R=0;R<120;R++){let{DBClusters:w}=await d.describeDBClusters({DBClusterIdentifier:S}),N=w?.[0]?.Status;if(N&&N!=="creating")break;await new Promise((T)=>setTimeout(T,15000))}return p("Adding a writer instance"),await d.createDBInstance({DBInstanceIdentifier:`${S}-1`,DBClusterIdentifier:S,Engine:"aurora-mysql",DBInstanceClass:"db.serverless"}),n(`Restore complete → cluster ${S} with writer ${S}-1. Point an env's database at it once available.`),S}
|
|
3
|
+
export{K,bt,zd,Do,Ts,Qp,No,ko,Es,Bt,Yp,Hd,Zp,em,z,xo,tm};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{
|
|
1
|
+
import{zs,vn,Ha,Cn,Gs,qs}from"./chunk-qbagghsb.js";import{e}from"./chunk-r3gxhy1k.js";import{yt}from"./chunk-2qdktx9h.js";import{execFileSync as C}from"node:child_process";import{mkdirSync as w,mkdtempSync as I,rmSync as U,writeFileSync as g}from"node:fs";import{tmpdir as j}from"node:os";import{dirname as O,join as o}from"node:path";function E(s,t){for(let r of t){let d=o(s,r.name);w(O(d),{recursive:!0}),g(d,r.data,r.mode?{mode:r.mode}:void 0)}}async function Pp(s){let{app:t,projectRoot:r,region:d,repository:u}=s,x=t.architecture??"x86_64",R=x==="arm64"?"linux/arm64":"linux/amd64",b=t.kind==="php",n=s.onStep??(()=>{}),a=I(o(j(),"tscloud-img-"));try{let h=o(a,"app");w(h,{recursive:!0});let f,y;if(b){Gs({projectRoot:r,app:t,skipBuild:s.skipBuild,onStep:n}),n("staging application tree");let i=qs(r);E(h,i),E(o(a,"runtime"),Cn().map((c)=>({name:c.path,data:c.contents,mode:c.mode})));let v=t.handlers?.http??"public/index.php";f={http:v,queue:t.handlers?.queue??v,cli:t.handlers?.cli??v},y=zs(i.map((c)=>`${c.name}:${c.data.length}`).join("|"))}else{n("bundling application");let i=await vn({projectRoot:r,app:t,skipBuild:s.skipBuild,onStep:n});g(o(h,"index.mjs"),i.bundle),f=i.handlers,y=i.sha256}let B=y.slice(0,16);g(o(a,"Dockerfile"),Ha({kind:t.kind??"node",phpVersion:t.phpVersion,architecture:x}));let k=new yt(d),p;try{p=(await k.describeRepositories({repositoryNames:[u]})).repositories?.[0]?.repositoryUri??""}catch{p=""}if(!p)n(`creating ECR repository ${u}`),p=(await k.createRepository({repositoryName:u,imageScanningConfiguration:{scanOnPush:!0}})).repository?.repositoryUri??"";if(!p)throw Error(`could not resolve ECR repository URI for ${u}`);let l=`${p}:${B}`;n("docker build"),C("docker",["build","--platform",R,"--provenance=false","--sbom=false","-t",l,a],{stdio:"inherit"}),n("ecr auth + push");let m=(await k.getAuthorizationToken()).authorizationData?.[0];if(!m?.authorizationToken||!m.proxyEndpoint)throw Error("failed to get an ECR authorization token");let A=m.proxyEndpoint.replace(/^https?:\/\//,""),S=o(a,".docker");return w(S,{recursive:!0}),g(o(S,"config.json"),JSON.stringify({auths:{[A]:{auth:m.authorizationToken}}})),C("docker",["push",l],{stdio:"inherit",env:{...process.env,DOCKER_CONFIG:S}}),e(`Image: ${l}`),{imageUri:l,tag:B,handlers:f}}finally{U(a,{recursive:!0,force:!0})}}
|
|
2
|
+
export{Pp};
|