@stacksjs/ts-cloud 0.16.72 → 0.16.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/dist/aws/index.js +1 -1
  2. package/dist/bin/{chunk-kcgs4z6p.js → chunk-0sswdcvq.js} +1 -1
  3. package/dist/bin/{chunk-whecvra8.js → chunk-10z6s9nj.js} +2 -2
  4. package/dist/bin/{chunk-7rb06mds.js → chunk-11xdxrp3.js} +75 -75
  5. package/dist/bin/chunk-1pj60edk.js +1 -0
  6. package/dist/bin/chunk-1qcztara.js +1 -0
  7. package/dist/bin/{chunk-s5gyhgw1.js → chunk-28a6yey5.js} +1 -1
  8. package/dist/bin/{chunk-8wvtmxpw.js → chunk-47yznk07.js} +1 -1
  9. package/dist/bin/{chunk-0g9ze9v3.js → chunk-613m8vf9.js} +1 -1
  10. package/dist/bin/{chunk-79n440fm.js → chunk-69j7md80.js} +8 -8
  11. package/dist/bin/{chunk-gsp1secn.js → chunk-6gspchrt.js} +1 -1
  12. package/dist/bin/{chunk-jnt0ypm6.js → chunk-8fspkmer.js} +8 -8
  13. package/dist/bin/{chunk-fvj9ktkm.js → chunk-9twr514q.js} +1 -1
  14. package/dist/bin/{chunk-9cqzzkrd.js → chunk-9zbfadg4.js} +1 -1
  15. package/dist/bin/{chunk-1c91h57k.js → chunk-c99xvba1.js} +3 -3
  16. package/dist/bin/{chunk-jk4v9sj1.js → chunk-cs2a075v.js} +4 -4
  17. package/dist/bin/chunk-cvet8kjp.js +1 -0
  18. package/dist/bin/{chunk-xt3jhs2k.js → chunk-e6kfkaxc.js} +1 -1
  19. package/dist/bin/{chunk-5z0g7y0s.js → chunk-eevqxagd.js} +100 -100
  20. package/dist/bin/{chunk-9362t52n.js → chunk-ekr2rzf6.js} +2 -2
  21. package/dist/bin/chunk-f80asgbh.js +1 -0
  22. package/dist/bin/{chunk-2j2xcq2h.js → chunk-fwcd0ef4.js} +1 -1
  23. package/dist/bin/{chunk-27t4ve22.js → chunk-gghy8mb4.js} +27 -27
  24. package/dist/bin/{chunk-jcbtp3aj.js → chunk-jh4ajbt1.js} +1 -1
  25. package/dist/bin/{chunk-00hq474q.js → chunk-qw5ch629.js} +1 -1
  26. package/dist/bin/{chunk-gwn9pezq.js → chunk-r5cpsqqk.js} +3 -3
  27. package/dist/bin/{chunk-efafd6hw.js → chunk-sfv47z62.js} +6 -6
  28. package/dist/bin/{chunk-8yv9ech5.js → chunk-t6njpv8j.js} +1 -1
  29. package/dist/bin/{chunk-efghc0tr.js → chunk-tvd5w8xq.js} +2 -2
  30. package/dist/bin/{chunk-erdkgb1d.js → chunk-w244mfsx.js} +2 -2
  31. package/dist/bin/{chunk-0k75pjkr.js → chunk-wkwcskhg.js} +1 -1
  32. package/dist/bin/{chunk-z7fnx9gx.js → chunk-yjmydj1w.js} +1 -1
  33. package/dist/bin/chunk-yqqx644v.js +1 -0
  34. package/dist/bin/{chunk-kb0yy9t1.js → chunk-zcq82zv1.js} +2 -2
  35. package/dist/bin/cli.js +212 -212
  36. package/dist/bin/dashboard-server.js +1 -1
  37. package/dist/{chunk-ms84y9kg.js → chunk-1ktv8jxf.js} +1 -1
  38. package/dist/{chunk-e32qtz2d.js → chunk-277enqjc.js} +78 -78
  39. package/dist/{chunk-rkashc9e.js → chunk-2r334egt.js} +1 -1
  40. package/dist/{chunk-2dffxn73.js → chunk-49raybtd.js} +1 -1
  41. package/dist/{chunk-1y1b1jy0.js → chunk-49rt1jbe.js} +1 -1
  42. package/dist/{chunk-ts2n068z.js → chunk-65fwpzeg.js} +14 -14
  43. package/dist/{chunk-vx5n4bhb.js → chunk-7qhcfnqf.js} +1 -1
  44. package/dist/{chunk-nx8dbae2.js → chunk-8ynkxbj6.js} +1 -1
  45. package/dist/{chunk-gssa1974.js → chunk-c2hvf1h5.js} +1 -1
  46. package/dist/chunk-c5pq3x7x.js +1 -0
  47. package/dist/{chunk-pydkxpf9.js → chunk-cfyn21gd.js} +1 -1
  48. package/dist/{chunk-3m5x6nrt.js → chunk-dq9g7cg9.js} +1 -1
  49. package/dist/{chunk-ysv0f0k5.js → chunk-ebb7j388.js} +1 -1
  50. package/dist/{chunk-0cd0mk3e.js → chunk-f4qv0c6w.js} +2 -2
  51. package/dist/{chunk-78xspqp6.js → chunk-fd6gsz34.js} +1 -1
  52. package/dist/chunk-fvad4wm8.js +1 -0
  53. package/dist/chunk-gc8r2gvd.js +1 -0
  54. package/dist/{chunk-3k9kdbsc.js → chunk-ggqxjcbe.js} +1 -1
  55. package/dist/chunk-k0scshn2.js +1 -0
  56. package/dist/{chunk-0nmtzbqn.js → chunk-mqr6s8wa.js} +1 -1
  57. package/dist/{chunk-65dddt6g.js → chunk-qcs3qkdf.js} +1 -1
  58. package/dist/{chunk-me647jxj.js → chunk-s7gv665w.js} +96 -96
  59. package/dist/chunk-sacbxd79.js +1 -0
  60. package/dist/{chunk-v3z51fs0.js → chunk-ssywr12y.js} +1 -1
  61. package/dist/{chunk-68pafbpe.js → chunk-yqzc3a9m.js} +108 -108
  62. package/dist/{chunk-1eg5wsn2.js → chunk-z90dv6jx.js} +5 -5
  63. package/dist/deploy/index.js +1 -1
  64. package/dist/dns/index.js +1 -1
  65. package/dist/drivers/hetzner/client.d.ts +5 -0
  66. package/dist/drivers/index.js +1 -1
  67. package/dist/index.js +39 -39
  68. package/dist/mail/index.js +1 -1
  69. package/dist/operations/index.js +1 -1
  70. package/dist/protection/index.js +1 -1
  71. package/dist/spend/index.js +1 -1
  72. package/dist/ui/404.html +1 -1
  73. package/dist/ui/accept-invitation.html +1 -1
  74. package/dist/ui/access-denied.html +1 -1
  75. package/dist/ui/account/automation.html +6 -6
  76. package/dist/ui/account/security.html +2 -2
  77. package/dist/ui/applications/compose.html +6 -6
  78. package/dist/ui/applications/new.html +2 -2
  79. package/dist/ui/data/backups.html +6 -6
  80. package/dist/ui/data/services.html +6 -6
  81. package/dist/ui/data/volumes.html +6 -6
  82. package/dist/ui/index.html +6 -6
  83. package/dist/ui/infrastructure/topology.html +6 -6
  84. package/dist/ui/integrations.html +1 -1
  85. package/dist/ui/operations/alerts.html +6 -6
  86. package/dist/ui/operations/configuration.html +6 -6
  87. package/dist/ui/operations/jobs.html +6 -6
  88. package/dist/ui/operations/maintenance.html +5 -5
  89. package/dist/ui/operations/observability.html +6 -6
  90. package/dist/ui/operations/previews.html +6 -6
  91. package/dist/ui/operations/queue.html +5 -5
  92. package/dist/ui/operations/regions.html +5 -5
  93. package/dist/ui/operations/releases.html +6 -6
  94. package/dist/ui/operations/spend.html +6 -6
  95. package/dist/ui/operations/workloads.html +6 -6
  96. package/dist/ui/security.html +1 -1
  97. package/dist/ui/server/actions.html +6 -6
  98. package/dist/ui/server/activity.html +1 -1
  99. package/dist/ui/server/capacity.html +5 -5
  100. package/dist/ui/server/database.html +6 -6
  101. package/dist/ui/server/deployments.html +6 -6
  102. package/dist/ui/server/diagnostics.html +2 -2
  103. package/dist/ui/server/firewall.html +6 -6
  104. package/dist/ui/server/fleet.html +6 -6
  105. package/dist/ui/server/logs.html +6 -6
  106. package/dist/ui/server/metrics.html +6 -6
  107. package/dist/ui/server/security.html +2 -2
  108. package/dist/ui/server/services.html +1 -1
  109. package/dist/ui/server/sites.html +6 -6
  110. package/dist/ui/server/ssh-keys.html +6 -6
  111. package/dist/ui/server/team.html +6 -6
  112. package/dist/ui/server/terminal.html +2 -2
  113. package/dist/ui/serverless/alarms.html +6 -6
  114. package/dist/ui/serverless/assets.html +2 -2
  115. package/dist/ui/serverless/cost.html +2 -2
  116. package/dist/ui/serverless/data.html +6 -6
  117. package/dist/ui/serverless/deployments.html +2 -2
  118. package/dist/ui/serverless/firewall.html +1 -1
  119. package/dist/ui/serverless/functions.html +6 -6
  120. package/dist/ui/serverless/logs.html +6 -6
  121. package/dist/ui/serverless/metrics.html +2 -2
  122. package/dist/ui/serverless/queues.html +6 -6
  123. package/dist/ui/serverless/secrets.html +6 -6
  124. package/dist/ui/serverless/traces.html +6 -6
  125. package/dist/ui/serverless.html +5 -5
  126. package/package.json +3 -3
  127. package/dist/bin/chunk-93pj5314.js +0 -1
  128. package/dist/bin/chunk-cq7gxt10.js +0 -1
  129. package/dist/bin/chunk-fy62gtke.js +0 -1
  130. package/dist/bin/chunk-h03hh7qw.js +0 -1
  131. package/dist/bin/chunk-jvwbq6j5.js +0 -1
  132. package/dist/chunk-2b4knhhy.js +0 -1
  133. package/dist/chunk-az9wzy1w.js +0 -1
  134. package/dist/chunk-g96mv4z5.js +0 -1
  135. package/dist/chunk-h3e1qc75.js +0 -1
  136. package/dist/chunk-qy8r2vwh.js +0 -1
