@stacksjs/ts-cloud 0.12.14 → 0.12.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/aws/index.js +1 -1
- package/dist/bin/chunk-005sxfmc.js +1 -0
- package/dist/bin/{chunk-pt2bz3kr.js → chunk-2shtky1g.js} +1 -1
- package/dist/bin/chunk-3zq0wkz2.js +1 -0
- package/dist/bin/chunk-4qzpqmhe.js +1 -0
- package/dist/bin/chunk-4vgbynq6.js +1 -0
- package/dist/bin/chunk-52wgrpe8.js +1 -0
- package/dist/bin/{chunk-fnr6k11h.js → chunk-5qann9n2.js} +1 -1
- package/dist/bin/{chunk-wr6a423y.js → chunk-6tty6sjf.js} +1 -1
- package/dist/bin/{chunk-ynr22ma8.js → chunk-7jwxgxxf.js} +1 -1
- package/dist/bin/{chunk-2paqksap.js → chunk-7xszcdqn.js} +4 -4
- package/dist/bin/{chunk-1wvrtg42.js → chunk-8sxb2rr0.js} +1 -1
- package/dist/bin/{chunk-7a7n6p2m.js → chunk-9jmnmhpy.js} +1 -1
- package/dist/bin/{chunk-z2ez8wn9.js → chunk-9k60q9qz.js} +3 -3
- package/dist/bin/{chunk-ydpnsp4x.js → chunk-9vrnrxay.js} +1 -1
- package/dist/bin/{chunk-n6qqa2fr.js → chunk-9wjgxjqp.js} +65 -65
- package/dist/bin/chunk-9yra64dd.js +1 -0
- package/dist/bin/{chunk-nrnq9adz.js → chunk-a76krpa1.js} +1 -1
- package/dist/bin/{chunk-y7ece16e.js → chunk-a8rn2wym.js} +6 -6
- package/dist/bin/{chunk-d7r6mhyv.js → chunk-b48j6k55.js} +2 -2
- package/dist/bin/{chunk-w637s5q0.js → chunk-be7rhw60.js} +3 -3
- package/dist/bin/chunk-bwvnfc74.js +1 -0
- package/dist/bin/chunk-cy4wwpnf.js +1 -0
- package/dist/bin/{chunk-3gwmejhk.js → chunk-dvm4n8m8.js} +1 -1
- package/dist/bin/{chunk-ngav845g.js → chunk-dxfsq94k.js} +2 -2
- package/dist/bin/chunk-dy10cmt9.js +1 -0
- package/dist/bin/{chunk-92nng29y.js → chunk-e3d9m062.js} +1 -1
- package/dist/bin/{chunk-9q8zjavc.js → chunk-ebdybz7x.js} +65 -65
- package/dist/bin/chunk-fbe5kk6w.js +1 -0
- package/dist/bin/{chunk-rpg5k3wt.js → chunk-hzj5r6b7.js} +2 -2
- package/dist/bin/chunk-j3w462ep.js +1 -0
- package/dist/bin/{chunk-80zkjpfz.js → chunk-k3er0h4j.js} +1 -1
- package/dist/bin/chunk-k7w2ztw9.js +1 -0
- package/dist/bin/{chunk-dhxwmkhz.js → chunk-mcqkjhgp.js} +1 -1
- package/dist/bin/{chunk-yt8rgkqt.js → chunk-mekcw1zn.js} +2 -2
- package/dist/bin/{chunk-dbmk60r7.js → chunk-ndbtr4mb.js} +2 -2
- package/dist/bin/chunk-ntahmgqg.js +1 -0
- package/dist/bin/{chunk-57w9nsjk.js → chunk-p197a99s.js} +1 -1
- package/dist/bin/{chunk-vymg9ywg.js → chunk-pd8v6bpd.js} +1 -1
- package/dist/bin/{chunk-yhxpmk29.js → chunk-pthfzst7.js} +1 -1
- package/dist/bin/{chunk-16rs9egs.js → chunk-srw2jmh3.js} +3 -3
- package/dist/bin/chunk-t1eft7s7.js +1 -0
- package/dist/bin/{chunk-49sthm4q.js → chunk-t7seq21w.js} +1 -1
- package/dist/bin/chunk-t8n2961n.js +1 -0
- package/dist/bin/{chunk-f8mbjwme.js → chunk-tpjepvwa.js} +1 -1
- package/dist/bin/chunk-xvn07b0e.js +1 -0
- package/dist/bin/{chunk-bj5nq0kn.js → chunk-xyk8qe2c.js} +41 -41
- package/dist/bin/{chunk-4zbnwt9b.js → chunk-y1r1evt0.js} +1 -1
- package/dist/bin/{chunk-6vay4ggv.js → chunk-y24gfke7.js} +5 -5
- package/dist/bin/{chunk-4201mvaj.js → chunk-zav02r6k.js} +1 -1
- package/dist/bin/{chunk-pega3x2x.js → chunk-zhpzxnpg.js} +1 -1
- package/dist/bin/{chunk-c51xp8f7.js → chunk-zs8bfer0.js} +1 -1
- package/dist/bin/cli.js +134 -134
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/{chunk-vva43vnp.js → chunk-1zz5n6q8.js} +4 -4
- package/dist/{chunk-thpce63q.js → chunk-4ywy6dp5.js} +2 -2
- package/dist/{chunk-9mhcjht7.js → chunk-6znnde1s.js} +3 -3
- package/dist/{chunk-6j8f4ahv.js → chunk-7hjsnwcv.js} +27 -27
- package/dist/chunk-8fcrgq31.js +1 -0
- package/dist/{chunk-pkan6evc.js → chunk-8msfne57.js} +2 -2
- package/dist/{chunk-6nvn041c.js → chunk-93mgdgd5.js} +1 -1
- package/dist/{chunk-5g1hsrab.js → chunk-a6zymyfs.js} +2 -2
- package/dist/{chunk-6g81m01r.js → chunk-a7v15116.js} +1 -1
- package/dist/{chunk-djd9xgkz.js → chunk-ajq92t46.js} +79 -79
- package/dist/{chunk-zftpjxkr.js → chunk-bga3mw5f.js} +1 -1
- package/dist/{chunk-r5emv4x8.js → chunk-bgrre2px.js} +1 -1
- package/dist/{chunk-e0919h5g.js → chunk-d1tv3wx0.js} +2 -2
- package/dist/chunk-eadp23eh.js +1 -0
- package/dist/{chunk-ttq6dvft.js → chunk-j9rv5m58.js} +3 -3
- package/dist/{chunk-7kwha0fw.js → chunk-jk7ecnmc.js} +78 -78
- package/dist/{chunk-9w32efae.js → chunk-jpbgr1wg.js} +1 -1
- package/dist/{chunk-e7ds04wb.js → chunk-kazw813q.js} +1 -1
- package/dist/{chunk-7hy9p6xr.js → chunk-mherymtx.js} +1 -1
- package/dist/{chunk-wjgnfg6q.js → chunk-nr1bdzwy.js} +1 -1
- package/dist/{chunk-jb8em9ba.js → chunk-qszktnnz.js} +1 -1
- package/dist/{chunk-3kapcdpn.js → chunk-rtg6nw3n.js} +1 -1
- package/dist/{chunk-xxbvjq8g.js → chunk-thghrpf9.js} +39 -39
- package/dist/chunk-w7710vzg.js +1 -0
- package/dist/{chunk-bqaqkmtr.js → chunk-wxv3ypt5.js} +1 -1
- package/dist/{chunk-5ww7kc5z.js → chunk-wz57brcf.js} +6 -6
- package/dist/chunk-xfdpxsbc.js +1 -0
- package/dist/deploy/index.js +1 -1
- package/dist/dns/index.js +1 -1
- package/dist/drivers/index.js +1 -1
- package/dist/drivers/shared/rpx-gateway.d.ts +17 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +48 -48
- package/dist/operations/index.js +1 -1
- package/dist/protection/index.js +1 -1
- package/dist/spend/index.js +1 -1
- package/dist/ui/404.html +1 -1
- package/dist/ui/accept-invitation.html +1 -1
- package/dist/ui/access-denied.html +1 -1
- package/dist/ui/account/automation.html +6 -6
- package/dist/ui/account/security.html +2 -2
- package/dist/ui/applications/compose.html +6 -6
- package/dist/ui/applications/new.html +2 -2
- package/dist/ui/data/backups.html +6 -6
- package/dist/ui/data/services.html +6 -6
- package/dist/ui/data/volumes.html +6 -6
- package/dist/ui/index.html +5 -5
- package/dist/ui/infrastructure/topology.html +6 -6
- package/dist/ui/integrations.html +2 -2
- package/dist/ui/operations/alerts.html +6 -6
- package/dist/ui/operations/configuration.html +6 -6
- package/dist/ui/operations/jobs.html +6 -6
- package/dist/ui/operations/maintenance.html +5 -5
- package/dist/ui/operations/observability.html +6 -6
- package/dist/ui/operations/previews.html +6 -6
- package/dist/ui/operations/queue.html +6 -6
- package/dist/ui/operations/regions.html +5 -5
- package/dist/ui/operations/releases.html +6 -6
- package/dist/ui/operations/spend.html +6 -6
- package/dist/ui/operations/workloads.html +6 -6
- package/dist/ui/security.html +1 -1
- package/dist/ui/server/actions.html +5 -5
- package/dist/ui/server/activity.html +1 -1
- package/dist/ui/server/capacity.html +6 -6
- package/dist/ui/server/database.html +6 -6
- package/dist/ui/server/deployments.html +5 -5
- package/dist/ui/server/diagnostics.html +2 -2
- package/dist/ui/server/firewall.html +6 -6
- package/dist/ui/server/fleet.html +6 -6
- package/dist/ui/server/logs.html +6 -6
- package/dist/ui/server/metrics.html +5 -5
- package/dist/ui/server/security.html +2 -2
- package/dist/ui/server/services.html +1 -1
- package/dist/ui/server/sites.html +6 -6
- package/dist/ui/server/ssh-keys.html +6 -6
- package/dist/ui/server/team.html +6 -6
- package/dist/ui/server/terminal.html +2 -2
- package/dist/ui/serverless/alarms.html +6 -6
- package/dist/ui/serverless/assets.html +2 -2
- package/dist/ui/serverless/cost.html +2 -2
- package/dist/ui/serverless/data.html +6 -6
- package/dist/ui/serverless/deployments.html +2 -2
- package/dist/ui/serverless/firewall.html +2 -2
- package/dist/ui/serverless/functions.html +6 -6
- package/dist/ui/serverless/logs.html +6 -6
- package/dist/ui/serverless/metrics.html +1 -1
- package/dist/ui/serverless/queues.html +6 -6
- package/dist/ui/serverless/secrets.html +6 -6
- package/dist/ui/serverless/traces.html +6 -6
- package/dist/ui/serverless.html +6 -6
- package/dist/ui-src/src/charts.ts +1 -1
- package/dist/ui-src/src/topology.ts +1 -1
- package/package.json +3 -3
- package/dist/bin/chunk-1rcsm0px.js +0 -1
- package/dist/bin/chunk-1s4dny8d.js +0 -1
- package/dist/bin/chunk-1x7mm26k.js +0 -1
- package/dist/bin/chunk-4yntpqbe.js +0 -1
- package/dist/bin/chunk-61ysn56t.js +0 -1
- package/dist/bin/chunk-7x0hrna6.js +0 -1
- package/dist/bin/chunk-f1ke4ygp.js +0 -1
- package/dist/bin/chunk-mzfct5en.js +0 -1
- package/dist/bin/chunk-p36ns96s.js +0 -1
- package/dist/bin/chunk-q5aj280b.js +0 -1
- package/dist/bin/chunk-r6cvc2pr.js +0 -1
- package/dist/bin/chunk-rh2sqtew.js +0 -1
- package/dist/bin/chunk-tkzpbb7n.js +0 -1
- package/dist/bin/chunk-vwyq2s2k.js +0 -1
- package/dist/bin/chunk-vx649y7t.js +0 -1
- package/dist/bin/chunk-yn34zgr2.js +0 -1
- package/dist/chunk-5qqb671d.js +0 -1
- package/dist/chunk-fdexq9e1.js +0 -1
- package/dist/chunk-vpy3zjqv.js +0 -1
- package/dist/chunk-wrnhbb13.js +0 -1
- /package/dist/bin/{chunk-bckm6fre.js → chunk-pdw0qjq1.js} +0 -0
- /package/dist/{chunk-30h9rgfn.js → chunk-crpjqnjb.js} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./chunk-
|
|
1
|
+
import"./chunk-xyk8qe2c.js";import"./chunk-6tty6sjf.js";import"./chunk-a8rn2wym.js";import{Zt}from"./chunk-9wjgxjqp.js";import"./chunk-pdw0qjq1.js";import"./chunk-t7seq21w.js";import"./chunk-k3er0h4j.js";import"./chunk-8sxb2rr0.js";import"./chunk-ebdybz7x.js";import"./chunk-pd8v6bpd.js";import"./chunk-hzj5r6b7.js";import"./chunk-9jmnmhpy.js";import"./chunk-pthfzst7.js";import"./chunk-dxfsq94k.js";import"./chunk-mekcw1zn.js";import"./chunk-b48j6k55.js";import"./chunk-mcqkjhgp.js";import"./chunk-y1r1evt0.js";import"./chunk-y24gfke7.js";import"./chunk-srw2jmh3.js";import"./chunk-7xszcdqn.js";import"./chunk-be7rhw60.js";import"./chunk-9vrnrxay.js";import"./chunk-94cfdvrn.js";import"./chunk-p197a99s.js";import"./chunk-7jwxgxxf.js";import n from"node:process";function r(o){let e=n.argv.indexOf(o);return e===-1?void 0:n.argv[e+1]}function t(o){return n.argv.includes(o)}async function i(){let o=await Zt({host:r("--host")??"127.0.0.1",port:Number(r("--port")??7676),environment:r("--env"),box:t("--box"),verbose:t("--verbose")});console.log("ts-cloud Local Dashboard"),console.log(`Serving ${o.url}`),await new Promise((e)=>{let s=()=>{o.server.stop(!0),e()};n.once("SIGINT",s),n.once("SIGTERM",s)})}i();
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{me,ie,T,se,rr}from"./chunk-8msfne57.js";import{a}from"./chunk-rtg6nw3n.js";import{y}from"./chunk-a7v15116.js";import{h}from"./chunk-nr1bdzwy.js";import{f}from"./chunk-qszktnnz.js";function ma(t){let{bucketName:s,domain:u,aliases:e,certificateArn:p,defaultRootObject:i="index.html",errorDocument:r="404.html",passthroughUrls:c=!1,singlePageApp:g=!1,dynamicApp:C=!1,computeOriginDomain:w,computeOriginPort:x=3008,computeOriginId:E="app-compute",retainOnStackDelete:M=!1}=t,S=M?{DeletionPolicy:"Retain",UpdateReplacePolicy:"Retain"}:{},N=C&&!!w,j=N?["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"]:["GET","HEAD"],v=N?["GET","HEAD"]:["GET","HEAD"],O={},B={};O.S3Bucket={Type:"AWS::S3::Bucket",...S,Properties:{BucketName:s,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:i,ErrorDocument:r}}},B.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},B.BucketArn={Description:"S3 Bucket ARN",Value:{"Fn::GetAtt":["S3Bucket","Arn"]}},O.CloudFrontOAC={Type:"AWS::CloudFront::OriginAccessControl",...S,Properties:{OriginAccessControlConfig:{Name:`OAC-${s}`,Description:`OAC for ${s}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}};let I;if(c&&N)I="InstallRootRedirectFunction",O[I]={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 {
|
|
@@ -24,7 +24,7 @@ import{ge,ne,T,ie,rr}from"./chunk-pkan6evc.js";import{a}from"./chunk-3kapcdpn.js
|
|
|
24
24
|
}
|
|
25
25
|
|
|
26
26
|
return request;
|
|
27
|
-
}`}};let R={Id:`S3-${s}`,DomainName:{"Fn::GetAtt":["S3Bucket","RegionalDomainName"]},S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{"Fn::GetAtt":["CloudFrontOAC","Id"]}},d=N?{Id:E,DomainName:w,CustomOriginConfig:{HTTPPort:x,HTTPSPort:443,OriginProtocolPolicy:"http-only",OriginSSLProtocols:["TLSv1.2"]}}:null,k=N?E:`S3-${s}`,A={Enabled:!0,DefaultRootObject:i,HttpVersion:"http2and3",IPV6Enabled:!0,PriceClass:"PriceClass_100",Origins:d?[d,R]:[R],DefaultCacheBehavior:{TargetOriginId:k,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:j,CachedMethods:v,Compress:!0,...N?{CachePolicyId:"4135ea2d-6df8-44a3-9df3-4b5a84be39ad",OriginRequestPolicyId:"b689b0a8-53d0-40ab-baf2-68738e2966ac",...c&&I?{FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":[I,"FunctionARN"]}}]}:{}}:{CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",...!c&&{FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":["UrlRewriteFunction","FunctionARN"]}}]}}},...N&&c?{CacheBehaviors:[{PathPattern:"/install.sh",TargetOriginId:`S3-${s}`,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6"}]}:{},CustomErrorResponses:g?[{ErrorCode:403,ResponseCode:200,ResponsePagePath:`/${i}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:200,ResponsePagePath:`/${i}`,ErrorCachingMinTTL:300}]:[{ErrorCode:403,ResponseCode:404,ResponsePagePath:`/${r}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:404,ResponsePagePath:`/${r}`,ErrorCachingMinTTL:300}]};if(u&&p)A.Aliases=e&&e.length>0?e:[u],A.ViewerCertificate={AcmCertificateArn:p,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};else A.ViewerCertificate={CloudFrontDefaultCertificate:!0};return O.CloudFrontDistribution={Type:"AWS::CloudFront::Distribution",...S,DependsOn:["S3Bucket","CloudFrontOAC",...c&&N&&I?[I]:[],...!c?["UrlRewriteFunction"]:[]],Properties:{DistributionConfig:A}},B.DistributionId={Description:"CloudFront Distribution ID",Value:{Ref:"CloudFrontDistribution"}},B.DistributionDomain={Description:"CloudFront Distribution Domain",Value:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]}},O.S3BucketPolicy={Type:"AWS::S3::BucketPolicy",...S,DependsOn:["S3Bucket","CloudFrontDistribution"],Properties:{Bucket:{Ref:"S3Bucket"},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":"arn:aws:s3:::${S3Bucket}/*"},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":"arn:aws:cloudfront::${AWS::AccountId}:distribution/${CloudFrontDistribution}"}}}}]}}},B.SiteUrl={Description:"Site URL",Value:u?`https://${u}`:{"Fn::Sub":"https://${CloudFrontDistribution.DomainName}"}},{AWSTemplateFormatVersion:"2010-09-09",Description:`Static site infrastructure for ${u||s} (External DNS)`,Resources:O,Outputs:B}}async function Zr(t){let s=t.region||"us-east-1",u="us-east-1",e=t.domain,p=t.bucket||e.replace(/\./g,"-"),i=t.stackName||`${t.siteName}-static-site`,r=new f("us-east-1"),c=new
|
|
27
|
+
}`}};let R={Id:`S3-${s}`,DomainName:{"Fn::GetAtt":["S3Bucket","RegionalDomainName"]},S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{"Fn::GetAtt":["CloudFrontOAC","Id"]}},d=N?{Id:E,DomainName:w,CustomOriginConfig:{HTTPPort:x,HTTPSPort:443,OriginProtocolPolicy:"http-only",OriginSSLProtocols:["TLSv1.2"]}}:null,k=N?E:`S3-${s}`,A={Enabled:!0,DefaultRootObject:i,HttpVersion:"http2and3",IPV6Enabled:!0,PriceClass:"PriceClass_100",Origins:d?[d,R]:[R],DefaultCacheBehavior:{TargetOriginId:k,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:j,CachedMethods:v,Compress:!0,...N?{CachePolicyId:"4135ea2d-6df8-44a3-9df3-4b5a84be39ad",OriginRequestPolicyId:"b689b0a8-53d0-40ab-baf2-68738e2966ac",...c&&I?{FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":[I,"FunctionARN"]}}]}:{}}:{CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",...!c&&{FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":["UrlRewriteFunction","FunctionARN"]}}]}}},...N&&c?{CacheBehaviors:[{PathPattern:"/install.sh",TargetOriginId:`S3-${s}`,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6"}]}:{},CustomErrorResponses:g?[{ErrorCode:403,ResponseCode:200,ResponsePagePath:`/${i}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:200,ResponsePagePath:`/${i}`,ErrorCachingMinTTL:300}]:[{ErrorCode:403,ResponseCode:404,ResponsePagePath:`/${r}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:404,ResponsePagePath:`/${r}`,ErrorCachingMinTTL:300}]};if(u&&p)A.Aliases=e&&e.length>0?e:[u],A.ViewerCertificate={AcmCertificateArn:p,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};else A.ViewerCertificate={CloudFrontDefaultCertificate:!0};return O.CloudFrontDistribution={Type:"AWS::CloudFront::Distribution",...S,DependsOn:["S3Bucket","CloudFrontOAC",...c&&N&&I?[I]:[],...!c?["UrlRewriteFunction"]:[]],Properties:{DistributionConfig:A}},B.DistributionId={Description:"CloudFront Distribution ID",Value:{Ref:"CloudFrontDistribution"}},B.DistributionDomain={Description:"CloudFront Distribution Domain",Value:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]}},O.S3BucketPolicy={Type:"AWS::S3::BucketPolicy",...S,DependsOn:["S3Bucket","CloudFrontDistribution"],Properties:{Bucket:{Ref:"S3Bucket"},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":"arn:aws:s3:::${S3Bucket}/*"},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":"arn:aws:cloudfront::${AWS::AccountId}:distribution/${CloudFrontDistribution}"}}}}]}}},B.SiteUrl={Description:"Site URL",Value:u?`https://${u}`:{"Fn::Sub":"https://${CloudFrontDistribution.DomainName}"}},{AWSTemplateFormatVersion:"2010-09-09",Description:`Static site infrastructure for ${u||s} (External DNS)`,Resources:O,Outputs:B}}async function Zr(t){let s=t.region||"us-east-1",u="us-east-1",e=t.domain,p=t.bucket||e.replace(/\./g,"-"),i=t.stackName||`${t.siteName}-static-site`,r=new f("us-east-1"),c=new se("us-east-1"),g=null;if(!t.skipDnsVerification){g=T(t.dnsProvider),console.log(`Verifying DNS provider can manage ${e}...`);let o=await g.listRecords(e);if(!o.success){let n=o.message||"unknown error — check API credentials and domain ownership";return{success:!1,stackName:i,bucket:p,message:`DNS provider '${g.name}' cannot manage domain ${e}: ${n}`}}console.log(`DNS provider '${g.name}' verified for ${e}`)}else console.log(`Skipping DNS verification for ${e}`);let C=t.certificateArn,E=e.split(".").length===2?`www.${e}`:void 0;if(!C){console.log(`Checking for existing SSL certificate for ${e}...`);let o=await c.findCertificateByDomain(e),n=!1;if(o&&o.Status==="ISSUED"){if(E&&o.SubjectAlternativeNames)n=o.SubjectAlternativeNames.includes(E)||o.SubjectAlternativeNames.some((m)=>m===`*.${e}`);else n=!0;if(n)C=o.CertificateArn,console.log(`Found existing certificate with www coverage: ${C}`);else console.log(`Existing certificate doesn't cover ${E}, requesting new one...`)}if(!C){if(!g)return{success:!1,stackName:i,bucket:p,message:`No DNS provider available to validate SSL certificate for ${e}. Provide a certificateArn or enable DNS verification.`};console.log(`Requesting new SSL certificate for ${e}${E?` (including ${E})`:""}...`);let b=await new ie(g,"us-east-1").findOrCreateCertificate({domainName:e,subjectAlternativeNames:E?[E]:void 0,waitForValidation:!0,maxWaitMinutes:10});if(b.status!=="issued")return{success:!1,stackName:i,bucket:p,message:`SSL certificate validation failed. Status: ${b.status}`};C=b.certificateArn,console.log(`Certificate issued: ${C}`)}}let M=!1,S;try{let o=await r.describeStacks({stackName:i});if(o.Stacks.length>0){let n=o.Stacks[0],m=n.StackStatus;if(m==="DELETE_IN_PROGRESS")console.log("Previous stack is still being deleted, waiting..."),await r.waitForStack(i,"stack-delete-complete"),M=!1;else if(m==="DELETE_COMPLETE")M=!1;else M=!0,S=(n.Outputs||[]).find((l)=>l.OutputKey==="BucketName")?.OutputValue}}catch(o){if(o.message?.includes("does not exist")||o.code==="ValidationError")M=!1;else throw o}let N=S||p;if(!M){let o=new a(s),n=new y,m=!1;if(e)try{console.log(`Checking for existing CloudFront distributions with alias ${e}...`);let b=await n.listDistributions();for(let l of b){let D=[];if(l.Aliases?.Items){if(Array.isArray(l.Aliases.Items))D=l.Aliases.Items;else if(typeof l.Aliases.Items==="object"){let F=l.Aliases.Items.CNAME;if(typeof F==="string")D=[F];else if(Array.isArray(F))D=F}}if(D.includes(e)){m=!0,console.log(`Found existing CloudFront distribution ${l.Id} with alias ${e}`),console.log("Reusing existing infrastructure for updates...");let P=(await n.getDistributionConfig(l.Id)).DistributionConfig?.Origins?.Items,V;if(P){let U=[];if(Array.isArray(P))U=P;else if(P.Origin)U=Array.isArray(P.Origin)?P.Origin:[P.Origin];else U=[P];for(let L of U){let W=(L.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(W){V=W[1];break}}}if(V)return console.log(`Using existing S3 bucket: ${V}`),{success:!0,stackName:`existing-${l.Id}`,bucket:V,distributionId:l.Id,distributionDomain:l.DomainName,domain:e,certificateArn:C,message:"Using existing CloudFront distribution",_existingInfrastructure:!0}}}}catch{}if(!m)try{if((await o.headBucket(p)).exists){console.log(`Found orphaned S3 bucket ${p}, cleaning up...`);try{let l=o.emptyBucket(p).then(()=>o.deleteBucket(p)),D=new Promise((F,P)=>setTimeout(()=>P(Error("Bucket cleanup timeout")),30000));await Promise.race([l,D]),console.log(`Deleted orphaned S3 bucket ${p}`)}catch(l){console.log(`Note: Could not clean up S3 bucket: ${l.message}`);let D=Date.now().toString(36);N=`${p}-${D}`,console.log(`Using alternative bucket name: ${N}`)}}}catch{}}let v=ma({bucketName:N,domain:e,aliases:E?[e,E]:[e],certificateArn:C,defaultRootObject:t.defaultRootObject,errorDocument:t.errorDocument,passthroughUrls:t.passthroughUrls,singlePageApp:t.singlePageApp,dynamicApp:t.dynamicApp,computeOriginDomain:t.computeOriginDomain,computeOriginPort:t.computeOriginPort,computeOriginId:t.computeOriginId}),O=Object.entries(t.tags||{}).map(([o,n])=>({Key:o,Value:n}));if(O.push({Key:"ManagedBy",Value:"ts-cloud"}),O.push({Key:"Application",Value:t.siteName}),g)O.push({Key:"DnsProvider",Value:g.name});let B,I=!1;if(M){I=!0,console.log(`Updating CloudFormation stack: ${i}`);try{B=(await r.updateStack({stackName:i,templateBody:JSON.stringify(v),capabilities:["CAPABILITY_IAM"],tags:O})).StackId,console.log(`Update initiated, stack ID: ${B}`)}catch(o){if(o.message?.includes("No updates are to be performed")){let n=await r.describeStacks({stackName:i});B=n.Stacks[0].StackId;let m=n.Stacks[0]?.Outputs||[],b=(D)=>m.find((F)=>F.OutputKey===D)?.OutputValue,l=b("DistributionDomain");if(l)await H(g,e,l);return{success:!0,stackId:B,stackName:i,bucket:b("BucketName")||N,distributionId:b("DistributionId"),distributionDomain:l,domain:e,certificateArn:C,message:"Static site infrastructure is already up to date"}}else throw o}}else console.log(`Creating CloudFormation stack: ${i}`),console.log(`Bucket name: ${N}`),console.log(`Domain: ${e}`),console.log(`Certificate ARN: ${C}`),B=(await r.createStack({stackName:i,templateBody:JSON.stringify(v),capabilities:["CAPABILITY_IAM"],tags:O,onFailure:"DELETE"})).StackId,console.log(`Create initiated, stack ID: ${B}`);console.log(`Waiting for stack to reach ${I?"stack-update-complete":"stack-create-complete"}...`);try{await r.waitForStack(i,I?"stack-update-complete":"stack-create-complete"),console.log("Stack operation completed successfully!")}catch(o){if(o.message?.includes("must be verified")||o.message?.includes("Access denied for operation")){console.log("CloudFront account verification required - checking for existing infrastructure...");try{let m=new y,b=await m.listDistributions();for(let l of b){let D=[];if(l.Aliases?.Items){if(Array.isArray(l.Aliases.Items))D=l.Aliases.Items;else if(typeof l.Aliases.Items==="object"){let F=l.Aliases.Items.CNAME;if(typeof F==="string")D=[F];else if(Array.isArray(F))D=F}}if(D.includes(e)){console.log(`Found existing CloudFront distribution ${l.Id} with alias ${e}`),console.log("Using existing infrastructure despite account verification requirement...");let P=(await m.getDistributionConfig(l.Id)).DistributionConfig?.Origins?.Items,V;if(P){let U=[];if(Array.isArray(P))U=P;else if(P.Origin)U=Array.isArray(P.Origin)?P.Origin:[P.Origin];else U=[P];for(let L of U){let W=(L.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(W){V=W[1];break}}}if(V){console.log(`Using existing S3 bucket: ${V}`);let U=l.DomainName;if(U)await H(g,e,U);return{success:!0,stackName:`existing-${l.Id}`,bucket:V,distributionId:l.Id,distributionDomain:l.DomainName,domain:e,certificateArn:C,message:"Using existing CloudFront distribution (account verification pending for new distributions)"}}}}}catch{}return console.log(`
|
|
28
28
|
┌─────────────────────────────────────────────────────────────────────────────┐
|
|
29
29
|
│ AWS ACCOUNT VERIFICATION REQUIRED │
|
|
30
30
|
├─────────────────────────────────────────────────────────────────────────────┤
|
|
@@ -42,7 +42,7 @@ import{ge,ne,T,ie,rr}from"./chunk-pkan6evc.js";import{a}from"./chunk-3kapcdpn.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:B,stackName:i,bucket:N,message:"CloudFront account verification required. Please contact AWS Support."}}return{success:!1,stackId:B,stackName:i,bucket:N,message:`Stack deployment failed: ${o.message}`}}let d=(await r.describeStacks({stackName:i})).Stacks[0]?.Outputs||[],k=(o)=>d.find((n)=>n.OutputKey===o)?.OutputValue,A=k("DistributionDomain");if(A&&g)console.log(`Creating DNS records via ${g.name}...`),await H(g,e,A);else if(A&&!g)console.log("Skipping DNS record creation (DNS verification was skipped)");return{success:!0,stackId:B,stackName:i,bucket:k("BucketName")||N,distributionId:k("DistributionId"),distributionDomain:A,domain:e,certificateArn:C,message:"Static site infrastructure deployed successfully with external DNS"}}async function H(t,s,u){if(!t){console.log("Skipping DNS record creation (DNS verification was skipped)");return}if(s.split(".").length===2)if(t instanceof
|
|
45
|
+
└─────────────────────────────────────────────────────────────────────────────┘`),{success:!1,stackId:B,stackName:i,bucket:N,message:"CloudFront account verification required. Please contact AWS Support."}}return{success:!1,stackId:B,stackName:i,bucket:N,message:`Stack deployment failed: ${o.message}`}}let d=(await r.describeStacks({stackName:i})).Stacks[0]?.Outputs||[],k=(o)=>d.find((n)=>n.OutputKey===o)?.OutputValue,A=k("DistributionDomain");if(A&&g)console.log(`Creating DNS records via ${g.name}...`),await H(g,e,A);else if(A&&!g)console.log("Skipping DNS record creation (DNS verification was skipped)");return{success:!0,stackId:B,stackName:i,bucket:k("BucketName")||N,distributionId:k("DistributionId"),distributionDomain:A,domain:e,certificateArn:C,message:"Static site infrastructure deployed successfully with external DNS"}}async function H(t,s,u){if(!t){console.log("Skipping DNS record creation (DNS verification was skipped)");return}if(s.split(".").length===2)if(t instanceof me){console.log(`Creating Route53 alias record for apex domain ${s} -> ${u}`);let i=await t.createCloudFrontAlias({domain:s,name:s,cloudFrontDomainName:u});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} -> ${u}`);else console.log(`Created Route53 alias record: ${s} -> ${u}`);let r=`www.${s}`;console.log(`Creating Route53 alias record for ${r} -> ${u}`);let c=await t.createCloudFrontAlias({domain:s,name:r,cloudFrontDomainName:u});if(!c.success)console.warn(`Warning: Could not create www Route53 alias: ${c.message}`),console.warn("Please manually create an A-record alias in Route53:"),console.warn(` ${r} -> ${u}`);else console.log(`Created Route53 alias record: ${r} -> ${u}`)}else{try{let g=await t.listRecords(s,"A");if(g.success)for(let C of g.records){let w=C.name.replace(/\.$/,"");if(w===s||w==="")console.log(`Removing existing root A record (${C.content}) to make room for ALIAS...`),await t.deleteRecord(s,{name:s,type:"A",content:C.content})}}catch(g){console.log(`Note: Could not check for conflicting A records: ${g instanceof Error?g.message:g}`)}console.log(`Creating ALIAS record for apex domain ${s} -> ${u}`);let i=await t.upsertRecord(s,{name:s,type:"ALIAS",content:u,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} -> ${u}`);else console.log(`Created ALIAS record: ${s} -> ${u}`);let r=`www.${s}`;console.log(`Creating CNAME record for ${r} -> ${u}`);let c=await t.upsertRecord(s,{name:r,type:"CNAME",content:u,ttl:600});if(!c.success)console.warn(`Warning: Could not create www DNS record: ${c.message}`),console.warn("Please manually create a CNAME record:"),console.warn(` ${r} -> ${u}`);else console.log(`Created CNAME record: ${r} -> ${u}`)}else{console.log(`Creating CNAME record for ${s} -> ${u}`);let i=await t.upsertRecord(s,{name:s,type:"CNAME",content:u,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} -> ${u}`);else console.log(`Created CNAME record: ${s} -> ${u}`)}}async function en(t){let{sourceDir:s,cleanBucket:u=!1,onProgress:e,...p}=t;e?.("infrastructure","Deploying CloudFormation stack...");let i=await Zr(p);if(!i.success)return i;if(u){e?.("clean","Cleaning old files from S3...");try{await new a(p.region||"us-east-1").emptyBucket(i.bucket)}catch(C){console.log(`Note: Could not clean bucket: ${C.message}`)}}e?.("upload","Uploading files to S3...");let{uploadStaticFiles:r}=await import("./chunk-xfdpxsbc.js"),c=await r({sourceDir:s,bucket:i.bucket,region:p.region||"us-east-1",cacheControl:p.cacheControl,onProgress:(C,w,x)=>{e?.("upload",`${C}/${w}: ${x}`)}});if(c.errors.length>0)return{...i,success:!1,message:`Upload errors: ${c.errors.join(", ")}`,filesUploaded:c.uploaded};if(i.distributionId&&c.uploaded>0){e?.("invalidate","Invalidating CloudFront cache...");let{invalidateCache:C}=await import("./chunk-xfdpxsbc.js");await C(i.distributionId)}e?.("complete","Deployment complete!");let g=c.skipped>0?`Deployed ${c.uploaded} files (${c.skipped} unchanged) with external DNS`:`Deployed ${c.uploaded} files successfully with external DNS`;return{...i,filesUploaded:c.uploaded,filesSkipped:c.skipped,message:g}}function Qi(t){let{bucketName:s,domain:u,certificateArn:e,hostedZoneId:p,defaultRootObject:i="index.html",errorDocument:r="404.html"}=t,c={},g={};c.S3Bucket={Type:"AWS::S3::Bucket",Properties:{BucketName:s,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:i,ErrorDocument:r}}},g.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},g.BucketArn={Description:"S3 Bucket ARN",Value:{"Fn::GetAtt":["S3Bucket","Arn"]}},c.CloudFrontOAC={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`OAC-${s}`,Description:`OAC for ${s}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},c.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
|
|
|
@@ -56,5 +56,5 @@ import{ge,ne,T,ie,rr}from"./chunk-pkan6evc.js";import{a}from"./chunk-3kapcdpn.js
|
|
|
56
56
|
}
|
|
57
57
|
|
|
58
58
|
return request;
|
|
59
|
-
}`}};let C={Enabled:!0,DefaultRootObject:i,HttpVersion:"http2and3",IPV6Enabled:!0,PriceClass:"PriceClass_100",Origins:[{Id:`S3-${s}`,DomainName:{"Fn::GetAtt":["S3Bucket","RegionalDomainName"]},S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{"Fn::GetAtt":["CloudFrontOAC","Id"]}}],DefaultCacheBehavior:{TargetOriginId:`S3-${s}`,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD"],CachedMethods:["GET","HEAD"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":["UrlRewriteFunction","FunctionARN"]}}]},CustomErrorResponses:[{ErrorCode:403,ResponseCode:200,ResponsePagePath:`/${i}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:404,ResponsePagePath:`/${r}`,ErrorCachingMinTTL:300}]};if(u&&e)C.Aliases=[u],C.ViewerCertificate={AcmCertificateArn:e,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};else C.ViewerCertificate={CloudFrontDefaultCertificate:!0};if(c.CloudFrontDistribution={Type:"AWS::CloudFront::Distribution",DependsOn:["S3Bucket","CloudFrontOAC","UrlRewriteFunction"],Properties:{DistributionConfig:C}},g.DistributionId={Description:"CloudFront Distribution ID",Value:{Ref:"CloudFrontDistribution"}},g.DistributionDomain={Description:"CloudFront Distribution Domain",Value:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]}},c.S3BucketPolicy={Type:"AWS::S3::BucketPolicy",DependsOn:["S3Bucket","CloudFrontDistribution"],Properties:{Bucket:{Ref:"S3Bucket"},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":"arn:aws:s3:::${S3Bucket}/*"},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":"arn:aws:cloudfront::${AWS::AccountId}:distribution/${CloudFrontDistribution}"}}}}]}}},u&&p)c.DNSRecord={Type:"AWS::Route53::RecordSet",DependsOn:"CloudFrontDistribution",Properties:{HostedZoneId:p,Name:u,Type:"A",AliasTarget:{DNSName:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}},c.DNSRecordIPv6={Type:"AWS::Route53::RecordSet",DependsOn:"CloudFrontDistribution",Properties:{HostedZoneId:p,Name:u,Type:"AAAA",AliasTarget:{DNSName:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}},g.SiteUrl={Description:"Site URL",Value:{"Fn::Sub":"https://${DNSRecord}"}};return{AWSTemplateFormatVersion:"2010-09-09",Description:`Static site infrastructure for ${u||s}`,Resources:c,Outputs:g}}async function Hi(t){if(t.dnsProvider&&t.dnsProvider.provider!=="route53"){let d=t.domain||(t.subdomain&&t.baseDomain?`${t.subdomain}.${t.baseDomain}`:void 0);if(!d)return{success:!1,stackName:t.stackName||`${t.siteName}-static-site`,bucket:t.bucket||`${t.siteName}-${Date.now()}`,message:"Domain is required when using external DNS provider"};return Zr({siteName:t.siteName,region:t.region,domain:d,bucket:t.bucket,certificateArn:t.certificateArn,stackName:t.stackName,defaultRootObject:t.defaultRootObject,errorDocument:t.errorDocument,cacheControl:t.cacheControl,tags:t.tags,dnsProvider:t.dnsProvider})}let s=t.region||"us-east-1",u="us-east-1",e;if(t.domain)e=t.domain;else if(t.subdomain&&t.baseDomain)e=`${t.subdomain}.${t.baseDomain}`;let p=t.bucket||(e?e.replace(/\./g,"-"):`${t.siteName}-${Date.now()}`),i=t.stackName||`${t.siteName}-static-site`,r=new f(u),c=new h,g=new ie("us-east-1"),C=new rr("us-east-1"),{hostedZoneId:w,certificateArn:x}=t;if(e&&!w){let d=await c.findHostedZoneForDomain(e);if(d)w=d.Id.replace("/hostedzone/","");else return{success:!1,stackName:i,bucket:p,message:`No Route53 hosted zone found for ${t.baseDomain||e}. Please create one first.`}}if(e&&!x&&w){let d=await g.findCertificateByDomain(e);if(d&&d.Status==="ISSUED")x=d.CertificateArn;else x=(await C.requestAndValidate({domainName:e,hostedZoneId:w,waitForValidation:!0,maxWaitMinutes:10})).certificateArn}let E=!1,M;try{let d=await r.describeStacks({stackName:i});if(d.Stacks.length>0){let k=d.Stacks[0],A=k.StackStatus;if(A==="DELETE_IN_PROGRESS")console.log("Previous stack is still being deleted, waiting..."),await r.waitForStack(i,"stack-delete-complete"),E=!1;else if(A==="DELETE_COMPLETE")E=!1;else E=!0,M=(k.Outputs||[]).find((n)=>n.OutputKey==="BucketName")?.OutputValue}}catch(d){if(d.message?.includes("does not exist")||d.code==="ValidationError")E=!1;else throw d}let S=M||p;if(!E){let d=new a(s),k=new y,A=!1;if(e){try{console.log(`Checking for existing CloudFront distribution for ${e}...`);let o=await k.listDistributions();for(let n of o){let m=[];if(n.Aliases?.Items){if(Array.isArray(n.Aliases.Items))m=n.Aliases.Items;else if(typeof n.Aliases.Items==="object"){let b=n.Aliases.Items.CNAME;if(typeof b==="string")m=[b];else if(Array.isArray(b))m=b}}if(m.includes(e)){A=!0,console.log(`Found existing CloudFront distribution ${n.Id} for ${e}`);let l=(await k.getDistributionConfig(n.Id)).DistributionConfig?.Origins?.Items,D;if(l){let F=[];if(Array.isArray(l))F=l;else if(l.Origin)F=Array.isArray(l.Origin)?l.Origin:[l.Origin];else F=[l];for(let P of F){let U=(P.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(U){D=U[1];break}}}if(D){let F=e.replace(/\./g,"-");if(!D.startsWith(F)&&!D.includes(t.siteName)){console.log(`Warning: Found distribution with mismatched bucket ${D}, skipping...`);continue}if(console.log(`Using existing S3 bucket: ${D}`),w&&n.DomainName)try{console.log(`Ensuring Route53 records exist for ${e}...`),await c.createAliasRecord({HostedZoneId:w,Name:e,Type:"A",TargetHostedZoneId:h.CloudFrontHostedZoneId,TargetDNSName:n.DomainName,EvaluateTargetHealth:!1}),await c.createAliasRecord({HostedZoneId:w,Name:e,Type:"AAAA",TargetHostedZoneId:h.CloudFrontHostedZoneId,TargetDNSName:n.DomainName,EvaluateTargetHealth:!1}),console.log(`Route53 records ensured for ${e}`)}catch(P){console.log(`Note: Could not update Route53 records: ${P.message}`)}return{success:!0,stackName:`existing-${n.Id}`,bucket:D,distributionId:n.Id,distributionDomain:n.DomainName,domain:e,certificateArn:x,message:"Using existing CloudFront distribution"}}}}}catch{}if(w)try{let n=(await c.listResourceRecordSets({HostedZoneId:w})).ResourceRecordSets||[];for(let m of n)if(m.Name===`${e}.`&&(m.Type==="A"||m.Type==="AAAA")){if(m.AliasTarget){console.log(`Found orphaned Route53 ${m.Type} record for ${e}, cleaning up...`);try{await c.deleteRecord({HostedZoneId:w,RecordSet:m}),console.log(`Deleted orphaned Route53 ${m.Type} record for ${e}`)}catch(b){console.log(`Note: Could not delete Route53 record: ${b.message}`)}}}}catch{}}if(!A)try{if((await d.headBucket(p)).exists){console.log(`Found orphaned S3 bucket ${p}, cleaning up...`);try{let n=d.emptyBucket(p).then(()=>d.deleteBucket(p)),m=new Promise((b,l)=>setTimeout(()=>l(Error("Bucket cleanup timeout")),30000));await Promise.race([n,m]),console.log(`Deleted orphaned S3 bucket ${p}`)}catch(n){console.log(`Note: Could not clean up S3 bucket: ${n.message}`);let m=Date.now().toString(36);S=`${p}-${m}`,console.log(`Using alternative bucket name: ${S}`)}}}catch{}}let N=Qi({bucketName:S,domain:e,certificateArn:x,hostedZoneId:w,defaultRootObject:t.defaultRootObject,errorDocument:t.errorDocument}),j=Object.entries(t.tags||{}).map(([d,k])=>({Key:d,Value:k}));j.push({Key:"ManagedBy",Value:"ts-cloud"}),j.push({Key:"Application",Value:t.siteName});let v,O=!1;if(E){O=!0,console.log(`Updating CloudFormation stack: ${i}`),console.log(`Using existing bucket: ${S}`),console.log(`Domain: ${e||"not specified"}`),console.log(`Certificate ARN: ${x||"not specified"}`);try{v=(await r.updateStack({stackName:i,templateBody:JSON.stringify(N),capabilities:["CAPABILITY_IAM"],tags:j})).StackId,console.log(`Update initiated, stack ID: ${v}`)}catch(d){if(d.message?.includes("No updates are to be performed")){let k=await r.describeStacks({stackName:i});v=k.Stacks[0].StackId;let A=k.Stacks[0]?.Outputs||[],o=(n)=>A.find((m)=>m.OutputKey===n)?.OutputValue;return{success:!0,stackId:v,stackName:i,bucket:o("BucketName")||S,distributionId:o("DistributionId"),distributionDomain:o("DistributionDomain"),domain:e,certificateArn:x,message:"Static site infrastructure is already up to date"}}else throw d}}else console.log(`Creating CloudFormation stack: ${i}`),console.log(`Bucket name: ${S}`),console.log(`Domain: ${e||"not specified"}`),console.log(`Certificate ARN: ${x||"not specified"}`),console.log("Stack does not exist, creating..."),v=(await r.createStack({stackName:i,templateBody:JSON.stringify(N),capabilities:["CAPABILITY_IAM"],tags:j,onFailure:"DELETE"})).StackId,console.log(`Create initiated, stack ID: ${v}`);console.log(`Waiting for stack to reach ${O?"stack-update-complete":"stack-create-complete"}...`);try{await r.waitForStack(i,O?"stack-update-complete":"stack-create-complete"),console.log("Stack operation completed successfully!")}catch(d){if(d.message?.includes("must be verified")||d.message?.includes("Access denied for operation")||d.message?.includes("failed")){console.log("CloudFormation deployment failed, trying direct API creation...");let k=new y;if(e)try{let A=await k.listDistributions();for(let o of A){let n=[];if(o.Aliases?.Items){if(Array.isArray(o.Aliases.Items))n=o.Aliases.Items;else if(typeof o.Aliases.Items==="object"){let m=o.Aliases.Items.CNAME;if(typeof m==="string")n=[m];else if(Array.isArray(m))n=m}}if(n.includes(e)){console.log(`Found existing CloudFront distribution ${o.Id} with alias ${e}`);let b=(await k.getDistributionConfig(o.Id)).DistributionConfig?.Origins?.Items,l;if(b){let D=[];if(Array.isArray(b))D=b;else if(b.Origin)D=Array.isArray(b.Origin)?b.Origin:[b.Origin];else D=[b];for(let F of D){let V=(F.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(V){l=V[1];break}}}if(l)return console.log(`Using existing S3 bucket: ${l}`),{success:!0,stackName:`existing-${o.Id}`,bucket:l,distributionId:o.Id,distributionDomain:o.DomainName,domain:e,certificateArn:x,message:"Using existing CloudFront distribution (account verification pending for new distributions)"}}}}catch{}console.log("No existing infrastructure found, creating via direct API calls...");try{let A=new a(s);if((await A.headBucket(S)).exists)console.log(`Using existing S3 bucket: ${S}`);else console.log(`Creating S3 bucket: ${S}...`),await A.createBucket(S);await A.putBucketWebsite(S,{IndexDocument:t.defaultRootObject||"index.html",ErrorDocument:t.errorDocument||"404.html"}),await A.putPublicAccessBlock(S,{BlockPublicAcls:!0,IgnorePublicAcls:!0,BlockPublicPolicy:!1,RestrictPublicBuckets:!1}),console.log(`S3 bucket ${S} configured`);let n=`OAC-${S}`;console.log(`Creating Origin Access Control: ${n}...`);let m=await k.findOrCreateOriginAccessControl(n);console.log(`Origin Access Control ${m.Id} ready`),console.log("Creating CloudFront distribution...");let b=await k.createDistributionForS3({bucketName:S,bucketRegion:s,originAccessControlId:m.Id,aliases:e?[e]:[],certificateArn:x,defaultRootObject:t.defaultRootObject||"index.html",comment:`Distribution for ${e||S}`});console.log(`CloudFront distribution ${b.Id} created`),console.log("Updating S3 bucket policy...");let l=y.getS3BucketPolicyForCloudFront(S,b.ARN);if(await A.putBucketPolicy(S,l),console.log("S3 bucket policy updated"),e&&w){console.log(`Creating Route53 records for ${e}...`);try{await c.createAliasRecord({HostedZoneId:w,Name:e,Type:"A",TargetHostedZoneId:h.CloudFrontHostedZoneId,TargetDNSName:b.DomainName,EvaluateTargetHealth:!1}),await c.createAliasRecord({HostedZoneId:w,Name:e,Type:"AAAA",TargetHostedZoneId:h.CloudFrontHostedZoneId,TargetDNSName:b.DomainName,EvaluateTargetHealth:!1}),console.log(`Route53 records created for ${e}`)}catch(D){console.log(`Note: Could not create Route53 records: ${D.message}`)}}return{success:!0,stackName:`direct-${b.Id}`,bucket:S,distributionId:b.Id,distributionDomain:b.DomainName,domain:e,certificateArn:x,message:"Static site infrastructure created via direct API calls"}}catch(A){return console.log(`Direct API creation failed: ${A.message}`),{success:!1,stackId:v,stackName:i,bucket:S,message:`Deployment failed: ${A.message}`}}}return{success:!1,stackId:v,stackName:i,bucket:S,message:`Stack deployment failed: ${d.message}`}}let I=(await r.describeStacks({stackName:i})).Stacks[0]?.Outputs||[],R=(d)=>I.find((k)=>k.OutputKey===d)?.OutputValue;return{success:!0,stackId:v,stackName:i,bucket:R("BucketName")||S,distributionId:R("DistributionId"),distributionDomain:R("DistributionDomain"),domain:e,certificateArn:x,message:"Static site infrastructure deployed successfully"}}async function Gi(t){let{sourceDir:s,bucket:u,region:e,cacheControl:p="max-age=31536000, public",onProgress:i}=t,r=new a(e),{readdir:c}=await import("node:fs/promises"),{join:g,relative:C}=await import("node:path"),{createHash:w}=await import("node:crypto");async function x(I){let R=[],d=await c(I,{withFileTypes:!0});for(let k of d){let A=g(I,k.name);if(k.isDirectory())R.push(...await x(A));else R.push(A)}return R}function E(I){let R=I.split(".").pop()?.toLowerCase();return{html:"text/html; charset=utf-8",css:"text/css; charset=utf-8",js:"application/javascript; charset=utf-8",json:"application/json; charset=utf-8",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",ico:"image/x-icon",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",xml:"application/xml",txt:"text/plain; charset=utf-8",sh:"text/plain; charset=utf-8",bash:"text/plain; charset=utf-8",ps1:"text/plain; charset=utf-8"}[R||""]||"application/octet-stream"}function M(I){return w("md5").update(I).digest("hex")}async function S(){let I=new Map,R;do{let d=await r.listObjects({bucket:u,maxKeys:1000,continuationToken:R});for(let k of d.objects){let A=k.ETag?.replace(/"/g,"")||"";I.set(k.Key,A)}R=d.nextContinuationToken}while(R);return I}let N=await x(s),j=[],v=0,O=0,B=await S();for(let I of N){let R=C(s,I),d=E(I),k=I.endsWith(".html")?"max-age=3600, public":p;try{let A=Buffer.from(await Bun.file(I).arrayBuffer()),o=M(A),n=B.get(R);if(n&&n===o){O++,i?.(v+O,N.length,R);continue}await r.putObject({bucket:u,key:R,body:A,contentType:d,cacheControl:k}),v++,i?.(v+O,N.length,R)}catch(A){j.push(`Failed to upload ${R}: ${A.message}`)}}return{uploaded:v,skipped:O,errors:j}}async function qi(t){return{invalidationId:(await new y().invalidateAll(t)).Id}}async function ha(t,s="us-east-1"){let u=new f(s);try{let r=((await u.describeStacks({stackName:t})).Stacks[0]?.Outputs||[]).find((c)=>c.OutputKey==="BucketName")?.OutputValue;if(r)await new a(s).emptyBucket(r)}catch{}await u.deleteStack(t);let e=await u.waitForStackComplete(t,60,1e4);return{success:e.success||e.status==="DELETE_COMPLETE",message:e.success?"Static site deleted successfully":`Deletion failed: ${e.status}`}}async function fa(t){let{sourceDir:s,cleanBucket:u=!1,onProgress:e,...p}=t;e?.("infrastructure","Deploying CloudFormation stack...");let i=await Hi(p);if(!i.success)return i;if(u){e?.("clean","Cleaning old files from S3...");try{await new a(p.region||"us-east-1").emptyBucket(i.bucket)}catch(g){console.log(`Note: Could not clean bucket: ${g.message}`)}}e?.("upload","Uploading files to S3...");let r=await Gi({sourceDir:s,bucket:i.bucket,region:p.region||"us-east-1",cacheControl:p.cacheControl,onProgress:(g,C,w)=>{e?.("upload",`${g}/${C}: ${w}`)}});if(r.errors.length>0)return{...i,success:!1,message:`Upload errors: ${r.errors.join(", ")}`,filesUploaded:r.uploaded};if(i.distributionId&&r.uploaded>0)e?.("invalidate","Invalidating CloudFront cache..."),await qi(i.distributionId);e?.("complete","Deployment complete!");let c=r.skipped>0?`Deployed ${r.uploaded} files (${r.skipped} unchanged)`:`Deployed ${r.uploaded} files successfully`;return{...i,filesUploaded:r.uploaded,filesSkipped:r.skipped,message:c}}
|
|
59
|
+
}`}};let C={Enabled:!0,DefaultRootObject:i,HttpVersion:"http2and3",IPV6Enabled:!0,PriceClass:"PriceClass_100",Origins:[{Id:`S3-${s}`,DomainName:{"Fn::GetAtt":["S3Bucket","RegionalDomainName"]},S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{"Fn::GetAtt":["CloudFrontOAC","Id"]}}],DefaultCacheBehavior:{TargetOriginId:`S3-${s}`,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD"],CachedMethods:["GET","HEAD"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":["UrlRewriteFunction","FunctionARN"]}}]},CustomErrorResponses:[{ErrorCode:403,ResponseCode:200,ResponsePagePath:`/${i}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:404,ResponsePagePath:`/${r}`,ErrorCachingMinTTL:300}]};if(u&&e)C.Aliases=[u],C.ViewerCertificate={AcmCertificateArn:e,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};else C.ViewerCertificate={CloudFrontDefaultCertificate:!0};if(c.CloudFrontDistribution={Type:"AWS::CloudFront::Distribution",DependsOn:["S3Bucket","CloudFrontOAC","UrlRewriteFunction"],Properties:{DistributionConfig:C}},g.DistributionId={Description:"CloudFront Distribution ID",Value:{Ref:"CloudFrontDistribution"}},g.DistributionDomain={Description:"CloudFront Distribution Domain",Value:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]}},c.S3BucketPolicy={Type:"AWS::S3::BucketPolicy",DependsOn:["S3Bucket","CloudFrontDistribution"],Properties:{Bucket:{Ref:"S3Bucket"},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":"arn:aws:s3:::${S3Bucket}/*"},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":"arn:aws:cloudfront::${AWS::AccountId}:distribution/${CloudFrontDistribution}"}}}}]}}},u&&p)c.DNSRecord={Type:"AWS::Route53::RecordSet",DependsOn:"CloudFrontDistribution",Properties:{HostedZoneId:p,Name:u,Type:"A",AliasTarget:{DNSName:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}},c.DNSRecordIPv6={Type:"AWS::Route53::RecordSet",DependsOn:"CloudFrontDistribution",Properties:{HostedZoneId:p,Name:u,Type:"AAAA",AliasTarget:{DNSName:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}},g.SiteUrl={Description:"Site URL",Value:{"Fn::Sub":"https://${DNSRecord}"}};return{AWSTemplateFormatVersion:"2010-09-09",Description:`Static site infrastructure for ${u||s}`,Resources:c,Outputs:g}}async function Hi(t){if(t.dnsProvider&&t.dnsProvider.provider!=="route53"){let d=t.domain||(t.subdomain&&t.baseDomain?`${t.subdomain}.${t.baseDomain}`:void 0);if(!d)return{success:!1,stackName:t.stackName||`${t.siteName}-static-site`,bucket:t.bucket||`${t.siteName}-${Date.now()}`,message:"Domain is required when using external DNS provider"};return Zr({siteName:t.siteName,region:t.region,domain:d,bucket:t.bucket,certificateArn:t.certificateArn,stackName:t.stackName,defaultRootObject:t.defaultRootObject,errorDocument:t.errorDocument,cacheControl:t.cacheControl,tags:t.tags,dnsProvider:t.dnsProvider})}let s=t.region||"us-east-1",u="us-east-1",e;if(t.domain)e=t.domain;else if(t.subdomain&&t.baseDomain)e=`${t.subdomain}.${t.baseDomain}`;let p=t.bucket||(e?e.replace(/\./g,"-"):`${t.siteName}-${Date.now()}`),i=t.stackName||`${t.siteName}-static-site`,r=new f(u),c=new h,g=new se("us-east-1"),C=new rr("us-east-1"),{hostedZoneId:w,certificateArn:x}=t;if(e&&!w){let d=await c.findHostedZoneForDomain(e);if(d)w=d.Id.replace("/hostedzone/","");else return{success:!1,stackName:i,bucket:p,message:`No Route53 hosted zone found for ${t.baseDomain||e}. Please create one first.`}}if(e&&!x&&w){let d=await g.findCertificateByDomain(e);if(d&&d.Status==="ISSUED")x=d.CertificateArn;else x=(await C.requestAndValidate({domainName:e,hostedZoneId:w,waitForValidation:!0,maxWaitMinutes:10})).certificateArn}let E=!1,M;try{let d=await r.describeStacks({stackName:i});if(d.Stacks.length>0){let k=d.Stacks[0],A=k.StackStatus;if(A==="DELETE_IN_PROGRESS")console.log("Previous stack is still being deleted, waiting..."),await r.waitForStack(i,"stack-delete-complete"),E=!1;else if(A==="DELETE_COMPLETE")E=!1;else E=!0,M=(k.Outputs||[]).find((n)=>n.OutputKey==="BucketName")?.OutputValue}}catch(d){if(d.message?.includes("does not exist")||d.code==="ValidationError")E=!1;else throw d}let S=M||p;if(!E){let d=new a(s),k=new y,A=!1;if(e){try{console.log(`Checking for existing CloudFront distribution for ${e}...`);let o=await k.listDistributions();for(let n of o){let m=[];if(n.Aliases?.Items){if(Array.isArray(n.Aliases.Items))m=n.Aliases.Items;else if(typeof n.Aliases.Items==="object"){let b=n.Aliases.Items.CNAME;if(typeof b==="string")m=[b];else if(Array.isArray(b))m=b}}if(m.includes(e)){A=!0,console.log(`Found existing CloudFront distribution ${n.Id} for ${e}`);let l=(await k.getDistributionConfig(n.Id)).DistributionConfig?.Origins?.Items,D;if(l){let F=[];if(Array.isArray(l))F=l;else if(l.Origin)F=Array.isArray(l.Origin)?l.Origin:[l.Origin];else F=[l];for(let P of F){let U=(P.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(U){D=U[1];break}}}if(D){let F=e.replace(/\./g,"-");if(!D.startsWith(F)&&!D.includes(t.siteName)){console.log(`Warning: Found distribution with mismatched bucket ${D}, skipping...`);continue}if(console.log(`Using existing S3 bucket: ${D}`),w&&n.DomainName)try{console.log(`Ensuring Route53 records exist for ${e}...`),await c.createAliasRecord({HostedZoneId:w,Name:e,Type:"A",TargetHostedZoneId:h.CloudFrontHostedZoneId,TargetDNSName:n.DomainName,EvaluateTargetHealth:!1}),await c.createAliasRecord({HostedZoneId:w,Name:e,Type:"AAAA",TargetHostedZoneId:h.CloudFrontHostedZoneId,TargetDNSName:n.DomainName,EvaluateTargetHealth:!1}),console.log(`Route53 records ensured for ${e}`)}catch(P){console.log(`Note: Could not update Route53 records: ${P.message}`)}return{success:!0,stackName:`existing-${n.Id}`,bucket:D,distributionId:n.Id,distributionDomain:n.DomainName,domain:e,certificateArn:x,message:"Using existing CloudFront distribution"}}}}}catch{}if(w)try{let n=(await c.listResourceRecordSets({HostedZoneId:w})).ResourceRecordSets||[];for(let m of n)if(m.Name===`${e}.`&&(m.Type==="A"||m.Type==="AAAA")){if(m.AliasTarget){console.log(`Found orphaned Route53 ${m.Type} record for ${e}, cleaning up...`);try{await c.deleteRecord({HostedZoneId:w,RecordSet:m}),console.log(`Deleted orphaned Route53 ${m.Type} record for ${e}`)}catch(b){console.log(`Note: Could not delete Route53 record: ${b.message}`)}}}}catch{}}if(!A)try{if((await d.headBucket(p)).exists){console.log(`Found orphaned S3 bucket ${p}, cleaning up...`);try{let n=d.emptyBucket(p).then(()=>d.deleteBucket(p)),m=new Promise((b,l)=>setTimeout(()=>l(Error("Bucket cleanup timeout")),30000));await Promise.race([n,m]),console.log(`Deleted orphaned S3 bucket ${p}`)}catch(n){console.log(`Note: Could not clean up S3 bucket: ${n.message}`);let m=Date.now().toString(36);S=`${p}-${m}`,console.log(`Using alternative bucket name: ${S}`)}}}catch{}}let N=Qi({bucketName:S,domain:e,certificateArn:x,hostedZoneId:w,defaultRootObject:t.defaultRootObject,errorDocument:t.errorDocument}),j=Object.entries(t.tags||{}).map(([d,k])=>({Key:d,Value:k}));j.push({Key:"ManagedBy",Value:"ts-cloud"}),j.push({Key:"Application",Value:t.siteName});let v,O=!1;if(E){O=!0,console.log(`Updating CloudFormation stack: ${i}`),console.log(`Using existing bucket: ${S}`),console.log(`Domain: ${e||"not specified"}`),console.log(`Certificate ARN: ${x||"not specified"}`);try{v=(await r.updateStack({stackName:i,templateBody:JSON.stringify(N),capabilities:["CAPABILITY_IAM"],tags:j})).StackId,console.log(`Update initiated, stack ID: ${v}`)}catch(d){if(d.message?.includes("No updates are to be performed")){let k=await r.describeStacks({stackName:i});v=k.Stacks[0].StackId;let A=k.Stacks[0]?.Outputs||[],o=(n)=>A.find((m)=>m.OutputKey===n)?.OutputValue;return{success:!0,stackId:v,stackName:i,bucket:o("BucketName")||S,distributionId:o("DistributionId"),distributionDomain:o("DistributionDomain"),domain:e,certificateArn:x,message:"Static site infrastructure is already up to date"}}else throw d}}else console.log(`Creating CloudFormation stack: ${i}`),console.log(`Bucket name: ${S}`),console.log(`Domain: ${e||"not specified"}`),console.log(`Certificate ARN: ${x||"not specified"}`),console.log("Stack does not exist, creating..."),v=(await r.createStack({stackName:i,templateBody:JSON.stringify(N),capabilities:["CAPABILITY_IAM"],tags:j,onFailure:"DELETE"})).StackId,console.log(`Create initiated, stack ID: ${v}`);console.log(`Waiting for stack to reach ${O?"stack-update-complete":"stack-create-complete"}...`);try{await r.waitForStack(i,O?"stack-update-complete":"stack-create-complete"),console.log("Stack operation completed successfully!")}catch(d){if(d.message?.includes("must be verified")||d.message?.includes("Access denied for operation")||d.message?.includes("failed")){console.log("CloudFormation deployment failed, trying direct API creation...");let k=new y;if(e)try{let A=await k.listDistributions();for(let o of A){let n=[];if(o.Aliases?.Items){if(Array.isArray(o.Aliases.Items))n=o.Aliases.Items;else if(typeof o.Aliases.Items==="object"){let m=o.Aliases.Items.CNAME;if(typeof m==="string")n=[m];else if(Array.isArray(m))n=m}}if(n.includes(e)){console.log(`Found existing CloudFront distribution ${o.Id} with alias ${e}`);let b=(await k.getDistributionConfig(o.Id)).DistributionConfig?.Origins?.Items,l;if(b){let D=[];if(Array.isArray(b))D=b;else if(b.Origin)D=Array.isArray(b.Origin)?b.Origin:[b.Origin];else D=[b];for(let F of D){let V=(F.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(V){l=V[1];break}}}if(l)return console.log(`Using existing S3 bucket: ${l}`),{success:!0,stackName:`existing-${o.Id}`,bucket:l,distributionId:o.Id,distributionDomain:o.DomainName,domain:e,certificateArn:x,message:"Using existing CloudFront distribution (account verification pending for new distributions)"}}}}catch{}console.log("No existing infrastructure found, creating via direct API calls...");try{let A=new a(s);if((await A.headBucket(S)).exists)console.log(`Using existing S3 bucket: ${S}`);else console.log(`Creating S3 bucket: ${S}...`),await A.createBucket(S);await A.putBucketWebsite(S,{IndexDocument:t.defaultRootObject||"index.html",ErrorDocument:t.errorDocument||"404.html"}),await A.putPublicAccessBlock(S,{BlockPublicAcls:!0,IgnorePublicAcls:!0,BlockPublicPolicy:!1,RestrictPublicBuckets:!1}),console.log(`S3 bucket ${S} configured`);let n=`OAC-${S}`;console.log(`Creating Origin Access Control: ${n}...`);let m=await k.findOrCreateOriginAccessControl(n);console.log(`Origin Access Control ${m.Id} ready`),console.log("Creating CloudFront distribution...");let b=await k.createDistributionForS3({bucketName:S,bucketRegion:s,originAccessControlId:m.Id,aliases:e?[e]:[],certificateArn:x,defaultRootObject:t.defaultRootObject||"index.html",comment:`Distribution for ${e||S}`});console.log(`CloudFront distribution ${b.Id} created`),console.log("Updating S3 bucket policy...");let l=y.getS3BucketPolicyForCloudFront(S,b.ARN);if(await A.putBucketPolicy(S,l),console.log("S3 bucket policy updated"),e&&w){console.log(`Creating Route53 records for ${e}...`);try{await c.createAliasRecord({HostedZoneId:w,Name:e,Type:"A",TargetHostedZoneId:h.CloudFrontHostedZoneId,TargetDNSName:b.DomainName,EvaluateTargetHealth:!1}),await c.createAliasRecord({HostedZoneId:w,Name:e,Type:"AAAA",TargetHostedZoneId:h.CloudFrontHostedZoneId,TargetDNSName:b.DomainName,EvaluateTargetHealth:!1}),console.log(`Route53 records created for ${e}`)}catch(D){console.log(`Note: Could not create Route53 records: ${D.message}`)}}return{success:!0,stackName:`direct-${b.Id}`,bucket:S,distributionId:b.Id,distributionDomain:b.DomainName,domain:e,certificateArn:x,message:"Static site infrastructure created via direct API calls"}}catch(A){return console.log(`Direct API creation failed: ${A.message}`),{success:!1,stackId:v,stackName:i,bucket:S,message:`Deployment failed: ${A.message}`}}}return{success:!1,stackId:v,stackName:i,bucket:S,message:`Stack deployment failed: ${d.message}`}}let I=(await r.describeStacks({stackName:i})).Stacks[0]?.Outputs||[],R=(d)=>I.find((k)=>k.OutputKey===d)?.OutputValue;return{success:!0,stackId:v,stackName:i,bucket:R("BucketName")||S,distributionId:R("DistributionId"),distributionDomain:R("DistributionDomain"),domain:e,certificateArn:x,message:"Static site infrastructure deployed successfully"}}async function Gi(t){let{sourceDir:s,bucket:u,region:e,cacheControl:p="max-age=31536000, public",onProgress:i}=t,r=new a(e),{readdir:c}=await import("node:fs/promises"),{join:g,relative:C}=await import("node:path"),{createHash:w}=await import("node:crypto");async function x(I){let R=[],d=await c(I,{withFileTypes:!0});for(let k of d){let A=g(I,k.name);if(k.isDirectory())R.push(...await x(A));else R.push(A)}return R}function E(I){let R=I.split(".").pop()?.toLowerCase();return{html:"text/html; charset=utf-8",css:"text/css; charset=utf-8",js:"application/javascript; charset=utf-8",json:"application/json; charset=utf-8",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",ico:"image/x-icon",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",xml:"application/xml",txt:"text/plain; charset=utf-8",sh:"text/plain; charset=utf-8",bash:"text/plain; charset=utf-8",ps1:"text/plain; charset=utf-8"}[R||""]||"application/octet-stream"}function M(I){return w("md5").update(I).digest("hex")}async function S(){let I=new Map,R;do{let d=await r.listObjects({bucket:u,maxKeys:1000,continuationToken:R});for(let k of d.objects){let A=k.ETag?.replace(/"/g,"")||"";I.set(k.Key,A)}R=d.nextContinuationToken}while(R);return I}let N=await x(s),j=[],v=0,O=0,B=await S();for(let I of N){let R=C(s,I),d=E(I),k=I.endsWith(".html")?"max-age=3600, public":p;try{let A=Buffer.from(await Bun.file(I).arrayBuffer()),o=M(A),n=B.get(R);if(n&&n===o){O++,i?.(v+O,N.length,R);continue}await r.putObject({bucket:u,key:R,body:A,contentType:d,cacheControl:k}),v++,i?.(v+O,N.length,R)}catch(A){j.push(`Failed to upload ${R}: ${A.message}`)}}return{uploaded:v,skipped:O,errors:j}}async function qi(t){return{invalidationId:(await new y().invalidateAll(t)).Id}}async function ha(t,s="us-east-1"){let u=new f(s);try{let r=((await u.describeStacks({stackName:t})).Stacks[0]?.Outputs||[]).find((c)=>c.OutputKey==="BucketName")?.OutputValue;if(r)await new a(s).emptyBucket(r)}catch{}await u.deleteStack(t);let e=await u.waitForStackComplete(t,60,1e4);return{success:e.success||e.status==="DELETE_COMPLETE",message:e.success?"Static site deleted successfully":`Deletion failed: ${e.status}`}}async function fa(t){let{sourceDir:s,cleanBucket:u=!1,onProgress:e,...p}=t;e?.("infrastructure","Deploying CloudFormation stack...");let i=await Hi(p);if(!i.success)return i;if(u){e?.("clean","Cleaning old files from S3...");try{await new a(p.region||"us-east-1").emptyBucket(i.bucket)}catch(g){console.log(`Note: Could not clean bucket: ${g.message}`)}}e?.("upload","Uploading files to S3...");let r=await Gi({sourceDir:s,bucket:i.bucket,region:p.region||"us-east-1",cacheControl:p.cacheControl,onProgress:(g,C,w)=>{e?.("upload",`${g}/${C}: ${w}`)}});if(r.errors.length>0)return{...i,success:!1,message:`Upload errors: ${r.errors.join(", ")}`,filesUploaded:r.uploaded};if(i.distributionId&&r.uploaded>0)e?.("invalidate","Invalidating CloudFront cache..."),await qi(i.distributionId);e?.("complete","Deployment complete!");let c=r.skipped>0?`Deployed ${r.uploaded} files (${r.skipped} unchanged)`:`Deployed ${r.uploaded} files successfully`;return{...i,filesUploaded:r.uploaded,filesSkipped:r.skipped,message:c}}
|
|
60
60
|
export{ma,Zr,en,Qi,Hi,Gi,qi,ha,fa};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{n}from"./chunk-30h9rgfn.js";import{a}from"./chunk-3kapcdpn.js";import{h}from"./chunk-wjgnfg6q.js";import{_e}from"./chunk-e0919h5g.js";function S(e,t){let s=[`Action=${e}`,"Version=2010-05-08"];for(let[o,i]of Object.entries(t)){if(i===void 0||i===null)continue;if(Array.isArray(i))i.forEach((c,u)=>{if(typeof c==="object"&&c!==null)for(let[d,m]of Object.entries(c))s.push(`${o}.member.${u+1}.${d}=${encodeURIComponent(String(m))}`);else s.push(`${o}.member.${u+1}=${encodeURIComponent(String(c))}`)});else if(typeof i==="object"){for(let[c,u]of Object.entries(i))if(u!==void 0&&u!==null)s.push(`${o}.${c}=${encodeURIComponent(String(u))}`)}else s.push(`${o}=${encodeURIComponent(String(i))}`)}return s.join("&")}function r(e,t){let s=new RegExp(`<${t}>([^<]*)</${t}>`),o=e.match(s);return o?o[1]:void 0}function l(e,t,s){let o=new RegExp(`<${t}>([\\s\\S]*?)</${t}>`),i=e.match(o);if(!i)return[];let c=[],u=new RegExp(`<${s}>([\\s\\S]*?)</${s}>`,"g"),d;while((d=u.exec(i[1]))!==null)c.push(d[1]);return c}class pe{client;region;constructor(e="us-east-1",t){this.client=new n(void 0,{profile:t}),this.region=e}async request(e,t={}){let s=S(e,t);return await this.client.request({service:"iam",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s})}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),s=this.parseUsers(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Users:s,IsTruncated:o,Marker:i}}async updateUser(e){await this.request("UpdateUser",e)}async deleteUser(e){await this.request("DeleteUser",e)}parseUser(e){return{UserName:r(e,"UserName")||"",UserId:r(e,"UserId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate"),PasswordLastUsed:r(e,"PasswordLastUsed")}}parseUsers(e){return l(e,"Users","member").map((s)=>({UserName:r(s,"UserName")||"",UserId:r(s,"UserId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate"),PasswordLastUsed:r(s,"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),s=this.parseGroup(t),o=this.parseUsers(t),i=r(t,"IsTruncated")==="true",c=r(t,"Marker");return{Group:s,Users:o,IsTruncated:i,Marker:c}}async listGroups(e={}){let t=await this.request("ListGroups",e),s=this.parseGroups(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Groups:s,IsTruncated:o,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),s=this.parseGroups(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Groups:s,IsTruncated:o,Marker:i}}parseGroup(e){return{GroupName:r(e,"GroupName")||"",GroupId:r(e,"GroupId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate")}}parseGroups(e){return l(e,"Groups","member").map((s)=>({GroupName:r(s,"GroupName")||"",GroupId:r(s,"GroupId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"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),s=this.parseRoles(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Roles:s,IsTruncated:o,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),s=this.parseTags(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Tags:s,IsTruncated:o,Marker:i}}parseRole(e){return{RoleName:r(e,"RoleName")||"",RoleId:r(e,"RoleId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate"),AssumeRolePolicyDocument:r(e,"AssumeRolePolicyDocument"),Description:r(e,"Description"),MaxSessionDuration:r(e,"MaxSessionDuration")?Number.parseInt(r(e,"MaxSessionDuration"),10):void 0}}parseRoles(e){return l(e,"Roles","member").map((s)=>({RoleName:r(s,"RoleName")||"",RoleId:r(s,"RoleId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate"),AssumeRolePolicyDocument:r(s,"AssumeRolePolicyDocument"),Description:r(s,"Description"),MaxSessionDuration:r(s,"MaxSessionDuration")?Number.parseInt(r(s,"MaxSessionDuration"),10):void 0}))}parseTags(e){return l(e,"Tags","member").map((s)=>({Key:r(s,"Key")||"",Value:r(s,"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:r(t,"VersionId")||"",IsDefaultVersion:r(t,"IsDefaultVersion")==="true",CreateDate:r(t,"CreateDate"),Document:r(t,"Document")}}async listPolicies(e={}){let t=await this.request("ListPolicies",e),s=this.parsePolicies(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Policies:s,IsTruncated:o,Marker:i}}async listPolicyVersions(e){let t=await this.request("ListPolicyVersions",e),s=this.parsePolicyVersions(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Versions:s,IsTruncated:o,Marker:i}}async createPolicyVersion(e){let t=await this.request("CreatePolicyVersion",e);return{VersionId:r(t,"VersionId")||"",IsDefaultVersion:r(t,"IsDefaultVersion")==="true",CreateDate:r(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),s=this.parseAttachedPolicies(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:o,Marker:i}}async listAttachedGroupPolicies(e){let t=await this.request("ListAttachedGroupPolicies",e),s=this.parseAttachedPolicies(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:o,Marker:i}}async listAttachedRolePolicies(e){let t=await this.request("ListAttachedRolePolicies",e),s=this.parseAttachedPolicies(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:o,Marker:i}}parsePolicy(e){return{PolicyName:r(e,"PolicyName")||"",PolicyId:r(e,"PolicyId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),DefaultVersionId:r(e,"DefaultVersionId"),AttachmentCount:r(e,"AttachmentCount")?Number.parseInt(r(e,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:r(e,"PermissionsBoundaryUsageCount")?Number.parseInt(r(e,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:r(e,"IsAttachable")==="true",Description:r(e,"Description"),CreateDate:r(e,"CreateDate"),UpdateDate:r(e,"UpdateDate")}}parsePolicies(e){return l(e,"Policies","member").map((s)=>({PolicyName:r(s,"PolicyName")||"",PolicyId:r(s,"PolicyId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),DefaultVersionId:r(s,"DefaultVersionId"),AttachmentCount:r(s,"AttachmentCount")?Number.parseInt(r(s,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:r(s,"PermissionsBoundaryUsageCount")?Number.parseInt(r(s,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:r(s,"IsAttachable")==="true",Description:r(s,"Description"),CreateDate:r(s,"CreateDate"),UpdateDate:r(s,"UpdateDate")}))}parsePolicyVersions(e){return l(e,"Versions","member").map((s)=>({VersionId:r(s,"VersionId")||"",IsDefaultVersion:r(s,"IsDefaultVersion")==="true",CreateDate:r(s,"CreateDate")}))}parseAttachedPolicies(e){return l(e,"AttachedPolicies","member").map((s)=>({PolicyName:r(s,"PolicyName")||"",PolicyArn:r(s,"PolicyArn")||""}))}async putUserPolicy(e){await this.request("PutUserPolicy",e)}async getUserPolicy(e){let t=await this.request("GetUserPolicy",e);return{UserName:r(t,"UserName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteUserPolicy(e){await this.request("DeleteUserPolicy",e)}async listUserPolicies(e){let t=await this.request("ListUserPolicies",e),s=l(t,"PolicyNames","member"),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:o,Marker:i}}async putGroupPolicy(e){await this.request("PutGroupPolicy",e)}async getGroupPolicy(e){let t=await this.request("GetGroupPolicy",e);return{GroupName:r(t,"GroupName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteGroupPolicy(e){await this.request("DeleteGroupPolicy",e)}async listGroupPolicies(e){let t=await this.request("ListGroupPolicies",e),s=l(t,"PolicyNames","member"),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:o,Marker:i}}async putRolePolicy(e){await this.request("PutRolePolicy",e)}async getRolePolicy(e){let t=await this.request("GetRolePolicy",e);return{RoleName:r(t,"RoleName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteRolePolicy(e){await this.request("DeleteRolePolicy",e)}async listRolePolicies(e){let t=await this.request("ListRolePolicies",e),s=l(t,"PolicyNames","member"),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:o,Marker:i}}async createAccessKey(e={}){let t=await this.request("CreateAccessKey",e);if(typeof t==="object"){let s=t?.CreateAccessKeyResult?.AccessKey||t?.AccessKey;if(s)return{AccessKey:{UserName:s.UserName||"",AccessKeyId:s.AccessKeyId||"",Status:s.Status||"Active",SecretAccessKey:s.SecretAccessKey||"",CreateDate:s.CreateDate}}}return{AccessKey:{UserName:r(t,"UserName")||"",AccessKeyId:r(t,"AccessKeyId")||"",Status:r(t,"Status")||"Active",SecretAccessKey:r(t,"SecretAccessKey")||"",CreateDate:r(t,"CreateDate")}}}async listAccessKeys(e={}){let t=await this.request("ListAccessKeys",e),s=this.parseAccessKeys(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AccessKeyMetadata:s,IsTruncated:o,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:r(t,"UserName")||"",AccessKeyLastUsed:{LastUsedDate:r(t,"LastUsedDate"),ServiceName:r(t,"ServiceName"),Region:r(t,"Region")}}}parseAccessKeys(e){return l(e,"AccessKeyMetadata","member").map((s)=>({UserName:r(s,"UserName"),AccessKeyId:r(s,"AccessKeyId")||"",Status:r(s,"Status")||"Active",CreateDate:r(s,"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),s=this.parseInstanceProfiles(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{InstanceProfiles:s,IsTruncated:o,Marker:i}}async listInstanceProfilesForRole(e){let t=await this.request("ListInstanceProfilesForRole",e),s=this.parseInstanceProfiles(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{InstanceProfiles:s,IsTruncated:o,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:r(e,"InstanceProfileName")||"",InstanceProfileId:r(e,"InstanceProfileId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate")}}parseInstanceProfiles(e){return l(e,"InstanceProfiles","member").map((s)=>({InstanceProfileName:r(s,"InstanceProfileName")||"",InstanceProfileId:r(s,"InstanceProfileId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate")}))}async getAccountPasswordPolicy(){let e=await this.request("GetAccountPasswordPolicy");return{MinimumPasswordLength:r(e,"MinimumPasswordLength")?Number.parseInt(r(e,"MinimumPasswordLength"),10):void 0,RequireSymbols:r(e,"RequireSymbols")==="true",RequireNumbers:r(e,"RequireNumbers")==="true",RequireUppercaseCharacters:r(e,"RequireUppercaseCharacters")==="true",RequireLowercaseCharacters:r(e,"RequireLowercaseCharacters")==="true",AllowUsersToChangePassword:r(e,"AllowUsersToChangePassword")==="true",ExpirePasswords:r(e,"ExpirePasswords")==="true",MaxPasswordAge:r(e,"MaxPasswordAge")?Number.parseInt(r(e,"MaxPasswordAge"),10):void 0,PasswordReusePrevention:r(e,"PasswordReusePrevention")?Number.parseInt(r(e,"PasswordReusePrevention"),10):void 0,HardExpiry:r(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={},s=l(e,"SummaryMap","entry");for(let o of s){let i=r(o,"key"),c=r(o,"value");if(i&&c)t[i]=Number.parseInt(c,10)}return t}async listAccountAliases(){let e=await this.request("ListAccountAliases"),t=l(e,"AccountAliases","member"),s=r(e,"IsTruncated")==="true",o=r(e,"Marker");return{AccountAliases:t,IsTruncated:s,Marker:o}}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 s=l(e,"EvaluationResults","member").map((c)=>{let d=l(c,"MatchedStatements","member").map((m)=>({SourcePolicyId:r(m,"SourcePolicyId"),SourcePolicyType:r(m,"SourcePolicyType")}));return{EvalActionName:r(c,"EvalActionName")||"",EvalResourceName:r(c,"EvalResourceName"),EvalDecision:r(c,"EvalDecision")||"",MatchedStatements:d.length>0?d:void 0}}),o=r(e,"IsTruncated")==="true",i=r(e,"Marker");return{EvaluationResults:s,IsTruncated:o,Marker:i}}}class Je{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",s=[];if(e?.PageSize)s.push(`PageSize=${e.PageSize}`);if(e?.NextToken)s.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(s.length>0)t+=`?${s.join("&")}`;let o=await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}});return{EmailIdentities:o.EmailIdentities,NextToken:o.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",s=[];if(e?.PageSize)s.push(`PageSize=${e.PageSize}`);if(e?.NextToken)s.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(s.length>0)t+=`?${s.join("&")}`;return await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}})}async getSendStatistics(){return{SendDataPoints:(await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendStatistics&Version=2010-12-01"})).GetSendStatisticsResponse?.GetSendStatisticsResult?.SendDataPoints?.member}}async getSendQuota(){let t=(await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendQuota&Version=2010-12-01"})).GetSendQuotaResponse?.GetSendQuotaResult;return{Max24HourSend:t?.Max24HourSend?Number(t.Max24HourSend):void 0,MaxSendRate:t?.MaxSendRate?Number(t.MaxSendRate):void 0,SentLast24Hours:t?.SentLast24Hours?Number(t.SentLast24Hours):void 0}}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],s=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0,o={};if(e.text)o.Text={Data:e.text};if(e.html)o.Html={Data:e.html};return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Simple:{Subject:{Data:e.subject},Body:o}},ReplyToAddresses:s})}async sendTemplatedEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],s=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:s})}async getDkimRecords(e){let t=await this.getEmailIdentity(e);if(!t.DkimAttributes?.Tokens)return[];return t.DkimAttributes.Tokens.map((s)=>({name:`${s}._domainkey.${e}`,type:"CNAME",value:`${s}.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,s=30000){for(let o=0;o<t;o++){if(await this.isDomainVerified(e))return!0;await new Promise((c)=>setTimeout(c,s))}return!1}buildFormBody(e){return Object.entries(e).filter(([,s])=>s!==void 0).map(([s,o])=>`${encodeURIComponent(s)}=${encodeURIComponent(o)}`).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 s=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)}),o=s?.ListReceiptRuleSetsResponse?.ListReceiptRuleSetsResult||s?.ListReceiptRuleSetsResult,i=o?.RuleSets?.member;return{RuleSets:Array.isArray(i)?i:i?[i]:[],NextToken:o?.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})}),s=t?.DescribeReceiptRuleSetResponse?.DescribeReceiptRuleSetResult||t?.DescribeReceiptRuleSetResult,o=s?.Rules?.member;return{Metadata:s?.Metadata,Rules:Array.isArray(o)?o:o?[o]:[]}}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((s,o)=>{t[`Rule.Recipients.member.${o+1}`]=s});e.Rule.Actions.forEach((s,o)=>{let i=o+1;if(s.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=s.S3Action.BucketName,s.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=s.S3Action.ObjectKeyPrefix;if(s.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=s.S3Action.KmsKeyArn}if(s.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=s.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=s.LambdaAction.InvocationType||"Event";if(s.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=s.SNSAction.TopicArn,s.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=s.SNSAction.Encoding}if(s.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=s.StopAction.Scope,s.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=s.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 s=t?.Rules?.member;return{Metadata:t?.Metadata,Rules:Array.isArray(s)?s:s?[s]:[]}}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((s,o)=>{t[`Rule.Recipients.member.${o+1}`]=s});e.Rule.Actions.forEach((s,o)=>{let i=o+1;if(s.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=s.S3Action.BucketName,s.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=s.S3Action.ObjectKeyPrefix;if(s.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=s.S3Action.KmsKeyArn}if(s.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=s.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=s.LambdaAction.InvocationType||"Event";if(s.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=s.SNSAction.TopicArn,s.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=s.SNSAction.Encoding}if(s.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=s.StopAction.Scope,s.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=s.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"),s={Action:"SendRawEmail",Version:"2010-12-01",Source:e.source,"RawMessage.Data":t};e.destinations.forEach((c,u)=>{s[`Destinations.member.${u+1}`]=c});let o=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(s)});return{MessageId:(o?.SendRawEmailResponse?.SendRawEmailResult||o?.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 ln{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 Je(this.region),this.s3=new a(this.region),this.iam=new pe(this.region),this.route53=new h(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 s=e.fromName?`${e.fromName} <${t}>`:t,o=Array.isArray(e.to)?e.to:[e.to];if(!e.attachments||e.attachments.length===0)return{messageId:(await this.ses.sendSimpleEmail({from:s,to:o,subject:e.subject,text:e.text,html:e.html,replyTo:e.replyTo})).MessageId||""};let i=this.buildRawEmail(e,s,o);return{messageId:(await this.ses.sendEmail({FromEmailAddress:s,Destination:{ToAddresses:o,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 s=e.fromName?`${e.fromName} <${t}>`:t;return{messageId:(await this.ses.sendTemplatedEmail({from:s,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 s=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:s,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 o=await this.ses.createEmailIdentity({EmailIdentity:e});t={VerificationStatus:o.DkimAttributes?.Status,DkimAttributes:o.DkimAttributes,SendingEnabled:o.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 s=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=[],s=await this.ses.getDkimRecords(e);for(let o of s)t.push({type:o.type,name:o.name,value:o.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(o){if(!o.message?.includes("already exists")&&o.code!=="AlreadyExists")throw o}let s=[{S3Action:{BucketName:e.bucketName,ObjectKeyPrefix:e.prefix||"inbox/"}}];if(e.lambdaArn)s.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:s}})}catch(o){if(o.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:s}});else throw o}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((s)=>({key:s.Key||"",lastModified:s.LastModified||"",size:s.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:s}=await import("./chunk-9w32efae.js"),o=new s,i=(g,y)=>{let P={Action:g,Version:"2010-05-08",...y};return Object.entries(P).map(([A,R])=>`${encodeURIComponent(A)}=${encodeURIComponent(R)}`).join("&")};try{await o.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateUser",{UserName:t})})}catch(g){if(!g.message?.includes("EntityAlreadyExists"))throw g}let c={Version:"2012-10-17",Statement:[{Effect:"Allow",Action:"ses:SendRawEmail",Resource:"*",Condition:{StringLike:{"ses:FromAddress":`*@${e.domain}`}}}]},u=`ses-smtp-policy-${e.domain.replace(/\./g,"-")}`;try{await o.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("PutUserPolicy",{UserName:t,PolicyName:u,PolicyDocument:JSON.stringify(c)})})}catch{}let m=(await o.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 p=this.deriveSmtpPassword(m.SecretAccessKey);return{username:m.AccessKeyId,password:p,server:`email-smtp.${this.region}.amazonaws.com`,port:587}}deriveSmtpPassword(e){let t=_e("node:crypto"),s="SendRawEmail",o=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([o,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`,s=`${e.appName}-inbound-email`,o=e.storage?.bucketName||`${e.appName}-${e.environment}-email`,i=await this.setupDomain(e.domain);if(!(await this.s3.listBuckets()).Buckets?.some((m)=>m.Name===o))await this.s3.createBucket(o);await this.setupReceiving({domain:e.domain,ruleSetName:t,ruleName:s,bucketName:o,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:o,dnsRecords:d}}async undeploy(e){let t=`${e.appName}-${e.environment}-email-rules`,s=`${e.appName}-inbound-email`,o=`${e.appName}-${e.environment}-email`;try{await this.ses.deleteReceiptRule(t,s)}catch{}try{await this.ses.deleteReceiptRuleSet(t)}catch{}if(e.deleteBucket)try{await this.s3.emptyAndDeleteBucket(o)}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,s){let o=`----=_Part_${Date.now()}_${Math.random().toString(36).substring(2)}`,i="";if(i+=`From: ${t}\r
|
|
1
|
+
import{n}from"./chunk-crpjqnjb.js";import{a}from"./chunk-rtg6nw3n.js";import{h}from"./chunk-nr1bdzwy.js";import{Le}from"./chunk-d1tv3wx0.js";function S(e,t){let s=[`Action=${e}`,"Version=2010-05-08"];for(let[o,i]of Object.entries(t)){if(i===void 0||i===null)continue;if(Array.isArray(i))i.forEach((c,u)=>{if(typeof c==="object"&&c!==null)for(let[d,m]of Object.entries(c))s.push(`${o}.member.${u+1}.${d}=${encodeURIComponent(String(m))}`);else s.push(`${o}.member.${u+1}=${encodeURIComponent(String(c))}`)});else if(typeof i==="object"){for(let[c,u]of Object.entries(i))if(u!==void 0&&u!==null)s.push(`${o}.${c}=${encodeURIComponent(String(u))}`)}else s.push(`${o}=${encodeURIComponent(String(i))}`)}return s.join("&")}function r(e,t){let s=new RegExp(`<${t}>([^<]*)</${t}>`),o=e.match(s);return o?o[1]:void 0}function l(e,t,s){let o=new RegExp(`<${t}>([\\s\\S]*?)</${t}>`),i=e.match(o);if(!i)return[];let c=[],u=new RegExp(`<${s}>([\\s\\S]*?)</${s}>`,"g"),d;while((d=u.exec(i[1]))!==null)c.push(d[1]);return c}class ge{client;region;constructor(e="us-east-1",t){this.client=new n(void 0,{profile:t}),this.region=e}async request(e,t={}){let s=S(e,t);return await this.client.request({service:"iam",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s})}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),s=this.parseUsers(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Users:s,IsTruncated:o,Marker:i}}async updateUser(e){await this.request("UpdateUser",e)}async deleteUser(e){await this.request("DeleteUser",e)}parseUser(e){return{UserName:r(e,"UserName")||"",UserId:r(e,"UserId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate"),PasswordLastUsed:r(e,"PasswordLastUsed")}}parseUsers(e){return l(e,"Users","member").map((s)=>({UserName:r(s,"UserName")||"",UserId:r(s,"UserId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate"),PasswordLastUsed:r(s,"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),s=this.parseGroup(t),o=this.parseUsers(t),i=r(t,"IsTruncated")==="true",c=r(t,"Marker");return{Group:s,Users:o,IsTruncated:i,Marker:c}}async listGroups(e={}){let t=await this.request("ListGroups",e),s=this.parseGroups(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Groups:s,IsTruncated:o,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),s=this.parseGroups(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Groups:s,IsTruncated:o,Marker:i}}parseGroup(e){return{GroupName:r(e,"GroupName")||"",GroupId:r(e,"GroupId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate")}}parseGroups(e){return l(e,"Groups","member").map((s)=>({GroupName:r(s,"GroupName")||"",GroupId:r(s,"GroupId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"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),s=this.parseRoles(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Roles:s,IsTruncated:o,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),s=this.parseTags(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Tags:s,IsTruncated:o,Marker:i}}parseRole(e){return{RoleName:r(e,"RoleName")||"",RoleId:r(e,"RoleId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate"),AssumeRolePolicyDocument:r(e,"AssumeRolePolicyDocument"),Description:r(e,"Description"),MaxSessionDuration:r(e,"MaxSessionDuration")?Number.parseInt(r(e,"MaxSessionDuration"),10):void 0}}parseRoles(e){return l(e,"Roles","member").map((s)=>({RoleName:r(s,"RoleName")||"",RoleId:r(s,"RoleId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate"),AssumeRolePolicyDocument:r(s,"AssumeRolePolicyDocument"),Description:r(s,"Description"),MaxSessionDuration:r(s,"MaxSessionDuration")?Number.parseInt(r(s,"MaxSessionDuration"),10):void 0}))}parseTags(e){return l(e,"Tags","member").map((s)=>({Key:r(s,"Key")||"",Value:r(s,"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:r(t,"VersionId")||"",IsDefaultVersion:r(t,"IsDefaultVersion")==="true",CreateDate:r(t,"CreateDate"),Document:r(t,"Document")}}async listPolicies(e={}){let t=await this.request("ListPolicies",e),s=this.parsePolicies(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Policies:s,IsTruncated:o,Marker:i}}async listPolicyVersions(e){let t=await this.request("ListPolicyVersions",e),s=this.parsePolicyVersions(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Versions:s,IsTruncated:o,Marker:i}}async createPolicyVersion(e){let t=await this.request("CreatePolicyVersion",e);return{VersionId:r(t,"VersionId")||"",IsDefaultVersion:r(t,"IsDefaultVersion")==="true",CreateDate:r(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),s=this.parseAttachedPolicies(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:o,Marker:i}}async listAttachedGroupPolicies(e){let t=await this.request("ListAttachedGroupPolicies",e),s=this.parseAttachedPolicies(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:o,Marker:i}}async listAttachedRolePolicies(e){let t=await this.request("ListAttachedRolePolicies",e),s=this.parseAttachedPolicies(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:o,Marker:i}}parsePolicy(e){return{PolicyName:r(e,"PolicyName")||"",PolicyId:r(e,"PolicyId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),DefaultVersionId:r(e,"DefaultVersionId"),AttachmentCount:r(e,"AttachmentCount")?Number.parseInt(r(e,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:r(e,"PermissionsBoundaryUsageCount")?Number.parseInt(r(e,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:r(e,"IsAttachable")==="true",Description:r(e,"Description"),CreateDate:r(e,"CreateDate"),UpdateDate:r(e,"UpdateDate")}}parsePolicies(e){return l(e,"Policies","member").map((s)=>({PolicyName:r(s,"PolicyName")||"",PolicyId:r(s,"PolicyId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),DefaultVersionId:r(s,"DefaultVersionId"),AttachmentCount:r(s,"AttachmentCount")?Number.parseInt(r(s,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:r(s,"PermissionsBoundaryUsageCount")?Number.parseInt(r(s,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:r(s,"IsAttachable")==="true",Description:r(s,"Description"),CreateDate:r(s,"CreateDate"),UpdateDate:r(s,"UpdateDate")}))}parsePolicyVersions(e){return l(e,"Versions","member").map((s)=>({VersionId:r(s,"VersionId")||"",IsDefaultVersion:r(s,"IsDefaultVersion")==="true",CreateDate:r(s,"CreateDate")}))}parseAttachedPolicies(e){return l(e,"AttachedPolicies","member").map((s)=>({PolicyName:r(s,"PolicyName")||"",PolicyArn:r(s,"PolicyArn")||""}))}async putUserPolicy(e){await this.request("PutUserPolicy",e)}async getUserPolicy(e){let t=await this.request("GetUserPolicy",e);return{UserName:r(t,"UserName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteUserPolicy(e){await this.request("DeleteUserPolicy",e)}async listUserPolicies(e){let t=await this.request("ListUserPolicies",e),s=l(t,"PolicyNames","member"),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:o,Marker:i}}async putGroupPolicy(e){await this.request("PutGroupPolicy",e)}async getGroupPolicy(e){let t=await this.request("GetGroupPolicy",e);return{GroupName:r(t,"GroupName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteGroupPolicy(e){await this.request("DeleteGroupPolicy",e)}async listGroupPolicies(e){let t=await this.request("ListGroupPolicies",e),s=l(t,"PolicyNames","member"),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:o,Marker:i}}async putRolePolicy(e){await this.request("PutRolePolicy",e)}async getRolePolicy(e){let t=await this.request("GetRolePolicy",e);return{RoleName:r(t,"RoleName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteRolePolicy(e){await this.request("DeleteRolePolicy",e)}async listRolePolicies(e){let t=await this.request("ListRolePolicies",e),s=l(t,"PolicyNames","member"),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:o,Marker:i}}async createAccessKey(e={}){let t=await this.request("CreateAccessKey",e);if(typeof t==="object"){let s=t?.CreateAccessKeyResult?.AccessKey||t?.AccessKey;if(s)return{AccessKey:{UserName:s.UserName||"",AccessKeyId:s.AccessKeyId||"",Status:s.Status||"Active",SecretAccessKey:s.SecretAccessKey||"",CreateDate:s.CreateDate}}}return{AccessKey:{UserName:r(t,"UserName")||"",AccessKeyId:r(t,"AccessKeyId")||"",Status:r(t,"Status")||"Active",SecretAccessKey:r(t,"SecretAccessKey")||"",CreateDate:r(t,"CreateDate")}}}async listAccessKeys(e={}){let t=await this.request("ListAccessKeys",e),s=this.parseAccessKeys(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AccessKeyMetadata:s,IsTruncated:o,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:r(t,"UserName")||"",AccessKeyLastUsed:{LastUsedDate:r(t,"LastUsedDate"),ServiceName:r(t,"ServiceName"),Region:r(t,"Region")}}}parseAccessKeys(e){return l(e,"AccessKeyMetadata","member").map((s)=>({UserName:r(s,"UserName"),AccessKeyId:r(s,"AccessKeyId")||"",Status:r(s,"Status")||"Active",CreateDate:r(s,"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),s=this.parseInstanceProfiles(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{InstanceProfiles:s,IsTruncated:o,Marker:i}}async listInstanceProfilesForRole(e){let t=await this.request("ListInstanceProfilesForRole",e),s=this.parseInstanceProfiles(t),o=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{InstanceProfiles:s,IsTruncated:o,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:r(e,"InstanceProfileName")||"",InstanceProfileId:r(e,"InstanceProfileId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate")}}parseInstanceProfiles(e){return l(e,"InstanceProfiles","member").map((s)=>({InstanceProfileName:r(s,"InstanceProfileName")||"",InstanceProfileId:r(s,"InstanceProfileId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate")}))}async getAccountPasswordPolicy(){let e=await this.request("GetAccountPasswordPolicy");return{MinimumPasswordLength:r(e,"MinimumPasswordLength")?Number.parseInt(r(e,"MinimumPasswordLength"),10):void 0,RequireSymbols:r(e,"RequireSymbols")==="true",RequireNumbers:r(e,"RequireNumbers")==="true",RequireUppercaseCharacters:r(e,"RequireUppercaseCharacters")==="true",RequireLowercaseCharacters:r(e,"RequireLowercaseCharacters")==="true",AllowUsersToChangePassword:r(e,"AllowUsersToChangePassword")==="true",ExpirePasswords:r(e,"ExpirePasswords")==="true",MaxPasswordAge:r(e,"MaxPasswordAge")?Number.parseInt(r(e,"MaxPasswordAge"),10):void 0,PasswordReusePrevention:r(e,"PasswordReusePrevention")?Number.parseInt(r(e,"PasswordReusePrevention"),10):void 0,HardExpiry:r(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={},s=l(e,"SummaryMap","entry");for(let o of s){let i=r(o,"key"),c=r(o,"value");if(i&&c)t[i]=Number.parseInt(c,10)}return t}async listAccountAliases(){let e=await this.request("ListAccountAliases"),t=l(e,"AccountAliases","member"),s=r(e,"IsTruncated")==="true",o=r(e,"Marker");return{AccountAliases:t,IsTruncated:s,Marker:o}}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 s=l(e,"EvaluationResults","member").map((c)=>{let d=l(c,"MatchedStatements","member").map((m)=>({SourcePolicyId:r(m,"SourcePolicyId"),SourcePolicyType:r(m,"SourcePolicyType")}));return{EvalActionName:r(c,"EvalActionName")||"",EvalResourceName:r(c,"EvalResourceName"),EvalDecision:r(c,"EvalDecision")||"",MatchedStatements:d.length>0?d:void 0}}),o=r(e,"IsTruncated")==="true",i=r(e,"Marker");return{EvaluationResults:s,IsTruncated:o,Marker:i}}}class Ye{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",s=[];if(e?.PageSize)s.push(`PageSize=${e.PageSize}`);if(e?.NextToken)s.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(s.length>0)t+=`?${s.join("&")}`;let o=await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}});return{EmailIdentities:o.EmailIdentities,NextToken:o.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",s=[];if(e?.PageSize)s.push(`PageSize=${e.PageSize}`);if(e?.NextToken)s.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(s.length>0)t+=`?${s.join("&")}`;return await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}})}async getSendStatistics(){return{SendDataPoints:(await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendStatistics&Version=2010-12-01"})).GetSendStatisticsResponse?.GetSendStatisticsResult?.SendDataPoints?.member}}async getSendQuota(){let t=(await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendQuota&Version=2010-12-01"})).GetSendQuotaResponse?.GetSendQuotaResult;return{Max24HourSend:t?.Max24HourSend?Number(t.Max24HourSend):void 0,MaxSendRate:t?.MaxSendRate?Number(t.MaxSendRate):void 0,SentLast24Hours:t?.SentLast24Hours?Number(t.SentLast24Hours):void 0}}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],s=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0,o={};if(e.text)o.Text={Data:e.text};if(e.html)o.Html={Data:e.html};return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Simple:{Subject:{Data:e.subject},Body:o}},ReplyToAddresses:s})}async sendTemplatedEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],s=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:s})}async getDkimRecords(e){let t=await this.getEmailIdentity(e);if(!t.DkimAttributes?.Tokens)return[];return t.DkimAttributes.Tokens.map((s)=>({name:`${s}._domainkey.${e}`,type:"CNAME",value:`${s}.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,s=30000){for(let o=0;o<t;o++){if(await this.isDomainVerified(e))return!0;await new Promise((c)=>setTimeout(c,s))}return!1}buildFormBody(e){return Object.entries(e).filter(([,s])=>s!==void 0).map(([s,o])=>`${encodeURIComponent(s)}=${encodeURIComponent(o)}`).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 s=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)}),o=s?.ListReceiptRuleSetsResponse?.ListReceiptRuleSetsResult||s?.ListReceiptRuleSetsResult,i=o?.RuleSets?.member;return{RuleSets:Array.isArray(i)?i:i?[i]:[],NextToken:o?.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})}),s=t?.DescribeReceiptRuleSetResponse?.DescribeReceiptRuleSetResult||t?.DescribeReceiptRuleSetResult,o=s?.Rules?.member;return{Metadata:s?.Metadata,Rules:Array.isArray(o)?o:o?[o]:[]}}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((s,o)=>{t[`Rule.Recipients.member.${o+1}`]=s});e.Rule.Actions.forEach((s,o)=>{let i=o+1;if(s.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=s.S3Action.BucketName,s.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=s.S3Action.ObjectKeyPrefix;if(s.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=s.S3Action.KmsKeyArn}if(s.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=s.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=s.LambdaAction.InvocationType||"Event";if(s.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=s.SNSAction.TopicArn,s.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=s.SNSAction.Encoding}if(s.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=s.StopAction.Scope,s.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=s.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 s=t?.Rules?.member;return{Metadata:t?.Metadata,Rules:Array.isArray(s)?s:s?[s]:[]}}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((s,o)=>{t[`Rule.Recipients.member.${o+1}`]=s});e.Rule.Actions.forEach((s,o)=>{let i=o+1;if(s.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=s.S3Action.BucketName,s.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=s.S3Action.ObjectKeyPrefix;if(s.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=s.S3Action.KmsKeyArn}if(s.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=s.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=s.LambdaAction.InvocationType||"Event";if(s.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=s.SNSAction.TopicArn,s.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=s.SNSAction.Encoding}if(s.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=s.StopAction.Scope,s.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=s.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"),s={Action:"SendRawEmail",Version:"2010-12-01",Source:e.source,"RawMessage.Data":t};e.destinations.forEach((c,u)=>{s[`Destinations.member.${u+1}`]=c});let o=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(s)});return{MessageId:(o?.SendRawEmailResponse?.SendRawEmailResult||o?.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 ln{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 Ye(this.region),this.s3=new a(this.region),this.iam=new ge(this.region),this.route53=new h(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 s=e.fromName?`${e.fromName} <${t}>`:t,o=Array.isArray(e.to)?e.to:[e.to];if(!e.attachments||e.attachments.length===0)return{messageId:(await this.ses.sendSimpleEmail({from:s,to:o,subject:e.subject,text:e.text,html:e.html,replyTo:e.replyTo})).MessageId||""};let i=this.buildRawEmail(e,s,o);return{messageId:(await this.ses.sendEmail({FromEmailAddress:s,Destination:{ToAddresses:o,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 s=e.fromName?`${e.fromName} <${t}>`:t;return{messageId:(await this.ses.sendTemplatedEmail({from:s,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 s=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:s,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 o=await this.ses.createEmailIdentity({EmailIdentity:e});t={VerificationStatus:o.DkimAttributes?.Status,DkimAttributes:o.DkimAttributes,SendingEnabled:o.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 s=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=[],s=await this.ses.getDkimRecords(e);for(let o of s)t.push({type:o.type,name:o.name,value:o.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(o){if(!o.message?.includes("already exists")&&o.code!=="AlreadyExists")throw o}let s=[{S3Action:{BucketName:e.bucketName,ObjectKeyPrefix:e.prefix||"inbox/"}}];if(e.lambdaArn)s.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:s}})}catch(o){if(o.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:s}});else throw o}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((s)=>({key:s.Key||"",lastModified:s.LastModified||"",size:s.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:s}=await import("./chunk-jpbgr1wg.js"),o=new s,i=(g,y)=>{let P={Action:g,Version:"2010-05-08",...y};return Object.entries(P).map(([A,R])=>`${encodeURIComponent(A)}=${encodeURIComponent(R)}`).join("&")};try{await o.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateUser",{UserName:t})})}catch(g){if(!g.message?.includes("EntityAlreadyExists"))throw g}let c={Version:"2012-10-17",Statement:[{Effect:"Allow",Action:"ses:SendRawEmail",Resource:"*",Condition:{StringLike:{"ses:FromAddress":`*@${e.domain}`}}}]},u=`ses-smtp-policy-${e.domain.replace(/\./g,"-")}`;try{await o.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("PutUserPolicy",{UserName:t,PolicyName:u,PolicyDocument:JSON.stringify(c)})})}catch{}let m=(await o.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 p=this.deriveSmtpPassword(m.SecretAccessKey);return{username:m.AccessKeyId,password:p,server:`email-smtp.${this.region}.amazonaws.com`,port:587}}deriveSmtpPassword(e){let t=Le("node:crypto"),s="SendRawEmail",o=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([o,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`,s=`${e.appName}-inbound-email`,o=e.storage?.bucketName||`${e.appName}-${e.environment}-email`,i=await this.setupDomain(e.domain);if(!(await this.s3.listBuckets()).Buckets?.some((m)=>m.Name===o))await this.s3.createBucket(o);await this.setupReceiving({domain:e.domain,ruleSetName:t,ruleName:s,bucketName:o,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:o,dnsRecords:d}}async undeploy(e){let t=`${e.appName}-${e.environment}-email-rules`,s=`${e.appName}-inbound-email`,o=`${e.appName}-${e.environment}-email`;try{await this.ses.deleteReceiptRule(t,s)}catch{}try{await this.ses.deleteReceiptRuleSet(t)}catch{}if(e.deleteBucket)try{await this.s3.emptyAndDeleteBucket(o)}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,s){let o=`----=_Part_${Date.now()}_${Math.random().toString(36).substring(2)}`,i="";if(i+=`From: ${t}\r
|
|
2
2
|
`,i+=`To: ${s.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
|
|
@@ -31,4 +31,4 @@ import{n}from"./chunk-30h9rgfn.js";import{a}from"./chunk-3kapcdpn.js";import{h}f
|
|
|
31
31
|
`,i+=`${c.content}\r
|
|
32
32
|
`;return i+=`--${o}--\r
|
|
33
33
|
`,i}}var Lm=new ln;
|
|
34
|
-
export{
|
|
34
|
+
export{ge,Ye,ln,Lm};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var l={mode:"detection",paranoiaLevel:1,inboundThreshold:5,outboundThreshold:4,maxBodyBytes:13107200,rejectOversizedBody:!0,auditLogPath:"/var/log/ts-cloud/waf-audit.log",blockStatus:403},d={bypassBase:1e5,exclusionBase:101000,rateLimitBase:102000,customBase:109000};function
|
|
1
|
+
var l={mode:"detection",paranoiaLevel:1,inboundThreshold:5,outboundThreshold:4,maxBodyBytes:13107200,rejectOversizedBody:!0,auditLogPath:"/var/log/ts-cloud/waf-audit.log",blockStatus:403},d={bypassBase:1e5,exclusionBase:101000,rateLimitBase:102000,customBase:109000};function W(e){return e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/[\r\n]+/g," ")}function Vn(e){if(e.length>1000)return!1;if(/\([^)]*[+*]\)[+*]/.test(e))return!1;if(/\[[^\]]*\][+*]\{/.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}function b(e,r){let t=[],o=[],s=r;for(let n of e){if(n.enabled===!1)continue;if(n.key&&(n.key.source==="cookie"||n.key.source==="header")&&!n.key.name){o.push({ruleId:n.id,reason:"The rule keys on a header or cookie but names none."});continue}let c=n.path?hs(n.path):".*";if(!Vn(c)){o.push({ruleId:n.id,reason:"The path pattern compiles to an unsafe regular expression."});continue}let u=[`SecRule REQUEST_URI "@rx ${W(c)}"`];if(n.methods?.length)u.push(` "chain,id:${s},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${W(n.id)}'"`);else u.push(` "id:${s},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${W(n.id)}'"`);if(t.push(`# Marks requests governed by the ts-cloud rate limit "${W(n.id)}".`),t.push(u.join(" \\\n")),n.methods?.length)t.push(` SecRule REQUEST_METHOD "@within ${W(n.methods.join(" ").toUpperCase())}" "t:none"`);t.push(""),s++}return{lines:t,unmapped:o}}function hs(e){return`^${e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*")}$`}function oc(e={},r=[]){let t=e.mode??l.mode,o=[],s=e.paranoiaLevel??l.paranoiaLevel,n=e.inboundThreshold??l.inboundThreshold,c=e.outboundThreshold??l.outboundThreshold,u=e.maxBodyBytes??l.maxBodyBytes,h=e.rejectOversizedBody!==!1;if(t==="blocking"&&s>=3)o.push(`Paranoia level ${s} blocks legitimate traffic on most applications until it is tuned. Run it in detection mode first.`);if(t==="blocking")o.push("zig-waf is pre-alpha. Blocking mode makes it a failure path for every request.");if(!h)o.push("Oversized bodies are passed through uninspected, so padding a request bypasses every rule.");if(e.bypassPaths?.length)o.push(`${e.bypassPaths.length} path(s) bypass inspection entirely.`);let i=["# Managed by ts-cloud. Edits are overwritten on the next deploy.",`# Mode: ${t}. Paranoia level: ${s}.`,""];if(t==="off")return i.push("SecRuleEngine Off",""),{config:`${i.join(`
|
|
2
2
|
`)}
|
|
3
|
-
`,unmappedRateLimits:[],warnings:o,mode:t};i.push(`SecRuleEngine ${t==="blocking"?"On":"DetectionOnly"}`,"SecRequestBodyAccess On","SecResponseBodyAccess Off",`SecRequestBodyLimit ${u}`,`SecRequestBodyNoFilesLimit ${Math.min(u,131072)}`,`SecRequestBodyLimitAction ${h?"Reject":"ProcessPartial"}`,"SecRequestBodyInMemoryLimit 131072",`SecAuditEngine ${t==="blocking"?"RelevantOnly":"On"}`,"SecAuditLogParts ABIJDEFHZ",`SecAuditLog ${
|
|
3
|
+
`,unmappedRateLimits:[],warnings:o,mode:t};i.push(`SecRuleEngine ${t==="blocking"?"On":"DetectionOnly"}`,"SecRequestBodyAccess On","SecResponseBodyAccess Off",`SecRequestBodyLimit ${u}`,`SecRequestBodyNoFilesLimit ${Math.min(u,131072)}`,`SecRequestBodyLimitAction ${h?"Reject":"ProcessPartial"}`,"SecRequestBodyInMemoryLimit 131072",`SecAuditEngine ${t==="blocking"?"RelevantOnly":"On"}`,"SecAuditLogParts ABIJDEFHZ",`SecAuditLog ${W(e.auditLogPath??l.auditLogPath)}`,"SecAuditLogType Serial",`SecDefaultAction "phase:1,log,auditlog,${t==="blocking"?`deny,status:${e.blockStatus??l.blockStatus}`:"pass"}"`,"","# CRS anomaly scoring setup.",`SecAction "id:900000,phase:1,pass,nolog,t:none,setvar:tx.paranoia_level=${s}"`,`SecAction "id:900001,phase:1,pass,nolog,t:none,setvar:tx.inbound_anomaly_score_threshold=${n}"`,`SecAction "id:900002,phase:1,pass,nolog,t:none,setvar:tx.outbound_anomaly_score_threshold=${c}"`,'SecAction "id:900003,phase:1,pass,nolog,t:none,setvar:tx.critical_anomaly_score=5,setvar:tx.error_anomaly_score=4,setvar:tx.warning_anomaly_score=3,setvar:tx.notice_anomaly_score=2"','SecAction "id:900004,phase:1,pass,nolog,t:none,setvar:tx.anomaly_score=0"',"");let g=d.bypassBase;for(let a of e.bypassPaths??[]){let y=hs(a);if(!Vn(y)){o.push(`Bypass path "${a}" was dropped: it compiles to an unsafe regular expression.`);continue}i.push(`# Inspection bypass for ${W(a)}. Every bypass is an unguarded route.`,`SecRule REQUEST_URI "@rx ${W(y)}" "id:${g},phase:1,pass,nolog,ctl:ruleEngine=Off"`,""),g++}let m=d.exclusionBase;for(let a of e.exclusions??[]){if(!Number.isInteger(a.ruleId)||a.ruleId<=0){o.push(`Exclusion with rule id "${a.ruleId}" was dropped: the id is not a positive integer.`);continue}if(i.push(`# ${W(a.reason)}`),a.pathPattern){if(!Vn(a.pathPattern)){o.push(`Exclusion for rule ${a.ruleId} was dropped: its path pattern is unsafe.`);continue}i.push(`SecRule REQUEST_URI "@rx ${W(a.pathPattern)}" "id:${m},phase:1,pass,nolog,ctl:ruleRemoveById=${a.ruleId}"`),m++}else i.push(`SecRuleRemoveById ${a.ruleId}`);i.push("")}let p=b(r,d.rateLimitBase);if(p.lines.length>0)i.push("# Rate-limit route markers. SecLang has no counters, so the tag is set","# here and the counting stays in the ts-cloud limiter.",...p.lines);let f=d.customBase;for(let a of e.customRules??[])i.push(`# Operator-supplied rule ${f}.`,a.trim(),""),f++;if(t==="blocking")i.push("# Blocking decision: one rule, at the end, on the accumulated score.",`SecRule TX:ANOMALY_SCORE "@ge %{tx.inbound_anomaly_score_threshold}" "id:949110,phase:2,deny,status:${e.blockStatus??l.blockStatus},log,msg:'Inbound anomaly score exceeded (total: %{tx.anomaly_score})'"`,"");return{config:`${i.join(`
|
|
4
4
|
`)}
|
|
5
5
|
`,unmappedRateLimits:p.unmapped,warnings:o,mode:t}}function jn(e={},r=[],t={}){let o=t.binary??"/usr/local/bin/zig-waf",s=t.configPath??"/etc/ts-cloud/waf.conf",n=oc(e,r);return`#!/usr/bin/env bash
|
|
6
6
|
# Managed by ts-cloud. Installs the zig-waf ruleset.
|
|
@@ -34,4 +34,4 @@ fi
|
|
|
34
34
|
mv "${s}.new" "${s}"
|
|
35
35
|
echo "ts-cloud: WAF config installed (mode: ${n.mode})"
|
|
36
36
|
`}function Ru(e,r){return e.map((t)=>({projectId:r.projectId,environmentId:r.environmentId,resourceId:r.resourceId,kind:"event",source:"zig-waf",name:t.action==="blocked"?"waf.blocked":"waf.matched",timestamp:t.timestamp,value:1,host:t.host,pathTemplate:t.path,method:t.method,attributes:{ruleId:t.ruleId??null,anomalyScore:t.anomalyScore,action:t.action,messages:t.messages.slice(0,5)}}))}
|
|
37
|
-
export{
|
|
37
|
+
export{W,Vn,hs,oc,jn,Ru};
|