@@ -1,2 +1,2 @@
1
- import{n}from"./chunk-1eg5wsn2.js";import{h}from"./chunk-g0bh9atv.js";class A{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new n(void 0,{profile:t})}async createStack(e){let t={Action:"CreateStack",StackName:e.stackName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;else throw Error("Either templateBody or templateUrl must be provided");if(e.parameters)e.parameters.forEach((a,r)=>{t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.roleArn)t.RoleARN=e.roleArn;if(e.tags)e.tags.forEach((a,r)=>{t[`Tags.member.${r+1}.Key`]=a.Key,t[`Tags.member.${r+1}.Value`]=a.Value});if(e.timeoutInMinutes)t.TimeoutInMinutes=e.timeoutInMinutes;if(e.onFailure)t.OnFailure=e.onFailure;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackId:s.StackId||s.CreateStackResult?.StackId}}async updateStack(e){let t={Action:"UpdateStack",StackName:e.stackName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;if(e.parameters)e.parameters.forEach((a,r)=>{if(t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,a.UsePreviousValue)t[`Parameters.member.${r+1}.UsePreviousValue`]="true";else t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.roleArn)t.RoleARN=e.roleArn;if(e.tags)e.tags.forEach((a,r)=>{t[`Tags.member.${r+1}.Key`]=a.Key,t[`Tags.member.${r+1}.Value`]=a.Value});let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackId:s.StackId||s.UpdateStackResult?.StackId}}async deleteStack(e,t,s){let a={Action:"DeleteStack",StackName:e,Version:"2010-05-15"};if(t)a.RoleARN=t;if(s&&s.length>0)s.forEach((r,u)=>{a[`RetainResources.member.${u+1}`]=r});await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(a).toString()})}async describeStacks(e={}){let t={Action:"DescribeStacks",Version:"2010-05-15"};if(e.stackName)t.StackName=e.stackName;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{Stacks:this.parseStacksResponse(s)}}async describeStackEvents(e){let t={Action:"DescribeStackEvents",StackName:e,Version:"2010-05-15"},s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackEvents:this.parseStackEvents(s)}}async listStackResources(e){let t={Action:"ListStackResources",StackName:e,Version:"2010-05-15"},a=(await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}))?.ListStackResourcesResult?.StackResourceSummaries?.member,r=[];if(a)r=Array.isArray(a)?a:[a];return{StackResourceSummaries:r}}async waitForStack(e,t){let s={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},a=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],r=s[t],u=360,i=0;while(i<360)try{let c=await this.describeStacks({stackName:e});if(c.Stacks.length===0){if(t==="stack-delete-complete")return;if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Stack not visible yet`);await new Promise((m)=>setTimeout(m,2000)),i++;continue}let o=c.Stacks[0];if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Status = ${o.StackStatus}${o.StackStatusReason?` (${o.StackStatusReason})`:""}`);if(r.includes(o.StackStatus))return;if((t==="stack-create-complete"||t==="stack-update-complete")&&(o.StackStatus==="DELETE_IN_PROGRESS"||o.StackStatus==="DELETE_COMPLETE")){console.log("[waitForStack] Stack is being deleted (creation/update failed)");let m="";try{let S=await this.describeStackEvents(e);console.log("[waitForStack] Stack events (most recent first):");for(let k of S.StackEvents.slice(0,15))if(k.ResourceStatus.includes("FAILED")||k.ResourceStatusReason){if(console.log(` ${k.LogicalResourceId}: ${k.ResourceStatus} - ${k.ResourceStatusReason||"No reason provided"}`),k.ResourceStatus.includes("FAILED")&&k.ResourceStatusReason&&!m)m=k.ResourceStatusReason}}catch{}let l=m||o.StackStatusReason||"Check CloudFormation console for details.";throw Error(`Stack creation/update failed - stack is being deleted. Reason: ${l}`)}if(o.StackStatus==="DELETE_FAILED"&&t==="stack-delete-complete"){let m=Error("Stack deletion failed - may have resources that need to be retained");throw m.code="DELETE_FAILED",m.stackStatus=o.StackStatus,m.statusReason=o.StackStatusReason,m}if(a.includes(o.StackStatus))throw Error(`Stack reached failure status: ${o.StackStatus}`);await new Promise((m)=>setTimeout(m,5000)),i++}catch(c){if(t==="stack-delete-complete"&&c.message?.includes("does not exist"))return;if(t==="stack-create-complete"&&c.message?.includes("does not exist")){if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Stack does not exist (error), retrying...`);await new Promise((o)=>setTimeout(o,2000)),i++;continue}throw console.log(`[waitForStack] Unexpected error: ${c.message}`),c}throw console.log(`[waitForStack] Timeout after ${i} attempts`),Error(`Timeout waiting for stack to reach ${t}`)}async validateTemplate(e){let t={Action:"ValidateTemplate",TemplateBody:e,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()})}async listStacks(e){let t={Action:"ListStacks",Version:"2010-05-15"};if(e)e.forEach((c,o)=>{t[`StackStatusFilter.member.${o+1}`]=c});let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}),a=s.ListStacksResponse||s,r=a.ListStacksResult||a,u=r.StackSummaries?.member||r.StackSummaries||[];return{StackSummaries:(Array.isArray(u)?u:u?[u]:[]).map((c)=>({StackId:c.StackId||"",StackName:c.StackName||"",TemplateDescription:c.TemplateDescription,CreationTime:c.CreationTime||"",LastUpdatedTime:c.LastUpdatedTime,DeletionTime:c.DeletionTime,StackStatus:c.StackStatus||""}))}}async createChangeSet(e){let t={Action:"CreateChangeSet",StackName:e.stackName,ChangeSetName:e.changeSetName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;if(e.parameters)e.parameters.forEach((r,u)=>{t[`Parameters.member.${u+1}.ParameterKey`]=r.ParameterKey,t[`Parameters.member.${u+1}.ParameterValue`]=r.ParameterValue});if(e.capabilities)e.capabilities.forEach((r,u)=>{t[`Capabilities.member.${u+1}`]=r});if(e.changeSetType)t.ChangeSetType=e.changeSetType;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}),a=h(s,"CreateChangeSet");return{Id:a?.Id,StackId:a?.StackId}}async describeChangeSet(e,t){let s={Action:"DescribeChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async executeChangeSet(e,t){let s={Action:"ExecuteChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async deleteChangeSet(e,t){let s={Action:"DeleteChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async getStackOutputs(e){let t=await this.describeStacks({stackName:e});if(!t.Stacks||t.Stacks.length===0)throw Error(`Stack ${e} not found`);let s=t.Stacks[0],a={};if(s.Outputs)for(let r of s.Outputs)a[r.OutputKey]=r.OutputValue;return a}async getTemplate(e){let t={Action:"GetTemplate",StackName:e,Version:"2010-05-15"},s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{TemplateBody:s?.GetTemplateResult?.TemplateBody||s?.TemplateBody||""}}parseStacksResponse(e){let t=[],s=e?.DescribeStacksResult?.Stacks?.member||e?.Stacks?.member||e?.Stacks||e;if(s&&!Array.isArray(s))s=[s];if(Array.isArray(s)){for(let a of s)if(a.StackId||a.StackName){let r;if(a.Outputs?.member)r=(Array.isArray(a.Outputs.member)?a.Outputs.member:[a.Outputs.member]).map((i)=>({OutputKey:i.OutputKey,OutputValue:i.OutputValue,Description:i.Description,ExportName:i.ExportName}));t.push({StackId:a.StackId,StackName:a.StackName,StackStatus:a.StackStatus,CreationTime:a.CreationTime,LastUpdatedTime:a.LastUpdatedTime,StackStatusReason:a.StackStatusReason,Outputs:r})}}else if(e.StackId)t.push({StackId:e.StackId,StackName:e.StackName,StackStatus:e.StackStatus,CreationTime:e.CreationTime,LastUpdatedTime:e.LastUpdatedTime});return t}parseStackEvents(e){let t=[],s=e?.DescribeStackEventsResult?.StackEvents?.member||e?.StackEvents?.member||e?.StackEvents||[];if(s&&!Array.isArray(s))s=[s];for(let a of s)if(a.LogicalResourceId)t.push({Timestamp:a.Timestamp,ResourceType:a.ResourceType,LogicalResourceId:a.LogicalResourceId,ResourceStatus:a.ResourceStatus,ResourceStatusReason:a.ResourceStatusReason});return t}async waitForStackWithProgress(e,t,s){let a={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},r=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],u=a[t],i=360,c=0,o=new Set;while(c<360)try{if(s)try{let k=[...(await this.describeStackEvents(e)).StackEvents||[]].reverse();for(let d of k){let g=`${d.LogicalResourceId}-${d.ResourceStatus}-${d.Timestamp}`;if(!o.has(g))o.add(g),s({resourceId:d.LogicalResourceId,resourceType:d.ResourceType,status:d.ResourceStatus,reason:d.ResourceStatusReason,timestamp:d.Timestamp})}}catch{}let m=await this.describeStacks({stackName:e});if(m.Stacks.length===0){if(t==="stack-delete-complete")return;await new Promise((S)=>setTimeout(S,2000)),c++;continue}let l=m.Stacks[0];if(u.includes(l.StackStatus))return;if(l.StackStatus==="DELETE_FAILED"&&t==="stack-delete-complete"){let S=Error("Stack deletion failed - may have resources that need to be retained");throw S.code="DELETE_FAILED",S.stackStatus=l.StackStatus,S.statusReason=l.StackStatusReason,S}if(r.includes(l.StackStatus))throw Error(`Stack reached failure status: ${l.StackStatus}`);await new Promise((S)=>setTimeout(S,3000)),c++}catch(m){if(t==="stack-delete-complete"&&m.message?.includes("does not exist"))return;if(t==="stack-create-complete"&&m.message?.includes("does not exist")){await new Promise((l)=>setTimeout(l,2000)),c++;continue}throw m}throw Error(`Timeout waiting for stack to reach ${t}`)}async waitForStackComplete(e,t=120,s=5000){let a=["CREATE_COMPLETE","UPDATE_COMPLETE","DELETE_COMPLETE"],r=["CREATE_FAILED","UPDATE_FAILED","DELETE_FAILED","ROLLBACK_COMPLETE","ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED"];for(let u=0;u<t;u++)try{let i=await this.describeStacks({stackName:e});if(i.Stacks.length===0)return{success:!0,status:"DELETE_COMPLETE"};let c=i.Stacks[0],o=c.StackStatus;if(a.includes(o))return{success:!0,status:o};if(r.includes(o))return{success:!1,status:o,reason:c.StackStatusReason};await new Promise((m)=>setTimeout(m,s))}catch(i){if(i.message?.includes("does not exist"))return{success:!0,status:"DELETE_COMPLETE"};throw i}return{success:!1,status:"TIMEOUT",reason:"Timeout waiting for stack operation"}}}
1
+ import{n}from"./chunk-z90dv6jx.js";import{h}from"./chunk-g0bh9atv.js";class A{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new n(void 0,{profile:t})}async createStack(e){let t={Action:"CreateStack",StackName:e.stackName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;else throw Error("Either templateBody or templateUrl must be provided");if(e.parameters)e.parameters.forEach((a,r)=>{t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.roleArn)t.RoleARN=e.roleArn;if(e.tags)e.tags.forEach((a,r)=>{t[`Tags.member.${r+1}.Key`]=a.Key,t[`Tags.member.${r+1}.Value`]=a.Value});if(e.timeoutInMinutes)t.TimeoutInMinutes=e.timeoutInMinutes;if(e.onFailure)t.OnFailure=e.onFailure;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackId:s.StackId||s.CreateStackResult?.StackId}}async updateStack(e){let t={Action:"UpdateStack",StackName:e.stackName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;if(e.parameters)e.parameters.forEach((a,r)=>{if(t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,a.UsePreviousValue)t[`Parameters.member.${r+1}.UsePreviousValue`]="true";else t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.roleArn)t.RoleARN=e.roleArn;if(e.tags)e.tags.forEach((a,r)=>{t[`Tags.member.${r+1}.Key`]=a.Key,t[`Tags.member.${r+1}.Value`]=a.Value});let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackId:s.StackId||s.UpdateStackResult?.StackId}}async deleteStack(e,t,s){let a={Action:"DeleteStack",StackName:e,Version:"2010-05-15"};if(t)a.RoleARN=t;if(s&&s.length>0)s.forEach((r,u)=>{a[`RetainResources.member.${u+1}`]=r});await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(a).toString()})}async describeStacks(e={}){let t={Action:"DescribeStacks",Version:"2010-05-15"};if(e.stackName)t.StackName=e.stackName;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{Stacks:this.parseStacksResponse(s)}}async describeStackEvents(e){let t={Action:"DescribeStackEvents",StackName:e,Version:"2010-05-15"},s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackEvents:this.parseStackEvents(s)}}async listStackResources(e){let t={Action:"ListStackResources",StackName:e,Version:"2010-05-15"},a=(await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}))?.ListStackResourcesResult?.StackResourceSummaries?.member,r=[];if(a)r=Array.isArray(a)?a:[a];return{StackResourceSummaries:r}}async waitForStack(e,t){let s={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},a=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],r=s[t],u=360,i=0;while(i<360)try{let c=await this.describeStacks({stackName:e});if(c.Stacks.length===0){if(t==="stack-delete-complete")return;if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Stack not visible yet`);await new Promise((m)=>setTimeout(m,2000)),i++;continue}let o=c.Stacks[0];if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Status = ${o.StackStatus}${o.StackStatusReason?` (${o.StackStatusReason})`:""}`);if(r.includes(o.StackStatus))return;if((t==="stack-create-complete"||t==="stack-update-complete")&&(o.StackStatus==="DELETE_IN_PROGRESS"||o.StackStatus==="DELETE_COMPLETE")){console.log("[waitForStack] Stack is being deleted (creation/update failed)");let m="";try{let S=await this.describeStackEvents(e);console.log("[waitForStack] Stack events (most recent first):");for(let k of S.StackEvents.slice(0,15))if(k.ResourceStatus.includes("FAILED")||k.ResourceStatusReason){if(console.log(` ${k.LogicalResourceId}: ${k.ResourceStatus} - ${k.ResourceStatusReason||"No reason provided"}`),k.ResourceStatus.includes("FAILED")&&k.ResourceStatusReason&&!m)m=k.ResourceStatusReason}}catch{}let l=m||o.StackStatusReason||"Check CloudFormation console for details.";throw Error(`Stack creation/update failed - stack is being deleted. Reason: ${l}`)}if(o.StackStatus==="DELETE_FAILED"&&t==="stack-delete-complete"){let m=Error("Stack deletion failed - may have resources that need to be retained");throw m.code="DELETE_FAILED",m.stackStatus=o.StackStatus,m.statusReason=o.StackStatusReason,m}if(a.includes(o.StackStatus))throw Error(`Stack reached failure status: ${o.StackStatus}`);await new Promise((m)=>setTimeout(m,5000)),i++}catch(c){if(t==="stack-delete-complete"&&c.message?.includes("does not exist"))return;if(t==="stack-create-complete"&&c.message?.includes("does not exist")){if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Stack does not exist (error), retrying...`);await new Promise((o)=>setTimeout(o,2000)),i++;continue}throw console.log(`[waitForStack] Unexpected error: ${c.message}`),c}throw console.log(`[waitForStack] Timeout after ${i} attempts`),Error(`Timeout waiting for stack to reach ${t}`)}async validateTemplate(e){let t={Action:"ValidateTemplate",TemplateBody:e,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()})}async listStacks(e){let t={Action:"ListStacks",Version:"2010-05-15"};if(e)e.forEach((c,o)=>{t[`StackStatusFilter.member.${o+1}`]=c});let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}),a=s.ListStacksResponse||s,r=a.ListStacksResult||a,u=r.StackSummaries?.member||r.StackSummaries||[];return{StackSummaries:(Array.isArray(u)?u:u?[u]:[]).map((c)=>({StackId:c.StackId||"",StackName:c.StackName||"",TemplateDescription:c.TemplateDescription,CreationTime:c.CreationTime||"",LastUpdatedTime:c.LastUpdatedTime,DeletionTime:c.DeletionTime,StackStatus:c.StackStatus||""}))}}async createChangeSet(e){let t={Action:"CreateChangeSet",StackName:e.stackName,ChangeSetName:e.changeSetName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;if(e.parameters)e.parameters.forEach((r,u)=>{t[`Parameters.member.${u+1}.ParameterKey`]=r.ParameterKey,t[`Parameters.member.${u+1}.ParameterValue`]=r.ParameterValue});if(e.capabilities)e.capabilities.forEach((r,u)=>{t[`Capabilities.member.${u+1}`]=r});if(e.changeSetType)t.ChangeSetType=e.changeSetType;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}),a=h(s,"CreateChangeSet");return{Id:a?.Id,StackId:a?.StackId}}async describeChangeSet(e,t){let s={Action:"DescribeChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async executeChangeSet(e,t){let s={Action:"ExecuteChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async deleteChangeSet(e,t){let s={Action:"DeleteChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async getStackOutputs(e){let t=await this.describeStacks({stackName:e});if(!t.Stacks||t.Stacks.length===0)throw Error(`Stack ${e} not found`);let s=t.Stacks[0],a={};if(s.Outputs)for(let r of s.Outputs)a[r.OutputKey]=r.OutputValue;return a}async getTemplate(e){let t={Action:"GetTemplate",StackName:e,Version:"2010-05-15"},s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{TemplateBody:s?.GetTemplateResult?.TemplateBody||s?.TemplateBody||""}}parseStacksResponse(e){let t=[],s=e?.DescribeStacksResult?.Stacks?.member||e?.Stacks?.member||e?.Stacks||e;if(s&&!Array.isArray(s))s=[s];if(Array.isArray(s)){for(let a of s)if(a.StackId||a.StackName){let r;if(a.Outputs?.member)r=(Array.isArray(a.Outputs.member)?a.Outputs.member:[a.Outputs.member]).map((i)=>({OutputKey:i.OutputKey,OutputValue:i.OutputValue,Description:i.Description,ExportName:i.ExportName}));t.push({StackId:a.StackId,StackName:a.StackName,StackStatus:a.StackStatus,CreationTime:a.CreationTime,LastUpdatedTime:a.LastUpdatedTime,StackStatusReason:a.StackStatusReason,Outputs:r})}}else if(e.StackId)t.push({StackId:e.StackId,StackName:e.StackName,StackStatus:e.StackStatus,CreationTime:e.CreationTime,LastUpdatedTime:e.LastUpdatedTime});return t}parseStackEvents(e){let t=[],s=e?.DescribeStackEventsResult?.StackEvents?.member||e?.StackEvents?.member||e?.StackEvents||[];if(s&&!Array.isArray(s))s=[s];for(let a of s)if(a.LogicalResourceId)t.push({Timestamp:a.Timestamp,ResourceType:a.ResourceType,LogicalResourceId:a.LogicalResourceId,ResourceStatus:a.ResourceStatus,ResourceStatusReason:a.ResourceStatusReason});return t}async waitForStackWithProgress(e,t,s){let a={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},r=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],u=a[t],i=360,c=0,o=new Set;while(c<360)try{if(s)try{let k=[...(await this.describeStackEvents(e)).StackEvents||[]].reverse();for(let d of k){let g=`${d.LogicalResourceId}-${d.ResourceStatus}-${d.Timestamp}`;if(!o.has(g))o.add(g),s({resourceId:d.LogicalResourceId,resourceType:d.ResourceType,status:d.ResourceStatus,reason:d.ResourceStatusReason,timestamp:d.Timestamp})}}catch{}let m=await this.describeStacks({stackName:e});if(m.Stacks.length===0){if(t==="stack-delete-complete")return;await new Promise((S)=>setTimeout(S,2000)),c++;continue}let l=m.Stacks[0];if(u.includes(l.StackStatus))return;if(l.StackStatus==="DELETE_FAILED"&&t==="stack-delete-complete"){let S=Error("Stack deletion failed - may have resources that need to be retained");throw S.code="DELETE_FAILED",S.stackStatus=l.StackStatus,S.statusReason=l.StackStatusReason,S}if(r.includes(l.StackStatus))throw Error(`Stack reached failure status: ${l.StackStatus}`);await new Promise((S)=>setTimeout(S,3000)),c++}catch(m){if(t==="stack-delete-complete"&&m.message?.includes("does not exist"))return;if(t==="stack-create-complete"&&m.message?.includes("does not exist")){await new Promise((l)=>setTimeout(l,2000)),c++;continue}throw m}throw Error(`Timeout waiting for stack to reach ${t}`)}async waitForStackComplete(e,t=120,s=5000){let a=["CREATE_COMPLETE","UPDATE_COMPLETE","DELETE_COMPLETE"],r=["CREATE_FAILED","UPDATE_FAILED","DELETE_FAILED","ROLLBACK_COMPLETE","ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED"];for(let u=0;u<t;u++)try{let i=await this.describeStacks({stackName:e});if(i.Stacks.length===0)return{success:!0,status:"DELETE_COMPLETE"};let c=i.Stacks[0],o=c.StackStatus;if(a.includes(o))return{success:!0,status:o};if(r.includes(o))return{success:!1,status:o,reason:c.StackStatusReason};await new Promise((m)=>setTimeout(m,s))}catch(i){if(i.message?.includes("does not exist"))return{success:!0,status:"DELETE_COMPLETE"};throw i}return{success:!1,status:"TIMEOUT",reason:"Timeout waiting for stack operation"}}}
2
2
  export{A};
@@ -1,4 +1,4 @@
1
- import{Et,n}from"./chunk-1eg5wsn2.js";import{o}from"./chunk-1y1b1jy0.js";import{b}from"./chunk-gssa1974.js";import{h}from"./chunk-g0bh9atv.js";import{it}from"./chunk-tdhm38cg.js";function f(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((c,l)=>{if(typeof c==="object"&&c!==null)for(let[d,m]of Object.entries(c))r.push(`${a}.member.${l+1}.${d}=${encodeURIComponent(String(m))}`);else r.push(`${a}.member.${l+1}=${encodeURIComponent(String(c))}`)});else if(typeof i==="object"){for(let[c,l]of Object.entries(i))if(l!==void 0&&l!==null)r.push(`${a}.${c}=${encodeURIComponent(String(l))}`)}else r.push(`${a}=${encodeURIComponent(String(i))}`)}return r.join("&")}var S=new Et({ignoreAttributes:!0,parseTagValue:!1,trimValues:!0});function N(e){if(typeof e!=="string"||!e.trim())return{};return S.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 c=i[t];return typeof c==="string"?c:void 0}a.push(...Object.values(i))}r=a}return}function u(e,t,r){let a=[e];while(a.length>0){let i=[];for(let c of a){if(!c||typeof c!=="object")continue;if(Array.isArray(c)){i.push(...c);continue}if(t in c){let l=c[t]?.[r];return l===void 0||l===null?[]:Array.isArray(l)?l:[l]}i.push(...Object.values(c))}a=i}return[]}class Re{client;region;constructor(e="us-east-1",t){this.client=new n(void 0,{profile:t}),this.region=e}async request(e,t={}){let r=f(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 N(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 u(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",c=s(t,"Marker");return{Group:r,Users:a,IsTruncated:i,Marker:c}}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 u(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 u(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 u(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 u(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 u(e,"Versions","member").map((r)=>({VersionId:s(r,"VersionId")||"",IsDefaultVersion:s(r,"IsDefaultVersion")==="true",CreateDate:s(r,"CreateDate")}))}parseAttachedPolicies(e){return u(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=u(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=u(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=u(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 u(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 u(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=u(e,"SummaryMap","entry");for(let a of r){let i=s(a,"key"),c=s(a,"value");if(i&&c)t[i]=Number.parseInt(c,10)}return t}async listAccountAliases(){let e=await this.request("ListAccountAliases"),t=u(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=u(e,"EvaluationResults","member").map((c)=>{let d=u(c,"MatchedStatements","member").map((m)=>({SourcePolicyId:s(m,"SourcePolicyId"),SourcePolicyType:s(m,"SourcePolicyType")}));return{EvalActionName:s(c,"EvalActionName")||"",EvalResourceName:s(c,"EvalResourceName"),EvalDecision:s(c,"EvalDecision")||"",MatchedStatements:d.length>0?d:void 0}}),a=s(e,"IsTruncated")==="true",i=s(e,"Marker");return{EvaluationResults:r,IsTruncated:a,Marker:i}}}class pt{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new n(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=h(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=h(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((c)=>setTimeout(c,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((c,l)=>{r[`Destinations.member.${l+1}`]=c});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 jn{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 pt(this.region),this.s3=new o(this.region),this.iam=new Re(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-qy8r2vwh.js"),a=new r,i=(p,y)=>{let P={Action:p,Version:"2010-05-08",...y};return Object.entries(P).map(([A,R])=>`${encodeURIComponent(A)}=${encodeURIComponent(R)}`).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(p){if(!p.message?.includes("EntityAlreadyExists"))throw p}let c={Version:"2012-10-17",Statement:[{Effect:"Allow",Action:"ses:SendRawEmail",Resource:"*",Condition:{StringLike:{"ses:FromAddress":`*@${e.domain}`}}}]},l=`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:l,PolicyDocument:JSON.stringify(c)})})}catch{}let m=(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(!m?.AccessKeyId||!m?.SecretAccessKey)throw Error("Failed to create access key");let g=this.deriveSmtpPassword(m.SecretAccessKey);return{username:m.AccessKeyId,password:g,server:`email-smtp.${this.region}.amazonaws.com`,port:587}}deriveSmtpPassword(e){let t=it("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((m)=>m.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 d=await this.getDnsRecords(e.domain);return{success:!0,domainVerified:i.domainVerified,dkimStatus:i.dkimStatus,receiptRuleSet:t,storageBucket:a,dnsRecords:d}}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{Et,n}from"./chunk-z90dv6jx.js";import{o}from"./chunk-49rt1jbe.js";import{b}from"./chunk-c2hvf1h5.js";import{h}from"./chunk-g0bh9atv.js";import{it}from"./chunk-tdhm38cg.js";function f(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((c,l)=>{if(typeof c==="object"&&c!==null)for(let[d,m]of Object.entries(c))r.push(`${a}.member.${l+1}.${d}=${encodeURIComponent(String(m))}`);else r.push(`${a}.member.${l+1}=${encodeURIComponent(String(c))}`)});else if(typeof i==="object"){for(let[c,l]of Object.entries(i))if(l!==void 0&&l!==null)r.push(`${a}.${c}=${encodeURIComponent(String(l))}`)}else r.push(`${a}=${encodeURIComponent(String(i))}`)}return r.join("&")}var S=new Et({ignoreAttributes:!0,parseTagValue:!1,trimValues:!0});function N(e){if(typeof e!=="string"||!e.trim())return{};return S.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 c=i[t];return typeof c==="string"?c:void 0}a.push(...Object.values(i))}r=a}return}function u(e,t,r){let a=[e];while(a.length>0){let i=[];for(let c of a){if(!c||typeof c!=="object")continue;if(Array.isArray(c)){i.push(...c);continue}if(t in c){let l=c[t]?.[r];return l===void 0||l===null?[]:Array.isArray(l)?l:[l]}i.push(...Object.values(c))}a=i}return[]}class Re{client;region;constructor(e="us-east-1",t){this.client=new n(void 0,{profile:t}),this.region=e}async request(e,t={}){let r=f(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 N(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 u(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",c=s(t,"Marker");return{Group:r,Users:a,IsTruncated:i,Marker:c}}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 u(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 u(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 u(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 u(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 u(e,"Versions","member").map((r)=>({VersionId:s(r,"VersionId")||"",IsDefaultVersion:s(r,"IsDefaultVersion")==="true",CreateDate:s(r,"CreateDate")}))}parseAttachedPolicies(e){return u(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=u(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=u(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=u(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 u(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 u(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=u(e,"SummaryMap","entry");for(let a of r){let i=s(a,"key"),c=s(a,"value");if(i&&c)t[i]=Number.parseInt(c,10)}return t}async listAccountAliases(){let e=await this.request("ListAccountAliases"),t=u(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=u(e,"EvaluationResults","member").map((c)=>{let d=u(c,"MatchedStatements","member").map((m)=>({SourcePolicyId:s(m,"SourcePolicyId"),SourcePolicyType:s(m,"SourcePolicyType")}));return{EvalActionName:s(c,"EvalActionName")||"",EvalResourceName:s(c,"EvalResourceName"),EvalDecision:s(c,"EvalDecision")||"",MatchedStatements:d.length>0?d:void 0}}),a=s(e,"IsTruncated")==="true",i=s(e,"Marker");return{EvaluationResults:r,IsTruncated:a,Marker:i}}}class pt{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new n(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=h(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=h(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((c)=>setTimeout(c,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((c,l)=>{r[`Destinations.member.${l+1}`]=c});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 jn{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 pt(this.region),this.s3=new o(this.region),this.iam=new Re(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-gc8r2gvd.js"),a=new r,i=(p,y)=>{let P={Action:p,Version:"2010-05-08",...y};return Object.entries(P).map(([A,R])=>`${encodeURIComponent(A)}=${encodeURIComponent(R)}`).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(p){if(!p.message?.includes("EntityAlreadyExists"))throw p}let c={Version:"2012-10-17",Statement:[{Effect:"Allow",Action:"ses:SendRawEmail",Resource:"*",Condition:{StringLike:{"ses:FromAddress":`*@${e.domain}`}}}]},l=`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:l,PolicyDocument:JSON.stringify(c)})})}catch{}let m=(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(!m?.AccessKeyId||!m?.SecretAccessKey)throw Error("Failed to create access key");let g=this.deriveSmtpPassword(m.SecretAccessKey);return{username:m.AccessKeyId,password:g,server:`email-smtp.${this.region}.amazonaws.com`,port:587}}deriveSmtpPassword(e){let t=it("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((m)=>m.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 d=await this.getDnsRecords(e.domain);return{success:!0,domainVerified:i.domainVerified,dkimStatus:i.dkimStatus,receiptRuleSet:t,storageBucket:a,dnsRecords:d}}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 c=Array.isArray(e.cc)?e.cc:[e.cc];i+=`Cc: ${c.join(", ")}\r
4
4
  `}if(i+=`Subject: ${e.subject}\r
@@ -1,4 +1,4 @@
1
- import{n}from"./chunk-1eg5wsn2.js";class b{client;region;constructor(e="us-east-1"){this.region=e,this.client=new n}async createHostedZone(e){let t=e.CallerReference||`${Date.now()}-${Math.random().toString(36).slice(2)}`,o=`<?xml version="1.0" encoding="UTF-8"?>
1
+ import{n}from"./chunk-z90dv6jx.js";class b{client;region;constructor(e="us-east-1"){this.region=e,this.client=new n}async createHostedZone(e){let t=e.CallerReference||`${Date.now()}-${Math.random().toString(36).slice(2)}`,o=`<?xml version="1.0" encoding="UTF-8"?>
2
2
  <CreateHostedZoneRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
3
3
  <Name>${e.Name}</Name>
4
4
  <CallerReference>${t}</CallerReference>`;if(e.HostedZoneConfig){if(o+=`
@@ -0,0 +1 @@
1
+ import{Ac}from"./chunk-qcs3qkdf.js";import"./chunk-ebb7j388.js";import"./chunk-z90dv6jx.js";import"./chunk-277enqjc.js";import"./chunk-928z0h9b.js";export{Ac as buildAndPushServerlessImage};
@@ -1,4 +1,4 @@
1
- import{n}from"./chunk-1eg5wsn2.js";class Vr{client;region;constructor(e="us-east-1"){this.region=e,this.client=new n}async describeInstances(e){let t={Action:"DescribeInstances",Version:"2016-11-15"};if(e?.InstanceIds)e.InstanceIds.forEach((s,i)=>{t[`InstanceId.${i+1}`]=s});if(e?.Filters)e.Filters.forEach((s,i)=>{t[`Filter.${i+1}.Name`]=s.Name,s.Values.forEach((o,c)=>{t[`Filter.${i+1}.Value.${c+1}`]=o})});if(e?.MaxResults)t.MaxResults=String(e.MaxResults);if(e?.NextToken)t.NextToken=e.NextToken;let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),r=a.DescribeInstancesResponse||a;return{Reservations:this.parseReservations(r.reservationSet?.item),NextToken:r.nextToken}}async getInstance(e){return(await this.describeInstances({InstanceIds:[e]})).Reservations?.[0]?.Instances?.[0]}async getConsoleOutput(e,t){let a={Action:"GetConsoleOutput",Version:"2016-11-15",InstanceId:e};if(t)a.Latest="true";let r=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(a).toString()}),s=r.GetConsoleOutputResponse||r;return{InstanceId:s.instanceId,Output:s.output,Timestamp:s.timestamp}}async getConsoleOutputDecoded(e,t){let a=await this.getConsoleOutput(e,t?.latest);if(!a.Output)return"No console output available yet";let r=Buffer.from(a.Output,"base64").toString("utf-8");if(t?.tailLines)return r.split(`
1
+ import{n}from"./chunk-z90dv6jx.js";class Vr{client;region;constructor(e="us-east-1"){this.region=e,this.client=new n}async describeInstances(e){let t={Action:"DescribeInstances",Version:"2016-11-15"};if(e?.InstanceIds)e.InstanceIds.forEach((s,i)=>{t[`InstanceId.${i+1}`]=s});if(e?.Filters)e.Filters.forEach((s,i)=>{t[`Filter.${i+1}.Name`]=s.Name,s.Values.forEach((o,c)=>{t[`Filter.${i+1}.Value.${c+1}`]=o})});if(e?.MaxResults)t.MaxResults=String(e.MaxResults);if(e?.NextToken)t.NextToken=e.NextToken;let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),r=a.DescribeInstancesResponse||a;return{Reservations:this.parseReservations(r.reservationSet?.item),NextToken:r.nextToken}}async getInstance(e){return(await this.describeInstances({InstanceIds:[e]})).Reservations?.[0]?.Instances?.[0]}async getConsoleOutput(e,t){let a={Action:"GetConsoleOutput",Version:"2016-11-15",InstanceId:e};if(t)a.Latest="true";let r=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(a).toString()}),s=r.GetConsoleOutputResponse||r;return{InstanceId:s.instanceId,Output:s.output,Timestamp:s.timestamp}}async getConsoleOutputDecoded(e,t){let a=await this.getConsoleOutput(e,t?.latest);if(!a.Output)return"No console output available yet";let r=Buffer.from(a.Output,"base64").toString("utf-8");if(t?.tailLines)return r.split(`
2
2
  `).slice(-t.tailLines).join(`
3
3
  `);return r}async describeInstanceStatus(e){let t={Action:"DescribeInstanceStatus",Version:"2016-11-15"};if(e?.InstanceIds)e.InstanceIds.forEach((r,s)=>{t[`InstanceId.${s+1}`]=r});if(e?.IncludeAllInstances)t.IncludeAllInstances="true";if(e?.Filters)e.Filters.forEach((r,s)=>{t[`Filter.${s+1}.Name`]=r.Name,r.Values.forEach((i,o)=>{t[`Filter.${s+1}.Value.${o+1}`]=i})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{InstanceStatuses:this.parseArray(a.instanceStatusSet?.item).map((r)=>({InstanceId:r.instanceId,InstanceState:r.instanceState?{Code:Number.parseInt(r.instanceState.code),Name:r.instanceState.name}:void 0,InstanceStatus:r.instanceStatus?{Status:r.instanceStatus.status,Details:this.parseArray(r.instanceStatus.details?.item).map((s)=>({Name:s.name,Status:s.status}))}:void 0,SystemStatus:r.systemStatus?{Status:r.systemStatus.status,Details:this.parseArray(r.systemStatus.details?.item).map((s)=>({Name:s.name,Status:s.status}))}:void 0}))}}async startInstances(e){let t={Action:"StartInstances",Version:"2016-11-15"};e.forEach((r,s)=>{t[`InstanceId.${s+1}`]=r});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{StartingInstances:this.parseArray(a.instancesSet?.item).map((r)=>({InstanceId:r.instanceId,CurrentState:r.currentState?{Name:r.currentState.name}:void 0,PreviousState:r.previousState?{Name:r.previousState.name}:void 0}))}}async stopInstances(e,t){let a={Action:"StopInstances",Version:"2016-11-15"};if(e.forEach((s,i)=>{a[`InstanceId.${i+1}`]=s}),t)a.Force="true";let r=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(a).toString()});return{StoppingInstances:this.parseArray(r.instancesSet?.item).map((s)=>({InstanceId:s.instanceId,CurrentState:s.currentState?{Name:s.currentState.name}:void 0,PreviousState:s.previousState?{Name:s.previousState.name}:void 0}))}}async rebootInstances(e){let t={Action:"RebootInstances",Version:"2016-11-15"};e.forEach((a,r)=>{t[`InstanceId.${r+1}`]=a}),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async terminateInstances(e){let t={Action:"TerminateInstances",Version:"2016-11-15"};e.forEach((r,s)=>{t[`InstanceId.${s+1}`]=r});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{TerminatingInstances:this.parseArray(a.instancesSet?.item).map((r)=>({InstanceId:r.instanceId,CurrentState:r.currentState?{Name:r.currentState.name}:void 0,PreviousState:r.previousState?{Name:r.previousState.name}:void 0}))}}async createImage(e){let t={Action:"CreateImage",Version:"2016-11-15",InstanceId:e.InstanceId,Name:e.Name};if(e.Description)t.Description=e.Description;if(e.NoReboot!==void 0)t.NoReboot=String(e.NoReboot);if(e.TagSpecifications)e.TagSpecifications.forEach((s,i)=>{t[`TagSpecification.${i+1}.ResourceType`]=s.ResourceType,s.Tags.forEach((o,c)=>{t[`TagSpecification.${i+1}.Tag.${c+1}.Key`]=o.Key,t[`TagSpecification.${i+1}.Tag.${c+1}.Value`]=o.Value})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{ImageId:(a.CreateImageResponse||a).imageId}}async deregisterImage(e){await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({Action:"DeregisterImage",Version:"2016-11-15",ImageId:e}).toString()})}async describeVpcs(e){let t={Action:"DescribeVpcs",Version:"2016-11-15"};if(e?.VpcIds)e.VpcIds.forEach((r,s)=>{t[`VpcId.${s+1}`]=r});if(e?.Filters)e.Filters.forEach((r,s)=>{t[`Filter.${s+1}.Name`]=r.Name,r.Values.forEach((i,o)=>{t[`Filter.${s+1}.Value.${o+1}`]=i})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{Vpcs:this.parseArray(a.vpcSet?.item).map((r)=>({VpcId:r.vpcId,CidrBlock:r.cidrBlock,State:r.state,DhcpOptionsId:r.dhcpOptionsId,InstanceTenancy:r.instanceTenancy,IsDefault:r.isDefault==="true",Tags:this.parseTags(r.tagSet?.item)}))}}async describeSubnets(e){let t={Action:"DescribeSubnets",Version:"2016-11-15"};if(e?.SubnetIds)e.SubnetIds.forEach((r,s)=>{t[`SubnetId.${s+1}`]=r});if(e?.Filters)e.Filters.forEach((r,s)=>{t[`Filter.${s+1}.Name`]=r.Name,r.Values.forEach((i,o)=>{t[`Filter.${s+1}.Value.${o+1}`]=i})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{Subnets:this.parseArray(a.subnetSet?.item).map((r)=>({SubnetId:r.subnetId,VpcId:r.vpcId,CidrBlock:r.cidrBlock,AvailabilityZone:r.availabilityZone,AvailableIpAddressCount:Number.parseInt(r.availableIpAddressCount),State:r.state,MapPublicIpOnLaunch:r.mapPublicIpOnLaunch==="true",Tags:this.parseTags(r.tagSet?.item)}))}}async describeSecurityGroups(e){let t={Action:"DescribeSecurityGroups",Version:"2016-11-15"};if(e?.GroupIds)e.GroupIds.forEach((r,s)=>{t[`GroupId.${s+1}`]=r});if(e?.GroupNames)e.GroupNames.forEach((r,s)=>{t[`GroupName.${s+1}`]=r});if(e?.Filters)e.Filters.forEach((r,s)=>{t[`Filter.${s+1}.Name`]=r.Name,r.Values.forEach((i,o)=>{t[`Filter.${s+1}.Value.${o+1}`]=i})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{SecurityGroups:this.parseArray(a.securityGroupInfo?.item).map((r)=>({GroupId:r.groupId,GroupName:r.groupName,Description:r.groupDescription,VpcId:r.vpcId,IpPermissions:this.parseIpPermissions(r.ipPermissions?.item),IpPermissionsEgress:this.parseIpPermissions(r.ipPermissionsEgress?.item),Tags:this.parseTags(r.tagSet?.item)}))}}async describeInternetGateways(e){let t={Action:"DescribeInternetGateways",Version:"2016-11-15"};if(e?.InternetGatewayIds)e.InternetGatewayIds.forEach((r,s)=>{t[`InternetGatewayId.${s+1}`]=r});if(e?.Filters)e.Filters.forEach((r,s)=>{t[`Filter.${s+1}.Name`]=r.Name,r.Values.forEach((i,o)=>{t[`Filter.${s+1}.Value.${o+1}`]=i})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{InternetGateways:this.parseArray(a.internetGatewaySet?.item).map((r)=>({InternetGatewayId:r.internetGatewayId,Attachments:this.parseArray(r.attachmentSet?.item).map((s)=>({VpcId:s.vpcId,State:s.state})),Tags:this.parseTags(r.tagSet?.item)}))}}async describeAddresses(e){let t={Action:"DescribeAddresses",Version:"2016-11-15"};if(e?.AllocationIds)e.AllocationIds.forEach((r,s)=>{t[`AllocationId.${s+1}`]=r});if(e?.PublicIps)e.PublicIps.forEach((r,s)=>{t[`PublicIp.${s+1}`]=r});if(e?.Filters)e.Filters.forEach((r,s)=>{t[`Filter.${s+1}.Name`]=r.Name,r.Values.forEach((i,o)=>{t[`Filter.${s+1}.Value.${o+1}`]=i})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{Addresses:this.parseArray(a.addressesSet?.item).map((r)=>({PublicIp:r.publicIp,AllocationId:r.allocationId,AssociationId:r.associationId,InstanceId:r.instanceId,NetworkInterfaceId:r.networkInterfaceId,PrivateIpAddress:r.privateIpAddress,Domain:r.domain,Tags:this.parseTags(r.tagSet?.item)}))}}async allocateAddress(e){let t={Action:"AllocateAddress",Version:"2016-11-15"};if(e?.Domain)t.Domain=e.Domain;if(e?.TagSpecifications)e.TagSpecifications.forEach((r,s)=>{t[`TagSpecification.${s+1}.ResourceType`]=r.ResourceType,r.Tags.forEach((i,o)=>{t[`TagSpecification.${s+1}.Tag.${o+1}.Key`]=i.Key,t[`TagSpecification.${s+1}.Tag.${o+1}.Value`]=i.Value})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{AllocationId:a.allocationId,PublicIp:a.publicIp,Domain:a.domain}}async associateAddress(e){let t={Action:"AssociateAddress",Version:"2016-11-15"};if(e.AllocationId)t.AllocationId=e.AllocationId;if(e.PublicIp)t.PublicIp=e.PublicIp;if(e.InstanceId)t.InstanceId=e.InstanceId;if(e.NetworkInterfaceId)t.NetworkInterfaceId=e.NetworkInterfaceId;if(e.PrivateIpAddress)t.PrivateIpAddress=e.PrivateIpAddress;if(e.AllowReassociation)t.AllowReassociation="true";return{AssociationId:(await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})).associationId}}async createTags(e){let t={Action:"CreateTags",Version:"2016-11-15"};e.Resources.forEach((a,r)=>{t[`ResourceId.${r+1}`]=a}),e.Tags.forEach((a,r)=>{t[`Tag.${r+1}.Key`]=a.Key,t[`Tag.${r+1}.Value`]=a.Value}),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async waitForInstanceState(e,t,a){let r=a?.maxWaitMs||300000,s=a?.pollIntervalMs||5000,i=Date.now();while(Date.now()-i<r){let o;try{o=await this.getInstance(e)}catch{o=void 0}if(o?.State?.Name===t)return o;await new Promise((c)=>setTimeout(c,s))}return}async createVpc(e){let t={Action:"CreateVpc",Version:"2016-11-15",CidrBlock:e.CidrBlock};if(e.InstanceTenancy)t.InstanceTenancy=e.InstanceTenancy;if(e.TagSpecifications)e.TagSpecifications.forEach((i,o)=>{t[`TagSpecification.${o+1}.ResourceType`]=i.ResourceType,i.Tags.forEach((c,d)=>{t[`TagSpecification.${o+1}.Tag.${d+1}.Key`]=c.Key,t[`TagSpecification.${o+1}.Tag.${d+1}.Value`]=c.Value})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),s=(a.CreateVpcResponse||a).vpc;return{Vpc:s?{VpcId:s.vpcId,CidrBlock:s.cidrBlock,State:s.state,DhcpOptionsId:s.dhcpOptionsId,InstanceTenancy:s.instanceTenancy,IsDefault:s.isDefault==="true",Tags:this.parseTags(s.tagSet?.item)}:void 0}}async createSubnet(e){let t={Action:"CreateSubnet",Version:"2016-11-15",VpcId:e.VpcId,CidrBlock:e.CidrBlock};if(e.AvailabilityZone)t.AvailabilityZone=e.AvailabilityZone;if(e.TagSpecifications)e.TagSpecifications.forEach((i,o)=>{t[`TagSpecification.${o+1}.ResourceType`]=i.ResourceType,i.Tags.forEach((c,d)=>{t[`TagSpecification.${o+1}.Tag.${d+1}.Key`]=c.Key,t[`TagSpecification.${o+1}.Tag.${d+1}.Value`]=c.Value})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),s=(a.CreateSubnetResponse||a).subnet;return{Subnet:s?{SubnetId:s.subnetId,VpcId:s.vpcId,CidrBlock:s.cidrBlock,AvailabilityZone:s.availabilityZone,AvailableIpAddressCount:s.availableIpAddressCount?Number.parseInt(s.availableIpAddressCount):void 0,State:s.state,MapPublicIpOnLaunch:s.mapPublicIpOnLaunch==="true",Tags:this.parseTags(s.tagSet?.item)}:void 0}}async modifySubnetAttribute(e){let t={Action:"ModifySubnetAttribute",Version:"2016-11-15",SubnetId:e.SubnetId};if(e.MapPublicIpOnLaunch!==void 0)t["MapPublicIpOnLaunch.Value"]=String(e.MapPublicIpOnLaunch.Value);await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async importKeyPair(e){let t={Action:"ImportKeyPair",Version:"2016-11-15",KeyName:e.KeyName,PublicKeyMaterial:Buffer.from(e.PublicKeyMaterial.trim()).toString("base64")};e.TagSpecifications?.forEach((s,i)=>{t[`TagSpecification.${i+1}.ResourceType`]=s.ResourceType,s.Tags.forEach((o,c)=>{t[`TagSpecification.${i+1}.Tag.${c+1}.Key`]=o.Key,t[`TagSpecification.${i+1}.Tag.${c+1}.Value`]=o.Value})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),r=a.ImportKeyPairResponse||a;return{KeyName:r.keyName,KeyPairId:r.keyPairId,KeyFingerprint:r.keyFingerprint}}async deleteKeyPair(e){await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({Action:"DeleteKeyPair",Version:"2016-11-15",KeyName:e}).toString()})}async createSecurityGroup(e){let t={Action:"CreateSecurityGroup",Version:"2016-11-15",GroupName:e.GroupName,GroupDescription:e.Description};if(e.VpcId)t.VpcId=e.VpcId;if(e.TagSpecifications)e.TagSpecifications.forEach((s,i)=>{t[`TagSpecification.${i+1}.ResourceType`]=s.ResourceType,s.Tags.forEach((o,c)=>{t[`TagSpecification.${i+1}.Tag.${c+1}.Key`]=o.Key,t[`TagSpecification.${i+1}.Tag.${c+1}.Value`]=o.Value})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{GroupId:(a.CreateSecurityGroupResponse||a).groupId}}async authorizeSecurityGroupIngress(e){let t={Action:"AuthorizeSecurityGroupIngress",Version:"2016-11-15",GroupId:e.GroupId};this.encodeIpPermissions(t,e.IpPermissions),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async authorizeSecurityGroupEgress(e){let t={Action:"AuthorizeSecurityGroupEgress",Version:"2016-11-15",GroupId:e.GroupId};this.encodeIpPermissions(t,e.IpPermissions),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async describeRouteTables(e){let t={Action:"DescribeRouteTables",Version:"2016-11-15"};if(e?.RouteTableIds)e.RouteTableIds.forEach((s,i)=>{t[`RouteTableId.${i+1}`]=s});if(e?.Filters)e.Filters.forEach((s,i)=>{t[`Filter.${i+1}.Name`]=s.Name,s.Values.forEach((o,c)=>{t[`Filter.${i+1}.Value.${c+1}`]=o})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),r=a.DescribeRouteTablesResponse||a;return{RouteTables:this.parseArray(r.routeTableSet?.item).map((s)=>({RouteTableId:s.routeTableId,VpcId:s.vpcId,Routes:this.parseArray(s.routeSet?.item).map((i)=>({DestinationCidrBlock:i.destinationCidrBlock,GatewayId:i.gatewayId,NatGatewayId:i.natGatewayId,State:i.state})),Associations:this.parseArray(s.associationSet?.item).map((i)=>({RouteTableAssociationId:i.routeTableAssociationId,SubnetId:i.subnetId,Main:i.main==="true"||i.main===!0})),Tags:this.parseTags(s.tagSet?.item)}))}}async deleteVpc(e){let t={Action:"DeleteVpc",Version:"2016-11-15",VpcId:e};await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async deleteSubnet(e){let t={Action:"DeleteSubnet",Version:"2016-11-15",SubnetId:e};await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async deleteSecurityGroup(e){await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({Action:"DeleteSecurityGroup",Version:"2016-11-15",GroupId:e}).toString()})}async describeNetworkInterfaces(e){let t={Action:"DescribeNetworkInterfaces",Version:"2016-11-15"};if(e?.NetworkInterfaceIds)e.NetworkInterfaceIds.forEach((s,i)=>{t[`NetworkInterfaceId.${i+1}`]=s});if(e?.Filters)e.Filters.forEach((s,i)=>{t[`Filter.${i+1}.Name`]=s.Name,s.Values.forEach((o,c)=>{t[`Filter.${i+1}.Value.${c+1}`]=o})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),r=a.DescribeNetworkInterfacesResponse||a;return{NetworkInterfaces:this.parseArray(r.networkInterfaceSet?.item).map((s)=>({NetworkInterfaceId:s.networkInterfaceId,SubnetId:s.subnetId,VpcId:s.vpcId,Status:s.status,Attachment:s.attachment?{AttachmentId:s.attachment.attachmentId,InstanceId:s.attachment.instanceId,Status:s.attachment.status}:void 0}))}}async detachNetworkInterface(e,t){let a={Action:"DetachNetworkInterface",Version:"2016-11-15",AttachmentId:e};if(t)a.Force="true";await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(a).toString()})}async deleteNetworkInterface(e){let t={Action:"DeleteNetworkInterface",Version:"2016-11-15",NetworkInterfaceId:e};await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async describeRegions(){let e={Action:"DescribeRegions",Version:"2016-11-15"},t=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(e).toString()}),a=t.DescribeRegionsResponse||t;return{Regions:this.parseArray(a.regionInfo?.item).map((r)=>({RegionName:r.regionName,Endpoint:r.regionEndpoint}))}}async runInstances(e){let t={Action:"RunInstances",Version:"2016-11-15",ImageId:e.ImageId,InstanceType:e.InstanceType,MinCount:String(e.MinCount),MaxCount:String(e.MaxCount)};if(e.SecurityGroupIds)e.SecurityGroupIds.forEach((s,i)=>{t[`SecurityGroupId.${i+1}`]=s});if(e.SubnetId)t.SubnetId=e.SubnetId;if(e.UserData)t.UserData=e.UserData;if(e.IamInstanceProfile){if(e.IamInstanceProfile.Name)t["IamInstanceProfile.Name"]=e.IamInstanceProfile.Name;if(e.IamInstanceProfile.Arn)t["IamInstanceProfile.Arn"]=e.IamInstanceProfile.Arn}if(e.KeyName)t.KeyName=e.KeyName;if(e.InstanceInitiatedShutdownBehavior)t.InstanceInitiatedShutdownBehavior=e.InstanceInitiatedShutdownBehavior;if(e.BlockDeviceMappings?.forEach((s,i)=>{let o=`BlockDeviceMapping.${i+1}`;t[`${o}.DeviceName`]=s.DeviceName;let c=s.Ebs;if(!c)return;if(c.VolumeSize!==void 0)t[`${o}.Ebs.VolumeSize`]=String(c.VolumeSize);if(c.VolumeType)t[`${o}.Ebs.VolumeType`]=c.VolumeType;if(c.Iops!==void 0)t[`${o}.Ebs.Iops`]=String(c.Iops);if(c.Throughput!==void 0)t[`${o}.Ebs.Throughput`]=String(c.Throughput);if(c.DeleteOnTermination!==void 0)t[`${o}.Ebs.DeleteOnTermination`]=String(c.DeleteOnTermination);if(c.Encrypted!==void 0)t[`${o}.Ebs.Encrypted`]=String(c.Encrypted)}),e.MetadataOptions?.HttpTokens)t["MetadataOptions.HttpTokens"]=e.MetadataOptions.HttpTokens;if(e.MetadataOptions?.HttpEndpoint)t["MetadataOptions.HttpEndpoint"]=e.MetadataOptions.HttpEndpoint;if(e.TagSpecifications)e.TagSpecifications.forEach((s,i)=>{t[`TagSpecification.${i+1}.ResourceType`]=s.ResourceType,s.Tags.forEach((o,c)=>{t[`TagSpecification.${i+1}.Tag.${c+1}.Key`]=o.Key,t[`TagSpecification.${i+1}.Tag.${c+1}.Value`]=o.Value})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),r=a.RunInstancesResponse||a;return{Instances:this.parseInstances(r.instancesSet?.item||r.instancesSet)}}encodeIpPermissions(e,t){t.forEach((a,r)=>{let s=`IpPermissions.${r+1}`;if(a.IpProtocol!==void 0)e[`${s}.IpProtocol`]=a.IpProtocol;if(a.FromPort!==void 0)e[`${s}.FromPort`]=String(a.FromPort);if(a.ToPort!==void 0)e[`${s}.ToPort`]=String(a.ToPort);if(a.IpRanges)a.IpRanges.forEach((i,o)=>{if(i.CidrIp)e[`${s}.IpRanges.${o+1}.CidrIp`]=i.CidrIp;if(i.Description)e[`${s}.IpRanges.${o+1}.Description`]=i.Description});if(a.Ipv6Ranges)a.Ipv6Ranges.forEach((i,o)=>{if(i.CidrIpv6)e[`${s}.Ipv6Ranges.${o+1}.CidrIpv6`]=i.CidrIpv6;if(i.Description)e[`${s}.Ipv6Ranges.${o+1}.Description`]=i.Description});if(a.UserIdGroupPairs)a.UserIdGroupPairs.forEach((i,o)=>{if(i.GroupId)e[`${s}.Groups.${o+1}.GroupId`]=i.GroupId;if(i.UserId)e[`${s}.Groups.${o+1}.UserId`]=i.UserId;if(i.Description)e[`${s}.Groups.${o+1}.Description`]=i.Description})})}parseArray(e){if(!e)return[];return Array.isArray(e)?e:[e]}parseFirstIpv6Address(e){for(let t of this.parseArray(e))for(let a of this.parseArray(t?.ipv6AddressesSet?.item))if(a?.ipv6Address)return a.ipv6Address;return}parseTags(e){return this.parseArray(e).map((t)=>({Key:t.key,Value:t.value}))}parseReservations(e){return this.parseArray(e).map((t)=>({ReservationId:t.reservationId,Instances:this.parseInstances(t.instancesSet?.item||t.instancesSet)}))}parseInstances(e){return this.parseArray(e).map((t)=>({InstanceId:t.instanceId,ImageId:t.imageId,InstanceType:t.instanceType,State:t.instanceState?{Code:Number.parseInt(t.instanceState.code),Name:t.instanceState.name}:void 0,PrivateIpAddress:t.privateIpAddress,PublicIpAddress:t.ipAddress,Ipv6Address:this.parseFirstIpv6Address(t.networkInterfaceSet?.item),SubnetId:t.subnetId,VpcId:t.vpcId,SecurityGroups:this.parseArray(t.groupSet?.item).map((a)=>({GroupId:a.groupId,GroupName:a.groupName})),Tags:this.parseTags(t.tagSet?.item),LaunchTime:t.launchTime,Placement:t.placement?{AvailabilityZone:t.placement.availabilityZone,Tenancy:t.placement.tenancy}:void 0,Architecture:t.architecture,RootDeviceType:t.rootDeviceType,RootDeviceName:t.rootDeviceName,BlockDeviceMappings:this.parseArray(t.blockDeviceMapping?.item).map((a)=>({DeviceName:a.deviceName,Ebs:a.ebs?{VolumeId:a.ebs.volumeId,Status:a.ebs.status,AttachTime:a.ebs.attachTime,DeleteOnTermination:a.ebs.deleteOnTermination==="true"}:void 0})),IamInstanceProfile:t.iamInstanceProfile?{Arn:t.iamInstanceProfile.arn,Id:t.iamInstanceProfile.id}:void 0}))}parseIpPermissions(e){return this.parseArray(e).map((t)=>({IpProtocol:t.ipProtocol,FromPort:t.fromPort?Number.parseInt(t.fromPort):void 0,ToPort:t.toPort?Number.parseInt(t.toPort):void 0,IpRanges:this.parseArray(t.ipRanges?.item).map((a)=>({CidrIp:a.cidrIp,Description:a.description})),Ipv6Ranges:this.parseArray(t.ipv6Ranges?.item).map((a)=>({CidrIpv6:a.cidrIpv6,Description:a.description})),UserIdGroupPairs:this.parseArray(t.groups?.item).map((a)=>({GroupId:a.groupId,UserId:a.userId,Description:a.description}))}))}}class Be{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new n}async putParameter(e){let t={Name:e.Name,Value:e.Value};if(e.Type)t.Type=e.Type;if(e.Description)t.Description=e.Description;if(e.KeyId)t.KeyId=e.KeyId;if(e.Overwrite!==void 0)t.Overwrite=e.Overwrite;if(e.AllowedPattern)t.AllowedPattern=e.AllowedPattern;if(e.Tags&&e.Tags.length>0)t.Tags=e.Tags;if(e.Tier)t.Tier=e.Tier;if(e.DataType)t.DataType=e.DataType;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.PutParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Version:a.Version,Tier:a.Tier}}async getParameter(e){let t={Name:e.Name};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameter:a.Parameter?this.parseParameter(a.Parameter):void 0}}async getParameters(e){let t={Names:e.Names};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:a.Parameters?.map((r)=>this.parseParameter(r)),InvalidParameters:a.InvalidParameters}}async getParametersByPath(e){let t={Path:e.Path};if(e.Recursive!==void 0)t.Recursive=e.Recursive;if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;if(e.MaxResults)t.MaxResults=e.MaxResults;if(e.NextToken)t.NextToken=e.NextToken;if(e.ParameterFilters&&e.ParameterFilters.length>0)t.ParameterFilters=e.ParameterFilters;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParametersByPath","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:a.Parameters?.map((r)=>this.parseParameter(r)),NextToken:a.NextToken}}async deleteParameter(e){let t={Name:e.Name};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DeleteParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async deleteParameters(e){let t={Names:e},a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DeleteParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{DeletedParameters:a.DeletedParameters,InvalidParameters:a.InvalidParameters}}async describeParameters(e){let t={};if(e?.Filters&&e.Filters.length>0)t.Filters=e.Filters;if(e?.ParameterFilters&&e.ParameterFilters.length>0)t.ParameterFilters=e.ParameterFilters;if(e?.MaxResults)t.MaxResults=e.MaxResults;if(e?.NextToken)t.NextToken=e.NextToken;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DescribeParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:a.Parameters?.map((r)=>this.parseParameter(r)),NextToken:a.NextToken}}async getParameterHistory(e){let t={Name:e.Name};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;if(e.MaxResults)t.MaxResults=e.MaxResults;if(e.NextToken)t.NextToken=e.NextToken;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameterHistory","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:a.Parameters?.map((r)=>({Name:r.Name,Type:r.Type,KeyId:r.KeyId,LastModifiedDate:r.LastModifiedDate,LastModifiedUser:r.LastModifiedUser,Description:r.Description,Value:r.Value,Version:r.Version,Labels:r.Labels,Tier:r.Tier})),NextToken:a.NextToken}}async labelParameterVersion(e){let t={Name:e.Name,Labels:e.Labels};if(e.ParameterVersion!==void 0)t.ParameterVersion=e.ParameterVersion;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.LabelParameterVersion","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{InvalidLabels:a.InvalidLabels,ParameterVersion:a.ParameterVersion}}async addTagsToResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId,Tags:e.Tags};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.AddTagsToResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async removeTagsFromResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId,TagKeys:e.TagKeys};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.RemoveTagsFromResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async listTagsForResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId};return{TagList:(await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.ListTagsForResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})).TagList}}async setString(e,t,a){return this.putParameter({Name:e,Value:t,Type:"String",Description:a?.description,Overwrite:a?.overwrite??!0,Tags:a?.tags})}async setSecureString(e,t,a){return this.putParameter({Name:e,Value:t,Type:"SecureString",Description:a?.description,Overwrite:a?.overwrite??!0,KeyId:a?.kmsKeyId,Tags:a?.tags})}async getValue(e){return(await this.getParameter({Name:e,WithDecryption:!0})).Parameter?.Value}async getAllByPath(e,t=!0){let a=[],r;do{let s=await this.getParametersByPath({Path:e,Recursive:t,WithDecryption:!0,NextToken:r});if(s.Parameters)a.push(...s.Parameters);r=s.NextToken}while(r);return a}parseParameter(e){return{Name:e.Name,Type:e.Type,Value:e.Value,Version:e.Version,LastModifiedDate:e.LastModifiedDate,ARN:e.ARN,DataType:e.DataType,Description:e.Description,AllowedPattern:e.AllowedPattern,KeyId:e.KeyId,Tier:e.Tier}}async sendCommand(e){if(!e.InstanceIds&&!e.Targets)throw Error("SendCommand requires either InstanceIds or Targets");let t={DocumentName:e.DocumentName};if(e.InstanceIds)t.InstanceIds=e.InstanceIds;if(e.Targets)t.Targets=e.Targets;if(e.Parameters)t.Parameters=e.Parameters;if(e.TimeoutSeconds)t.TimeoutSeconds=e.TimeoutSeconds;if(e.Comment)t.Comment=e.Comment;if(e.OutputS3BucketName)t.OutputS3BucketName=e.OutputS3BucketName;if(e.OutputS3KeyPrefix)t.OutputS3KeyPrefix=e.OutputS3KeyPrefix;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.SendCommand","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{CommandId:a.Command?.CommandId,Status:a.Command?.Status,StatusDetails:a.Command?.StatusDetails}}async getCommandInvocation(e){let t={CommandId:e.CommandId,InstanceId:e.InstanceId},a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetCommandInvocation","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Status:a.Status,StatusDetails:a.StatusDetails,StandardOutputContent:a.StandardOutputContent,StandardErrorContent:a.StandardErrorContent,ResponseCode:a.ResponseCode}}async runShellCommand(e,t,a){let r=await this.sendCommand({InstanceIds:[e],DocumentName:"AWS-RunShellScript",Parameters:{commands:t},TimeoutSeconds:a?.timeoutSeconds||600});if(!r.CommandId)return{success:!1,error:"Failed to send command"};if(a?.waitForCompletion===!1)return{success:!0,status:"Pending"};let s=a?.pollIntervalMs||2000,i=a?.maxWaitMs||300000,o=Date.now();while(Date.now()-o<i){await new Promise((c)=>setTimeout(c,s));try{let c=await this.getCommandInvocation({CommandId:r.CommandId,InstanceId:e});if(c.Status==="Success")return{success:!0,output:c.StandardOutputContent,error:c.StandardErrorContent,status:c.Status};if(c.Status==="Failed"||c.Status==="Cancelled"||c.Status==="TimedOut")return{success:!1,output:c.StandardOutputContent,error:c.StandardErrorContent||c.StatusDetails,status:c.Status}}catch(c){if(!c.message?.includes("InvocationDoesNotExist"))return{success:!1,error:c.message}}}return{success:!1,error:"Command timed out waiting for completion"}}async listCommandInvocations(e){let t={CommandId:e.CommandId};if(e.Details)t.Details=!0;return((await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.ListCommandInvocations","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})).CommandInvocations||[]).map((s)=>({InstanceId:s.InstanceId,Status:s.Status,StatusDetails:s.StatusDetails,StandardOutputContent:s.CommandPlugins?.[0]?.Output,StandardErrorContent:s.CommandPlugins?.[0]?.StandardErrorUrl}))}async sendCommandByTags(e){let t=Object.entries(e.tags).map(([d,g])=>({Key:`tag:${d}`,Values:[g]})),a=await this.sendCommand({Targets:t,DocumentName:"AWS-RunShellScript",Parameters:{commands:e.commands},TimeoutSeconds:e.timeoutSeconds||600,Comment:e.comment});if(!a.CommandId)return{success:!1,instanceCount:0,perInstance:[],error:"Failed to send command"};let r=e.pollIntervalMs||3000,s=e.maxWaitMs||600000,i=Date.now(),o=new Set(["Success","Failed","Cancelled","TimedOut"]),c=[];while(Date.now()-i<s){await new Promise((d)=>setTimeout(d,r));try{if(c=await this.listCommandInvocations({CommandId:a.CommandId,Details:!0}),c.length===0)continue;if(c.every((g)=>o.has(g.Status||""))){let g=c.map((u)=>({instanceId:u.InstanceId,status:u.Status||"Unknown",output:u.StandardOutputContent,error:u.StandardErrorContent||u.StatusDetails})),m=c.every((u)=>u.Status==="Success");return{success:m,instanceCount:c.length,perInstance:g,error:m?void 0:"One or more instances reported a non-success status"}}}catch(d){if(!d.message?.includes("InvocationDoesNotExist"))return{success:!1,instanceCount:0,perInstance:[],error:d.message}}}return{success:!1,instanceCount:c.length,perInstance:c.map((d)=>({instanceId:d.InstanceId,status:d.Status||"Unknown"})),error:"Command timed out waiting for all instances to complete"}}}
4
4
  export{Vr,Be};
@@ -1,4 +1,4 @@
1
- import{vt,xi,Oi,_i}from"./chunk-rkashc9e.js";function S(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function rA(t,e="/var/www"){let n=`${e}/${t}-`;return["set -u",`for TS_CLOUD_DIR in ${n}*; do`,' [ -d "$TS_CLOUD_DIR" ] || continue',' [ -d "$TS_CLOUD_DIR/releases" ] || continue',` TS_CLOUD_SITE="\${TS_CLOUD_DIR#${n}}"`," TS_CLOUD_ACTIVE=no",` for TS_CLOUD_UNIT in $(ls /etc/systemd/system/ 2>/dev/null | grep -E "^${S(t)}-$TS_CLOUD_SITE[-@.]" || true); do`,' systemctl is-active "$TS_CLOUD_UNIT" >/dev/null 2>&1 && TS_CLOUD_ACTIVE=yes'," done",' TS_CLOUD_SIZE="$(du -sh "$TS_CLOUD_DIR" 2>/dev/null | cut -f1)"',' echo "site:$TS_CLOUD_SITE:$TS_CLOUD_ACTIVE:${TS_CLOUD_SIZE:-?}"',"done","exit 0"]}function nA(t){if(!t)return[];let e=[];for(let n of t.split(`
1
+ import{vt,xi,Oi,_i}from"./chunk-2r334egt.js";function S(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function rA(t,e="/var/www"){let n=`${e}/${t}-`;return["set -u",`for TS_CLOUD_DIR in ${n}*; do`,' [ -d "$TS_CLOUD_DIR" ] || continue',' [ -d "$TS_CLOUD_DIR/releases" ] || continue',` TS_CLOUD_SITE="\${TS_CLOUD_DIR#${n}}"`," TS_CLOUD_ACTIVE=no",` for TS_CLOUD_UNIT in $(ls /etc/systemd/system/ 2>/dev/null | grep -E "^${S(t)}-$TS_CLOUD_SITE[-@.]" || true); do`,' systemctl is-active "$TS_CLOUD_UNIT" >/dev/null 2>&1 && TS_CLOUD_ACTIVE=yes'," done",' TS_CLOUD_SIZE="$(du -sh "$TS_CLOUD_DIR" 2>/dev/null | cut -f1)"',' echo "site:$TS_CLOUD_SITE:$TS_CLOUD_ACTIVE:${TS_CLOUD_SIZE:-?}"',"done","exit 0"]}function nA(t){if(!t)return[];let e=[];for(let n of t.split(`
2
2
  `)){let r=n.trim();if(!r.startsWith("site:"))continue;let[,s,o,i]=r.split(":");if(!s||o!=="no")continue;e.push({name:s,size:i||"?"})}return e}function iA(t,e,n){let r=t.map((o)=>` ${e}-${o.name} (${o.size})`).join(`
3
3
  `),s=t.length===1?"it":"them";return`This server still holds ${t.length} site tree${t.length===1?"":"s"} with nothing running for ${s}:
4
4
  ${r}
@@ -1,2 +1,2 @@
1
- import{n}from"./chunk-1eg5wsn2.js";class He{client;region;constructor(e="us-east-1",r){this.region=e,this.client=new n(void 0,{profile:r})}async createRepository(e){let r={repositoryName:e.repositoryName};if(e.imageTagMutability)r.imageTagMutability=e.imageTagMutability;if(e.imageScanningConfiguration)r.imageScanningConfiguration=e.imageScanningConfiguration;if(e.encryptionConfiguration)r.encryptionConfiguration=e.encryptionConfiguration;if(e.tags&&e.tags.length>0)r.tags=e.tags;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.CreateRepository","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{repository:t.repository?this.parseRepository(t.repository):void 0}}async describeRepositories(e){let r={};if(e?.repositoryNames&&e.repositoryNames.length>0)r.repositoryNames=e.repositoryNames;if(e?.registryId)r.registryId=e.registryId;if(e?.maxResults)r.maxResults=e.maxResults;if(e?.nextToken)r.nextToken=e.nextToken;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.DescribeRepositories","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{repositories:t.repositories?.map((i)=>this.parseRepository(i)),nextToken:t.nextToken}}async getAuthorizationToken(e){let r={};if(e&&e.length>0)r.registryIds=e;return{authorizationData:(await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.GetAuthorizationToken","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)})).authorizationData?.map((i)=>({authorizationToken:i.authorizationToken,expiresAt:i.expiresAt,proxyEndpoint:i.proxyEndpoint}))}}async deleteRepository(e){let r={repositoryName:e.repositoryName};if(e.registryId)r.registryId=e.registryId;if(e.force!==void 0)r.force=e.force;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.DeleteRepository","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{repository:t.repository?this.parseRepository(t.repository):void 0}}async describeImages(e){let r={repositoryName:e.repositoryName};if(e.registryId)r.registryId=e.registryId;if(e.imageIds&&e.imageIds.length>0)r.imageIds=e.imageIds;if(e.filter)r.filter=e.filter;if(e.maxResults)r.maxResults=e.maxResults;if(e.nextToken)r.nextToken=e.nextToken;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.DescribeImages","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{imageDetails:t.imageDetails?.map((i)=>this.parseImageDetail(i)),nextToken:t.nextToken}}async batchDeleteImage(e){let r={repositoryName:e.repositoryName,imageIds:e.imageIds};if(e.registryId)r.registryId=e.registryId;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.BatchDeleteImage","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{imageIds:t.imageIds,failures:t.failures}}async putLifecyclePolicy(e){let r={repositoryName:e.repositoryName,lifecyclePolicyText:e.lifecyclePolicyText};if(e.registryId)r.registryId=e.registryId;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.PutLifecyclePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{registryId:t.registryId,repositoryName:t.repositoryName,lifecyclePolicyText:t.lifecyclePolicyText}}async getLifecyclePolicy(e){let r={repositoryName:e.repositoryName};if(e.registryId)r.registryId=e.registryId;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.GetLifecyclePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{registryId:t.registryId,repositoryName:t.repositoryName,lifecyclePolicyText:t.lifecyclePolicyText,lastEvaluatedAt:t.lastEvaluatedAt}}async setRepositoryPolicy(e){let r={repositoryName:e.repositoryName,policyText:e.policyText};if(e.registryId)r.registryId=e.registryId;if(e.force!==void 0)r.force=e.force;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.SetRepositoryPolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{registryId:t.registryId,repositoryName:t.repositoryName,policyText:t.policyText}}async getRepositoryPolicy(e){let r={repositoryName:e.repositoryName};if(e.registryId)r.registryId=e.registryId;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.GetRepositoryPolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{registryId:t.registryId,repositoryName:t.repositoryName,policyText:t.policyText}}async tagResource(e){let r={resourceArn:e.resourceArn,tags:e.tags};await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.TagResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)})}async listTagsForResource(e){let r={resourceArn:e};return{tags:(await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.ListTagsForResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)})).tags}}createLifecyclePolicyText(e){return JSON.stringify({rules:e.map((r)=>({rulePriority:r.rulePriority,description:r.description,selection:r.selection,action:r.action}))})}async getDockerLoginCommand(){let e=await this.getAuthorizationToken();if(!e.authorizationData?.[0])throw Error("Failed to get authorization token");let r=e.authorizationData[0],t=r.authorizationToken||"",i=r.proxyEndpoint||"";return`echo "${Buffer.from(t,"base64").toString("utf8").split(":")[1]}" | docker login --username AWS --password-stdin ${i}`}getRegistryUri(e){return`${e}.dkr.ecr.${this.region}.amazonaws.com`}parseRepository(e){return{repositoryArn:e.repositoryArn,registryId:e.registryId,repositoryName:e.repositoryName,repositoryUri:e.repositoryUri,createdAt:e.createdAt,imageTagMutability:e.imageTagMutability,imageScanningConfiguration:e.imageScanningConfiguration,encryptionConfiguration:e.encryptionConfiguration}}parseImageDetail(e){return{registryId:e.registryId,repositoryName:e.repositoryName,imageDigest:e.imageDigest,imageTags:e.imageTags,imageSizeInBytes:e.imageSizeInBytes,imagePushedAt:e.imagePushedAt,imageScanStatus:e.imageScanStatus,imageScanFindingsSummary:e.imageScanFindingsSummary}}}
1
+ import{n}from"./chunk-z90dv6jx.js";class He{client;region;constructor(e="us-east-1",r){this.region=e,this.client=new n(void 0,{profile:r})}async createRepository(e){let r={repositoryName:e.repositoryName};if(e.imageTagMutability)r.imageTagMutability=e.imageTagMutability;if(e.imageScanningConfiguration)r.imageScanningConfiguration=e.imageScanningConfiguration;if(e.encryptionConfiguration)r.encryptionConfiguration=e.encryptionConfiguration;if(e.tags&&e.tags.length>0)r.tags=e.tags;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.CreateRepository","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{repository:t.repository?this.parseRepository(t.repository):void 0}}async describeRepositories(e){let r={};if(e?.repositoryNames&&e.repositoryNames.length>0)r.repositoryNames=e.repositoryNames;if(e?.registryId)r.registryId=e.registryId;if(e?.maxResults)r.maxResults=e.maxResults;if(e?.nextToken)r.nextToken=e.nextToken;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.DescribeRepositories","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{repositories:t.repositories?.map((i)=>this.parseRepository(i)),nextToken:t.nextToken}}async getAuthorizationToken(e){let r={};if(e&&e.length>0)r.registryIds=e;return{authorizationData:(await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.GetAuthorizationToken","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)})).authorizationData?.map((i)=>({authorizationToken:i.authorizationToken,expiresAt:i.expiresAt,proxyEndpoint:i.proxyEndpoint}))}}async deleteRepository(e){let r={repositoryName:e.repositoryName};if(e.registryId)r.registryId=e.registryId;if(e.force!==void 0)r.force=e.force;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.DeleteRepository","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{repository:t.repository?this.parseRepository(t.repository):void 0}}async describeImages(e){let r={repositoryName:e.repositoryName};if(e.registryId)r.registryId=e.registryId;if(e.imageIds&&e.imageIds.length>0)r.imageIds=e.imageIds;if(e.filter)r.filter=e.filter;if(e.maxResults)r.maxResults=e.maxResults;if(e.nextToken)r.nextToken=e.nextToken;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.DescribeImages","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{imageDetails:t.imageDetails?.map((i)=>this.parseImageDetail(i)),nextToken:t.nextToken}}async batchDeleteImage(e){let r={repositoryName:e.repositoryName,imageIds:e.imageIds};if(e.registryId)r.registryId=e.registryId;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.BatchDeleteImage","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{imageIds:t.imageIds,failures:t.failures}}async putLifecyclePolicy(e){let r={repositoryName:e.repositoryName,lifecyclePolicyText:e.lifecyclePolicyText};if(e.registryId)r.registryId=e.registryId;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.PutLifecyclePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{registryId:t.registryId,repositoryName:t.repositoryName,lifecyclePolicyText:t.lifecyclePolicyText}}async getLifecyclePolicy(e){let r={repositoryName:e.repositoryName};if(e.registryId)r.registryId=e.registryId;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.GetLifecyclePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{registryId:t.registryId,repositoryName:t.repositoryName,lifecyclePolicyText:t.lifecyclePolicyText,lastEvaluatedAt:t.lastEvaluatedAt}}async setRepositoryPolicy(e){let r={repositoryName:e.repositoryName,policyText:e.policyText};if(e.registryId)r.registryId=e.registryId;if(e.force!==void 0)r.force=e.force;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.SetRepositoryPolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{registryId:t.registryId,repositoryName:t.repositoryName,policyText:t.policyText}}async getRepositoryPolicy(e){let r={repositoryName:e.repositoryName};if(e.registryId)r.registryId=e.registryId;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.GetRepositoryPolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{registryId:t.registryId,repositoryName:t.repositoryName,policyText:t.policyText}}async tagResource(e){let r={resourceArn:e.resourceArn,tags:e.tags};await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.TagResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)})}async listTagsForResource(e){let r={resourceArn:e};return{tags:(await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.ListTagsForResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)})).tags}}createLifecyclePolicyText(e){return JSON.stringify({rules:e.map((r)=>({rulePriority:r.rulePriority,description:r.description,selection:r.selection,action:r.action}))})}async getDockerLoginCommand(){let e=await this.getAuthorizationToken();if(!e.authorizationData?.[0])throw Error("Failed to get authorization token");let r=e.authorizationData[0],t=r.authorizationToken||"",i=r.proxyEndpoint||"";return`echo "${Buffer.from(t,"base64").toString("utf8").split(":")[1]}" | docker login --username AWS --password-stdin ${i}`}getRegistryUri(e){return`${e}.dkr.ecr.${this.region}.amazonaws.com`}parseRepository(e){return{repositoryArn:e.repositoryArn,registryId:e.registryId,repositoryName:e.repositoryName,repositoryUri:e.repositoryUri,createdAt:e.createdAt,imageTagMutability:e.imageTagMutability,imageScanningConfiguration:e.imageScanningConfiguration,encryptionConfiguration:e.encryptionConfiguration}}parseImageDetail(e){return{registryId:e.registryId,repositoryName:e.repositoryName,imageDigest:e.imageDigest,imageTags:e.imageTags,imageSizeInBytes:e.imageSizeInBytes,imagePushedAt:e.imagePushedAt,imageScanStatus:e.imageScanStatus,imageScanFindingsSummary:e.imageScanFindingsSummary}}}
2
2
  export{He};
@@ -1,4 +1,4 @@
1
- import{ie,ye,N,Se,xr}from"./chunk-ms84y9kg.js";import{o}from"./chunk-1y1b1jy0.js";import{Qe,I}from"./chunk-3k9kdbsc.js";import{b}from"./chunk-gssa1974.js";import{A}from"./chunk-vx5n4bhb.js";function mc(t){let{bucketName:s,domain:c,aliases:e,certificateArn:g,defaultRootObject:i="index.html",errorDocument:r="404.html",passthroughUrls:a=!1,singlePageApp:d=!1,dynamicApp:m=!1,computeOriginDomain:w,computeOriginPort:O=3008,computeOriginId:F="app-compute",retainOnStackDelete:v=!1}=t,S=v?{DeletionPolicy:"Retain",UpdateReplacePolicy:"Retain"}:{},y=m&&!!w,B=y?["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"]:["GET","HEAD"],E=y?["GET","HEAD"]:["GET","HEAD"],R={},x={};R.S3Bucket={Type:"AWS::S3::Bucket",...S,Properties:{BucketName:s,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:i,ErrorDocument:r}}},x.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},x.BucketArn={Description:"S3 Bucket ARN",Value:{"Fn::GetAtt":["S3Bucket","Arn"]}},R.CloudFrontOAC={Type:"AWS::CloudFront::OriginAccessControl",...S,Properties:{OriginAccessControlConfig:{Name:`OAC-${s}`,Description:`OAC for ${s}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}};let h;if(a&&y)h="InstallRootRedirectFunction",R[h]={Type:"AWS::CloudFront::Function",Properties:{Name:{"Fn::Sub":"${AWS::StackName}-install-root-redirect"},AutoPublish:!0,FunctionConfig:{Comment:"Redirect curl pantry.dev | bash (GET /) to /install.sh on S3",Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) {
1
+ import{ie,ye,N,Se,xr}from"./chunk-1ktv8jxf.js";import{o}from"./chunk-49rt1jbe.js";import{Qe,I}from"./chunk-ggqxjcbe.js";import{b}from"./chunk-c2hvf1h5.js";import{A}from"./chunk-7qhcfnqf.js";function mc(t){let{bucketName:s,domain:c,aliases:e,certificateArn:g,defaultRootObject:i="index.html",errorDocument:r="404.html",passthroughUrls:a=!1,singlePageApp:d=!1,dynamicApp:m=!1,computeOriginDomain:w,computeOriginPort:O=3008,computeOriginId:F="app-compute",retainOnStackDelete:v=!1}=t,S=v?{DeletionPolicy:"Retain",UpdateReplacePolicy:"Retain"}:{},y=m&&!!w,B=y?["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"]:["GET","HEAD"],E=y?["GET","HEAD"]:["GET","HEAD"],R={},x={};R.S3Bucket={Type:"AWS::S3::Bucket",...S,Properties:{BucketName:s,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:i,ErrorDocument:r}}},x.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},x.BucketArn={Description:"S3 Bucket ARN",Value:{"Fn::GetAtt":["S3Bucket","Arn"]}},R.CloudFrontOAC={Type:"AWS::CloudFront::OriginAccessControl",...S,Properties:{OriginAccessControlConfig:{Name:`OAC-${s}`,Description:`OAC for ${s}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}};let h;if(a&&y)h="InstallRootRedirectFunction",R[h]={Type:"AWS::CloudFront::Function",Properties:{Name:{"Fn::Sub":"${AWS::StackName}-install-root-redirect"},AutoPublish:!0,FunctionConfig:{Comment:"Redirect curl pantry.dev | bash (GET /) to /install.sh on S3",Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) {
2
2
  var request = event.request;
3
3
  if (request.uri === '/' || request.uri === '') {
4
4
  return {
@@ -42,7 +42,7 @@ import{ie,ye,N,Se,xr}from"./chunk-ms84y9kg.js";import{o}from"./chunk-1y1b1jy0.js
42
42
  │ │
43
43
  │ Verification typically takes 1-2 business days. │
44
44
  │ After verification, re-run: bunx bunpress deploy │
45
- └─────────────────────────────────────────────────────────────────────────────┘`),{success:!1,stackId:x,stackName:i,bucket:y,message:"CloudFront account verification required. Please contact AWS Support."}}return{success:!1,stackId:x,stackName:i,bucket:y,message:`Stack deployment failed: ${n.message}`}}let u=(await r.describeStacks({stackName:i})).Stacks[0]?.Outputs||[],k=(n)=>u.find((l)=>l.OutputKey===n)?.OutputValue,p=k("DistributionDomain");if(p&&d)console.log(`Creating DNS records via ${d.name}...`),await W(d,e,p);else if(p&&!d)console.log("Skipping DNS record creation (DNS verification was skipped)");return{success:!0,stackId:x,stackName:i,bucket:k("BucketName")||y,distributionId:k("DistributionId"),distributionDomain:p,domain:e,certificateArn:m,message:"Static site infrastructure deployed successfully with external DNS"}}async function W(t,s,c){if(!t){console.log("Skipping DNS record creation (DNS verification was skipped)");return}if(s.split(".").length===2)if(t instanceof ie){console.log(`Creating Route53 alias record for apex domain ${s} -> ${c}`);let i=await t.createCloudFrontAlias({domain:s,name:s,cloudFrontDomainName:c});if(!i.success)console.warn(`Warning: Could not create Route53 alias record: ${i.message}`),console.warn("Please manually create an A-record alias in Route53:"),console.warn(` ${s} -> ${c}`);else console.log(`Created Route53 alias record: ${s} -> ${c}`);let r=`www.${s}`;console.log(`Creating Route53 alias record for ${r} -> ${c}`);let a=await t.createCloudFrontAlias({domain:s,name:r,cloudFrontDomainName:c});if(!a.success)console.warn(`Warning: Could not create www Route53 alias: ${a.message}`),console.warn("Please manually create an A-record alias in Route53:"),console.warn(` ${r} -> ${c}`);else console.log(`Created Route53 alias record: ${r} -> ${c}`)}else{try{let d=await t.listRecords(s,"A");if(d.success)for(let m of d.records){let w=m.name.replace(/\.$/,"");if(w===s||w==="")console.log(`Removing existing root A record (${m.content}) to make room for ALIAS...`),await t.deleteRecord(s,{name:s,type:"A",content:m.content})}}catch(d){console.log(`Note: Could not check for conflicting A records: ${d instanceof Error?d.message:d}`)}console.log(`Creating ALIAS record for apex domain ${s} -> ${c}`);let i=await t.upsertRecord(s,{name:s,type:"ALIAS",content:c,ttl:600});if(!i.success)console.warn(`Warning: Could not create ALIAS record: ${i.message}`),console.warn("Please manually create an ALIAS record in your DNS provider:"),console.warn(` ${s} -> ${c}`);else console.log(`Created ALIAS record: ${s} -> ${c}`);let r=`www.${s}`;console.log(`Creating CNAME record for ${r} -> ${c}`);let a=await t.upsertRecord(s,{name:r,type:"CNAME",content:c,ttl:600});if(!a.success)console.warn(`Warning: Could not create www DNS record: ${a.message}`),console.warn("Please manually create a CNAME record:"),console.warn(` ${r} -> ${c}`);else console.log(`Created CNAME record: ${r} -> ${c}`)}else{console.log(`Creating CNAME record for ${s} -> ${c}`);let i=await t.upsertRecord(s,{name:s,type:"CNAME",content:c,ttl:600});if(!i.success)console.warn(`Warning: Could not create DNS record: ${i.message}`),console.warn("Please manually create a CNAME record:"),console.warn(` ${s} -> ${c}`);else console.log(`Created CNAME record: ${s} -> ${c}`)}}async function Ln(t){let{sourceDir:s,cleanBucket:c=!1,onProgress:e,...g}=t;e?.("infrastructure","Deploying CloudFormation stack...");let i=await _n(g);if(!i.success)return i;if(c){e?.("clean","Cleaning old files from S3...");try{await new o(g.region||"us-east-1").emptyBucket(i.bucket)}catch(m){console.log(`Note: Could not clean bucket: ${m.message}`)}}e?.("upload","Uploading files to S3...");let{uploadStaticFiles:r}=await import("./chunk-2b4knhhy.js"),a=await r({sourceDir:s,bucket:i.bucket,region:g.region||"us-east-1",cacheControl:g.cacheControl,onProgress:(m,w,O)=>{e?.("upload",`${m}/${w}: ${O}`)}});if(a.errors.length>0)return{...i,success:!1,message:`Upload errors: ${a.errors.join(", ")}`,filesUploaded:a.uploaded};if(i.distributionId&&a.uploaded>0){e?.("invalidate","Invalidating CloudFront cache...");let{invalidateCache:m}=await import("./chunk-2b4knhhy.js");await m(i.distributionId)}e?.("complete","Deployment complete!");let d=a.skipped>0?`Deployed ${a.uploaded} files (${a.skipped} unchanged) with external DNS`:`Deployed ${a.uploaded} files successfully with external DNS`;return{...i,filesUploaded:a.uploaded,filesSkipped:a.skipped,message:d}}function Ds(t){let{bucketName:s,domain:c,certificateArn:e,hostedZoneId:g,defaultRootObject:i="index.html",errorDocument:r="404.html"}=t,a={},d={};a.S3Bucket={Type:"AWS::S3::Bucket",Properties:{BucketName:s,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:i,ErrorDocument:r}}},d.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},d.BucketArn={Description:"S3 Bucket ARN",Value:{"Fn::GetAtt":["S3Bucket","Arn"]}},a.CloudFrontOAC={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`OAC-${s}`,Description:`OAC for ${s}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},a.UrlRewriteFunction={Type:"AWS::CloudFront::Function",Properties:{Name:{"Fn::Sub":"${AWS::StackName}-url-rewrite"},AutoPublish:!0,FunctionConfig:{Comment:"Append .html extension to URLs without extensions",Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) {
45
+ └─────────────────────────────────────────────────────────────────────────────┘`),{success:!1,stackId:x,stackName:i,bucket:y,message:"CloudFront account verification required. Please contact AWS Support."}}return{success:!1,stackId:x,stackName:i,bucket:y,message:`Stack deployment failed: ${n.message}`}}let u=(await r.describeStacks({stackName:i})).Stacks[0]?.Outputs||[],k=(n)=>u.find((l)=>l.OutputKey===n)?.OutputValue,p=k("DistributionDomain");if(p&&d)console.log(`Creating DNS records via ${d.name}...`),await W(d,e,p);else if(p&&!d)console.log("Skipping DNS record creation (DNS verification was skipped)");return{success:!0,stackId:x,stackName:i,bucket:k("BucketName")||y,distributionId:k("DistributionId"),distributionDomain:p,domain:e,certificateArn:m,message:"Static site infrastructure deployed successfully with external DNS"}}async function W(t,s,c){if(!t){console.log("Skipping DNS record creation (DNS verification was skipped)");return}if(s.split(".").length===2)if(t instanceof ie){console.log(`Creating Route53 alias record for apex domain ${s} -> ${c}`);let i=await t.createCloudFrontAlias({domain:s,name:s,cloudFrontDomainName:c});if(!i.success)console.warn(`Warning: Could not create Route53 alias record: ${i.message}`),console.warn("Please manually create an A-record alias in Route53:"),console.warn(` ${s} -> ${c}`);else console.log(`Created Route53 alias record: ${s} -> ${c}`);let r=`www.${s}`;console.log(`Creating Route53 alias record for ${r} -> ${c}`);let a=await t.createCloudFrontAlias({domain:s,name:r,cloudFrontDomainName:c});if(!a.success)console.warn(`Warning: Could not create www Route53 alias: ${a.message}`),console.warn("Please manually create an A-record alias in Route53:"),console.warn(` ${r} -> ${c}`);else console.log(`Created Route53 alias record: ${r} -> ${c}`)}else{try{let d=await t.listRecords(s,"A");if(d.success)for(let m of d.records){let w=m.name.replace(/\.$/,"");if(w===s||w==="")console.log(`Removing existing root A record (${m.content}) to make room for ALIAS...`),await t.deleteRecord(s,{name:s,type:"A",content:m.content})}}catch(d){console.log(`Note: Could not check for conflicting A records: ${d instanceof Error?d.message:d}`)}console.log(`Creating ALIAS record for apex domain ${s} -> ${c}`);let i=await t.upsertRecord(s,{name:s,type:"ALIAS",content:c,ttl:600});if(!i.success)console.warn(`Warning: Could not create ALIAS record: ${i.message}`),console.warn("Please manually create an ALIAS record in your DNS provider:"),console.warn(` ${s} -> ${c}`);else console.log(`Created ALIAS record: ${s} -> ${c}`);let r=`www.${s}`;console.log(`Creating CNAME record for ${r} -> ${c}`);let a=await t.upsertRecord(s,{name:r,type:"CNAME",content:c,ttl:600});if(!a.success)console.warn(`Warning: Could not create www DNS record: ${a.message}`),console.warn("Please manually create a CNAME record:"),console.warn(` ${r} -> ${c}`);else console.log(`Created CNAME record: ${r} -> ${c}`)}else{console.log(`Creating CNAME record for ${s} -> ${c}`);let i=await t.upsertRecord(s,{name:s,type:"CNAME",content:c,ttl:600});if(!i.success)console.warn(`Warning: Could not create DNS record: ${i.message}`),console.warn("Please manually create a CNAME record:"),console.warn(` ${s} -> ${c}`);else console.log(`Created CNAME record: ${s} -> ${c}`)}}async function Ln(t){let{sourceDir:s,cleanBucket:c=!1,onProgress:e,...g}=t;e?.("infrastructure","Deploying CloudFormation stack...");let i=await _n(g);if(!i.success)return i;if(c){e?.("clean","Cleaning old files from S3...");try{await new o(g.region||"us-east-1").emptyBucket(i.bucket)}catch(m){console.log(`Note: Could not clean bucket: ${m.message}`)}}e?.("upload","Uploading files to S3...");let{uploadStaticFiles:r}=await import("./chunk-sacbxd79.js"),a=await r({sourceDir:s,bucket:i.bucket,region:g.region||"us-east-1",cacheControl:g.cacheControl,onProgress:(m,w,O)=>{e?.("upload",`${m}/${w}: ${O}`)}});if(a.errors.length>0)return{...i,success:!1,message:`Upload errors: ${a.errors.join(", ")}`,filesUploaded:a.uploaded};if(i.distributionId&&a.uploaded>0){e?.("invalidate","Invalidating CloudFront cache...");let{invalidateCache:m}=await import("./chunk-sacbxd79.js");await m(i.distributionId)}e?.("complete","Deployment complete!");let d=a.skipped>0?`Deployed ${a.uploaded} files (${a.skipped} unchanged) with external DNS`:`Deployed ${a.uploaded} files successfully with external DNS`;return{...i,filesUploaded:a.uploaded,filesSkipped:a.skipped,message:d}}function Ds(t){let{bucketName:s,domain:c,certificateArn:e,hostedZoneId:g,defaultRootObject:i="index.html",errorDocument:r="404.html"}=t,a={},d={};a.S3Bucket={Type:"AWS::S3::Bucket",Properties:{BucketName:s,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:i,ErrorDocument:r}}},d.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},d.BucketArn={Description:"S3 Bucket ARN",Value:{"Fn::GetAtt":["S3Bucket","Arn"]}},a.CloudFrontOAC={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`OAC-${s}`,Description:`OAC for ${s}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},a.UrlRewriteFunction={Type:"AWS::CloudFront::Function",Properties:{Name:{"Fn::Sub":"${AWS::StackName}-url-rewrite"},AutoPublish:!0,FunctionConfig:{Comment:"Append .html extension to URLs without extensions",Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) {
46
46
  const request = event.request;
47
47
  var uri = request.uri;
48
48
 
@@ -1,2 +1,2 @@
1
- import{K,ol}from"./chunk-e32qtz2d.js";function U(t,s){return`/var/www/${t}-${s}`}var y=new Set(["laravel","php","statamic","wordpress"]);function jr(t){return t.type!=null&&y.has(t.type)}function zr(t){let s=t.proxyTo;if(s==null)return[];return(Array.isArray(s)?s:[s]).map((n)=>String(n).trim()).filter((n)=>n.length>0)}function Ad(t){return zr(t).length>0}function Ao(t){if(t.deploy)return t.deploy;if(jr(t))return"server";if(t.start)return"server";return"bucket"}function d(t){if(t.redirect)return"redirect";if(Ad(t))return"proxy";if(jr(t))return"server-php";if(Ao(t)==="bucket")return"bucket";return t.start?"server-app":"server-static"}function RA(t){return t.infrastructure?.compute!=null||Boolean(t.cloud?.attachTo?.trim())}function zp(t,s={}){let r=[],n=[],a=t.sites||{},p=RA(t),l=ol(t);if(l)r.push(l);let f=new Map;for(let[o,e]of Object.entries(a)){if(!e)continue;let h=Ao(e),c=d(e);if(c==="redirect"){if(!e.domain)r.push(`Site '${o}' is a redirect site but has no \`domain\` to redirect from.`);if(!(typeof e.redirect==="string"?e.redirect:e.redirect?.to))r.push(`Site '${o}' is a redirect site but has no redirect target (\`redirect\` / \`redirect.to\`).`);if(!p)r.push(`Site '${o}' is a redirect site but no \`infrastructure.compute\` is configured to host the gateway that serves the redirect.`);let u=[];if(e.start)u.push("start");if(e.root)u.push("root");if(e.proxyTo)u.push("proxyTo");if(u.length>0)n.push(`Site '${o}' is a redirect site but also sets ${u.join(", ")}. These are ignored.`);continue}if(c==="proxy"){if(!e.domain)r.push(`Site '${o}' is a proxy site but has no \`domain\` to route from.`);if(!p)r.push(`Site '${o}' is a proxy site but no \`infrastructure.compute\` is configured to host the gateway that forwards it.`);let i=[];if(e.start)i.push("start");if(e.root)i.push("root");if(typeof e.port==="number")i.push("port");if(e.build)i.push("build");if(e.preStart&&e.preStart.length>0)i.push("preStart");if(i.length>0)n.push(`Site '${o}' sets \`proxyTo\`, so ts-cloud ships and supervises nothing for it. ${i.join(", ")} ${i.length===1?"is":"are"} ignored — remove ${i.length===1?"it":"them"}, or drop \`proxyTo\` to let ts-cloud own the service.`);continue}if(h==="server"&&!e.start&&!e.root){r.push(`Site '${o}' sets deploy:'server' but declares neither \`start\` (dynamic app) nor \`root\` (static site to serve). Add one.`);continue}if(c==="server-php"){if(!p)r.push(`Site '${o}' is a PHP site (type:'${e.type}') but no \`infrastructure.compute\` is configured. Add a server (infrastructure.compute) with PHP provisioning.`);if(!e.repository?.url)r.push(`Site '${o}' is a PHP site (type:'${e.type}') but has no \`repository.url\` to clone. PHP sites deploy via git.`)}else if(c==="server-app"){if(!p)r.push(`Site '${o}' deploys to a server (deploy:'server'${e.deploy?"":" inferred from `start`"}) but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`);if(typeof e.port==="number"){let i=s.occupiedPorts?.get(e.port);if(i)r.push(`Site '${o}' wants port ${e.port}, which project '${i}' already serves on this box. Attached projects share one port namespace. Give '${o}' a free port, or let the attach allocate one.`);let u=f.get(e.port);if(u)r.push(`Sites '${u}' and '${o}' both use port ${e.port}. Server apps sharing a box must use distinct ports.`);else f.set(e.port,o)}}else if(c==="server-static"){if(!e.root)r.push(`Site '${o}' is a server static site (deploy:'server', no \`start\`) but has no \`root\` directory to serve.`);if(!p)r.push(`Site '${o}' deploys to a server (deploy:'server') but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`)}else{if(!e.root)r.push(`Site '${o}' deploys to a bucket but has no \`root\` directory to upload.`);let i=[];if(e.start)i.push("start");if(typeof e.port==="number")i.push("port");if(e.preStart&&e.preStart.length>0)i.push("preStart");if(i.length>0)n.push(`Site '${o}' deploys to a bucket but sets server-only field(s): ${i.join(", ")}. These are ignored. Set deploy:'server' to use them.`)}}return{errors:r,warnings:n}}function Kp(t){let s=d(t);return s!=="bucket"&&s!=="redirect"&&s!=="proxy"}function NI(t){return d(t)==="bucket"}function BI(t,s){if(K(t)==="serverless")return!0;let r=Object.entries(t.sites??{}).filter(([,a])=>a!=null),n=s?r.filter(([a])=>a===s):r;if(n.length===0)return!0;return!n.every(([,a])=>{let p=d(a);return p==="redirect"||p==="proxy"})}
1
+ import{K,ol}from"./chunk-277enqjc.js";function U(t,s){return`/var/www/${t}-${s}`}var y=new Set(["laravel","php","statamic","wordpress"]);function jr(t){return t.type!=null&&y.has(t.type)}function zr(t){let s=t.proxyTo;if(s==null)return[];return(Array.isArray(s)?s:[s]).map((n)=>String(n).trim()).filter((n)=>n.length>0)}function Ad(t){return zr(t).length>0}function Ao(t){if(t.deploy)return t.deploy;if(jr(t))return"server";if(t.start)return"server";return"bucket"}function d(t){if(t.redirect)return"redirect";if(Ad(t))return"proxy";if(jr(t))return"server-php";if(Ao(t)==="bucket")return"bucket";return t.start?"server-app":"server-static"}function RA(t){return t.infrastructure?.compute!=null||Boolean(t.cloud?.attachTo?.trim())}function zp(t,s={}){let r=[],n=[],a=t.sites||{},p=RA(t),l=ol(t);if(l)r.push(l);let f=new Map;for(let[o,e]of Object.entries(a)){if(!e)continue;let h=Ao(e),c=d(e);if(c==="redirect"){if(!e.domain)r.push(`Site '${o}' is a redirect site but has no \`domain\` to redirect from.`);if(!(typeof e.redirect==="string"?e.redirect:e.redirect?.to))r.push(`Site '${o}' is a redirect site but has no redirect target (\`redirect\` / \`redirect.to\`).`);if(!p)r.push(`Site '${o}' is a redirect site but no \`infrastructure.compute\` is configured to host the gateway that serves the redirect.`);let u=[];if(e.start)u.push("start");if(e.root)u.push("root");if(e.proxyTo)u.push("proxyTo");if(u.length>0)n.push(`Site '${o}' is a redirect site but also sets ${u.join(", ")}. These are ignored.`);continue}if(c==="proxy"){if(!e.domain)r.push(`Site '${o}' is a proxy site but has no \`domain\` to route from.`);if(!p)r.push(`Site '${o}' is a proxy site but no \`infrastructure.compute\` is configured to host the gateway that forwards it.`);let i=[];if(e.start)i.push("start");if(e.root)i.push("root");if(typeof e.port==="number")i.push("port");if(e.build)i.push("build");if(e.preStart&&e.preStart.length>0)i.push("preStart");if(i.length>0)n.push(`Site '${o}' sets \`proxyTo\`, so ts-cloud ships and supervises nothing for it. ${i.join(", ")} ${i.length===1?"is":"are"} ignored — remove ${i.length===1?"it":"them"}, or drop \`proxyTo\` to let ts-cloud own the service.`);continue}if(h==="server"&&!e.start&&!e.root){r.push(`Site '${o}' sets deploy:'server' but declares neither \`start\` (dynamic app) nor \`root\` (static site to serve). Add one.`);continue}if(c==="server-php"){if(!p)r.push(`Site '${o}' is a PHP site (type:'${e.type}') but no \`infrastructure.compute\` is configured. Add a server (infrastructure.compute) with PHP provisioning.`);if(!e.repository?.url)r.push(`Site '${o}' is a PHP site (type:'${e.type}') but has no \`repository.url\` to clone. PHP sites deploy via git.`)}else if(c==="server-app"){if(!p)r.push(`Site '${o}' deploys to a server (deploy:'server'${e.deploy?"":" inferred from `start`"}) but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`);if(typeof e.port==="number"){let i=s.occupiedPorts?.get(e.port);if(i)r.push(`Site '${o}' wants port ${e.port}, which project '${i}' already serves on this box. Attached projects share one port namespace. Give '${o}' a free port, or let the attach allocate one.`);let u=f.get(e.port);if(u)r.push(`Sites '${u}' and '${o}' both use port ${e.port}. Server apps sharing a box must use distinct ports.`);else f.set(e.port,o)}}else if(c==="server-static"){if(!e.root)r.push(`Site '${o}' is a server static site (deploy:'server', no \`start\`) but has no \`root\` directory to serve.`);if(!p)r.push(`Site '${o}' deploys to a server (deploy:'server') but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`)}else{if(!e.root)r.push(`Site '${o}' deploys to a bucket but has no \`root\` directory to upload.`);let i=[];if(e.start)i.push("start");if(typeof e.port==="number")i.push("port");if(e.preStart&&e.preStart.length>0)i.push("preStart");if(i.length>0)n.push(`Site '${o}' deploys to a bucket but sets server-only field(s): ${i.join(", ")}. These are ignored. Set deploy:'server' to use them.`)}}return{errors:r,warnings:n}}function Kp(t){let s=d(t);return s!=="bucket"&&s!=="redirect"&&s!=="proxy"}function NI(t){return d(t)==="bucket"}function BI(t,s){if(K(t)==="serverless")return!0;let r=Object.entries(t.sites??{}).filter(([,a])=>a!=null),n=s?r.filter(([a])=>a===s):r;if(n.length===0)return!0;return!n.every(([,a])=>{let p=d(a);return p==="redirect"||p==="proxy"})}
2
2
  export{U,jr,zr,Ad,Ao,d,RA,zp,Kp,NI,BI};
@@ -0,0 +1 @@
1
+ import{jn,Mh}from"./chunk-8ynkxbj6.js";import"./chunk-c2hvf1h5.js";import"./chunk-49rt1jbe.js";import"./chunk-z90dv6jx.js";export{jn as EmailClient,Mh as email};
@@ -0,0 +1 @@
1
+ import{Ke,Tp,wp,Ni,n,g,tA}from"./chunk-z90dv6jx.js";export{n as AWSClient,g as buildQueryParams,wp as canonicalUriFor,Ni as coerceXmlValues,tA as detectCredentialSource,Ke as resolveS3Endpoint,Tp as signingNameFor};
@@ -1,4 +1,4 @@
1
- import{n}from"./chunk-1eg5wsn2.js";import{y}from"./chunk-g0bh9atv.js";function P(e){let i=Array.isArray(e?.Items)?e.Items:y(e?.Items?.CNAME);return{Quantity:i.length,Items:i.map(String)}}function Pc(e){return y(e?.Origins?.Items?.Origin)}function Qe(e){for(let i of Pc(e)){let t=String(i.DomainName??"").match(/^(.+?)\.s3[.-]/)?.[1];if(t)return t}return}class I{client;constructor(e,i){this.client=i??new n(void 0,{profile:e})}collectionItems(e,i){let t=e?.Items??e?.[i];if(!t)return[];if(Array.isArray(t))return t;let r=t[i]??t.Item;if(r===void 0)return typeof t==="object"&&(t.Id||t.PathPattern)?[t]:[];return Array.isArray(r)?r:[r]}validateExistingOriginInput(e,i){if(!/^[A-Z0-9]{8,32}$/.test(e))throw Error("CloudFront distribution ID is invalid");if(!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(i.id))throw Error("CloudFront origin ID is invalid");if(!/^(?=.{1,253}$)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/.test(i.domainName))throw Error("CloudFront origin must be a hostname without a scheme or path");let t=i.pathPattern.startsWith("/")?i.pathPattern:`/${i.pathPattern}`;if(t==="/"||t==="/*"||!/^\/[A-Za-z0-9_.*?~!$&'()+,;=:@%/-]{1,255}$/.test(t))throw Error("CloudFront path pattern must be a non-default absolute pattern");if(i.originPath&&(!i.originPath.startsWith("/")||i.originPath.includes("..")))throw Error("CloudFront origin path must be absolute and traversal-free");if(Object.entries(i.customHeaders??{}).some(([r,s])=>!/^[A-Za-z0-9-]{1,64}$/.test(r)||!s||s.length>1024))throw Error("CloudFront custom origin headers are invalid");return{...i,pathPattern:t}}async upsertExistingDistributionOrigin(e,i){let t=this.validateExistingOriginInput(e,i),r=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${e}/config`,returnHeaders:!0}),s=r.headers?.etag||r.headers?.ETag||r.ETag||"",o=r.body?.DistributionConfig||r.DistributionConfig||r.body;if(!o||o.Enabled===void 0||!s)throw Error("Failed to read an ETag-protected CloudFront distribution config");let a=this.collectionItems(o.Origins,"Origin"),c=this.collectionItems(o.CacheBehaviors,"CacheBehavior"),u=a.find((f)=>String(f.Id)===t.id),d=c.find((f)=>String(f.PathPattern)===t.pathPattern);if(u&&String(u.DomainName)!==t.domainName&&!t.replaceExisting)throw Error(`Origin ${t.id} already targets ${u.DomainName}; pass replaceExisting only after reviewing the live config`);if(d&&String(d.TargetOriginId)!==t.id&&!t.replaceExisting)throw Error(`Path ${t.pathPattern} already targets ${d.TargetOriginId}; pass replaceExisting only after reviewing the live config`);let g={Id:t.id,DomainName:t.domainName,OriginPath:t.originPath??"",CustomHeaders:{Quantity:Object.keys(t.customHeaders??{}).length,...Object.keys(t.customHeaders??{}).length?{Items:{OriginCustomHeader:Object.entries(t.customHeaders).map(([f,A])=>({HeaderName:f,HeaderValue:A}))}}:{}},CustomOriginConfig:{HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:t.protocolPolicy??"https-only",OriginSslProtocols:{Quantity:1,Items:{SslProtocol:["TLSv1.2"]}},OriginReadTimeout:30,OriginKeepaliveTimeout:5},ConnectionAttempts:3,ConnectionTimeout:10,...t.originAccessControlId?{OriginAccessControlId:t.originAccessControlId}:{}},h=["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"],l={PathPattern:t.pathPattern,TargetOriginId:t.id,ViewerProtocolPolicy:"redirect-to-https",Compress:!0,CachePolicyId:"4135ea2d-6df8-44a3-9df3-4b5a84be39ad",OriginRequestPolicyId:"b689b0a8-53d0-40ab-baf2-68738e2966ac",AllowedMethods:{Quantity:h.length,Items:{Method:h},CachedMethods:{Quantity:2,Items:{Method:["GET","HEAD"]}}},SmoothStreaming:!1,FieldLevelEncryptionId:"",TrustedSigners:{Enabled:!1,Quantity:0},TrustedKeyGroups:{Enabled:!1,Quantity:0},LambdaFunctionAssociations:{Quantity:0},FunctionAssociations:{Quantity:0}},C=u?a.map((f)=>String(f.Id)===t.id?g:f):[...a,g],m=d?c.map((f)=>String(f.PathPattern)===t.pathPattern?l:f):[...c,l],E=JSON.stringify(a)!==JSON.stringify(C)||JSON.stringify(c)!==JSON.stringify(m);if(!E||t.dryRun)return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:E,applied:!1,etag:s};o.Origins={Quantity:C.length,Items:{Origin:C}},o.CacheBehaviors={Quantity:m.length,...m.length?{Items:{CacheBehavior:m}}:{}};let b=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${e}/config`,body:this.buildDistributionConfigXml(o),headers:{"Content-Type":"application/xml","If-Match":s},returnHeaders:!0});return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!0,applied:!0,etag:b.headers?.etag||b.headers?.ETag||""}}async removeExistingDistributionOrigin(e,i){let t=this.validateExistingOriginInput(e,i),r=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${e}/config`,returnHeaders:!0}),s=r.headers?.etag||r.headers?.ETag||r.ETag||"",o=r.body?.DistributionConfig||r.DistributionConfig||r.body;if(!o||o.Enabled===void 0||!s)throw Error("Failed to read an ETag-protected CloudFront distribution config");let a=this.collectionItems(o.Origins,"Origin"),c=this.collectionItems(o.CacheBehaviors,"CacheBehavior"),u=a.find((m)=>String(m.Id)===t.id),d=c.find((m)=>String(m.PathPattern)===t.pathPattern);if(u&&String(u.DomainName)!==t.domainName)throw Error(`Origin ${t.id} no longer targets ${t.domainName}; refusing ambiguous removal`);if(d&&String(d.TargetOriginId)!==t.id)throw Error(`Path ${t.pathPattern} no longer targets ${t.id}; refusing ambiguous removal`);if(!d)return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!1,applied:!1,originRemoved:!1,etag:s};let g=c.filter((m)=>String(m.PathPattern)!==t.pathPattern),h=String(o.DefaultCacheBehavior?.TargetOriginId)===t.id||g.some((m)=>String(m.TargetOriginId)===t.id),l=h?a:a.filter((m)=>String(m.Id)!==t.id);if(t.dryRun)return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!0,applied:!1,originRemoved:!h&&!!u,etag:s};o.Origins={Quantity:l.length,Items:{Origin:l}},o.CacheBehaviors={Quantity:g.length,...g.length?{Items:{CacheBehavior:g}}:{}};let C=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${e}/config`,body:this.buildDistributionConfigXml(o),headers:{"Content-Type":"application/xml","If-Match":s},returnHeaders:!0});return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!0,applied:!0,originRemoved:!h&&!!u,etag:C.headers?.etag||C.headers?.ETag||""}}async createInvalidation(e){let i=e.callerReference||Date.now().toString(),t=`<?xml version="1.0" encoding="UTF-8"?>
1
+ import{n}from"./chunk-z90dv6jx.js";import{y}from"./chunk-g0bh9atv.js";function P(e){let i=Array.isArray(e?.Items)?e.Items:y(e?.Items?.CNAME);return{Quantity:i.length,Items:i.map(String)}}function Pc(e){return y(e?.Origins?.Items?.Origin)}function Qe(e){for(let i of Pc(e)){let t=String(i.DomainName??"").match(/^(.+?)\.s3[.-]/)?.[1];if(t)return t}return}class I{client;constructor(e,i){this.client=i??new n(void 0,{profile:e})}collectionItems(e,i){let t=e?.Items??e?.[i];if(!t)return[];if(Array.isArray(t))return t;let r=t[i]??t.Item;if(r===void 0)return typeof t==="object"&&(t.Id||t.PathPattern)?[t]:[];return Array.isArray(r)?r:[r]}validateExistingOriginInput(e,i){if(!/^[A-Z0-9]{8,32}$/.test(e))throw Error("CloudFront distribution ID is invalid");if(!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(i.id))throw Error("CloudFront origin ID is invalid");if(!/^(?=.{1,253}$)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/.test(i.domainName))throw Error("CloudFront origin must be a hostname without a scheme or path");let t=i.pathPattern.startsWith("/")?i.pathPattern:`/${i.pathPattern}`;if(t==="/"||t==="/*"||!/^\/[A-Za-z0-9_.*?~!$&'()+,;=:@%/-]{1,255}$/.test(t))throw Error("CloudFront path pattern must be a non-default absolute pattern");if(i.originPath&&(!i.originPath.startsWith("/")||i.originPath.includes("..")))throw Error("CloudFront origin path must be absolute and traversal-free");if(Object.entries(i.customHeaders??{}).some(([r,s])=>!/^[A-Za-z0-9-]{1,64}$/.test(r)||!s||s.length>1024))throw Error("CloudFront custom origin headers are invalid");return{...i,pathPattern:t}}async upsertExistingDistributionOrigin(e,i){let t=this.validateExistingOriginInput(e,i),r=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${e}/config`,returnHeaders:!0}),s=r.headers?.etag||r.headers?.ETag||r.ETag||"",o=r.body?.DistributionConfig||r.DistributionConfig||r.body;if(!o||o.Enabled===void 0||!s)throw Error("Failed to read an ETag-protected CloudFront distribution config");let a=this.collectionItems(o.Origins,"Origin"),c=this.collectionItems(o.CacheBehaviors,"CacheBehavior"),u=a.find((f)=>String(f.Id)===t.id),d=c.find((f)=>String(f.PathPattern)===t.pathPattern);if(u&&String(u.DomainName)!==t.domainName&&!t.replaceExisting)throw Error(`Origin ${t.id} already targets ${u.DomainName}; pass replaceExisting only after reviewing the live config`);if(d&&String(d.TargetOriginId)!==t.id&&!t.replaceExisting)throw Error(`Path ${t.pathPattern} already targets ${d.TargetOriginId}; pass replaceExisting only after reviewing the live config`);let g={Id:t.id,DomainName:t.domainName,OriginPath:t.originPath??"",CustomHeaders:{Quantity:Object.keys(t.customHeaders??{}).length,...Object.keys(t.customHeaders??{}).length?{Items:{OriginCustomHeader:Object.entries(t.customHeaders).map(([f,A])=>({HeaderName:f,HeaderValue:A}))}}:{}},CustomOriginConfig:{HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:t.protocolPolicy??"https-only",OriginSslProtocols:{Quantity:1,Items:{SslProtocol:["TLSv1.2"]}},OriginReadTimeout:30,OriginKeepaliveTimeout:5},ConnectionAttempts:3,ConnectionTimeout:10,...t.originAccessControlId?{OriginAccessControlId:t.originAccessControlId}:{}},h=["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"],l={PathPattern:t.pathPattern,TargetOriginId:t.id,ViewerProtocolPolicy:"redirect-to-https",Compress:!0,CachePolicyId:"4135ea2d-6df8-44a3-9df3-4b5a84be39ad",OriginRequestPolicyId:"b689b0a8-53d0-40ab-baf2-68738e2966ac",AllowedMethods:{Quantity:h.length,Items:{Method:h},CachedMethods:{Quantity:2,Items:{Method:["GET","HEAD"]}}},SmoothStreaming:!1,FieldLevelEncryptionId:"",TrustedSigners:{Enabled:!1,Quantity:0},TrustedKeyGroups:{Enabled:!1,Quantity:0},LambdaFunctionAssociations:{Quantity:0},FunctionAssociations:{Quantity:0}},C=u?a.map((f)=>String(f.Id)===t.id?g:f):[...a,g],m=d?c.map((f)=>String(f.PathPattern)===t.pathPattern?l:f):[...c,l],E=JSON.stringify(a)!==JSON.stringify(C)||JSON.stringify(c)!==JSON.stringify(m);if(!E||t.dryRun)return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:E,applied:!1,etag:s};o.Origins={Quantity:C.length,Items:{Origin:C}},o.CacheBehaviors={Quantity:m.length,...m.length?{Items:{CacheBehavior:m}}:{}};let b=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${e}/config`,body:this.buildDistributionConfigXml(o),headers:{"Content-Type":"application/xml","If-Match":s},returnHeaders:!0});return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!0,applied:!0,etag:b.headers?.etag||b.headers?.ETag||""}}async removeExistingDistributionOrigin(e,i){let t=this.validateExistingOriginInput(e,i),r=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${e}/config`,returnHeaders:!0}),s=r.headers?.etag||r.headers?.ETag||r.ETag||"",o=r.body?.DistributionConfig||r.DistributionConfig||r.body;if(!o||o.Enabled===void 0||!s)throw Error("Failed to read an ETag-protected CloudFront distribution config");let a=this.collectionItems(o.Origins,"Origin"),c=this.collectionItems(o.CacheBehaviors,"CacheBehavior"),u=a.find((m)=>String(m.Id)===t.id),d=c.find((m)=>String(m.PathPattern)===t.pathPattern);if(u&&String(u.DomainName)!==t.domainName)throw Error(`Origin ${t.id} no longer targets ${t.domainName}; refusing ambiguous removal`);if(d&&String(d.TargetOriginId)!==t.id)throw Error(`Path ${t.pathPattern} no longer targets ${t.id}; refusing ambiguous removal`);if(!d)return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!1,applied:!1,originRemoved:!1,etag:s};let g=c.filter((m)=>String(m.PathPattern)!==t.pathPattern),h=String(o.DefaultCacheBehavior?.TargetOriginId)===t.id||g.some((m)=>String(m.TargetOriginId)===t.id),l=h?a:a.filter((m)=>String(m.Id)!==t.id);if(t.dryRun)return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!0,applied:!1,originRemoved:!h&&!!u,etag:s};o.Origins={Quantity:l.length,Items:{Origin:l}},o.CacheBehaviors={Quantity:g.length,...g.length?{Items:{CacheBehavior:g}}:{}};let C=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${e}/config`,body:this.buildDistributionConfigXml(o),headers:{"Content-Type":"application/xml","If-Match":s},returnHeaders:!0});return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!0,applied:!0,originRemoved:!h&&!!u,etag:C.headers?.etag||C.headers?.ETag||""}}async createInvalidation(e){let i=e.callerReference||Date.now().toString(),t=`<?xml version="1.0" encoding="UTF-8"?>
2
2
  <InvalidationBatch>
3
3
  <Paths>
4
4
  <Quantity>${e.paths.length}</Quantity>
@@ -0,0 +1 @@
1
+ import{ne}from"./chunk-ssywr12y.js";import"./chunk-z90dv6jx.js";export{ne as RDSClient};
@@ -1,4 +1,4 @@
1
- import{Q,l}from"./chunk-e32qtz2d.js";import{an}from"./chunk-207hnnpp.js";var We=40,yd=[{version:1,name:"core_control_plane",sql:`
1
+ import{Q,l}from"./chunk-277enqjc.js";import{an}from"./chunk-207hnnpp.js";var We=40,yd=[{version:1,name:"core_control_plane",sql:`
2
2
  CREATE TABLE projects (
3
3
  id TEXT PRIMARY KEY,
4
4
  slug TEXT NOT NULL UNIQUE,