@stacksjs/ts-cloud 0.16.50 → 0.16.51
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/bin/{chunk-cw3rhg1c.js → chunk-20dp8658.js} +1 -1
- package/dist/bin/{chunk-k9f94hg4.js → chunk-45thdtvf.js} +165 -165
- package/dist/bin/{chunk-7cs9nnjy.js → chunk-5c4xh61a.js} +1 -1
- package/dist/bin/chunk-67vf8myy.js +1 -0
- package/dist/bin/{chunk-e6ewfmbp.js → chunk-83brtkvn.js} +1 -1
- package/dist/bin/chunk-87g6jcfm.js +1 -0
- package/dist/bin/{chunk-11y7yang.js → chunk-93yw46n7.js} +1 -1
- package/dist/bin/{chunk-qsfhb3x7.js → chunk-9qdrv6zp.js} +1 -1
- package/dist/bin/{chunk-j2wkxp7d.js → chunk-a7hhzbvm.js} +1 -1
- package/dist/bin/{chunk-hdqxyxs0.js → chunk-cjagqdk3.js} +5 -5
- package/dist/bin/{chunk-mdkd46c5.js → chunk-d24ztt54.js} +1 -1
- package/dist/bin/{chunk-f2t67d76.js → chunk-ddyd6f14.js} +1 -1
- package/dist/bin/{chunk-y12vn1h1.js → chunk-f0vedy45.js} +1 -1
- package/dist/bin/{chunk-w89fyres.js → chunk-f578z20t.js} +1 -1
- package/dist/bin/{chunk-e7pce8jb.js → chunk-f78wmcvb.js} +1 -1
- package/dist/bin/{chunk-vavwhhrp.js → chunk-fhe0mdjg.js} +1 -1
- package/dist/bin/chunk-g6ph425d.js +1 -0
- package/dist/bin/{chunk-7jj0g6jk.js → chunk-gc199s7a.js} +4 -4
- package/dist/bin/chunk-m5jvp6ph.js +1 -0
- package/dist/bin/{chunk-9ehb4hc6.js → chunk-n5kdne4p.js} +1 -1
- package/dist/bin/{chunk-tcj1z34y.js → chunk-ngmewar1.js} +1 -1
- package/dist/bin/{chunk-xaqkj8fn.js → chunk-p6wxv8yq.js} +1 -1
- package/dist/bin/{chunk-f4mpkpbf.js → chunk-vpt43nwa.js} +1 -1
- package/dist/bin/{chunk-kmpvqby6.js → chunk-wv8060cw.js} +1 -1
- package/dist/bin/{chunk-r524t8v8.js → chunk-zywk12mp.js} +1 -1
- package/dist/bin/cli.js +16 -16
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/chunk-2gqm2h84.js +1 -0
- package/dist/{chunk-5hgcr7r2.js → chunk-53kyxata.js} +2 -2
- package/dist/{chunk-zbx9yehq.js → chunk-6gnmrtp9.js} +1 -1
- package/dist/{chunk-85fyadq0.js → chunk-dw0cvqdr.js} +13 -13
- package/dist/{chunk-a8hs75xd.js → chunk-p101nhg2.js} +1 -1
- package/dist/{chunk-18h7na1g.js → chunk-prtvb2fh.js} +27 -27
- package/dist/{chunk-cpba1hz2.js → chunk-pz33w7gv.js} +1 -1
- package/dist/{chunk-nnnhq6sx.js → chunk-qcv4twc6.js} +1 -1
- package/dist/{chunk-nmnf1ha6.js → chunk-x4qye2rc.js} +1 -1
- package/dist/{chunk-fqgvackc.js → chunk-xgc6hskd.js} +1 -1
- package/dist/deploy/index.js +1 -1
- package/dist/drivers/index.js +1 -1
- package/dist/index.js +1 -1
- package/dist/mail/index.js +2 -2
- 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 +5 -5
- package/dist/ui/data/volumes.html +5 -5
- package/dist/ui/index.html +6 -6
- package/dist/ui/infrastructure/topology.html +5 -5
- package/dist/ui/integrations.html +1 -1
- package/dist/ui/operations/alerts.html +5 -5
- package/dist/ui/operations/configuration.html +6 -6
- package/dist/ui/operations/jobs.html +6 -6
- package/dist/ui/operations/maintenance.html +6 -6
- 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 +6 -6
- 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 +6 -6
- package/dist/ui/server/activity.html +2 -2
- 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 +5 -5
- package/dist/ui/server/logs.html +5 -5
- package/dist/ui/server/metrics.html +5 -5
- package/dist/ui/server/security.html +2 -2
- package/dist/ui/server/services.html +1 -1
- package/dist/ui/server/sites.html +6 -6
- package/dist/ui/server/ssh-keys.html +6 -6
- package/dist/ui/server/team.html +6 -6
- package/dist/ui/server/terminal.html +2 -2
- package/dist/ui/serverless/alarms.html +6 -6
- package/dist/ui/serverless/assets.html +2 -2
- package/dist/ui/serverless/cost.html +2 -2
- package/dist/ui/serverless/data.html +6 -6
- package/dist/ui/serverless/deployments.html +2 -2
- package/dist/ui/serverless/firewall.html +1 -1
- package/dist/ui/serverless/functions.html +6 -6
- package/dist/ui/serverless/logs.html +6 -6
- package/dist/ui/serverless/metrics.html +2 -2
- package/dist/ui/serverless/queues.html +6 -6
- package/dist/ui/serverless/secrets.html +6 -6
- package/dist/ui/serverless/traces.html +5 -5
- package/dist/ui/serverless.html +5 -5
- package/package.json +3 -3
- package/dist/bin/chunk-512ecg6y.js +0 -1
- package/dist/bin/chunk-7ewbxsan.js +0 -1
- package/dist/bin/chunk-q9awn1n3.js +0 -1
- package/dist/bin/chunk-v2qk9jeb.js +0 -1
- package/dist/chunk-r4kedmas.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{N,zo}from"./chunk-6m8p1n88.js";import{pn,nt}from"./chunk-erfh93dq.js";var fm={};pn(fm,{default:()=>Rr,handler:()=>At});var hm={};pn(hm,{default:()=>Pr,handler:()=>Ct});var af={};pn(af,{EmailAnalyticsModule:()=>ze,EmailRules:()=>Ut,EmailScheduling:()=>Wt,EmailSearch:()=>Gt,EmailTemplates:()=>De,EmailThreading:()=>_t,SharedMailboxes:()=>Vt});var cf={};pn(cf,{default:()=>ki,handler:()=>xi});var df={};pn(df,{CallAnalytics:()=>jt,CallRecording:()=>Ht,Callbacks:()=>lt,IVRBuilder:()=>Me});var lf={};pn(lf,{AbTesting:()=>Re,LinkTracking:()=>Jt,MmsSupport:()=>zt,SmsAnalytics:()=>qt,SmsCampaigns:()=>Kt,SmsChatbot:()=>Qt});var EI={backgroundJobs:{visibilityTimeout:120,messageRetentionPeriod:604800,deadLetterQueue:!0,maxReceiveCount:3,encrypted:!0},fifo:{fifo:!0,contentBasedDeduplication:!0,visibilityTimeout:30,encrypted:!0},highThroughput:{visibilityTimeout:30,receiveMessageWaitTime:20,encrypted:!0},delayed:{delaySeconds:60,visibilityTimeout:60,encrypted:!0},longRunning:{visibilityTimeout:900,messageRetentionPeriod:1209600,deadLetterQueue:!0,maxReceiveCount:2,encrypted:!0},monitored:{visibilityTimeout:60,messageRetentionPeriod:604800,deadLetterQueue:!0,maxReceiveCount:3,encrypted:!0,alarms:{enabled:!0,queueDepthThreshold:1000,messageAgeThreshold:3600,dlqAlarm:!0}},lambdaOptimized:{visibilityTimeout:360,receiveMessageWaitTime:20,deadLetterQueue:!0,maxReceiveCount:3,encrypted:!0},fanOut:{visibilityTimeout:30,receiveMessageWaitTime:20,encrypted:!0}},vI={serverless:{development:{enabled:!0,mode:"serverless",channels:{public:!0,private:!0,presence:!0},storage:{type:"dynamodb",dynamodb:{billingMode:"PAY_PER_REQUEST"}},scaling:{maxConnections:1000,handlerMemory:128}},production:{enabled:!0,mode:"serverless",channels:{public:!0,private:!0,presence:{enabled:!0,maxMembers:100,heartbeatInterval:30,inactivityTimeout:60}},storage:{type:"dynamodb",dynamodb:{billingMode:"PAY_PER_REQUEST",pointInTimeRecovery:!0,connectionTTL:86400}},scaling:{maxConnections:50000,messagesPerSecond:5000,handlerMemory:256,handlerTimeout:30},monitoring:{enabled:!0,connectionThreshold:40000,errorThreshold:100,latencyThreshold:500},keepAlive:!0,keepAliveInterval:30,idleTimeout:600},notifications:{enabled:!0,mode:"serverless",channels:{public:!1,private:!0,presence:!1},storage:{type:"dynamodb",dynamodb:{billingMode:"PAY_PER_REQUEST"}},scaling:{maxConnections:50000,messagesPerSecond:2000,handlerMemory:128},keepAlive:!0,keepAliveInterval:60,idleTimeout:1800}},server:{development:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"ws",driver:"bun",idleTimeout:120,perMessageDeflate:!1,metrics:!1}},production:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:120,maxPayloadLength:16777216,backpressureLimit:1048576,sendPings:!0,perMessageDeflate:!0,instances:2,redis:{enabled:!0,keyPrefix:"broadcasting:"},rateLimit:{enabled:!0,max:100,window:60000,perChannel:!0,perUser:!0},loadManagement:{enabled:!0,maxConnections:1e4,maxSubscriptionsPerConnection:100,shedLoadThreshold:0.8},metrics:!0,autoScaling:{min:2,max:10,targetCPU:70}},monitoring:{enabled:!0,connectionThreshold:8000,errorThreshold:100}},highPerformance:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:60,maxPayloadLength:8388608,backpressureLimit:2097152,closeOnBackpressureLimit:!0,sendPings:!0,perMessageDeflate:!0,instances:4,redis:{enabled:!0,useElastiCache:!0,keyPrefix:"rt:"},rateLimit:{enabled:!0,max:200,window:60000,perChannel:!0},loadManagement:{enabled:!0,maxConnections:25000,maxSubscriptionsPerConnection:50,shedLoadThreshold:0.7},metrics:{enabled:!0,path:"/metrics"},autoScaling:{min:4,max:20,targetCPU:60,targetConnections:20000}},monitoring:{enabled:!0,connectionThreshold:80000,errorThreshold:50,latencyThreshold:50}},chat:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:{enabled:!0,maxMembers:200,heartbeatInterval:20,inactivityTimeout:60}},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:300,maxPayloadLength:1048576,sendPings:!0,perMessageDeflate:!0,instances:2,redis:{enabled:!0,keyPrefix:"chat:"},rateLimit:{enabled:!0,max:60,window:60000,perChannel:!0},loadManagement:{enabled:!0,maxConnections:15000,maxSubscriptionsPerConnection:20},metrics:!0},keepAlive:!0,keepAliveInterval:25,idleTimeout:900},gaming:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:{enabled:!0,maxMembers:100,heartbeatInterval:10,inactivityTimeout:30}},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:30,maxPayloadLength:65536,backpressureLimit:524288,closeOnBackpressureLimit:!0,sendPings:!0,perMessageDeflate:!1,instances:4,redis:{enabled:!0,useElastiCache:!0},rateLimit:{enabled:!0,max:120,window:60000},loadManagement:{enabled:!0,maxConnections:5000,maxSubscriptionsPerConnection:10,shedLoadThreshold:0.6},metrics:!0,autoScaling:{min:4,max:16,targetCPU:50}},keepAlive:!0,keepAliveInterval:10,idleTimeout:60},single:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:120,sendPings:!0,perMessageDeflate:!0,instances:1,rateLimit:{enabled:!0,max:100,window:60000},loadManagement:{enabled:!0,maxConnections:1e4},metrics:!0}}}};import{isAbsolute as bt,join as Qe,relative as pr}from"node:path";var qd=".ts-cloud",nm="TS_CLOUD_STATE_DIR",St=null;function jd(n){St=n?.trim()||null}function zd(){return Boolean(process.env[nm]?.trim()||St)}function sn(){return process.env[nm]?.trim()||St||qd}function Q(...n){return Qe(sn(),...n)}function l(n,...i){let s=sn();return bt(s)?Qe(s,...i):Qe(n,s,...i)}function Kd(n,i=process.cwd()){let s=(c,u)=>{let d=pr(c,u);return d===""||!d.startsWith("..")&&!bt(d)},o=bt(n)?n:Qe(i,n);return s(l(i),o)}function im(n){let i=n.infrastructure?.compute!=null,s=Object.values(n.environments??{}).some((o)=>o?.app!=null);return{server:i,serverless:s}}function K(n){if(n.mode==="server"||n.mode==="serverless")return n.mode;let{serverless:i}=im(n);return i?"serverless":"server"}function Wd(n){let{server:i,serverless:s}=im(n);if(i&&s)return"A project cannot be both a server and a serverless deployment. Found `infrastructure.compute` (server) AND `environments.<env>.app` (serverless Lambda). Keep one: remove `infrastructure.compute` for a serverless app, or remove `environments.<env>.app` for a server.";if(n.mode==="server"&&s&&!i)return"Config sets `mode: 'server'` but declares a serverless app (`environments.<env>.app`). Remove the app or change the mode.";if(n.mode==="serverless"&&i&&!s)return"Config sets `mode: 'serverless'` but declares a server (`infrastructure.compute`). Remove the compute block or change the mode.";return null}function g(n){return n.infrastructure?.appDatabase??n.infrastructure?.compute?.database}function yr(n){return typeof n==="object"&&n!==null?n:{}}function HA(n){return n===!0||typeof n==="object"&&n!==null}function fr(n,i){let s=i?n.environments?.[i]:void 0;if(s?.domain)return s.domain;let o=Object.values(n.sites??{}),c=n.sites?.main?.domain??o.find((u)=>u.domain)?.domain;if(c)return c;return`${n.project?.slug??"app"}.local`}function hr(n){let i=n.indexOf(".");return i>0?n.slice(i+1):void 0}function b(n,i={}){let s=n.infrastructure?.compute?.managedServices?.mail,o=yr(s),c=i.environmentType??(i.environment?n.environments?.[i.environment]?.type:void 0),u=o.mode??(c==="production"?"server":"catcher"),d=u==="server",f=fr(n,i.environment),h=o.hostname??(d?`mail.${f}`:"localhost"),S=o.ports??{},A=d?{smtp:S.smtp??25,submission:S.submission??587,submissions:S.submissions??465,imap:S.imap??143,imaps:S.imaps??993,webmail:S.webmail??8080,managesieve:S.managesieve}:{smtp:S.smtp??1025,submission:S.submission,submissions:S.submissions,imap:S.imap,imaps:S.imaps,webmail:S.webmail??8025,managesieve:S.managesieve},T=o.tls??{},v=T.enabled??d,R=!!(T.certPath&&T.keyPath),P=(o.accounts??[]).map((ue)=>({address:ue.address,password:ue.password,passwordPolicy:ue.passwordPolicy??"initial"})),E=typeof o.dkim==="object"&&o.dkim!==null?o.dkim:{},I=o.dkim===!1?!1:o.dkim===!0||d,M=typeof o.webmail==="object"&&o.webmail!==null?o.webmail:{},L=o.webmail===!1?!1:M.enabled??!0,x=h.includes(".")&&!h.endsWith(".local")&&!/^\d+\.\d+\.\d+\.\d+$/.test(h),O=M.domain===!1?void 0:M.domain??(d&&x?h:void 0),B=M.tls??(O?!1:v),F=[...new Set(M.aliases??[])].filter((ue)=>ue!==O),U=o.spam??{},j=o.delivery??(d?"direct":"none"),H=o.expose??d,z=hr(h),se=[...new Set([h,...z?[z]:[],...o.domains??[]])];return{enabled:HA(s),mode:u,version:o.version,hostname:h,domains:se,ports:A,tls:{enabled:v,acme:v&&!R&&(T.acme??!0),certPath:T.certPath,keyPath:T.keyPath,requireForAuth:T.requireForAuth??(v&&d),acmeEmail:T.acmeEmail??P[0]?.address},dkim:{enabled:I,selector:E.selector??"default",rotate:E.rotate??!1,rotateIntervalDays:E.rotateIntervalDays??90},webmail:{enabled:L,port:M.port??A.webmail,domain:O,aliases:F,tls:B,secureCookies:M.secureCookies??(!!O||B)},delivery:j,sesRegion:o.sesRegion??"us-east-1",accounts:P,storagePath:o.storagePath??"/var/lib/mail",maxMessageSize:o.maxMessageSize??26214400,spam:{enabled:U.enabled??d,enforce:U.enforce??!1,junkScore:U.junkScore??5,rejectScore:U.rejectScore??12,dnsbl:U.dnsbl??d,greylist:U.greylist??!1},webhookUrl:o.webhookUrl,expose:H,bindAddress:H?"0.0.0.0":"127.0.0.1"}}function Xe(n){if(!n.enabled||!n.expose)return[];let i=[n.ports.smtp,n.ports.submission,n.ports.submissions,n.ports.imap,n.ports.imaps,n.ports.managesieve].filter((s)=>typeof s==="number");if(n.webmail.enabled&&!n.webmail.domain)i.push(n.webmail.port);return[...new Set(i)].sort((s,o)=>s-o)}function Hi(n){if(!n.enabled)return{};let i=n.ports.submission??n.ports.smtp,s={MAIL_MAILER:"smtp",MAIL_HOST:"127.0.0.1",MAIL_PORT:String(i)};if(n.mode==="server"){s.MAIL_ENCRYPTION=n.tls.enabled?"tls":"null";let o=n.accounts[0];if(o)s.MAIL_USERNAME=o.address,s.MAIL_PASSWORD=o.password}else s.MAIL_ENCRYPTION="null",s.MAIL_USERNAME="null",s.MAIL_PASSWORD="null";return s}function on(n){if(!n.enabled||!n.webmail.enabled||!n.webmail.domain)return{};let i=[n.webmail.domain,...n.webmail.aliases];if(!Number.isInteger(n.webmail.port)||n.webmail.port<1||n.webmail.port>65535)throw Error("Mail webmail port must be between 1 and 65535");return Object.fromEntries(i.map((s,o)=>{if(!/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(s))throw Error(`Invalid mail webmail hostname: ${s}`);return[`__mail_webmail_${o}`,{domain:s,proxyTo:`localhost:${n.webmail.port}`}]}))}function w(n,i={}){let s=n.infrastructure?.compute?.proxy,o=b(n,i);if(!o.enabled||!o.webmail.enabled||!o.webmail.domain)return s;return{engine:"rpx",onDemandTls:!0,onDemandTlsEmail:o.tls.acmeEmail??`webmaster@${o.webmail.domain}`,...s}}function be(n){if(n.cloud?.provider)return n.cloud.provider;if(n.ssh?.hosts?.length)return"ssh";if(n.hetzner?.apiToken)return"hetzner";return"aws"}class Jd{template;constructor(n){this.template={AWSTemplateFormatVersion:"2010-09-09",Description:n,Resources:{}}}addResource(n,i){return this.template.Resources[n]=i,this}addResources(n){return Object.assign(this.template.Resources,n),this}addParameter(n,i){if(!this.template.Parameters)this.template.Parameters={};return this.template.Parameters[n]=i,this}addOutput(n,i){if(!this.template.Outputs)this.template.Outputs={};return this.template.Outputs[n]=i,this}addMetadata(n,i){if(!this.template.Metadata)this.template.Metadata={};return this.template.Metadata[n]=i,this}hasResource(n){return n in this.template.Resources}getResources(){return this.template.Resources}build(){return this.template}toJSON(n=!0){return JSON.stringify(this.template,null,n?2:0)}toYAML(){return this.convertToYAML(this.template)}convertToYAML(n,i=0){let s=" ".repeat(i),o="";for(let[c,u]of Object.entries(n)){if(u===null||u===void 0)continue;if(typeof u==="object"&&!Array.isArray(u))o+=`${s}${c}:
|
|
1
|
+
import{N,zo}from"./chunk-6m8p1n88.js";import{pn,nt}from"./chunk-erfh93dq.js";var fm={};pn(fm,{default:()=>Rr,handler:()=>At});var hm={};pn(hm,{default:()=>Pr,handler:()=>Ct});var af={};pn(af,{EmailAnalyticsModule:()=>it,EmailRules:()=>Ut,EmailScheduling:()=>Wt,EmailSearch:()=>Gt,EmailTemplates:()=>ke,EmailThreading:()=>_t,SharedMailboxes:()=>Vt});var cf={};pn(cf,{default:()=>ki,handler:()=>xi});var df={};pn(df,{CallAnalytics:()=>jt,CallRecording:()=>Ht,Callbacks:()=>mt,IVRBuilder:()=>Be});var lf={};pn(lf,{AbTesting:()=>Ee,LinkTracking:()=>Jt,MmsSupport:()=>zt,SmsAnalytics:()=>qt,SmsCampaigns:()=>Kt,SmsChatbot:()=>Qt});var EI={backgroundJobs:{visibilityTimeout:120,messageRetentionPeriod:604800,deadLetterQueue:!0,maxReceiveCount:3,encrypted:!0},fifo:{fifo:!0,contentBasedDeduplication:!0,visibilityTimeout:30,encrypted:!0},highThroughput:{visibilityTimeout:30,receiveMessageWaitTime:20,encrypted:!0},delayed:{delaySeconds:60,visibilityTimeout:60,encrypted:!0},longRunning:{visibilityTimeout:900,messageRetentionPeriod:1209600,deadLetterQueue:!0,maxReceiveCount:2,encrypted:!0},monitored:{visibilityTimeout:60,messageRetentionPeriod:604800,deadLetterQueue:!0,maxReceiveCount:3,encrypted:!0,alarms:{enabled:!0,queueDepthThreshold:1000,messageAgeThreshold:3600,dlqAlarm:!0}},lambdaOptimized:{visibilityTimeout:360,receiveMessageWaitTime:20,deadLetterQueue:!0,maxReceiveCount:3,encrypted:!0},fanOut:{visibilityTimeout:30,receiveMessageWaitTime:20,encrypted:!0}},vI={serverless:{development:{enabled:!0,mode:"serverless",channels:{public:!0,private:!0,presence:!0},storage:{type:"dynamodb",dynamodb:{billingMode:"PAY_PER_REQUEST"}},scaling:{maxConnections:1000,handlerMemory:128}},production:{enabled:!0,mode:"serverless",channels:{public:!0,private:!0,presence:{enabled:!0,maxMembers:100,heartbeatInterval:30,inactivityTimeout:60}},storage:{type:"dynamodb",dynamodb:{billingMode:"PAY_PER_REQUEST",pointInTimeRecovery:!0,connectionTTL:86400}},scaling:{maxConnections:50000,messagesPerSecond:5000,handlerMemory:256,handlerTimeout:30},monitoring:{enabled:!0,connectionThreshold:40000,errorThreshold:100,latencyThreshold:500},keepAlive:!0,keepAliveInterval:30,idleTimeout:600},notifications:{enabled:!0,mode:"serverless",channels:{public:!1,private:!0,presence:!1},storage:{type:"dynamodb",dynamodb:{billingMode:"PAY_PER_REQUEST"}},scaling:{maxConnections:50000,messagesPerSecond:2000,handlerMemory:128},keepAlive:!0,keepAliveInterval:60,idleTimeout:1800}},server:{development:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"ws",driver:"bun",idleTimeout:120,perMessageDeflate:!1,metrics:!1}},production:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:120,maxPayloadLength:16777216,backpressureLimit:1048576,sendPings:!0,perMessageDeflate:!0,instances:2,redis:{enabled:!0,keyPrefix:"broadcasting:"},rateLimit:{enabled:!0,max:100,window:60000,perChannel:!0,perUser:!0},loadManagement:{enabled:!0,maxConnections:1e4,maxSubscriptionsPerConnection:100,shedLoadThreshold:0.8},metrics:!0,autoScaling:{min:2,max:10,targetCPU:70}},monitoring:{enabled:!0,connectionThreshold:8000,errorThreshold:100}},highPerformance:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:60,maxPayloadLength:8388608,backpressureLimit:2097152,closeOnBackpressureLimit:!0,sendPings:!0,perMessageDeflate:!0,instances:4,redis:{enabled:!0,useElastiCache:!0,keyPrefix:"rt:"},rateLimit:{enabled:!0,max:200,window:60000,perChannel:!0},loadManagement:{enabled:!0,maxConnections:25000,maxSubscriptionsPerConnection:50,shedLoadThreshold:0.7},metrics:{enabled:!0,path:"/metrics"},autoScaling:{min:4,max:20,targetCPU:60,targetConnections:20000}},monitoring:{enabled:!0,connectionThreshold:80000,errorThreshold:50,latencyThreshold:50}},chat:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:{enabled:!0,maxMembers:200,heartbeatInterval:20,inactivityTimeout:60}},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:300,maxPayloadLength:1048576,sendPings:!0,perMessageDeflate:!0,instances:2,redis:{enabled:!0,keyPrefix:"chat:"},rateLimit:{enabled:!0,max:60,window:60000,perChannel:!0},loadManagement:{enabled:!0,maxConnections:15000,maxSubscriptionsPerConnection:20},metrics:!0},keepAlive:!0,keepAliveInterval:25,idleTimeout:900},gaming:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:{enabled:!0,maxMembers:100,heartbeatInterval:10,inactivityTimeout:30}},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:30,maxPayloadLength:65536,backpressureLimit:524288,closeOnBackpressureLimit:!0,sendPings:!0,perMessageDeflate:!1,instances:4,redis:{enabled:!0,useElastiCache:!0},rateLimit:{enabled:!0,max:120,window:60000},loadManagement:{enabled:!0,maxConnections:5000,maxSubscriptionsPerConnection:10,shedLoadThreshold:0.6},metrics:!0,autoScaling:{min:4,max:16,targetCPU:50}},keepAlive:!0,keepAliveInterval:10,idleTimeout:60},single:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:120,sendPings:!0,perMessageDeflate:!0,instances:1,rateLimit:{enabled:!0,max:100,window:60000},loadManagement:{enabled:!0,maxConnections:1e4},metrics:!0}}}};import{isAbsolute as bt,join as at,relative as pr}from"node:path";var qd=".ts-cloud",nm="TS_CLOUD_STATE_DIR",St=null;function jd(n){St=n?.trim()||null}function zd(){return Boolean(process.env[nm]?.trim()||St)}function sn(){return process.env[nm]?.trim()||St||qd}function Q(...n){return at(sn(),...n)}function l(n,...i){let s=sn();return bt(s)?at(s,...i):at(n,s,...i)}function Kd(n,i=process.cwd()){let s=(c,u)=>{let d=pr(c,u);return d===""||!d.startsWith("..")&&!bt(d)},o=bt(n)?n:at(i,n);return s(l(i),o)}function im(n){let i=n.infrastructure?.compute!=null,s=Object.values(n.environments??{}).some((o)=>o?.app!=null);return{server:i,serverless:s}}function K(n){if(n.mode==="server"||n.mode==="serverless")return n.mode;let{serverless:i}=im(n);return i?"serverless":"server"}function Wd(n){let{server:i,serverless:s}=im(n);if(i&&s)return"A project cannot be both a server and a serverless deployment. Found `infrastructure.compute` (server) AND `environments.<env>.app` (serverless Lambda). Keep one: remove `infrastructure.compute` for a serverless app, or remove `environments.<env>.app` for a server.";if(n.mode==="server"&&s&&!i)return"Config sets `mode: 'server'` but declares a serverless app (`environments.<env>.app`). Remove the app or change the mode.";if(n.mode==="serverless"&&i&&!s)return"Config sets `mode: 'serverless'` but declares a server (`infrastructure.compute`). Remove the compute block or change the mode.";return null}function g(n){return n.infrastructure?.appDatabase??n.infrastructure?.compute?.database}function yr(n){return typeof n==="object"&&n!==null?n:{}}function HA(n){return n===!0||typeof n==="object"&&n!==null}function fr(n,i){let s=i?n.environments?.[i]:void 0;if(s?.domain)return s.domain;let o=Object.values(n.sites??{}),c=n.sites?.main?.domain??o.find((u)=>u.domain)?.domain;if(c)return c;return`${n.project?.slug??"app"}.local`}function hr(n){let i=n.indexOf(".");return i>0?n.slice(i+1):void 0}function b(n,i={}){let s=n.infrastructure?.compute?.managedServices?.mail,o=yr(s),c=i.environmentType??(i.environment?n.environments?.[i.environment]?.type:void 0),u=o.mode??(c==="production"?"server":"catcher"),d=u==="server",f=fr(n,i.environment),h=o.hostname??(d?`mail.${f}`:"localhost"),S=o.ports??{},A=d?{smtp:S.smtp??25,submission:S.submission??587,submissions:S.submissions??465,imap:S.imap??143,imaps:S.imaps??993,webmail:S.webmail??8080,managesieve:S.managesieve}:{smtp:S.smtp??1025,submission:S.submission,submissions:S.submissions,imap:S.imap,imaps:S.imaps,webmail:S.webmail??8025,managesieve:S.managesieve},T=o.tls??{},v=T.enabled??d,R=!!(T.certPath&&T.keyPath),P=(o.accounts??[]).map((me)=>({address:me.address,password:me.password,passwordPolicy:me.passwordPolicy??"initial"})),E=typeof o.dkim==="object"&&o.dkim!==null?o.dkim:{},I=o.dkim===!1?!1:o.dkim===!0||d,M=typeof o.webmail==="object"&&o.webmail!==null?o.webmail:{},L=o.webmail===!1?!1:M.enabled??!0,x=h.includes(".")&&!h.endsWith(".local")&&!/^\d+\.\d+\.\d+\.\d+$/.test(h),O=M.domain===!1?void 0:M.domain??(d&&x?h:void 0),B=M.tls??(O?!1:v),F=[...new Set(M.aliases??[])].filter((me)=>me!==O),U=o.spam??{},j=o.delivery??(d?"direct":"none"),H=o.expose??d,z=hr(h),ae=[...new Set([h,...z?[z]:[],...o.domains??[]])],Te=M.attachments?.maxFileBytes??20971520,oe=M.attachments?.maxTotalBytes??20971520,pe=M.attachments?.maxCount??20,se=M.undoSendSeconds??10;for(let[me,Ie,Le]of[["maxFileBytes",Te,104857600],["maxTotalBytes",oe,104857600],["maxCount",pe,100],["undoSendSeconds",se,30]])if(!Number.isInteger(Ie)||Ie<0||Ie>Le)throw Error(`Mail webmail ${me} must be an integer from 0 to ${Le}`);return{enabled:HA(s),mode:u,version:o.version,hostname:h,domains:ae,ports:A,tls:{enabled:v,acme:v&&!R&&(T.acme??!0),certPath:T.certPath,keyPath:T.keyPath,requireForAuth:T.requireForAuth??(v&&d),acmeEmail:T.acmeEmail??P[0]?.address},dkim:{enabled:I,selector:E.selector??"default",rotate:E.rotate??!1,rotateIntervalDays:E.rotateIntervalDays??90},webmail:{enabled:L,port:M.port??A.webmail,domain:O,aliases:F,tls:B,secureCookies:M.secureCookies??(!!O||B),attachmentMaxFileBytes:Te,attachmentMaxTotalBytes:oe,attachmentMaxCount:pe,undoSendSeconds:se},delivery:j,sesRegion:o.sesRegion??"us-east-1",accounts:P,storagePath:o.storagePath??"/var/lib/mail",maxMessageSize:o.maxMessageSize??26214400,spam:{enabled:U.enabled??d,enforce:U.enforce??!1,junkScore:U.junkScore??5,rejectScore:U.rejectScore??12,dnsbl:U.dnsbl??d,greylist:U.greylist??!1},webhookUrl:o.webhookUrl,expose:H,bindAddress:H?"0.0.0.0":"127.0.0.1"}}function Xe(n){if(!n.enabled||!n.expose)return[];let i=[n.ports.smtp,n.ports.submission,n.ports.submissions,n.ports.imap,n.ports.imaps,n.ports.managesieve].filter((s)=>typeof s==="number");if(n.webmail.enabled&&!n.webmail.domain)i.push(n.webmail.port);return[...new Set(i)].sort((s,o)=>s-o)}function Hi(n){if(!n.enabled)return{};let i=n.ports.submission??n.ports.smtp,s={MAIL_MAILER:"smtp",MAIL_HOST:"127.0.0.1",MAIL_PORT:String(i)};if(n.mode==="server"){s.MAIL_ENCRYPTION=n.tls.enabled?"tls":"null";let o=n.accounts[0];if(o)s.MAIL_USERNAME=o.address,s.MAIL_PASSWORD=o.password}else s.MAIL_ENCRYPTION="null",s.MAIL_USERNAME="null",s.MAIL_PASSWORD="null";return s}function on(n){if(!n.enabled||!n.webmail.enabled||!n.webmail.domain)return{};let i=[n.webmail.domain,...n.webmail.aliases];if(!Number.isInteger(n.webmail.port)||n.webmail.port<1||n.webmail.port>65535)throw Error("Mail webmail port must be between 1 and 65535");return Object.fromEntries(i.map((s,o)=>{if(!/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(s))throw Error(`Invalid mail webmail hostname: ${s}`);return[`__mail_webmail_${o}`,{domain:s,proxyTo:`localhost:${n.webmail.port}`}]}))}function w(n,i={}){let s=n.infrastructure?.compute?.proxy,o=b(n,i);if(!o.enabled||!o.webmail.enabled||!o.webmail.domain)return s;return{engine:"rpx",onDemandTls:!0,onDemandTlsEmail:o.tls.acmeEmail??`webmaster@${o.webmail.domain}`,...s}}function be(n){if(n.cloud?.provider)return n.cloud.provider;if(n.ssh?.hosts?.length)return"ssh";if(n.hetzner?.apiToken)return"hetzner";return"aws"}class Jd{template;constructor(n){this.template={AWSTemplateFormatVersion:"2010-09-09",Description:n,Resources:{}}}addResource(n,i){return this.template.Resources[n]=i,this}addResources(n){return Object.assign(this.template.Resources,n),this}addParameter(n,i){if(!this.template.Parameters)this.template.Parameters={};return this.template.Parameters[n]=i,this}addOutput(n,i){if(!this.template.Outputs)this.template.Outputs={};return this.template.Outputs[n]=i,this}addMetadata(n,i){if(!this.template.Metadata)this.template.Metadata={};return this.template.Metadata[n]=i,this}hasResource(n){return n in this.template.Resources}getResources(){return this.template.Resources}build(){return this.template}toJSON(n=!0){return JSON.stringify(this.template,null,n?2:0)}toYAML(){return this.convertToYAML(this.template)}convertToYAML(n,i=0){let s=" ".repeat(i),o="";for(let[c,u]of Object.entries(n)){if(u===null||u===void 0)continue;if(typeof u==="object"&&!Array.isArray(u))o+=`${s}${c}:
|
|
2
2
|
${this.convertToYAML(u,i+1)}`;else if(Array.isArray(u)){o+=`${s}${c}:
|
|
3
3
|
`;for(let d of u)if(typeof d==="object")o+=`${s} -
|
|
4
4
|
${this.convertToYAML(d,i+2)}`;else o+=`${s} - ${d}
|
|
@@ -8,7 +8,7 @@ ${this.convertToYAML(d,i+2)}`;else o+=`${s} - ${d}
|
|
|
8
8
|
`),i.join(`
|
|
9
9
|
`);if(i.push(`Total changes: ${n.summary.totalChanges}`),i.push(`Requires replacement: ${n.summary.requiresReplacement?"Yes":"No"}
|
|
10
10
|
`),n.summary.dangerousChanges.length>0){i.push("⚠️ DANGEROUS CHANGES DETECTED:");for(let s of n.summary.dangerousChanges)i.push(` • ${s}`);i.push("")}if(n.added.length>0){i.push(`✅ Resources to Add (${n.added.length}):`);for(let s of n.added)i.push(` + ${s.logicalId} (${s.resourceType})`);i.push("")}if(n.removed.length>0){i.push(`❌ Resources to Remove (${n.removed.length}):`);for(let s of n.removed)i.push(` - ${s.logicalId} (${s.resourceType})`);i.push("")}if(n.replaced.length>0){i.push(`\uD83D\uDD04 Resources to Replace (${n.replaced.length}):`);for(let s of n.replaced){if(i.push(` ~ ${s.logicalId} (${s.resourceType})`),s.reason)i.push(` Reason: ${s.reason}`);if(s.changes){for(let o of s.changes.slice(0,3))i.push(` • ${o.path}: ${JSON.stringify(o.oldValue)} → ${JSON.stringify(o.newValue)}`);if(s.changes.length>3)i.push(` ... and ${s.changes.length-3} more changes`)}}i.push("")}if(n.updated.length>0){i.push(`\uD83D\uDCDD Resources to Update (${n.updated.length}):`);for(let s of n.updated)if(i.push(` ~ ${s.logicalId} (${s.resourceType})`),s.changes){for(let o of s.changes.slice(0,3))i.push(` • ${o.path}: ${JSON.stringify(o.oldValue)} → ${JSON.stringify(o.newValue)}`);if(s.changes.length>3)i.push(` ... and ${s.changes.length-3} more changes`)}i.push("")}if(n.unchanged.length>0)i.push(`⚪ Unchanged Resources (${n.unchanged.length})`);return i.join(`
|
|
11
|
-
`)}import{existsSync as We,readdirSync as Ar}from"node:fs";import{join as Te}from"node:path";class xe{static createBucket(n){let{name:i,bucketName:s,slug:o,environment:c,public:u=!1,versioning:d=!1,website:f=!1,encryption:h=!0,intelligentTiering:S=!1,cors:A,lifecycleRules:T}=n,v=s??r({slug:o,environment:c,resourceType:"s3",suffix:i}),R=t(v),P={Type:"AWS::S3::Bucket",Properties:{BucketName:v}};if(h)P.Properties.BucketEncryption={ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]};if(d)P.Properties.VersioningConfiguration={Status:"Enabled"};if(f)P.Properties.WebsiteConfiguration={IndexDocument:"index.html",ErrorDocument:"error.html"};if(!u)P.Properties.PublicAccessBlockConfiguration={BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0};if(A&&A.length>0)P.Properties.CorsConfiguration={CorsRules:A.map((I)=>({AllowedOrigins:I.allowedOrigins,AllowedMethods:I.allowedMethods,AllowedHeaders:I.allowedHeaders,MaxAge:I.maxAge}))};if(T&&T.length>0)P.Properties.LifecycleConfiguration={Rules:T.map((I)=>({Id:I.id,Status:I.enabled?"Enabled":"Disabled",ExpirationInDays:I.expirationDays,Transitions:I.transitions?.map((M)=>({TransitionInDays:M.days,StorageClass:M.storageClass}))}))};if(S&&T){let I={id:"IntelligentTieringRule",enabled:!0,transitions:[{days:0,storageClass:"INTELLIGENT_TIERING"}]};if(!P.Properties.LifecycleConfiguration)P.Properties.LifecycleConfiguration={Rules:[]};P.Properties.LifecycleConfiguration.Rules.push({Id:I.id,Status:"Enabled",Transitions:I.transitions?.map((M)=>({TransitionInDays:M.days,StorageClass:M.storageClass}))})}let E;if(u)E={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:k.Ref(R),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadGetObject",Effect:"Allow",Principal:"*",Action:["s3:GetObject"],Resource:[k.Join("",[k.GetAtt(R,"Arn"),"/*"])]}]}}};return{bucket:P,bucketPolicy:E,logicalId:R}}static enableVersioning(n){if(!n.Properties)n.Properties={};return n.Properties.VersioningConfiguration={Status:"Enabled"},n}static enableWebsiteHosting(n,i="index.html",s="error.html"){if(!n.Properties)n.Properties={};return n.Properties.WebsiteConfiguration={IndexDocument:i,ErrorDocument:s},n}static setLifecycleRules(n,i){if(!n.Properties)n.Properties={};return n.Properties.LifecycleConfiguration={Rules:i.map((s)=>({Id:s.id,Status:s.enabled?"Enabled":"Disabled",ExpirationInDays:s.expirationDays,Transitions:s.transitions?.map((o)=>({TransitionInDays:o.days,StorageClass:o.storageClass}))}))},n}static enableIntelligentTiering(n){if(!n.Properties)n.Properties={};if(!n.Properties.LifecycleConfiguration)n.Properties.LifecycleConfiguration={Rules:[]};return n.Properties.LifecycleConfiguration.Rules.push({Id:"IntelligentTieringRule",Status:"Enabled",Transitions:[{TransitionInDays:0,StorageClass:"INTELLIGENT_TIERING"}]}),n}static addLambdaNotification(n,i){if(!n.Properties)n.Properties={};if(!n.Properties.NotificationConfiguration)n.Properties.NotificationConfiguration={};if(!n.Properties.NotificationConfiguration.LambdaConfigurations)n.Properties.NotificationConfiguration.LambdaConfigurations=[];let s={Event:i.events[0],Function:i.functionArn};if(i.filter)s.Filter={S3Key:{Rules:[...i.filter.prefix?[{Name:"prefix",Value:i.filter.prefix}]:[],...i.filter.suffix?[{Name:"suffix",Value:i.filter.suffix}]:[]]}};for(let o of i.events){let c={...s,Event:o};n.Properties.NotificationConfiguration.LambdaConfigurations.push(c)}return n}static Notifications={onObjectCreated:(n)=>({functionArn:n,events:["s3:ObjectCreated:*"]}),onObjectRemoved:(n)=>({functionArn:n,events:["s3:ObjectRemoved:*"]}),onImageUpload:(n,i)=>({functionArn:n,events:["s3:ObjectCreated:*"],filter:{prefix:i,suffix:".jpg"}}),onFileType:(n,i,s)=>({functionArn:n,events:["s3:ObjectCreated:*"],filter:{prefix:s,suffix:i}}),onFolderUpload:(n,i)=>({functionArn:n,events:["s3:ObjectCreated:*"],filter:{prefix:i.endsWith("/")?i:`${i}/`}})};static createBackupPlan(n){let{name:i,slug:s,environment:o,bucketLogicalIds:c,retentionDays:u,schedule:d="cron(0 5 * * ? *)",vaultName:f,enableContinuousBackup:h=!1,moveToColdStorageAfterDays:S}=n,A=f||r({slug:s,environment:o,resourceType:"backup-vault",suffix:i}),T=t(A),v={Type:"AWS::Backup::BackupVault",Properties:{BackupVaultName:A}},R=r({slug:s,environment:o,resourceType:"backup-role",suffix:i}),P=t(R),E={Type:"AWS::IAM::Role",Properties:{RoleName:R,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"backup.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSBackupServiceRolePolicyForBackup","arn:aws:iam::aws:policy/service-role/AWSBackupServiceRolePolicyForRestores"]}},I=r({slug:s,environment:o,resourceType:"backup-plan",suffix:i}),M=t(I),L={DeleteAfterDays:u};if(S&&S<u)L.MoveToColdStorageAfterDays=S;let x={Type:"AWS::Backup::BackupPlan",Properties:{BackupPlan:{BackupPlanName:I,BackupPlanRule:[{RuleName:`${i}-daily-backup`,TargetBackupVault:k.Ref(T),ScheduleExpression:d,StartWindowMinutes:60,CompletionWindowMinutes:120,Lifecycle:L,EnableContinuousBackup:h}]}}},O=r({slug:s,environment:o,resourceType:"backup-selection",suffix:i}),B=t(O),F=c.map((j)=>k.GetAtt(j,"Arn")),U={Type:"AWS::Backup::BackupSelection",Properties:{BackupPlanId:k.Ref(M),BackupSelection:{SelectionName:O,IamRoleArn:k.GetAtt(P,"Arn"),Resources:F}}};return{vault:v,plan:x,selection:U,role:E,vaultLogicalId:T,planLogicalId:M,selectionLogicalId:B,roleLogicalId:P}}static BackupSchedules={HOURLY:"cron(0 * * * ? *)",DAILY_5AM:"cron(0 5 * * ? *)",DAILY_MIDNIGHT:"cron(0 0 * * ? *)",WEEKLY_SUNDAY:"cron(0 5 ? * SUN *)",WEEKLY_SATURDAY:"cron(0 5 ? * SAT *)",MONTHLY_FIRST:"cron(0 5 1 * ? *)",EVERY_12_HOURS:"cron(0 */12 * * ? *)",EVERY_6_HOURS:"cron(0 */6 * * ? *)"};static BackupRetention={ONE_DAY:1,ONE_WEEK:7,TWO_WEEKS:14,ONE_MONTH:30,THREE_MONTHS:90,SIX_MONTHS:180,ONE_YEAR:365,TWO_YEARS:730,FIVE_YEARS:1825,SEVEN_YEARS:2555};static createWwwRedirectBucket(n){let{slug:i,environment:s,sourceDomain:o,targetDomain:c,protocol:u="https"}=n,d=r({slug:i,environment:s,resourceType:"s3",suffix:"www-redirect"}),f=t(d),h={Type:"AWS::S3::Bucket",Properties:{BucketName:o,WebsiteConfiguration:{RedirectAllRequestsTo:{HostName:c,Protocol:u}},PublicAccessBlockConfiguration:{BlockPublicAcls:!1,BlockPublicPolicy:!1,IgnorePublicAcls:!1,RestrictPublicBuckets:!1}}},S={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:k.Ref(f),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadForRedirect",Effect:"Allow",Principal:"*",Action:["s3:GetObject"],Resource:[k.Join("",[k.GetAtt(f,"Arn"),"/*"])]}]}}};return{bucket:h,bucketPolicy:S,logicalId:f}}static createDocsBucket(n){let{slug:i,environment:s,domain:o}=n,c=o||r({slug:i,environment:s,resourceType:"s3",suffix:"docs"}),u=t(c);return{bucket:{Type:"AWS::S3::Bucket",Properties:{BucketName:c,BucketEncryption:{ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]},PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},Tags:[{Key:"backup",Value:"weekly"}]}},logicalId:u}}static createEmailBucket(n){let{slug:i,environment:s}=n,o=r({slug:i,environment:s,resourceType:"s3",suffix:"email"}),c=t(o),u={Type:"AWS::S3::Bucket",Properties:{BucketName:o,BucketEncryption:{ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]},PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},LifecycleConfiguration:{Rules:[{Id:"EmailRetention",Status:"Enabled",ExpirationInDays:90,Transitions:[{TransitionInDays:30,StorageClass:"STANDARD_IA"}]}]}}},d={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:k.Ref(c),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowSESPuts",Effect:"Allow",Principal:{Service:"ses.amazonaws.com"},Action:"s3:PutObject",Resource:k.Join("",[k.GetAtt(c,"Arn"),"/*"]),Condition:{StringEquals:{"AWS:SourceAccount":k.Ref("AWS::AccountId")}}}]}}};return{bucket:u,bucketPolicy:d,logicalId:c}}static docsExist(n={}){let{projectRoot:i=process.cwd(),docsPaths:s=["docs","documentation","doc"]}=n;for(let o of s){let c=Te(i,o);if(We(c)){let u=["dist","build",".bunpress/dist","_site","out","public"];for(let d of u){let f=Te(c,d);if(We(f))try{if(Ar(f).length>0)return{exists:!0,path:c,hasDistFolder:!0,distPath:f}}catch{}}return{exists:!0,path:c,hasDistFolder:!1,distPath:null}}}return{exists:!1,path:null,hasDistFolder:!1,distPath:null}}static createDocsBucketIfExists(n){let i=xe.docsExist({projectRoot:n.projectRoot,docsPaths:n.docsPaths});if(!i.exists)return{bucket:null,logicalId:null,docsInfo:i};let s=xe.createDocsBucket({slug:n.slug,environment:n.environment,domain:n.domain});return{bucket:s.bucket,bucketPolicy:s.bucketPolicy,logicalId:s.logicalId,docsInfo:i}}static createPrivateBucket(n){let{slug:i,environment:s,enableVersioning:o=!0,retentionDays:c,encryptionKeyArn:u}=n,d=r({slug:i,environment:s,resourceType:"s3",suffix:"private"}),f=t(d);return{bucket:{Type:"AWS::S3::Bucket",Properties:{BucketName:d,BucketEncryption:{ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:u?{SSEAlgorithm:"aws:kms",KMSMasterKeyID:u}:{SSEAlgorithm:"AES256"}}]},PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},VersioningConfiguration:o?{Status:"Enabled"}:void 0,LifecycleConfiguration:c?{Rules:[{Id:"RetentionPolicy",Status:"Enabled",ExpirationInDays:c}]}:void 0,Tags:[{Key:"backup",Value:"daily"}]}},logicalId:f}}static checkSourcePaths(n={}){let{projectRoot:i=process.cwd(),paths:s={}}=n,o=s.web||"views/web/dist",c=s.docs||"docs/dist",u=s.private||"private";return{web:{exists:We(Te(i,o)),path:Te(i,o)},docs:{exists:We(Te(i,c)),path:Te(i,c)},private:{exists:We(Te(i,u)),path:Te(i,u)}}}static createDeploymentBuckets(n){let{slug:i,environment:s,domain:o,projectRoot:c,paths:u}=n,d=xe.checkSourcePaths({projectRoot:c,paths:u}),f={},h={web:!1,docs:!1,private:!1},S=xe.createBucket({name:"web",slug:i,environment:s,public:!1,versioning:!1,encryption:!0});if(f[S.logicalId]=S.bucket,h.web=!0,d.docs.exists){let A=xe.createDocsBucket({slug:i,environment:s,domain:o?`docs.${o}`:void 0});if(f[A.logicalId]=A.bucket,A.bucketPolicy)f[`${A.logicalId}Policy`]=A.bucketPolicy;h.docs=!0}if(d.private.exists){let A=xe.createPrivateBucket({slug:i,environment:s,enableVersioning:!0});f[A.logicalId]=A.bucket,h.private=!0}return{resources:f,created:h,sourcePaths:d}}}class Ye{static createRepository(n){let{name:i,slug:s,environment:o,scanOnPush:c=!0,imageMutability:u="MUTABLE",encryption:d="AES256",kmsKey:f,lifecyclePolicy:h,tags:S}=n,A=r({slug:s,environment:o,resourceType:"ecr",suffix:i}),T=t(A),v={Type:"AWS::ECR::Repository",Properties:{RepositoryName:A,ImageTagMutability:u,ImageScanningConfiguration:{ScanOnPush:c},EncryptionConfiguration:{EncryptionType:d,...f&&d==="KMS"?{KmsKey:f}:{}}}};if(h)v.Properties.LifecyclePolicy={LifecyclePolicyText:JSON.stringify(Ye.generateLifecyclePolicy(h))};if(S)v.Properties.Tags=Object.entries(S).map(([R,P])=>({Key:R,Value:P}));return{repository:v,logicalId:T}}static generateLifecyclePolicy(n){let i=[];if(n.untaggedImageExpireDays!==void 0)i.push({rulePriority:1,description:"Delete untagged images",selection:{tagStatus:"untagged",countType:"sinceImagePushed",countNumber:n.untaggedImageExpireDays,countUnit:"days"},action:{type:"expire"}});if(n.maxImageCount!==void 0)i.push({rulePriority:i.length+1,description:"Keep only most recent images",selection:{tagStatus:"any",countType:"imageCountMoreThan",countNumber:n.maxImageCount},action:{type:"expire"}});if(n.maxImageAgeDays!==void 0)i.push({rulePriority:i.length+1,description:"Delete images older than specified days",selection:{tagStatus:"any",countType:"sinceImagePushed",countNumber:n.maxImageAgeDays,countUnit:"days"},action:{type:"expire"}});return{rules:i}}static LifecyclePolicies={production:{maxImageCount:10,untaggedImageExpireDays:7},development:{maxImageCount:5,untaggedImageExpireDays:3},minimal:{maxImageCount:3,untaggedImageExpireDays:1},archive:{maxImageCount:50,untaggedImageExpireDays:30}};static enableImmutableTags(n){if(!n.Properties)n.Properties={};return n.Properties.ImageTagMutability="IMMUTABLE",n}static enableScanOnPush(n){if(!n.Properties)n.Properties={};return n.Properties.ImageScanningConfiguration={ScanOnPush:!0},n}static setLifecyclePolicy(n,i){if(!n.Properties)n.Properties={};return n.Properties.LifecyclePolicy={LifecyclePolicyText:JSON.stringify(Ye.generateLifecyclePolicy(i))},n}static addCrossAccountAccess(n,i){if(!n.Properties)n.Properties={};return n.Properties.RepositoryPolicyText={Version:"2012-10-17",Statement:[{Sid:"CrossAccountPull",Effect:"Allow",Principal:{AWS:i.map((s)=>`arn:aws:iam::${s}:root`)},Action:["ecr:GetDownloadUrlForLayer","ecr:BatchGetImage","ecr:BatchCheckLayerAvailability"]}]},n}static addLambdaAccess(n){if(!n.Properties)n.Properties={};return n.Properties.RepositoryPolicyText={Version:"2012-10-17",Statement:[{Sid:"LambdaECRImageRetrievalPolicy",Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:["ecr:GetDownloadUrlForLayer","ecr:BatchGetImage"]}]},n}static generateBunDockerfile(n){let{baseImage:i="oven/bun:1-debian",serverPath:s,port:o=3000,additionalDirs:c=[],healthCheckEndpoint:u="/health",nodeCompatible:d=!1,envVars:f={},buildCommands:h=[],runCommand:S}=n,A=["app","config",...c],T=S||`bun run ${s}`,v=`# Multi-stage build for Bun application
|
|
11
|
+
`)}import{existsSync as He,readdirSync as Ar}from"node:fs";import{join as Pe}from"node:path";class xe{static createBucket(n){let{name:i,bucketName:s,slug:o,environment:c,public:u=!1,versioning:d=!1,website:f=!1,encryption:h=!0,intelligentTiering:S=!1,cors:A,lifecycleRules:T}=n,v=s??r({slug:o,environment:c,resourceType:"s3",suffix:i}),R=t(v),P={Type:"AWS::S3::Bucket",Properties:{BucketName:v}};if(h)P.Properties.BucketEncryption={ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]};if(d)P.Properties.VersioningConfiguration={Status:"Enabled"};if(f)P.Properties.WebsiteConfiguration={IndexDocument:"index.html",ErrorDocument:"error.html"};if(!u)P.Properties.PublicAccessBlockConfiguration={BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0};if(A&&A.length>0)P.Properties.CorsConfiguration={CorsRules:A.map((I)=>({AllowedOrigins:I.allowedOrigins,AllowedMethods:I.allowedMethods,AllowedHeaders:I.allowedHeaders,MaxAge:I.maxAge}))};if(T&&T.length>0)P.Properties.LifecycleConfiguration={Rules:T.map((I)=>({Id:I.id,Status:I.enabled?"Enabled":"Disabled",ExpirationInDays:I.expirationDays,Transitions:I.transitions?.map((M)=>({TransitionInDays:M.days,StorageClass:M.storageClass}))}))};if(S&&T){let I={id:"IntelligentTieringRule",enabled:!0,transitions:[{days:0,storageClass:"INTELLIGENT_TIERING"}]};if(!P.Properties.LifecycleConfiguration)P.Properties.LifecycleConfiguration={Rules:[]};P.Properties.LifecycleConfiguration.Rules.push({Id:I.id,Status:"Enabled",Transitions:I.transitions?.map((M)=>({TransitionInDays:M.days,StorageClass:M.storageClass}))})}let E;if(u)E={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:k.Ref(R),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadGetObject",Effect:"Allow",Principal:"*",Action:["s3:GetObject"],Resource:[k.Join("",[k.GetAtt(R,"Arn"),"/*"])]}]}}};return{bucket:P,bucketPolicy:E,logicalId:R}}static enableVersioning(n){if(!n.Properties)n.Properties={};return n.Properties.VersioningConfiguration={Status:"Enabled"},n}static enableWebsiteHosting(n,i="index.html",s="error.html"){if(!n.Properties)n.Properties={};return n.Properties.WebsiteConfiguration={IndexDocument:i,ErrorDocument:s},n}static setLifecycleRules(n,i){if(!n.Properties)n.Properties={};return n.Properties.LifecycleConfiguration={Rules:i.map((s)=>({Id:s.id,Status:s.enabled?"Enabled":"Disabled",ExpirationInDays:s.expirationDays,Transitions:s.transitions?.map((o)=>({TransitionInDays:o.days,StorageClass:o.storageClass}))}))},n}static enableIntelligentTiering(n){if(!n.Properties)n.Properties={};if(!n.Properties.LifecycleConfiguration)n.Properties.LifecycleConfiguration={Rules:[]};return n.Properties.LifecycleConfiguration.Rules.push({Id:"IntelligentTieringRule",Status:"Enabled",Transitions:[{TransitionInDays:0,StorageClass:"INTELLIGENT_TIERING"}]}),n}static addLambdaNotification(n,i){if(!n.Properties)n.Properties={};if(!n.Properties.NotificationConfiguration)n.Properties.NotificationConfiguration={};if(!n.Properties.NotificationConfiguration.LambdaConfigurations)n.Properties.NotificationConfiguration.LambdaConfigurations=[];let s={Event:i.events[0],Function:i.functionArn};if(i.filter)s.Filter={S3Key:{Rules:[...i.filter.prefix?[{Name:"prefix",Value:i.filter.prefix}]:[],...i.filter.suffix?[{Name:"suffix",Value:i.filter.suffix}]:[]]}};for(let o of i.events){let c={...s,Event:o};n.Properties.NotificationConfiguration.LambdaConfigurations.push(c)}return n}static Notifications={onObjectCreated:(n)=>({functionArn:n,events:["s3:ObjectCreated:*"]}),onObjectRemoved:(n)=>({functionArn:n,events:["s3:ObjectRemoved:*"]}),onImageUpload:(n,i)=>({functionArn:n,events:["s3:ObjectCreated:*"],filter:{prefix:i,suffix:".jpg"}}),onFileType:(n,i,s)=>({functionArn:n,events:["s3:ObjectCreated:*"],filter:{prefix:s,suffix:i}}),onFolderUpload:(n,i)=>({functionArn:n,events:["s3:ObjectCreated:*"],filter:{prefix:i.endsWith("/")?i:`${i}/`}})};static createBackupPlan(n){let{name:i,slug:s,environment:o,bucketLogicalIds:c,retentionDays:u,schedule:d="cron(0 5 * * ? *)",vaultName:f,enableContinuousBackup:h=!1,moveToColdStorageAfterDays:S}=n,A=f||r({slug:s,environment:o,resourceType:"backup-vault",suffix:i}),T=t(A),v={Type:"AWS::Backup::BackupVault",Properties:{BackupVaultName:A}},R=r({slug:s,environment:o,resourceType:"backup-role",suffix:i}),P=t(R),E={Type:"AWS::IAM::Role",Properties:{RoleName:R,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"backup.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSBackupServiceRolePolicyForBackup","arn:aws:iam::aws:policy/service-role/AWSBackupServiceRolePolicyForRestores"]}},I=r({slug:s,environment:o,resourceType:"backup-plan",suffix:i}),M=t(I),L={DeleteAfterDays:u};if(S&&S<u)L.MoveToColdStorageAfterDays=S;let x={Type:"AWS::Backup::BackupPlan",Properties:{BackupPlan:{BackupPlanName:I,BackupPlanRule:[{RuleName:`${i}-daily-backup`,TargetBackupVault:k.Ref(T),ScheduleExpression:d,StartWindowMinutes:60,CompletionWindowMinutes:120,Lifecycle:L,EnableContinuousBackup:h}]}}},O=r({slug:s,environment:o,resourceType:"backup-selection",suffix:i}),B=t(O),F=c.map((j)=>k.GetAtt(j,"Arn")),U={Type:"AWS::Backup::BackupSelection",Properties:{BackupPlanId:k.Ref(M),BackupSelection:{SelectionName:O,IamRoleArn:k.GetAtt(P,"Arn"),Resources:F}}};return{vault:v,plan:x,selection:U,role:E,vaultLogicalId:T,planLogicalId:M,selectionLogicalId:B,roleLogicalId:P}}static BackupSchedules={HOURLY:"cron(0 * * * ? *)",DAILY_5AM:"cron(0 5 * * ? *)",DAILY_MIDNIGHT:"cron(0 0 * * ? *)",WEEKLY_SUNDAY:"cron(0 5 ? * SUN *)",WEEKLY_SATURDAY:"cron(0 5 ? * SAT *)",MONTHLY_FIRST:"cron(0 5 1 * ? *)",EVERY_12_HOURS:"cron(0 */12 * * ? *)",EVERY_6_HOURS:"cron(0 */6 * * ? *)"};static BackupRetention={ONE_DAY:1,ONE_WEEK:7,TWO_WEEKS:14,ONE_MONTH:30,THREE_MONTHS:90,SIX_MONTHS:180,ONE_YEAR:365,TWO_YEARS:730,FIVE_YEARS:1825,SEVEN_YEARS:2555};static createWwwRedirectBucket(n){let{slug:i,environment:s,sourceDomain:o,targetDomain:c,protocol:u="https"}=n,d=r({slug:i,environment:s,resourceType:"s3",suffix:"www-redirect"}),f=t(d),h={Type:"AWS::S3::Bucket",Properties:{BucketName:o,WebsiteConfiguration:{RedirectAllRequestsTo:{HostName:c,Protocol:u}},PublicAccessBlockConfiguration:{BlockPublicAcls:!1,BlockPublicPolicy:!1,IgnorePublicAcls:!1,RestrictPublicBuckets:!1}}},S={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:k.Ref(f),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadForRedirect",Effect:"Allow",Principal:"*",Action:["s3:GetObject"],Resource:[k.Join("",[k.GetAtt(f,"Arn"),"/*"])]}]}}};return{bucket:h,bucketPolicy:S,logicalId:f}}static createDocsBucket(n){let{slug:i,environment:s,domain:o}=n,c=o||r({slug:i,environment:s,resourceType:"s3",suffix:"docs"}),u=t(c);return{bucket:{Type:"AWS::S3::Bucket",Properties:{BucketName:c,BucketEncryption:{ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]},PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},Tags:[{Key:"backup",Value:"weekly"}]}},logicalId:u}}static createEmailBucket(n){let{slug:i,environment:s}=n,o=r({slug:i,environment:s,resourceType:"s3",suffix:"email"}),c=t(o),u={Type:"AWS::S3::Bucket",Properties:{BucketName:o,BucketEncryption:{ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]},PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},LifecycleConfiguration:{Rules:[{Id:"EmailRetention",Status:"Enabled",ExpirationInDays:90,Transitions:[{TransitionInDays:30,StorageClass:"STANDARD_IA"}]}]}}},d={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:k.Ref(c),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowSESPuts",Effect:"Allow",Principal:{Service:"ses.amazonaws.com"},Action:"s3:PutObject",Resource:k.Join("",[k.GetAtt(c,"Arn"),"/*"]),Condition:{StringEquals:{"AWS:SourceAccount":k.Ref("AWS::AccountId")}}}]}}};return{bucket:u,bucketPolicy:d,logicalId:c}}static docsExist(n={}){let{projectRoot:i=process.cwd(),docsPaths:s=["docs","documentation","doc"]}=n;for(let o of s){let c=Pe(i,o);if(He(c)){let u=["dist","build",".bunpress/dist","_site","out","public"];for(let d of u){let f=Pe(c,d);if(He(f))try{if(Ar(f).length>0)return{exists:!0,path:c,hasDistFolder:!0,distPath:f}}catch{}}return{exists:!0,path:c,hasDistFolder:!1,distPath:null}}}return{exists:!1,path:null,hasDistFolder:!1,distPath:null}}static createDocsBucketIfExists(n){let i=xe.docsExist({projectRoot:n.projectRoot,docsPaths:n.docsPaths});if(!i.exists)return{bucket:null,logicalId:null,docsInfo:i};let s=xe.createDocsBucket({slug:n.slug,environment:n.environment,domain:n.domain});return{bucket:s.bucket,bucketPolicy:s.bucketPolicy,logicalId:s.logicalId,docsInfo:i}}static createPrivateBucket(n){let{slug:i,environment:s,enableVersioning:o=!0,retentionDays:c,encryptionKeyArn:u}=n,d=r({slug:i,environment:s,resourceType:"s3",suffix:"private"}),f=t(d);return{bucket:{Type:"AWS::S3::Bucket",Properties:{BucketName:d,BucketEncryption:{ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:u?{SSEAlgorithm:"aws:kms",KMSMasterKeyID:u}:{SSEAlgorithm:"AES256"}}]},PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},VersioningConfiguration:o?{Status:"Enabled"}:void 0,LifecycleConfiguration:c?{Rules:[{Id:"RetentionPolicy",Status:"Enabled",ExpirationInDays:c}]}:void 0,Tags:[{Key:"backup",Value:"daily"}]}},logicalId:f}}static checkSourcePaths(n={}){let{projectRoot:i=process.cwd(),paths:s={}}=n,o=s.web||"views/web/dist",c=s.docs||"docs/dist",u=s.private||"private";return{web:{exists:He(Pe(i,o)),path:Pe(i,o)},docs:{exists:He(Pe(i,c)),path:Pe(i,c)},private:{exists:He(Pe(i,u)),path:Pe(i,u)}}}static createDeploymentBuckets(n){let{slug:i,environment:s,domain:o,projectRoot:c,paths:u}=n,d=xe.checkSourcePaths({projectRoot:c,paths:u}),f={},h={web:!1,docs:!1,private:!1},S=xe.createBucket({name:"web",slug:i,environment:s,public:!1,versioning:!1,encryption:!0});if(f[S.logicalId]=S.bucket,h.web=!0,d.docs.exists){let A=xe.createDocsBucket({slug:i,environment:s,domain:o?`docs.${o}`:void 0});if(f[A.logicalId]=A.bucket,A.bucketPolicy)f[`${A.logicalId}Policy`]=A.bucketPolicy;h.docs=!0}if(d.private.exists){let A=xe.createPrivateBucket({slug:i,environment:s,enableVersioning:!0});f[A.logicalId]=A.bucket,h.private=!0}return{resources:f,created:h,sourcePaths:d}}}class Ye{static createRepository(n){let{name:i,slug:s,environment:o,scanOnPush:c=!0,imageMutability:u="MUTABLE",encryption:d="AES256",kmsKey:f,lifecyclePolicy:h,tags:S}=n,A=r({slug:s,environment:o,resourceType:"ecr",suffix:i}),T=t(A),v={Type:"AWS::ECR::Repository",Properties:{RepositoryName:A,ImageTagMutability:u,ImageScanningConfiguration:{ScanOnPush:c},EncryptionConfiguration:{EncryptionType:d,...f&&d==="KMS"?{KmsKey:f}:{}}}};if(h)v.Properties.LifecyclePolicy={LifecyclePolicyText:JSON.stringify(Ye.generateLifecyclePolicy(h))};if(S)v.Properties.Tags=Object.entries(S).map(([R,P])=>({Key:R,Value:P}));return{repository:v,logicalId:T}}static generateLifecyclePolicy(n){let i=[];if(n.untaggedImageExpireDays!==void 0)i.push({rulePriority:1,description:"Delete untagged images",selection:{tagStatus:"untagged",countType:"sinceImagePushed",countNumber:n.untaggedImageExpireDays,countUnit:"days"},action:{type:"expire"}});if(n.maxImageCount!==void 0)i.push({rulePriority:i.length+1,description:"Keep only most recent images",selection:{tagStatus:"any",countType:"imageCountMoreThan",countNumber:n.maxImageCount},action:{type:"expire"}});if(n.maxImageAgeDays!==void 0)i.push({rulePriority:i.length+1,description:"Delete images older than specified days",selection:{tagStatus:"any",countType:"sinceImagePushed",countNumber:n.maxImageAgeDays,countUnit:"days"},action:{type:"expire"}});return{rules:i}}static LifecyclePolicies={production:{maxImageCount:10,untaggedImageExpireDays:7},development:{maxImageCount:5,untaggedImageExpireDays:3},minimal:{maxImageCount:3,untaggedImageExpireDays:1},archive:{maxImageCount:50,untaggedImageExpireDays:30}};static enableImmutableTags(n){if(!n.Properties)n.Properties={};return n.Properties.ImageTagMutability="IMMUTABLE",n}static enableScanOnPush(n){if(!n.Properties)n.Properties={};return n.Properties.ImageScanningConfiguration={ScanOnPush:!0},n}static setLifecyclePolicy(n,i){if(!n.Properties)n.Properties={};return n.Properties.LifecyclePolicy={LifecyclePolicyText:JSON.stringify(Ye.generateLifecyclePolicy(i))},n}static addCrossAccountAccess(n,i){if(!n.Properties)n.Properties={};return n.Properties.RepositoryPolicyText={Version:"2012-10-17",Statement:[{Sid:"CrossAccountPull",Effect:"Allow",Principal:{AWS:i.map((s)=>`arn:aws:iam::${s}:root`)},Action:["ecr:GetDownloadUrlForLayer","ecr:BatchGetImage","ecr:BatchCheckLayerAvailability"]}]},n}static addLambdaAccess(n){if(!n.Properties)n.Properties={};return n.Properties.RepositoryPolicyText={Version:"2012-10-17",Statement:[{Sid:"LambdaECRImageRetrievalPolicy",Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:["ecr:GetDownloadUrlForLayer","ecr:BatchGetImage"]}]},n}static generateBunDockerfile(n){let{baseImage:i="oven/bun:1-debian",serverPath:s,port:o=3000,additionalDirs:c=[],healthCheckEndpoint:u="/health",nodeCompatible:d=!1,envVars:f={},buildCommands:h=[],runCommand:S}=n,A=["app","config",...c],T=S||`bun run ${s}`,v=`# Multi-stage build for Bun application
|
|
12
12
|
# Generated by ts-cloud
|
|
13
13
|
|
|
14
14
|
# Builder stage
|
|
@@ -91,7 +91,7 @@ echo "Image: $IMAGE_URI:${o}"
|
|
|
91
91
|
docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG
|
|
92
92
|
docker push $ECR_REGISTRY/$ECR_REPOSITORY:latest`},...n.ecsCluster&&n.ecsService?[{name:"Deploy to ECS",run:`aws ecs update-service --cluster ${n.ecsCluster} --service ${n.ecsService} --force-new-deployment`}]:[]]}}};return`# Generated by ts-cloud
|
|
93
93
|
${JSON.stringify(i,null,2).replace(/"/g,"").replace(/,\n/g,`
|
|
94
|
-
`)}`}};static DockerfileTemplates={bunServer:(n,i=3000)=>Ye.generateBunDockerfile({serverPath:n,port:i}),bunWithBuild:(n,i,s=3000)=>Ye.generateBunDockerfile({serverPath:n,port:s,buildCommands:[i]}),bunFullStack:(n,i=3000)=>Ye.generateBunDockerfile({serverPath:n,port:i,additionalDirs:["public","views","dist"],buildCommands:["bun run build"]}),bunApi:(n,i=3000)=>Ye.generateBunDockerfile({serverPath:n,port:i,healthCheckEndpoint:"/api/health"})}}var Yd=[400,403,404,416,429,500,502,503,504],sm=[500,502,503,504],om=["GET","HEAD","OPTIONS"],OI="-failover-group",am=["default","media-quality-based"],cm={min:1,max:3},dm={min:1,max:10};function Bo(n){if(n===void 0)return[...sm];if(n.length===0)throw Error(`CloudFront origin failover: statusCodes must list at least one code (allowed: ${Yd.join(", ")}). Omit it to use the default ${sm.join(", ")}.`);let i=n.filter((s)=>!Yd.includes(s));if(i.length>0)throw Error(`CloudFront origin failover: ${i.join(", ")} ${i.length===1?"is not a status code":"are not status codes"} CloudFront can fail over on. Allowed: ${Yd.join(", ")}.`);return[...new Set(n)].sort((s,o)=>s-o)}function Zd(n){let{primaryOriginId:i,secondaryOriginId:s}=n;if(!i||!s)throw Error("CloudFront origin failover: both a primary and a secondary origin id are required");if(i===s)throw Error(`CloudFront origin failover: the secondary origin must differ from the primary (both are "${i}")`);let o=Bo(n.statusCodes);return nn(n.selectionCriteria),{Id:n.groupId??`${i}-failover-group`,FailoverCriteria:{StatusCodes:{Quantity:o.length,Items:o}},Members:{Quantity:2,Items:[{OriginId:i},{OriginId:s}]},...n.selectionCriteria?{SelectionCriteria:n.selectionCriteria}:{}}}function nn(n,i="the origin group"){if(n===void 0)return;if(!am.includes(n))throw Error(`CloudFront origin failover: ${i} has selection criteria ${JSON.stringify(n)}. Allowed: ${am.join(", ")}.`)}function Je(n,i,s){if(typeof n!=="number"||!Number.isInteger(n)||n<i.min||n>i.max)throw Error(`CloudFront origin: ${s} must be a whole number from ${i.min} to ${i.max}, got ${JSON.stringify(n)}.`)}function ce(n,i="the origin"){let s={};if(n?.connectionAttempts!==void 0)Je(n.connectionAttempts,cm,`${i} connectionAttempts`),s.ConnectionAttempts=n.connectionAttempts;if(n?.connectionTimeout!==void 0)Je(n.connectionTimeout,dm,`${i} connectionTimeout (seconds)`),s.ConnectionTimeout=n.connectionTimeout;return s}function an(n){return{Quantity:1,Items:[Zd(n)]}}function Tt(n,i="the cache behavior"){let o=(Array.isArray(n)?n:n?.Items??[]).filter((c)=>!om.includes(c.toUpperCase()));if(o.length>0)throw Error(`CloudFront origin failover: ${i} allows ${o.join(", ")}, but a cache behavior that targets an origin group may only allow ${om.join(", ")}. CloudFront never fails over a write, so point the write paths at a single origin in their own cache behavior.`)}function xo(n){return/\.s3[.-](?:[a-z0-9-]+\.)?amazonaws\.com(?:\.cn)?$/i.test(n)&&!/s3-website/i.test(n)}function Ve(n){if(!n)return[];if(Array.isArray(n))return n;return n.Items??[]}function Se(n){return typeof n==="string"?n:void 0}var Cr=/\.mediapackagev2\.[a-z0-9-]+\.amazonaws\.com$/i;function wt(n,i="the distribution"){let s=Ve(n.Origins),o=new Set(s.map((A)=>Se(A.Id)).filter((A)=>!!A)),c=new Map(s.map((A)=>[Se(A.Id)??"",A.DomainName])),u=s.some((A)=>Se(A.Id)===void 0);for(let A of s){let T=Se(A.Id)??"(unnamed origin)";if(A.ConnectionAttempts!==void 0)Je(A.ConnectionAttempts,cm,`${i} origin "${T}" ConnectionAttempts`);if(A.ConnectionTimeout!==void 0)Je(A.ConnectionTimeout,dm,`${i} origin "${T}" ConnectionTimeout (seconds)`)}let d=n.OriginGroups,f=Ve(d);if(d&&!Array.isArray(d)&&d.Quantity!==void 0&&d.Quantity!==f.length)throw Error(`CloudFront origin failover: ${i} OriginGroups.Quantity is ${d.Quantity} but it lists ${f.length} group(s).`);let h=new Set;for(let A of f){let T=Se(A.Id);if(A.Id===void 0||A.Id==="")throw Error(`CloudFront origin failover: ${i} has an origin group without an Id.`);let v=`${i} origin group "${T??"(intrinsic id)"}"`;if(T){if(h.has(T))throw Error(`CloudFront origin failover: ${i} declares origin group "${T}" twice.`);if(o.has(T))throw Error(`CloudFront origin failover: ${v} has the same id as an origin. Cache behaviors target groups and origins by id, so the two must differ.`);h.add(T)}let R=A.Members,P=Ve(R);if(P.length!==2||R?.Quantity!==void 0&&R.Quantity!==P.length)throw Error(`CloudFront origin failover: ${v} must have exactly 2 members (a primary and a secondary), it has ${P.length}${R?.Quantity!==void 0&&R.Quantity!==P.length?` with Quantity ${R.Quantity}`:""}.`);let E=P.map((L)=>Se(L.OriginId));for(let L of E)if(L&&!o.has(L)&&!u)throw Error(`CloudFront origin failover: ${v} lists member "${L}", which is not an origin of this distribution. Origins: ${[...o].join(", ")||"(none)"}.`);if(E[0]&&E[0]===E[1])throw Error(`CloudFront origin failover: ${v} lists "${E[0]}" as both primary and secondary.`);let I=A.FailoverCriteria?.StatusCodes,M=Ve(I);if(Bo(M),I?.Quantity!==void 0&&I.Quantity!==M.length)throw Error(`CloudFront origin failover: ${v} FailoverCriteria.StatusCodes.Quantity is ${I.Quantity} but it lists ${M.length} code(s).`);if(nn(A.SelectionCriteria,v),A.SelectionCriteria==="media-quality-based")for(let L of E){let x=L?Se(c.get(L)):void 0;if(x&&!Cr.test(x))throw Error(`CloudFront origin failover: ${v} uses media-quality-based selection, which only works between AWS Elemental MediaPackage v2 origins, but member "${L}" is ${x}. Use 'default'.`)}}let S=[];if(n.DefaultCacheBehavior)S.push({behavior:n.DefaultCacheBehavior,name:"the default cache behavior"});for(let A of Ve(n.CacheBehaviors))S.push({behavior:A,name:`the cache behavior for ${JSON.stringify(A.PathPattern)}`});for(let{behavior:A,name:T}of S){let v=Se(A.TargetOriginId);if(!v)continue;if(h.has(v))Tt(A.AllowedMethods??["GET","HEAD"],`${T} of ${i} (origin group "${v}")`);else if(!o.has(v)&&!u&&f.every((R)=>Se(R.Id)!==void 0))throw Error(`CloudFront: ${T} of ${i} targets "${v}", which is neither an origin nor an origin group of this distribution.`)}}class Ce{static createDistribution(n){let{slug:i,environment:s,origin:o,customDomain:c,certificateArn:u,errorPages:d,cachePolicy:f,edgeFunctions:h,http3:S=!1,comment:A,failoverOrigin:T}=n,v=r({slug:i,environment:s,resourceType:"cdn"}),R=t(v),P={Id:"DefaultOrigin",DomainName:o.domainName,OriginPath:o.originPath||"",...ce(o,"the CDN origin")},E;if(o.type==="s3"){let M=`${R}OAC`;E={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`${v}-oac`,Description:`Origin Access Control for ${v}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},P.OriginAccessControlId=k.Ref(M)}else if(o.type==="alb"||o.type==="custom")P.CustomOriginConfig={HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only"};let I={Type:"AWS::CloudFront::Distribution",Properties:{DistributionConfig:{Enabled:!0,Comment:A||`CDN for ${v}`,DefaultRootObject:"index.html",Origins:[P],DefaultCacheBehavior:{TargetOriginId:"DefaultOrigin",ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0},PriceClass:"PriceClass_100",HttpVersion:S?"http2and3":"http2"}}};if(c&&u)I.Properties.DistributionConfig.Aliases=[c],I.Properties.DistributionConfig.ViewerCertificate={AcmCertificateArn:u,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};if(d&&d.length>0)I.Properties.DistributionConfig.CustomErrorResponses=d.map((M)=>({ErrorCode:M.errorCode,ResponseCode:M.responseCode,ResponsePagePath:M.responsePagePath}));if(h&&h.length>0)I.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations=h.map((M)=>({EventType:M.event,LambdaFunctionARN:M.functionArn}));if(T)Ce.addOriginFailover(I,T);return{distribution:I,originAccessControl:E,logicalId:R}}static addOriginFailover(n,i){let s=n.Properties.DistributionConfig,o=s.DefaultCacheBehavior,c=o.TargetOriginId,u=i.id??"FailoverOrigin";if(s.OriginGroups&&s.OriginGroups.Quantity>0)throw Error("CloudFront origin failover: this distribution already has an origin group");if(Tt(o.AllowedMethods??["GET","HEAD"],"the default cache behavior"),s.Origins.some((A)=>A.Id===u))throw Error(`CloudFront origin failover: an origin with id "${u}" already exists`);let d=Zd({primaryOriginId:c,secondaryOriginId:u,statusCodes:i.statusCodes,selectionCriteria:i.selectionCriteria}),f=i.type??(xo(i.domainName)?"s3":"custom"),h={Id:u,DomainName:i.domainName,OriginPath:i.originPath||"",...ce(i,"the failover origin")},S=ce(i.primary,"the primary origin");if(Object.keys(S).length>0){let A=s.Origins.find((T)=>T.Id===c);if(A)Object.assign(A,S)}if(f==="s3"){let A=s.Origins.find((T)=>T.Id===c);if(h.S3OriginConfig={OriginAccessIdentity:""},A?.OriginAccessControlId)h.OriginAccessControlId=A.OriginAccessControlId}else h.CustomOriginConfig={HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only"};return s.Origins.push(h),s.OriginGroups={Quantity:1,Items:[d]},o.TargetOriginId=d.Id,wt(s),n}static setCustomDomain(n,i,s){return n.Properties.DistributionConfig.Aliases=[i],n.Properties.DistributionConfig.ViewerCertificate={AcmCertificateArn:s,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"},n}static setErrorPages(n,i){return n.Properties.DistributionConfig.CustomErrorResponses=i.map((s)=>({ErrorCode:s.errorCode,ResponseCode:s.responseCode,ResponsePagePath:s.responsePagePath})),n}static enableHttp3(n){return n.Properties.DistributionConfig.HttpVersion="http2and3",n}static addEdgeFunction(n,i,s){if(!n.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations)n.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations=[];return n.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations.push({EventType:i,LambdaFunctionARN:s}),n}static setCachePolicy(n,i){return n.Properties.DistributionConfig.Comment=`${n.Properties.DistributionConfig.Comment||""} (TTL: ${i.default||86400}s)`,n}static createSpaDistribution(n){return Ce.createDistribution({...n,errorPages:[{errorCode:404,responseCode:200,responsePagePath:"/index.html"},{errorCode:403,responseCode:200,responsePagePath:"/index.html"}]})}static createDocsOriginRequestFunction(n){let{slug:i,environment:s}=n,o=r({slug:i,environment:s,resourceType:"edge-docs"}),c=t(o),u=t(`${o}-role`),d=t(`${o}-version`),f={Type:"AWS::IAM::Role",Properties:{RoleName:`${o}-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:["lambda.amazonaws.com","edgelambda.amazonaws.com"]},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"]}},h=`
|
|
94
|
+
`)}`}};static DockerfileTemplates={bunServer:(n,i=3000)=>Ye.generateBunDockerfile({serverPath:n,port:i}),bunWithBuild:(n,i,s=3000)=>Ye.generateBunDockerfile({serverPath:n,port:s,buildCommands:[i]}),bunFullStack:(n,i=3000)=>Ye.generateBunDockerfile({serverPath:n,port:i,additionalDirs:["public","views","dist"],buildCommands:["bun run build"]}),bunApi:(n,i=3000)=>Ye.generateBunDockerfile({serverPath:n,port:i,healthCheckEndpoint:"/api/health"})}}var Yd=[400,403,404,416,429,500,502,503,504],sm=[500,502,503,504],om=["GET","HEAD","OPTIONS"],OI="-failover-group",am=["default","media-quality-based"],cm={min:1,max:3},dm={min:1,max:10};function Bo(n){if(n===void 0)return[...sm];if(n.length===0)throw Error(`CloudFront origin failover: statusCodes must list at least one code (allowed: ${Yd.join(", ")}). Omit it to use the default ${sm.join(", ")}.`);let i=n.filter((s)=>!Yd.includes(s));if(i.length>0)throw Error(`CloudFront origin failover: ${i.join(", ")} ${i.length===1?"is not a status code":"are not status codes"} CloudFront can fail over on. Allowed: ${Yd.join(", ")}.`);return[...new Set(n)].sort((s,o)=>s-o)}function Zd(n){let{primaryOriginId:i,secondaryOriginId:s}=n;if(!i||!s)throw Error("CloudFront origin failover: both a primary and a secondary origin id are required");if(i===s)throw Error(`CloudFront origin failover: the secondary origin must differ from the primary (both are "${i}")`);let o=Bo(n.statusCodes);return nn(n.selectionCriteria),{Id:n.groupId??`${i}-failover-group`,FailoverCriteria:{StatusCodes:{Quantity:o.length,Items:o}},Members:{Quantity:2,Items:[{OriginId:i},{OriginId:s}]},...n.selectionCriteria?{SelectionCriteria:n.selectionCriteria}:{}}}function nn(n,i="the origin group"){if(n===void 0)return;if(!am.includes(n))throw Error(`CloudFront origin failover: ${i} has selection criteria ${JSON.stringify(n)}. Allowed: ${am.join(", ")}.`)}function st(n,i,s){if(typeof n!=="number"||!Number.isInteger(n)||n<i.min||n>i.max)throw Error(`CloudFront origin: ${s} must be a whole number from ${i.min} to ${i.max}, got ${JSON.stringify(n)}.`)}function ce(n,i="the origin"){let s={};if(n?.connectionAttempts!==void 0)st(n.connectionAttempts,cm,`${i} connectionAttempts`),s.ConnectionAttempts=n.connectionAttempts;if(n?.connectionTimeout!==void 0)st(n.connectionTimeout,dm,`${i} connectionTimeout (seconds)`),s.ConnectionTimeout=n.connectionTimeout;return s}function an(n){return{Quantity:1,Items:[Zd(n)]}}function Tt(n,i="the cache behavior"){let o=(Array.isArray(n)?n:n?.Items??[]).filter((c)=>!om.includes(c.toUpperCase()));if(o.length>0)throw Error(`CloudFront origin failover: ${i} allows ${o.join(", ")}, but a cache behavior that targets an origin group may only allow ${om.join(", ")}. CloudFront never fails over a write, so point the write paths at a single origin in their own cache behavior.`)}function xo(n){return/\.s3[.-](?:[a-z0-9-]+\.)?amazonaws\.com(?:\.cn)?$/i.test(n)&&!/s3-website/i.test(n)}function je(n){if(!n)return[];if(Array.isArray(n))return n;return n.Items??[]}function Ae(n){return typeof n==="string"?n:void 0}var Cr=/\.mediapackagev2\.[a-z0-9-]+\.amazonaws\.com$/i;function wt(n,i="the distribution"){let s=je(n.Origins),o=new Set(s.map((A)=>Ae(A.Id)).filter((A)=>!!A)),c=new Map(s.map((A)=>[Ae(A.Id)??"",A.DomainName])),u=s.some((A)=>Ae(A.Id)===void 0);for(let A of s){let T=Ae(A.Id)??"(unnamed origin)";if(A.ConnectionAttempts!==void 0)st(A.ConnectionAttempts,cm,`${i} origin "${T}" ConnectionAttempts`);if(A.ConnectionTimeout!==void 0)st(A.ConnectionTimeout,dm,`${i} origin "${T}" ConnectionTimeout (seconds)`)}let d=n.OriginGroups,f=je(d);if(d&&!Array.isArray(d)&&d.Quantity!==void 0&&d.Quantity!==f.length)throw Error(`CloudFront origin failover: ${i} OriginGroups.Quantity is ${d.Quantity} but it lists ${f.length} group(s).`);let h=new Set;for(let A of f){let T=Ae(A.Id);if(A.Id===void 0||A.Id==="")throw Error(`CloudFront origin failover: ${i} has an origin group without an Id.`);let v=`${i} origin group "${T??"(intrinsic id)"}"`;if(T){if(h.has(T))throw Error(`CloudFront origin failover: ${i} declares origin group "${T}" twice.`);if(o.has(T))throw Error(`CloudFront origin failover: ${v} has the same id as an origin. Cache behaviors target groups and origins by id, so the two must differ.`);h.add(T)}let R=A.Members,P=je(R);if(P.length!==2||R?.Quantity!==void 0&&R.Quantity!==P.length)throw Error(`CloudFront origin failover: ${v} must have exactly 2 members (a primary and a secondary), it has ${P.length}${R?.Quantity!==void 0&&R.Quantity!==P.length?` with Quantity ${R.Quantity}`:""}.`);let E=P.map((L)=>Ae(L.OriginId));for(let L of E)if(L&&!o.has(L)&&!u)throw Error(`CloudFront origin failover: ${v} lists member "${L}", which is not an origin of this distribution. Origins: ${[...o].join(", ")||"(none)"}.`);if(E[0]&&E[0]===E[1])throw Error(`CloudFront origin failover: ${v} lists "${E[0]}" as both primary and secondary.`);let I=A.FailoverCriteria?.StatusCodes,M=je(I);if(Bo(M),I?.Quantity!==void 0&&I.Quantity!==M.length)throw Error(`CloudFront origin failover: ${v} FailoverCriteria.StatusCodes.Quantity is ${I.Quantity} but it lists ${M.length} code(s).`);if(nn(A.SelectionCriteria,v),A.SelectionCriteria==="media-quality-based")for(let L of E){let x=L?Ae(c.get(L)):void 0;if(x&&!Cr.test(x))throw Error(`CloudFront origin failover: ${v} uses media-quality-based selection, which only works between AWS Elemental MediaPackage v2 origins, but member "${L}" is ${x}. Use 'default'.`)}}let S=[];if(n.DefaultCacheBehavior)S.push({behavior:n.DefaultCacheBehavior,name:"the default cache behavior"});for(let A of je(n.CacheBehaviors))S.push({behavior:A,name:`the cache behavior for ${JSON.stringify(A.PathPattern)}`});for(let{behavior:A,name:T}of S){let v=Ae(A.TargetOriginId);if(!v)continue;if(h.has(v))Tt(A.AllowedMethods??["GET","HEAD"],`${T} of ${i} (origin group "${v}")`);else if(!o.has(v)&&!u&&f.every((R)=>Ae(R.Id)!==void 0))throw Error(`CloudFront: ${T} of ${i} targets "${v}", which is neither an origin nor an origin group of this distribution.`)}}class Ce{static createDistribution(n){let{slug:i,environment:s,origin:o,customDomain:c,certificateArn:u,errorPages:d,cachePolicy:f,edgeFunctions:h,http3:S=!1,comment:A,failoverOrigin:T}=n,v=r({slug:i,environment:s,resourceType:"cdn"}),R=t(v),P={Id:"DefaultOrigin",DomainName:o.domainName,OriginPath:o.originPath||"",...ce(o,"the CDN origin")},E;if(o.type==="s3"){let M=`${R}OAC`;E={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`${v}-oac`,Description:`Origin Access Control for ${v}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},P.OriginAccessControlId=k.Ref(M)}else if(o.type==="alb"||o.type==="custom")P.CustomOriginConfig={HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only"};let I={Type:"AWS::CloudFront::Distribution",Properties:{DistributionConfig:{Enabled:!0,Comment:A||`CDN for ${v}`,DefaultRootObject:"index.html",Origins:[P],DefaultCacheBehavior:{TargetOriginId:"DefaultOrigin",ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0},PriceClass:"PriceClass_100",HttpVersion:S?"http2and3":"http2"}}};if(c&&u)I.Properties.DistributionConfig.Aliases=[c],I.Properties.DistributionConfig.ViewerCertificate={AcmCertificateArn:u,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};if(d&&d.length>0)I.Properties.DistributionConfig.CustomErrorResponses=d.map((M)=>({ErrorCode:M.errorCode,ResponseCode:M.responseCode,ResponsePagePath:M.responsePagePath}));if(h&&h.length>0)I.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations=h.map((M)=>({EventType:M.event,LambdaFunctionARN:M.functionArn}));if(T)Ce.addOriginFailover(I,T);return{distribution:I,originAccessControl:E,logicalId:R}}static addOriginFailover(n,i){let s=n.Properties.DistributionConfig,o=s.DefaultCacheBehavior,c=o.TargetOriginId,u=i.id??"FailoverOrigin";if(s.OriginGroups&&s.OriginGroups.Quantity>0)throw Error("CloudFront origin failover: this distribution already has an origin group");if(Tt(o.AllowedMethods??["GET","HEAD"],"the default cache behavior"),s.Origins.some((A)=>A.Id===u))throw Error(`CloudFront origin failover: an origin with id "${u}" already exists`);let d=Zd({primaryOriginId:c,secondaryOriginId:u,statusCodes:i.statusCodes,selectionCriteria:i.selectionCriteria}),f=i.type??(xo(i.domainName)?"s3":"custom"),h={Id:u,DomainName:i.domainName,OriginPath:i.originPath||"",...ce(i,"the failover origin")},S=ce(i.primary,"the primary origin");if(Object.keys(S).length>0){let A=s.Origins.find((T)=>T.Id===c);if(A)Object.assign(A,S)}if(f==="s3"){let A=s.Origins.find((T)=>T.Id===c);if(h.S3OriginConfig={OriginAccessIdentity:""},A?.OriginAccessControlId)h.OriginAccessControlId=A.OriginAccessControlId}else h.CustomOriginConfig={HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only"};return s.Origins.push(h),s.OriginGroups={Quantity:1,Items:[d]},o.TargetOriginId=d.Id,wt(s),n}static setCustomDomain(n,i,s){return n.Properties.DistributionConfig.Aliases=[i],n.Properties.DistributionConfig.ViewerCertificate={AcmCertificateArn:s,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"},n}static setErrorPages(n,i){return n.Properties.DistributionConfig.CustomErrorResponses=i.map((s)=>({ErrorCode:s.errorCode,ResponseCode:s.responseCode,ResponsePagePath:s.responsePagePath})),n}static enableHttp3(n){return n.Properties.DistributionConfig.HttpVersion="http2and3",n}static addEdgeFunction(n,i,s){if(!n.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations)n.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations=[];return n.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations.push({EventType:i,LambdaFunctionARN:s}),n}static setCachePolicy(n,i){return n.Properties.DistributionConfig.Comment=`${n.Properties.DistributionConfig.Comment||""} (TTL: ${i.default||86400}s)`,n}static createSpaDistribution(n){return Ce.createDistribution({...n,errorPages:[{errorCode:404,responseCode:200,responsePagePath:"/index.html"},{errorCode:403,responseCode:200,responsePagePath:"/index.html"}]})}static createDocsOriginRequestFunction(n){let{slug:i,environment:s}=n,o=r({slug:i,environment:s,resourceType:"edge-docs"}),c=t(o),u=t(`${o}-role`),d=t(`${o}-version`),f={Type:"AWS::IAM::Role",Properties:{RoleName:`${o}-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:["lambda.amazonaws.com","edgelambda.amazonaws.com"]},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"]}},h=`
|
|
95
95
|
'use strict';
|
|
96
96
|
|
|
97
97
|
exports.handler = async (event) => {
|
|
@@ -197,7 +197,7 @@ exports.handler = async (event) => {
|
|
|
197
197
|
|
|
198
198
|
return request;
|
|
199
199
|
};
|
|
200
|
-
`.trim()};static Config={ttl:(n)=>{let{min:i=0,max:s=86400,default:o=86400}=n;return{MinTTL:i,MaxTTL:s,DefaultTTL:o}},cookies:(n,i)=>{let s={Forward:n==="allowList"?"whitelist":n};if(n==="allowList"&&i)s.WhitelistedNames=i;return s},allowedMethods:(n)=>{let i={ALL:["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"],GET_HEAD:["GET","HEAD"],GET_HEAD_OPTIONS:["GET","HEAD","OPTIONS"]};return i[n]||i.GET_HEAD},cachedMethods:(n)=>{let i={GET_HEAD:["GET","HEAD"],GET_HEAD_OPTIONS:["GET","HEAD","OPTIONS"]};return i[n]||i.GET_HEAD},ttlPresets:{static:{min:0,max:31536000,default:31536000},dynamic:{min:0,max:0,default:0},api:{min:0,max:3600,default:60},html:{min:0,max:86400,default:86400},images:{min:0,max:604800,default:604800}},cacheBehavior:(n)=>{let{ttl:i={min:0,max:86400,default:86400},cookies:s="none",allowedCookies:o,allowedMethods:c="GET_HEAD",cachedMethods:u="GET_HEAD",compress:d=!0,forwardQueryString:f=!0,forwardHeaders:h=[]}=n;return{MinTTL:i.min,MaxTTL:i.max,DefaultTTL:i.default,Compress:d,AllowedMethods:Ce.Config.allowedMethods(c),CachedMethods:Ce.Config.cachedMethods(u),ForwardedValues:{QueryString:f,Headers:h,Cookies:Ce.Config.cookies(s,o)}}}};static applyConfig(n,i){let s=n.Properties.DistributionConfig.DefaultCacheBehavior;if(i.ttl)s.MinTTL=i.ttl.min,s.MaxTTL=i.ttl.max,s.DefaultTTL=i.ttl.default;if(i.compress!==void 0)s.Compress=i.compress;if(i.allowedMethods)s.AllowedMethods=Ce.Config.allowedMethods(i.allowedMethods);if(i.cachedMethods)s.CachedMethods=Ce.Config.cachedMethods(i.cachedMethods);if(i.cookies){if(!s.ForwardedValues)s.ForwardedValues={QueryString:!0};s.ForwardedValues.Cookies=Ce.Config.cookies(i.cookies,i.allowedCookies)}return n}}var qA=[403,404,500,502,503,504],el="TsCloud::StorageFailover",Oo="AllowCloudFrontFailoverRead",vr=/^[a-z]{2}(?:-gov)?-[a-z]+-\d$/,Tr=/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/;function lm(n){let{failover:i,primaryBucket:s,primaryRegion:o}=n,c=n.where??"storage failover";if(!i||typeof i!=="object")throw Error(`${c}.failover must be an object such as { region: 'us-west-2' }.`);if(!i.region||!vr.test(i.region))throw Error(`${c}.failover.region must be an AWS region such as 'us-west-2', got ${JSON.stringify(i.region)}.`);if(i.region===o)throw Error(`${c}.failover.region is ${i.region}, the same region as the primary bucket. Failover only helps when the replica is in another region.`);let u=i.bucket??`${s}-${i.region}`;if(!Tr.test(u)||u.includes("..")){let d=i.bucket===void 0&&u.length>63?` The default name (<primary bucket>-<region>) is ${u.length} characters; S3 allows 63. Set ${c}.failover.bucket.`:"";throw Error(`${c}.failover: "${u}" is not a valid S3 bucket name.${d}`)}if(u===s)throw Error(`${c}.failover.bucket must differ from the primary bucket "${s}".`);return{replicaBucket:u,replicaRegion:i.region,replicate:i.replicate!==!1,statusCodes:Bo(i.statusCodes??qA),primaryConnection:ce(i,`${c}.failover`)}}function um(n,i){return`${n}.s3.${i}.amazonaws.com`}function gm(n){let i=`arn:aws:s3:::${n.primaryBucket}`,s=`arn:aws:s3:::${n.replicaBucket}`;return{Type:"AWS::IAM::Role",Properties:{...n.roleName?{RoleName:n.roleName}:{},AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"s3.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"failover-replication",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["s3:GetReplicationConfiguration","s3:ListBucket"],Resource:i},{Effect:"Allow",Action:["s3:GetObjectVersionForReplication","s3:GetObjectVersionAcl","s3:GetObjectVersionTagging"],Resource:`${i}/*`},{Effect:"Allow",Action:["s3:ReplicateObject","s3:ReplicateDelete","s3:ReplicateTags"],Resource:`${s}/*`}]}}]}}}function pm(n){return{Role:n.roleArn,Rules:[{Id:"cloudfront-failover-replica",Status:"Enabled",Priority:1,Filter:{Prefix:""},DeleteMarkerReplication:{Status:"Enabled"},Destination:{Bucket:`arn:aws:s3:::${n.replicaBucket}`}}]}}function tl(n){return{Sid:Oo,Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:`arn:aws:s3:::${n.replicaBucket}/*`,Condition:{StringEquals:{"AWS:SourceArn":n.distributionArn}}}}function _I(n){let s=(typeof n==="string"?JSON.parse(n):n)?.Metadata?.[el];return Array.isArray(s)?s:[]}class W{static createHostedZone(n){let{domain:i,slug:s,environment:o,comment:c}=n,u=r({slug:s,environment:o,resourceType:"hostedzone"}),d=t(`${u}-${i.replace(/\./g,"")}`);return{zone:{Type:"AWS::Route53::HostedZone",Properties:{Name:i,HostedZoneConfig:{Comment:c||`Hosted zone for ${i}`}}},logicalId:d}}static createRecord(n){let{hostedZoneId:i,hostedZoneName:s,name:o,type:c,ttl:u,values:d,aliasTarget:f}=n,h=t(`record-${o.replace(/\./g,"")}-${c}`),S={Type:"AWS::Route53::RecordSet",Properties:{Name:o,Type:c}};if(i)S.Properties.HostedZoneId=i;else if(s)S.Properties.HostedZoneName=s;if(f)S.Properties.AliasTarget={DNSName:f.dnsName,HostedZoneId:f.hostedZoneId,EvaluateTargetHealth:f.evaluateTargetHealth??!1};else S.Properties.TTL=u||300,S.Properties.ResourceRecords=d||[];return{record:S,logicalId:h}}static createCloudFrontAlias(n,i,s){return W.createRecord({hostedZoneId:s,name:n,type:"A",aliasTarget:{dnsName:i,hostedZoneId:"Z2FDTNDATAQYW2",evaluateTargetHealth:!1}})}static createAlbAlias(n,i,s,o){return W.createRecord({hostedZoneId:o,name:n,type:"A",aliasTarget:{dnsName:i,hostedZoneId:s,evaluateTargetHealth:!0}})}static createCname(n,i,s,o=300){return W.createRecord({hostedZoneId:s,name:n,type:"CNAME",ttl:o,values:[i]})}static createWwwRedirect(n,i){return W.createRecord({hostedZoneId:i,name:`www.${n}`,type:"CNAME",ttl:300,values:[n]})}static createMxRecords(n,i,s,o=300){return W.createRecord({hostedZoneId:s,name:n,type:"MX",ttl:o,values:i.map((c)=>`${c.priority} ${c.server}`)})}static createTxtRecord(n,i,s,o=300){return W.createRecord({hostedZoneId:s,name:n,type:"TXT",ttl:o,values:[`"${i}"`]})}static createSpfRecord(n,i,s){return W.createTxtRecord(n,i,s)}static createDmarcRecord(n,i,s,o){let c=`v=DMARC1; p=${i}; rua=mailto:${s}`;return W.createTxtRecord(`_dmarc.${n}`,c,o)}static createS3WebsiteAlias(n,i,s,o){return W.createRecord({hostedZoneId:o,name:n,type:"A",aliasTarget:{dnsName:i,hostedZoneId:s,evaluateTargetHealth:!1}})}static S3WebsiteHostedZoneIds={"us-east-1":"Z3AQBSTGFYJSTF","us-east-2":"Z2O1EMRO9K5GLX","us-west-1":"Z2F56UZL2M1ACD","us-west-2":"Z3BJ6K6RIION7M","af-south-1":"Z83WF9RJE8B12","ap-east-1":"ZNB98KWMFR0R6","ap-south-1":"Z11RGJOFQNVJUP","ap-south-2":"Z02976202B4EZMXIPMXF7","ap-northeast-1":"Z2M4EHUR26P7ZW","ap-northeast-2":"Z3W03O7B5YMIYP","ap-northeast-3":"Z2YQB5RD63NC85","ap-southeast-1":"Z3O0J2DXBE1FTB","ap-southeast-2":"Z1WCIBER6CPFUU","ap-southeast-3":"Z01613992JD795ZI93075","ca-central-1":"Z1QDHH18159H29","eu-central-1":"Z21DNDUVLTQW6Q","eu-central-2":"Z030506016YDQGETNASS","eu-west-1":"Z1BKCTXD74EZPE","eu-west-2":"Z3GKZC51ZF0DB4","eu-west-3":"Z3R1K369G5AVDG","eu-north-1":"Z3BAZG2TWCNX0D","eu-south-1":"Z30OZKI7KPW7MI","eu-south-2":"Z0081959F7139GRJC19J","me-south-1":"Z1MPMWCPA7YB62","me-central-1":"Z06143092I8HRBER9VXCO","sa-east-1":"Z7KQH4QJS55SO"};static getS3WebsiteEndpoint(n,i){return`${n}.s3-website-${i}.amazonaws.com`}static createStoreRecord(n,i,s){return W.createCname(`store.${n}`,i,s)}static createApiRecord(n,i,s){return W.createCname(`api.${n}`,i,s)}static createDocsRecord(n,i,s){return W.createCname(`docs.${n}`,i,s)}static CloudFrontHostedZoneId="Z2FDTNDATAQYW2"}class C{static createCertificate(n){let{domain:i,subdomains:s=[],slug:o,environment:c,validationMethod:u="DNS",hostedZoneId:d}=n,f=r({slug:o,environment:c,resourceType:"acm"}),h=t(`${f}-${i.replace(/\./g,"")}`),S=[i];for(let T of s)if(T==="*")S.push(`*.${i}`);else S.push(`${T}.${i}`);let A={Type:"AWS::CertificateManager::Certificate",Properties:{DomainName:i,SubjectAlternativeNames:S,ValidationMethod:u}};if(u==="DNS"&&d)A.Properties.DomainValidationOptions=S.map((T)=>({DomainName:T,HostedZoneId:d}));return{certificate:A,logicalId:h}}static createKmsKey(n){let{description:i,slug:s,environment:o,enableRotation:c=!0,multiRegion:u=!1}=n,d=r({slug:s,environment:o,resourceType:"kms"}),f=t(d),h={Version:"2012-10-17",Statement:[{Sid:"Enable IAM User Permissions",Effect:"Allow",Principal:{AWS:k.Sub("arn:aws:iam::${AWS::AccountId}:root")},Action:"kms:*",Resource:"*"},{Sid:"Allow services to use the key",Effect:"Allow",Principal:{Service:["s3.amazonaws.com","cloudfront.amazonaws.com","logs.amazonaws.com","secretsmanager.amazonaws.com"]},Action:["kms:Decrypt","kms:GenerateDataKey"],Resource:"*"}]},S={Type:"AWS::KMS::Key",Properties:{Description:i,Enabled:!0,EnableKeyRotation:c,KeyPolicy:h,KeySpec:"SYMMETRIC_DEFAULT",KeyUsage:"ENCRYPT_DECRYPT",MultiRegion:u}},A=t(`${d}-alias`),T={Type:"AWS::KMS::Alias",Properties:{AliasName:`alias/${s}-${o}`,TargetKeyId:k.Ref(f)}};return{key:S,alias:T,logicalId:f,aliasId:A}}static createFirewall(n){let{slug:i,environment:s,scope:o="CLOUDFRONT",defaultAction:c="allow"}=n,u=r({slug:i,environment:s,resourceType:"waf"}),d=t(u);return{webAcl:{Type:"AWS::WAFv2::WebACL",Properties:{Name:u,Scope:o,DefaultAction:c==="allow"?{Allow:{}}:{Block:{}},Description:`WAF for ${i} ${s}`,Rules:[],VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${u}-metric`}}},logicalId:d}}static setRateLimit(n,i){if(!n.Properties.Rules)n.Properties.Rules=[];return n.Properties.Rules.push({Name:i.name,Priority:i.priority,Statement:{RateBasedStatement:{Limit:i.requestsPerWindow,AggregateKeyType:i.aggregateKeyType||"IP"}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${i.name}-metric`}}),n}static blockCountries(n,i){if(!n.Properties.Rules)n.Properties.Rules=[];return n.Properties.Rules.push({Name:i.name,Priority:i.priority,Statement:{GeoMatchStatement:{CountryCodes:i.countryCodes}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${i.name}-metric`}}),n}static blockIpAddresses(n,i,s,o){let c=r({slug:s,environment:o,resourceType:"ipset"}),u=t(`${c}-${i.name}`),d={Type:"AWS::WAFv2::IPSet",Properties:{Name:`${c}-${i.name}`,Scope:n.Properties.Scope,IPAddressVersion:i.ipVersion||"IPV4",Addresses:i.ipAddresses,Description:`Blocked IPs for ${i.name}`}};if(!n.Properties.Rules)n.Properties.Rules=[];return n.Properties.Rules.push({Name:i.name,Priority:i.priority,Statement:{IPSetReferenceStatement:{Arn:k.GetAtt(u,"Arn")}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${i.name}-metric`}}),{webAcl:n,ipSet:d,ipSetLogicalId:u}}static addManagedRules(n,i){if(!n.Properties.Rules)n.Properties.Rules=[];let s={ManagedRuleGroupStatement:{VendorName:i.vendorName,Name:i.ruleName}};if(i.excludedRules&&i.excludedRules.length>0)s.ManagedRuleGroupStatement.ExcludedRules=i.excludedRules.map((o)=>({Name:o}));return n.Properties.Rules.push({Name:i.name,Priority:i.priority,Statement:s,VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${i.name}-metric`}}),n}static ManagedRuleGroups={CoreRuleSet:{vendorName:"AWS",ruleName:"AWSManagedRulesCommonRuleSet"},KnownBadInputs:{vendorName:"AWS",ruleName:"AWSManagedRulesKnownBadInputsRuleSet"},SqlDatabase:{vendorName:"AWS",ruleName:"AWSManagedRulesSQLiRuleSet"},LinuxOS:{vendorName:"AWS",ruleName:"AWSManagedRulesLinuxRuleSet"},PosixOS:{vendorName:"AWS",ruleName:"AWSManagedRulesUnixRuleSet"},AmazonIpReputation:{vendorName:"AWS",ruleName:"AWSManagedRulesAmazonIpReputationList"},AnonymousIpList:{vendorName:"AWS",ruleName:"AWSManagedRulesAnonymousIpList"},BotControl:{vendorName:"AWS",ruleName:"AWSManagedRulesBotControlRuleSet"}};static setPathRateLimit(n,i){if(!n.Properties.Rules)n.Properties.Rules=[];let s=i.paths.map((o)=>({SearchString:o,FieldToMatch:{UriPath:{}},TextTransformation:[{Priority:0,Type:"LOWERCASE"}],PositionalConstraint:"STARTS_WITH"}));return n.Properties.Rules.push({Name:i.name,Priority:i.priority,Statement:{RateBasedStatement:{Limit:i.requestsPerWindow,AggregateKeyType:i.aggregateKeyType||"IP",ScopeDownStatement:{OrStatement:{Statements:s.map((o)=>({ByteMatchStatement:o}))}}}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${i.name}-metric`}}),n}static setHeaderRateLimit(n,i){if(!n.Properties.Rules)n.Properties.Rules=[];let s={RateBasedStatement:{Limit:i.requestsPerWindow,AggregateKeyType:"CUSTOM_KEYS",CustomKeys:[{Header:{Name:i.headerName,TextTransformations:[{Priority:0,Type:"NONE"}]}}]}};if(i.headerValue)s.RateBasedStatement.ScopeDownStatement={ByteMatchStatement:{SearchString:i.headerValue,FieldToMatch:{SingleHeader:{Name:i.headerName}},TextTransformation:[{Priority:0,Type:"NONE"}],PositionalConstraint:"EXACTLY"}};return n.Properties.Rules.push({Name:i.name,Priority:i.priority,Statement:s,Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${i.name}-metric`}}),n}static protectLoginEndpoint(n,i){let{loginPaths:s,priority:o,requestsPerMinute:c=10}=i;return C.setPathRateLimit(n,{name:"LoginRateLimit",priority:o,requestsPerWindow:c*5,paths:s}),n}static protectApiEndpoints(n,i){let{apiPaths:s,priority:o,requestsPerMinute:c=100}=i;return C.setPathRateLimit(n,{name:"ApiRateLimit",priority:o,requestsPerWindow:c*5,paths:s}),n}static createProtectedFirewall(n){let{slug:i,environment:s,scope:o="CLOUDFRONT",enableBotControl:c=!1,enableRateLimiting:u=!0,rateLimitPerMinute:d=2000}=n,{webAcl:f,logicalId:h}=C.createFirewall({slug:i,environment:s,scope:o,defaultAction:"allow"}),S=0;if(f=C.addManagedRules(f,{name:"AWSIPReputationList",priority:S++,...C.ManagedRuleGroups.AmazonIpReputation}),f=C.addManagedRules(f,{name:"AWSAnonymousIPList",priority:S++,...C.ManagedRuleGroups.AnonymousIpList}),f=C.addManagedRules(f,{name:"AWSCoreRuleSet",priority:S++,...C.ManagedRuleGroups.CoreRuleSet}),f=C.addManagedRules(f,{name:"AWSKnownBadInputs",priority:S++,...C.ManagedRuleGroups.KnownBadInputs}),f=C.addManagedRules(f,{name:"AWSSQLi",priority:S++,...C.ManagedRuleGroups.SqlDatabase}),c)f=C.addManagedRules(f,{name:"AWSBotControl",priority:S++,...C.ManagedRuleGroups.BotControl});if(u)f=C.setRateLimit(f,{name:"GlobalRateLimit",priority:S++,requestsPerWindow:d*5});return{webAcl:f,logicalId:h}}static RateLimitPresets={STANDARD:2000,HIGH_TRAFFIC:1e4,STRICT:100,LOGIN:10,API:100}}function jA(n){let i=n.split(".")[0]??"";return i==="a1"||/^[a-z]+\d+g[a-z]*$/.test(i)}function zA(n="t3.micro"){return`/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-${jA(n)?"arm64":"x86_64"}`}function mm(n="t3.micro"){return`{{resolve:ssm:${zA(n)}}}`}class a{static createServer(n){let{slug:i,environment:s,instanceType:o="t3.micro",imageId:c=mm(o),keyName:u,securityGroupIds:d,subnetId:f,userData:h,volumeSize:S=20,volumeType:A="gp3",encrypted:T=!0}=n,v=r({slug:i,environment:s,resourceType:"ec2"}),R=t(v),P={Type:"AWS::EC2::Instance",Properties:{ImageId:c,InstanceType:o,Tags:[{Key:"Name",Value:v},{Key:"Environment",Value:s}]}};if(u)P.Properties.KeyName=u;if(d)P.Properties.SecurityGroupIds=d;if(f)P.Properties.SubnetId=f;if(h)P.Properties.UserData=k.Base64(h);return P.Properties.BlockDeviceMappings=[{DeviceName:"/dev/xvda",Ebs:{VolumeSize:S,VolumeType:A,Encrypted:T,DeleteOnTermination:!0}}],{instance:P,logicalId:R}}static createSecurityGroup(n){let{slug:i,environment:s,vpcId:o,description:c,ingress:u=[],egress:d=[]}=n,f=r({slug:i,environment:s,resourceType:"sg"}),h=t(f),S={Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:c||`Security group for ${i} ${s}`,Tags:[{Key:"Name",Value:f},{Key:"Environment",Value:s}]}};if(o)S.Properties.VpcId=o;if(u.length>0)S.Properties.SecurityGroupIngress=u.map((A)=>({IpProtocol:A.protocol,FromPort:A.fromPort,ToPort:A.toPort,CidrIp:A.cidr,SourceSecurityGroupId:A.sourceSecurityGroupId}));if(d.length>0)S.Properties.SecurityGroupEgress=d.map((A)=>({IpProtocol:A.protocol,FromPort:A.fromPort,ToPort:A.toPort,CidrIp:A.cidr,DestinationSecurityGroupId:A.sourceSecurityGroupId}));return{securityGroup:S,logicalId:h}}static createWebServerSecurityGroup(n,i,s){return a.createSecurityGroup({slug:n,environment:i,vpcId:s,description:"Security group for web servers - HTTP, HTTPS, SSH",ingress:[{protocol:"tcp",fromPort:80,toPort:80,cidr:"0.0.0.0/0"},{protocol:"tcp",fromPort:443,toPort:443,cidr:"0.0.0.0/0"},{protocol:"tcp",fromPort:22,toPort:22,cidr:"0.0.0.0/0"}],egress:[{protocol:"-1",fromPort:0,toPort:0,cidr:"0.0.0.0/0"}]})}static createLoadBalancer(n){let{slug:i,environment:s,scheme:o="internet-facing",subnets:c,securityGroups:u,type:d="application"}=n,f=r({slug:i,environment:s,resourceType:"alb"}),h=t(f),S={Type:"AWS::ElasticLoadBalancingV2::LoadBalancer",Properties:{Name:f,Scheme:o,Type:d,Subnets:c,Tags:[{Key:"Name",Value:f},{Key:"Environment",Value:s}]}};if(u)S.Properties.SecurityGroups=u;return{loadBalancer:S,logicalId:h}}static createTargetGroup(n){let{slug:i,environment:s,port:o,protocol:c="HTTP",vpcId:u,targetType:d="ip",healthCheckPath:f="/",healthCheckInterval:h=30,healthCheckTimeout:S=5,healthyThreshold:A=2,unhealthyThreshold:T=3}=n,v=r({slug:i,environment:s,resourceType:"tg"}),R=t(v);return{targetGroup:{Type:"AWS::ElasticLoadBalancingV2::TargetGroup",Properties:{Name:v,Port:o,Protocol:c,VpcId:u,TargetType:d,HealthCheckEnabled:!0,HealthCheckProtocol:c,HealthCheckPath:f,HealthCheckIntervalSeconds:h,HealthCheckTimeoutSeconds:S,HealthyThresholdCount:A,UnhealthyThresholdCount:T,Tags:[{Key:"Name",Value:v},{Key:"Environment",Value:s}]}},logicalId:R}}static createListener(n,i){let{port:s,protocol:o="HTTP",certificateArn:c,defaultTargetGroupArn:u}=i,d=t(`listener-${n}-${s}`),f={Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:k.Ref(n),Port:s,Protocol:o,DefaultActions:[{Type:"forward",TargetGroupArn:u}]}};if(o==="HTTPS"&&c)f.Properties.Certificates=[{CertificateArn:c}],f.Properties.SslPolicy="ELBSecurityPolicy-TLS13-1-2-2021-06";return{listener:f,logicalId:d}}static createEcsCluster(n,i){let s=r({slug:n,environment:i,resourceType:"ecs-cluster"}),o=t(s);return{cluster:{Type:"AWS::ECS::Cluster",Properties:{ClusterName:s,Tags:[{Key:"Name",Value:s},{Key:"Environment",Value:i}]}},logicalId:o}}static createFargateService(n){let{slug:i,environment:s,image:o,cpu:c="256",memory:u="512",desiredCount:d=1,containerPort:f=8080,environmentVariables:h={},secrets:S=[],healthCheck:A,logGroup:T,subnets:v,securityGroups:R,targetGroupArn:P}=n,{cluster:E,logicalId:I}=a.createEcsCluster(i,s),M=r({slug:i,environment:s,resourceType:"fargate"}),L=t(`${M}-execution-role`),x={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ecs-tasks.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"]}},O=t(`${M}-task-role`),B={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ecs-tasks.amazonaws.com"},Action:"sts:AssumeRole"}]}}},F=t(`${M}-task`),U={Type:"AWS::ECS::TaskDefinition",Properties:{Family:M,TaskRoleArn:k.GetAtt(O,"Arn"),ExecutionRoleArn:k.GetAtt(L,"Arn"),NetworkMode:"awsvpc",RequiresCompatibilities:["FARGATE"],Cpu:c,Memory:u,ContainerDefinitions:[{Name:i,Image:o,Essential:!0,PortMappings:[{ContainerPort:f,Protocol:"tcp"}],Environment:Object.entries(h).map(([z,se])=>({Name:z,Value:se})),Secrets:S.map((z)=>({Name:z.name,ValueFrom:z.valueFrom}))}],Tags:[{Key:"Name",Value:M},{Key:"Environment",Value:s}]}};if(A)U.Properties.ContainerDefinitions[0].HealthCheck={Command:A.command,Interval:A.interval||30,Timeout:A.timeout||5,Retries:A.retries||3,StartPeriod:60};if(T)U.Properties.ContainerDefinitions[0].LogConfiguration={LogDriver:"awslogs",Options:{"awslogs-group":T,"awslogs-region":k.Ref("AWS::Region"),"awslogs-stream-prefix":i}};let j=t(`${M}-service`),H={Type:"AWS::ECS::Service",Properties:{ServiceName:M,Cluster:k.Ref(I),TaskDefinition:k.Ref(F),DesiredCount:d,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{Subnets:v,SecurityGroups:R,AssignPublicIp:"ENABLED"}},Tags:[{Key:"Name",Value:M},{Key:"Environment",Value:s}]}};if(P)H.Properties.LoadBalancers=[{TargetGroupArn:P,ContainerName:i,ContainerPort:f}];return{cluster:E,taskDefinition:U,service:H,taskRole:B,executionRole:x,clusterLogicalId:I,taskDefinitionLogicalId:F,serviceLogicalId:j,taskRoleLogicalId:O,executionRoleLogicalId:L}}static createLambdaFunction(n){let{slug:i,environment:s,runtime:o,handler:c,code:u,timeout:d=30,memorySize:f=128,environmentVariables:h={},vpcConfig:S}=n,A=r({slug:i,environment:s,resourceType:"lambda"}),T=t(A),v=t(`${A}-role`),R={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"]}};if(S)R.Properties.ManagedPolicyArns.push("arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole");let P={Type:"AWS::Lambda::Function",Properties:{FunctionName:A,Runtime:o,Role:k.GetAtt(v,"Arn"),Handler:c,Code:{...u.s3Bucket&&{S3Bucket:u.s3Bucket},...u.s3Key&&{S3Key:u.s3Key},...u.zipFile&&{ZipFile:u.zipFile}},Timeout:d,MemorySize:f,Tags:[{Key:"Name",Value:A},{Key:"Environment",Value:s}]}};if(Object.keys(h).length>0)P.Properties.Environment={Variables:h};if(S)P.Properties.VpcConfig={SecurityGroupIds:S.securityGroupIds,SubnetIds:S.subnetIds};return{lambdaFunction:P,role:R,logicalId:T,roleLogicalId:v}}static generateNodeServerUserData(n={}){let{nodeVersion:i="20",appRepo:s,environment:o={}}=n,c=Object.entries(o).map(([u,d])=>`echo "export ${u}='${d}'" >> /etc/environment`).join(`
|
|
200
|
+
`.trim()};static Config={ttl:(n)=>{let{min:i=0,max:s=86400,default:o=86400}=n;return{MinTTL:i,MaxTTL:s,DefaultTTL:o}},cookies:(n,i)=>{let s={Forward:n==="allowList"?"whitelist":n};if(n==="allowList"&&i)s.WhitelistedNames=i;return s},allowedMethods:(n)=>{let i={ALL:["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"],GET_HEAD:["GET","HEAD"],GET_HEAD_OPTIONS:["GET","HEAD","OPTIONS"]};return i[n]||i.GET_HEAD},cachedMethods:(n)=>{let i={GET_HEAD:["GET","HEAD"],GET_HEAD_OPTIONS:["GET","HEAD","OPTIONS"]};return i[n]||i.GET_HEAD},ttlPresets:{static:{min:0,max:31536000,default:31536000},dynamic:{min:0,max:0,default:0},api:{min:0,max:3600,default:60},html:{min:0,max:86400,default:86400},images:{min:0,max:604800,default:604800}},cacheBehavior:(n)=>{let{ttl:i={min:0,max:86400,default:86400},cookies:s="none",allowedCookies:o,allowedMethods:c="GET_HEAD",cachedMethods:u="GET_HEAD",compress:d=!0,forwardQueryString:f=!0,forwardHeaders:h=[]}=n;return{MinTTL:i.min,MaxTTL:i.max,DefaultTTL:i.default,Compress:d,AllowedMethods:Ce.Config.allowedMethods(c),CachedMethods:Ce.Config.cachedMethods(u),ForwardedValues:{QueryString:f,Headers:h,Cookies:Ce.Config.cookies(s,o)}}}};static applyConfig(n,i){let s=n.Properties.DistributionConfig.DefaultCacheBehavior;if(i.ttl)s.MinTTL=i.ttl.min,s.MaxTTL=i.ttl.max,s.DefaultTTL=i.ttl.default;if(i.compress!==void 0)s.Compress=i.compress;if(i.allowedMethods)s.AllowedMethods=Ce.Config.allowedMethods(i.allowedMethods);if(i.cachedMethods)s.CachedMethods=Ce.Config.cachedMethods(i.cachedMethods);if(i.cookies){if(!s.ForwardedValues)s.ForwardedValues={QueryString:!0};s.ForwardedValues.Cookies=Ce.Config.cookies(i.cookies,i.allowedCookies)}return n}}var qA=[403,404,500,502,503,504],el="TsCloud::StorageFailover",Oo="AllowCloudFrontFailoverRead",vr=/^[a-z]{2}(?:-gov)?-[a-z]+-\d$/,Tr=/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/;function lm(n){let{failover:i,primaryBucket:s,primaryRegion:o}=n,c=n.where??"storage failover";if(!i||typeof i!=="object")throw Error(`${c}.failover must be an object such as { region: 'us-west-2' }.`);if(!i.region||!vr.test(i.region))throw Error(`${c}.failover.region must be an AWS region such as 'us-west-2', got ${JSON.stringify(i.region)}.`);if(i.region===o)throw Error(`${c}.failover.region is ${i.region}, the same region as the primary bucket. Failover only helps when the replica is in another region.`);let u=i.bucket??`${s}-${i.region}`;if(!Tr.test(u)||u.includes("..")){let d=i.bucket===void 0&&u.length>63?` The default name (<primary bucket>-<region>) is ${u.length} characters; S3 allows 63. Set ${c}.failover.bucket.`:"";throw Error(`${c}.failover: "${u}" is not a valid S3 bucket name.${d}`)}if(u===s)throw Error(`${c}.failover.bucket must differ from the primary bucket "${s}".`);return{replicaBucket:u,replicaRegion:i.region,replicate:i.replicate!==!1,statusCodes:Bo(i.statusCodes??qA),primaryConnection:ce(i,`${c}.failover`)}}function um(n,i){return`${n}.s3.${i}.amazonaws.com`}function gm(n){let i=`arn:aws:s3:::${n.primaryBucket}`,s=`arn:aws:s3:::${n.replicaBucket}`;return{Type:"AWS::IAM::Role",Properties:{...n.roleName?{RoleName:n.roleName}:{},AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"s3.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"failover-replication",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["s3:GetReplicationConfiguration","s3:ListBucket"],Resource:i},{Effect:"Allow",Action:["s3:GetObjectVersionForReplication","s3:GetObjectVersionAcl","s3:GetObjectVersionTagging"],Resource:`${i}/*`},{Effect:"Allow",Action:["s3:ReplicateObject","s3:ReplicateDelete","s3:ReplicateTags"],Resource:`${s}/*`}]}}]}}}function pm(n){return{Role:n.roleArn,Rules:[{Id:"cloudfront-failover-replica",Status:"Enabled",Priority:1,Filter:{Prefix:""},DeleteMarkerReplication:{Status:"Enabled"},Destination:{Bucket:`arn:aws:s3:::${n.replicaBucket}`}}]}}function tl(n){return{Sid:Oo,Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:`arn:aws:s3:::${n.replicaBucket}/*`,Condition:{StringEquals:{"AWS:SourceArn":n.distributionArn}}}}function _I(n){let s=(typeof n==="string"?JSON.parse(n):n)?.Metadata?.[el];return Array.isArray(s)?s:[]}class W{static createHostedZone(n){let{domain:i,slug:s,environment:o,comment:c}=n,u=r({slug:s,environment:o,resourceType:"hostedzone"}),d=t(`${u}-${i.replace(/\./g,"")}`);return{zone:{Type:"AWS::Route53::HostedZone",Properties:{Name:i,HostedZoneConfig:{Comment:c||`Hosted zone for ${i}`}}},logicalId:d}}static createRecord(n){let{hostedZoneId:i,hostedZoneName:s,name:o,type:c,ttl:u,values:d,aliasTarget:f}=n,h=t(`record-${o.replace(/\./g,"")}-${c}`),S={Type:"AWS::Route53::RecordSet",Properties:{Name:o,Type:c}};if(i)S.Properties.HostedZoneId=i;else if(s)S.Properties.HostedZoneName=s;if(f)S.Properties.AliasTarget={DNSName:f.dnsName,HostedZoneId:f.hostedZoneId,EvaluateTargetHealth:f.evaluateTargetHealth??!1};else S.Properties.TTL=u||300,S.Properties.ResourceRecords=d||[];return{record:S,logicalId:h}}static createCloudFrontAlias(n,i,s){return W.createRecord({hostedZoneId:s,name:n,type:"A",aliasTarget:{dnsName:i,hostedZoneId:"Z2FDTNDATAQYW2",evaluateTargetHealth:!1}})}static createAlbAlias(n,i,s,o){return W.createRecord({hostedZoneId:o,name:n,type:"A",aliasTarget:{dnsName:i,hostedZoneId:s,evaluateTargetHealth:!0}})}static createCname(n,i,s,o=300){return W.createRecord({hostedZoneId:s,name:n,type:"CNAME",ttl:o,values:[i]})}static createWwwRedirect(n,i){return W.createRecord({hostedZoneId:i,name:`www.${n}`,type:"CNAME",ttl:300,values:[n]})}static createMxRecords(n,i,s,o=300){return W.createRecord({hostedZoneId:s,name:n,type:"MX",ttl:o,values:i.map((c)=>`${c.priority} ${c.server}`)})}static createTxtRecord(n,i,s,o=300){return W.createRecord({hostedZoneId:s,name:n,type:"TXT",ttl:o,values:[`"${i}"`]})}static createSpfRecord(n,i,s){return W.createTxtRecord(n,i,s)}static createDmarcRecord(n,i,s,o){let c=`v=DMARC1; p=${i}; rua=mailto:${s}`;return W.createTxtRecord(`_dmarc.${n}`,c,o)}static createS3WebsiteAlias(n,i,s,o){return W.createRecord({hostedZoneId:o,name:n,type:"A",aliasTarget:{dnsName:i,hostedZoneId:s,evaluateTargetHealth:!1}})}static S3WebsiteHostedZoneIds={"us-east-1":"Z3AQBSTGFYJSTF","us-east-2":"Z2O1EMRO9K5GLX","us-west-1":"Z2F56UZL2M1ACD","us-west-2":"Z3BJ6K6RIION7M","af-south-1":"Z83WF9RJE8B12","ap-east-1":"ZNB98KWMFR0R6","ap-south-1":"Z11RGJOFQNVJUP","ap-south-2":"Z02976202B4EZMXIPMXF7","ap-northeast-1":"Z2M4EHUR26P7ZW","ap-northeast-2":"Z3W03O7B5YMIYP","ap-northeast-3":"Z2YQB5RD63NC85","ap-southeast-1":"Z3O0J2DXBE1FTB","ap-southeast-2":"Z1WCIBER6CPFUU","ap-southeast-3":"Z01613992JD795ZI93075","ca-central-1":"Z1QDHH18159H29","eu-central-1":"Z21DNDUVLTQW6Q","eu-central-2":"Z030506016YDQGETNASS","eu-west-1":"Z1BKCTXD74EZPE","eu-west-2":"Z3GKZC51ZF0DB4","eu-west-3":"Z3R1K369G5AVDG","eu-north-1":"Z3BAZG2TWCNX0D","eu-south-1":"Z30OZKI7KPW7MI","eu-south-2":"Z0081959F7139GRJC19J","me-south-1":"Z1MPMWCPA7YB62","me-central-1":"Z06143092I8HRBER9VXCO","sa-east-1":"Z7KQH4QJS55SO"};static getS3WebsiteEndpoint(n,i){return`${n}.s3-website-${i}.amazonaws.com`}static createStoreRecord(n,i,s){return W.createCname(`store.${n}`,i,s)}static createApiRecord(n,i,s){return W.createCname(`api.${n}`,i,s)}static createDocsRecord(n,i,s){return W.createCname(`docs.${n}`,i,s)}static CloudFrontHostedZoneId="Z2FDTNDATAQYW2"}class C{static createCertificate(n){let{domain:i,subdomains:s=[],slug:o,environment:c,validationMethod:u="DNS",hostedZoneId:d}=n,f=r({slug:o,environment:c,resourceType:"acm"}),h=t(`${f}-${i.replace(/\./g,"")}`),S=[i];for(let T of s)if(T==="*")S.push(`*.${i}`);else S.push(`${T}.${i}`);let A={Type:"AWS::CertificateManager::Certificate",Properties:{DomainName:i,SubjectAlternativeNames:S,ValidationMethod:u}};if(u==="DNS"&&d)A.Properties.DomainValidationOptions=S.map((T)=>({DomainName:T,HostedZoneId:d}));return{certificate:A,logicalId:h}}static createKmsKey(n){let{description:i,slug:s,environment:o,enableRotation:c=!0,multiRegion:u=!1}=n,d=r({slug:s,environment:o,resourceType:"kms"}),f=t(d),h={Version:"2012-10-17",Statement:[{Sid:"Enable IAM User Permissions",Effect:"Allow",Principal:{AWS:k.Sub("arn:aws:iam::${AWS::AccountId}:root")},Action:"kms:*",Resource:"*"},{Sid:"Allow services to use the key",Effect:"Allow",Principal:{Service:["s3.amazonaws.com","cloudfront.amazonaws.com","logs.amazonaws.com","secretsmanager.amazonaws.com"]},Action:["kms:Decrypt","kms:GenerateDataKey"],Resource:"*"}]},S={Type:"AWS::KMS::Key",Properties:{Description:i,Enabled:!0,EnableKeyRotation:c,KeyPolicy:h,KeySpec:"SYMMETRIC_DEFAULT",KeyUsage:"ENCRYPT_DECRYPT",MultiRegion:u}},A=t(`${d}-alias`),T={Type:"AWS::KMS::Alias",Properties:{AliasName:`alias/${s}-${o}`,TargetKeyId:k.Ref(f)}};return{key:S,alias:T,logicalId:f,aliasId:A}}static createFirewall(n){let{slug:i,environment:s,scope:o="CLOUDFRONT",defaultAction:c="allow"}=n,u=r({slug:i,environment:s,resourceType:"waf"}),d=t(u);return{webAcl:{Type:"AWS::WAFv2::WebACL",Properties:{Name:u,Scope:o,DefaultAction:c==="allow"?{Allow:{}}:{Block:{}},Description:`WAF for ${i} ${s}`,Rules:[],VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${u}-metric`}}},logicalId:d}}static setRateLimit(n,i){if(!n.Properties.Rules)n.Properties.Rules=[];return n.Properties.Rules.push({Name:i.name,Priority:i.priority,Statement:{RateBasedStatement:{Limit:i.requestsPerWindow,AggregateKeyType:i.aggregateKeyType||"IP"}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${i.name}-metric`}}),n}static blockCountries(n,i){if(!n.Properties.Rules)n.Properties.Rules=[];return n.Properties.Rules.push({Name:i.name,Priority:i.priority,Statement:{GeoMatchStatement:{CountryCodes:i.countryCodes}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${i.name}-metric`}}),n}static blockIpAddresses(n,i,s,o){let c=r({slug:s,environment:o,resourceType:"ipset"}),u=t(`${c}-${i.name}`),d={Type:"AWS::WAFv2::IPSet",Properties:{Name:`${c}-${i.name}`,Scope:n.Properties.Scope,IPAddressVersion:i.ipVersion||"IPV4",Addresses:i.ipAddresses,Description:`Blocked IPs for ${i.name}`}};if(!n.Properties.Rules)n.Properties.Rules=[];return n.Properties.Rules.push({Name:i.name,Priority:i.priority,Statement:{IPSetReferenceStatement:{Arn:k.GetAtt(u,"Arn")}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${i.name}-metric`}}),{webAcl:n,ipSet:d,ipSetLogicalId:u}}static addManagedRules(n,i){if(!n.Properties.Rules)n.Properties.Rules=[];let s={ManagedRuleGroupStatement:{VendorName:i.vendorName,Name:i.ruleName}};if(i.excludedRules&&i.excludedRules.length>0)s.ManagedRuleGroupStatement.ExcludedRules=i.excludedRules.map((o)=>({Name:o}));return n.Properties.Rules.push({Name:i.name,Priority:i.priority,Statement:s,VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${i.name}-metric`}}),n}static ManagedRuleGroups={CoreRuleSet:{vendorName:"AWS",ruleName:"AWSManagedRulesCommonRuleSet"},KnownBadInputs:{vendorName:"AWS",ruleName:"AWSManagedRulesKnownBadInputsRuleSet"},SqlDatabase:{vendorName:"AWS",ruleName:"AWSManagedRulesSQLiRuleSet"},LinuxOS:{vendorName:"AWS",ruleName:"AWSManagedRulesLinuxRuleSet"},PosixOS:{vendorName:"AWS",ruleName:"AWSManagedRulesUnixRuleSet"},AmazonIpReputation:{vendorName:"AWS",ruleName:"AWSManagedRulesAmazonIpReputationList"},AnonymousIpList:{vendorName:"AWS",ruleName:"AWSManagedRulesAnonymousIpList"},BotControl:{vendorName:"AWS",ruleName:"AWSManagedRulesBotControlRuleSet"}};static setPathRateLimit(n,i){if(!n.Properties.Rules)n.Properties.Rules=[];let s=i.paths.map((o)=>({SearchString:o,FieldToMatch:{UriPath:{}},TextTransformation:[{Priority:0,Type:"LOWERCASE"}],PositionalConstraint:"STARTS_WITH"}));return n.Properties.Rules.push({Name:i.name,Priority:i.priority,Statement:{RateBasedStatement:{Limit:i.requestsPerWindow,AggregateKeyType:i.aggregateKeyType||"IP",ScopeDownStatement:{OrStatement:{Statements:s.map((o)=>({ByteMatchStatement:o}))}}}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${i.name}-metric`}}),n}static setHeaderRateLimit(n,i){if(!n.Properties.Rules)n.Properties.Rules=[];let s={RateBasedStatement:{Limit:i.requestsPerWindow,AggregateKeyType:"CUSTOM_KEYS",CustomKeys:[{Header:{Name:i.headerName,TextTransformations:[{Priority:0,Type:"NONE"}]}}]}};if(i.headerValue)s.RateBasedStatement.ScopeDownStatement={ByteMatchStatement:{SearchString:i.headerValue,FieldToMatch:{SingleHeader:{Name:i.headerName}},TextTransformation:[{Priority:0,Type:"NONE"}],PositionalConstraint:"EXACTLY"}};return n.Properties.Rules.push({Name:i.name,Priority:i.priority,Statement:s,Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${i.name}-metric`}}),n}static protectLoginEndpoint(n,i){let{loginPaths:s,priority:o,requestsPerMinute:c=10}=i;return C.setPathRateLimit(n,{name:"LoginRateLimit",priority:o,requestsPerWindow:c*5,paths:s}),n}static protectApiEndpoints(n,i){let{apiPaths:s,priority:o,requestsPerMinute:c=100}=i;return C.setPathRateLimit(n,{name:"ApiRateLimit",priority:o,requestsPerWindow:c*5,paths:s}),n}static createProtectedFirewall(n){let{slug:i,environment:s,scope:o="CLOUDFRONT",enableBotControl:c=!1,enableRateLimiting:u=!0,rateLimitPerMinute:d=2000}=n,{webAcl:f,logicalId:h}=C.createFirewall({slug:i,environment:s,scope:o,defaultAction:"allow"}),S=0;if(f=C.addManagedRules(f,{name:"AWSIPReputationList",priority:S++,...C.ManagedRuleGroups.AmazonIpReputation}),f=C.addManagedRules(f,{name:"AWSAnonymousIPList",priority:S++,...C.ManagedRuleGroups.AnonymousIpList}),f=C.addManagedRules(f,{name:"AWSCoreRuleSet",priority:S++,...C.ManagedRuleGroups.CoreRuleSet}),f=C.addManagedRules(f,{name:"AWSKnownBadInputs",priority:S++,...C.ManagedRuleGroups.KnownBadInputs}),f=C.addManagedRules(f,{name:"AWSSQLi",priority:S++,...C.ManagedRuleGroups.SqlDatabase}),c)f=C.addManagedRules(f,{name:"AWSBotControl",priority:S++,...C.ManagedRuleGroups.BotControl});if(u)f=C.setRateLimit(f,{name:"GlobalRateLimit",priority:S++,requestsPerWindow:d*5});return{webAcl:f,logicalId:h}}static RateLimitPresets={STANDARD:2000,HIGH_TRAFFIC:1e4,STRICT:100,LOGIN:10,API:100}}function jA(n){let i=n.split(".")[0]??"";return i==="a1"||/^[a-z]+\d+g[a-z]*$/.test(i)}function zA(n="t3.micro"){return`/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-${jA(n)?"arm64":"x86_64"}`}function mm(n="t3.micro"){return`{{resolve:ssm:${zA(n)}}}`}class a{static createServer(n){let{slug:i,environment:s,instanceType:o="t3.micro",imageId:c=mm(o),keyName:u,securityGroupIds:d,subnetId:f,userData:h,volumeSize:S=20,volumeType:A="gp3",encrypted:T=!0}=n,v=r({slug:i,environment:s,resourceType:"ec2"}),R=t(v),P={Type:"AWS::EC2::Instance",Properties:{ImageId:c,InstanceType:o,Tags:[{Key:"Name",Value:v},{Key:"Environment",Value:s}]}};if(u)P.Properties.KeyName=u;if(d)P.Properties.SecurityGroupIds=d;if(f)P.Properties.SubnetId=f;if(h)P.Properties.UserData=k.Base64(h);return P.Properties.BlockDeviceMappings=[{DeviceName:"/dev/xvda",Ebs:{VolumeSize:S,VolumeType:A,Encrypted:T,DeleteOnTermination:!0}}],{instance:P,logicalId:R}}static createSecurityGroup(n){let{slug:i,environment:s,vpcId:o,description:c,ingress:u=[],egress:d=[]}=n,f=r({slug:i,environment:s,resourceType:"sg"}),h=t(f),S={Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:c||`Security group for ${i} ${s}`,Tags:[{Key:"Name",Value:f},{Key:"Environment",Value:s}]}};if(o)S.Properties.VpcId=o;if(u.length>0)S.Properties.SecurityGroupIngress=u.map((A)=>({IpProtocol:A.protocol,FromPort:A.fromPort,ToPort:A.toPort,CidrIp:A.cidr,SourceSecurityGroupId:A.sourceSecurityGroupId}));if(d.length>0)S.Properties.SecurityGroupEgress=d.map((A)=>({IpProtocol:A.protocol,FromPort:A.fromPort,ToPort:A.toPort,CidrIp:A.cidr,DestinationSecurityGroupId:A.sourceSecurityGroupId}));return{securityGroup:S,logicalId:h}}static createWebServerSecurityGroup(n,i,s){return a.createSecurityGroup({slug:n,environment:i,vpcId:s,description:"Security group for web servers - HTTP, HTTPS, SSH",ingress:[{protocol:"tcp",fromPort:80,toPort:80,cidr:"0.0.0.0/0"},{protocol:"tcp",fromPort:443,toPort:443,cidr:"0.0.0.0/0"},{protocol:"tcp",fromPort:22,toPort:22,cidr:"0.0.0.0/0"}],egress:[{protocol:"-1",fromPort:0,toPort:0,cidr:"0.0.0.0/0"}]})}static createLoadBalancer(n){let{slug:i,environment:s,scheme:o="internet-facing",subnets:c,securityGroups:u,type:d="application"}=n,f=r({slug:i,environment:s,resourceType:"alb"}),h=t(f),S={Type:"AWS::ElasticLoadBalancingV2::LoadBalancer",Properties:{Name:f,Scheme:o,Type:d,Subnets:c,Tags:[{Key:"Name",Value:f},{Key:"Environment",Value:s}]}};if(u)S.Properties.SecurityGroups=u;return{loadBalancer:S,logicalId:h}}static createTargetGroup(n){let{slug:i,environment:s,port:o,protocol:c="HTTP",vpcId:u,targetType:d="ip",healthCheckPath:f="/",healthCheckInterval:h=30,healthCheckTimeout:S=5,healthyThreshold:A=2,unhealthyThreshold:T=3}=n,v=r({slug:i,environment:s,resourceType:"tg"}),R=t(v);return{targetGroup:{Type:"AWS::ElasticLoadBalancingV2::TargetGroup",Properties:{Name:v,Port:o,Protocol:c,VpcId:u,TargetType:d,HealthCheckEnabled:!0,HealthCheckProtocol:c,HealthCheckPath:f,HealthCheckIntervalSeconds:h,HealthCheckTimeoutSeconds:S,HealthyThresholdCount:A,UnhealthyThresholdCount:T,Tags:[{Key:"Name",Value:v},{Key:"Environment",Value:s}]}},logicalId:R}}static createListener(n,i){let{port:s,protocol:o="HTTP",certificateArn:c,defaultTargetGroupArn:u}=i,d=t(`listener-${n}-${s}`),f={Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:k.Ref(n),Port:s,Protocol:o,DefaultActions:[{Type:"forward",TargetGroupArn:u}]}};if(o==="HTTPS"&&c)f.Properties.Certificates=[{CertificateArn:c}],f.Properties.SslPolicy="ELBSecurityPolicy-TLS13-1-2-2021-06";return{listener:f,logicalId:d}}static createEcsCluster(n,i){let s=r({slug:n,environment:i,resourceType:"ecs-cluster"}),o=t(s);return{cluster:{Type:"AWS::ECS::Cluster",Properties:{ClusterName:s,Tags:[{Key:"Name",Value:s},{Key:"Environment",Value:i}]}},logicalId:o}}static createFargateService(n){let{slug:i,environment:s,image:o,cpu:c="256",memory:u="512",desiredCount:d=1,containerPort:f=8080,environmentVariables:h={},secrets:S=[],healthCheck:A,logGroup:T,subnets:v,securityGroups:R,targetGroupArn:P}=n,{cluster:E,logicalId:I}=a.createEcsCluster(i,s),M=r({slug:i,environment:s,resourceType:"fargate"}),L=t(`${M}-execution-role`),x={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ecs-tasks.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"]}},O=t(`${M}-task-role`),B={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ecs-tasks.amazonaws.com"},Action:"sts:AssumeRole"}]}}},F=t(`${M}-task`),U={Type:"AWS::ECS::TaskDefinition",Properties:{Family:M,TaskRoleArn:k.GetAtt(O,"Arn"),ExecutionRoleArn:k.GetAtt(L,"Arn"),NetworkMode:"awsvpc",RequiresCompatibilities:["FARGATE"],Cpu:c,Memory:u,ContainerDefinitions:[{Name:i,Image:o,Essential:!0,PortMappings:[{ContainerPort:f,Protocol:"tcp"}],Environment:Object.entries(h).map(([z,ae])=>({Name:z,Value:ae})),Secrets:S.map((z)=>({Name:z.name,ValueFrom:z.valueFrom}))}],Tags:[{Key:"Name",Value:M},{Key:"Environment",Value:s}]}};if(A)U.Properties.ContainerDefinitions[0].HealthCheck={Command:A.command,Interval:A.interval||30,Timeout:A.timeout||5,Retries:A.retries||3,StartPeriod:60};if(T)U.Properties.ContainerDefinitions[0].LogConfiguration={LogDriver:"awslogs",Options:{"awslogs-group":T,"awslogs-region":k.Ref("AWS::Region"),"awslogs-stream-prefix":i}};let j=t(`${M}-service`),H={Type:"AWS::ECS::Service",Properties:{ServiceName:M,Cluster:k.Ref(I),TaskDefinition:k.Ref(F),DesiredCount:d,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{Subnets:v,SecurityGroups:R,AssignPublicIp:"ENABLED"}},Tags:[{Key:"Name",Value:M},{Key:"Environment",Value:s}]}};if(P)H.Properties.LoadBalancers=[{TargetGroupArn:P,ContainerName:i,ContainerPort:f}];return{cluster:E,taskDefinition:U,service:H,taskRole:B,executionRole:x,clusterLogicalId:I,taskDefinitionLogicalId:F,serviceLogicalId:j,taskRoleLogicalId:O,executionRoleLogicalId:L}}static createLambdaFunction(n){let{slug:i,environment:s,runtime:o,handler:c,code:u,timeout:d=30,memorySize:f=128,environmentVariables:h={},vpcConfig:S}=n,A=r({slug:i,environment:s,resourceType:"lambda"}),T=t(A),v=t(`${A}-role`),R={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"]}};if(S)R.Properties.ManagedPolicyArns.push("arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole");let P={Type:"AWS::Lambda::Function",Properties:{FunctionName:A,Runtime:o,Role:k.GetAtt(v,"Arn"),Handler:c,Code:{...u.s3Bucket&&{S3Bucket:u.s3Bucket},...u.s3Key&&{S3Key:u.s3Key},...u.zipFile&&{ZipFile:u.zipFile}},Timeout:d,MemorySize:f,Tags:[{Key:"Name",Value:A},{Key:"Environment",Value:s}]}};if(Object.keys(h).length>0)P.Properties.Environment={Variables:h};if(S)P.Properties.VpcConfig={SecurityGroupIds:S.securityGroupIds,SubnetIds:S.subnetIds};return{lambdaFunction:P,role:R,logicalId:T,roleLogicalId:v}}static generateNodeServerUserData(n={}){let{nodeVersion:i="20",appRepo:s,environment:o={}}=n,c=Object.entries(o).map(([u,d])=>`echo "export ${u}='${d}'" >> /etc/environment`).join(`
|
|
201
201
|
`);return`#!/bin/bash
|
|
202
202
|
# Update system
|
|
203
203
|
yum update -y
|
|
@@ -569,7 +569,7 @@ ufw default allow outgoing
|
|
|
569
569
|
${n.map((i)=>`ufw allow ${i}`).join(`
|
|
570
570
|
`)}
|
|
571
571
|
ufw --force enable
|
|
572
|
-
`},Presets:{bunWithNginx:(n,i=3000)=>a.UserData.generateAppServerScript({runtime:"bun",webServer:"nginx",processManager:"systemd",domain:n,appPort:i,enableSsl:!0}),bunWithCaddy:(n,i=3000)=>a.UserData.generateAppServerScript({runtime:"bun",webServer:"caddy",processManager:"systemd",domain:n,appPort:i,enableSsl:!1}),nodeWithPm2:(n,i=3000)=>a.UserData.generateAppServerScript({runtime:"node",webServer:"nginx",processManager:"pm2",domain:n,appPort:i,enableSsl:!0}),worker:(n="bun")=>a.UserData.generateAppServerScript({runtime:n,webServer:"none",processManager:"systemd",enableSsl:!1})}};static createElasticIp(n){let{slug:i,environment:s,domain:o,instanceLogicalId:c}=n,u=r({slug:i,environment:s,resourceType:"eip"}),d=t(u),f={Type:"AWS::EC2::EIP",Properties:{Domain:"vpc",Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:s},...o?[{Key:"Domain",Value:o}]:[]]}},h={[d]:f},S,A;if(c)A=t(`${u}-assoc`),S={Type:"AWS::EC2::EIPAssociation",Properties:{AllocationId:k.GetAtt(d,"AllocationId"),InstanceId:k.Ref(c)}},h[A]=S;return{eip:f,eipAssociation:S,eipLogicalId:d,associationLogicalId:A,resources:h}}static createServerModeStack(n){let{slug:i,environment:s,vpcId:o,subnetId:c,instanceType:u="t3.small",imageId:d="ami-0f3caa1cf4417e51b",keyName:f,domain:h,userData:S,allowedPorts:A=[22,80,443],volumeSize:T=20,volumeType:v="gp3"}=n,R={},P=r({slug:i,environment:s,resourceType:"server-sg"}),E=t(P),I={Type:"AWS::EC2::SecurityGroup",Properties:{GroupName:P,GroupDescription:`Security group for ${i} server`,VpcId:o,SecurityGroupIngress:A.map((
|
|
572
|
+
`},Presets:{bunWithNginx:(n,i=3000)=>a.UserData.generateAppServerScript({runtime:"bun",webServer:"nginx",processManager:"systemd",domain:n,appPort:i,enableSsl:!0}),bunWithCaddy:(n,i=3000)=>a.UserData.generateAppServerScript({runtime:"bun",webServer:"caddy",processManager:"systemd",domain:n,appPort:i,enableSsl:!1}),nodeWithPm2:(n,i=3000)=>a.UserData.generateAppServerScript({runtime:"node",webServer:"nginx",processManager:"pm2",domain:n,appPort:i,enableSsl:!0}),worker:(n="bun")=>a.UserData.generateAppServerScript({runtime:n,webServer:"none",processManager:"systemd",enableSsl:!1})}};static createElasticIp(n){let{slug:i,environment:s,domain:o,instanceLogicalId:c}=n,u=r({slug:i,environment:s,resourceType:"eip"}),d=t(u),f={Type:"AWS::EC2::EIP",Properties:{Domain:"vpc",Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:s},...o?[{Key:"Domain",Value:o}]:[]]}},h={[d]:f},S,A;if(c)A=t(`${u}-assoc`),S={Type:"AWS::EC2::EIPAssociation",Properties:{AllocationId:k.GetAtt(d,"AllocationId"),InstanceId:k.Ref(c)}},h[A]=S;return{eip:f,eipAssociation:S,eipLogicalId:d,associationLogicalId:A,resources:h}}static createServerModeStack(n){let{slug:i,environment:s,vpcId:o,subnetId:c,instanceType:u="t3.small",imageId:d="ami-0f3caa1cf4417e51b",keyName:f,domain:h,userData:S,allowedPorts:A=[22,80,443],volumeSize:T=20,volumeType:v="gp3"}=n,R={},P=r({slug:i,environment:s,resourceType:"server-sg"}),E=t(P),I={Type:"AWS::EC2::SecurityGroup",Properties:{GroupName:P,GroupDescription:`Security group for ${i} server`,VpcId:o,SecurityGroupIngress:A.map((se)=>({IpProtocol:"tcp",FromPort:se,ToPort:se,CidrIp:"0.0.0.0/0",Description:`Port ${se}`})),SecurityGroupEgress:[{IpProtocol:"-1",CidrIp:"0.0.0.0/0",Description:"Allow all outbound"}],Tags:[{Key:"Name",Value:P},{Key:"Environment",Value:s}]}};R[E]=I;let M=r({slug:i,environment:s,resourceType:"server-role"}),L=t(M),x={Type:"AWS::IAM::Role",Properties:{RoleName:M,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ec2.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore","arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy"],Policies:[{PolicyName:"StacksServerPermissions",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["ses:SendEmail","ses:SendRawEmail","ses:SendBulkEmail","ses:VerifyDomainIdentity","ses:VerifyDomainDkim","ses:GetIdentityDkimAttributes","ses:GetIdentityVerificationAttributes"],Resource:"*"},{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:ListBucket"],Resource:"*"},{Effect:"Allow",Action:["route53:ChangeResourceRecordSets","route53:ListResourceRecordSets","route53:GetHostedZone"],Resource:"*"},{Effect:"Allow",Action:["ssm:GetParameter","ssm:GetParameters"],Resource:"*"}]}}]}};R[L]=x;let O=r({slug:i,environment:s,resourceType:"server-profile"}),B=t(O),F={Type:"AWS::IAM::InstanceProfile",Properties:{InstanceProfileName:O,Roles:[k.Ref(L)]}};R[B]=F;let U=r({slug:i,environment:s,resourceType:"server"}),j=t(U),H={Type:"AWS::EC2::Instance",DependsOn:[B],Properties:{ImageId:d,InstanceType:u,KeyName:f,SubnetId:c,SecurityGroupIds:[k.Ref(E)],IamInstanceProfile:k.Ref(B),BlockDeviceMappings:[{DeviceName:"/dev/xvda",Ebs:{VolumeSize:T,VolumeType:v,Encrypted:!0,DeleteOnTermination:!0}}],Tags:[{Key:"Name",Value:U},{Key:"Environment",Value:s},...h?[{Key:"Domain",Value:h}]:[]]}};if(S)H.Properties.UserData=k.Base64(S);R[j]=H;let{eip:z,eipAssociation:ae,eipLogicalId:Te,associationLogicalId:oe,resources:pe}=a.createElasticIp({slug:i,environment:s,domain:h,instanceLogicalId:j});return Object.assign(R,pe),{instance:H,securityGroup:I,eip:z,eipAssociation:ae,instanceRole:x,instanceProfile:F,resources:R,outputs:{instanceLogicalId:j,securityGroupLogicalId:E,eipLogicalId:Te,associationLogicalId:oe,roleLogicalId:L,profileLogicalId:B}}}static ServerMode={webServer:(n)=>{let i=a.UserData.generateAppServerScript({runtime:n.runtime||"bun",webServer:n.webServer||"nginx",domain:n.domain,enableSsl:!0});return a.createServerModeStack({...n,userData:i,instanceType:"t3.small",allowedPorts:[22,80,443]})},workerServer:(n)=>{let i=a.UserData.generateAppServerScript({runtime:n.runtime||"bun",webServer:"none",installRedis:n.installRedis});return a.createServerModeStack({...n,userData:i,instanceType:"t3.medium",allowedPorts:[22]})},cacheServer:(n)=>a.createServerModeStack({...n,userData:`#!/bin/bash
|
|
573
573
|
set -e
|
|
574
574
|
apt-get update && apt-get upgrade -y
|
|
575
575
|
apt-get install -y redis-server
|
|
@@ -577,7 +577,7 @@ sed -i 's/bind 127.0.0.1/bind 0.0.0.0/' /etc/redis/redis.conf
|
|
|
577
577
|
systemctl enable redis-server
|
|
578
578
|
systemctl restart redis-server
|
|
579
579
|
echo "Redis server setup complete!"
|
|
580
|
-
`,instanceType:"t3.medium",allowedPorts:[22,6379]})}}class y{static createVpc(n){let{slug:i,environment:s,cidr:o="10.0.0.0/16",enableDnsHostnames:c=!0,enableDnsSupport:u=!0}=n,d=r({slug:i,environment:s,resourceType:"vpc"}),f=t(d);return{vpc:{Type:"AWS::EC2::VPC",Properties:{CidrBlock:o,EnableDnsHostnames:c,EnableDnsSupport:u,Tags:[{Key:"Name",Value:d},{Key:"Environment",Value:s}]}},logicalId:f}}static createSubnet(n){let{slug:i,environment:s,vpcId:o,type:c,cidr:u,availabilityZone:d,mapPublicIp:f=c==="public"}=n,h=r({slug:i,environment:s,resourceType:`subnet-${c}`}),S=t(`${h}-${d}`);return{subnet:{Type:"AWS::EC2::Subnet",Properties:{VpcId:o,CidrBlock:u,AvailabilityZone:d,MapPublicIpOnLaunch:f,Tags:[{Key:"Name",Value:`${h}-${d}`},{Key:"Environment",Value:s},{Key:"Type",Value:c}]}},logicalId:S}}static createInternetGateway(n,i){let s=r({slug:n,environment:i,resourceType:"igw"}),o=t(s);return{internetGateway:{Type:"AWS::EC2::InternetGateway",Properties:{Tags:[{Key:"Name",Value:s},{Key:"Environment",Value:i}]}},logicalId:o}}static attachInternetGateway(n,i){let s=t(`${n}-igw-attachment`);return{attachment:{Type:"AWS::EC2::VPCGatewayAttachment",Properties:{VpcId:k.Ref(n),InternetGatewayId:k.Ref(i)}},logicalId:s}}static createEip(n,i){let s=r({slug:n,environment:i,resourceType:"eip"}),o=t(s);return{eip:{Type:"AWS::EC2::EIP",Properties:{Domain:"vpc",Tags:[{Key:"Name",Value:s},{Key:"Environment",Value:i}]}},logicalId:o}}static createNatGateway(n,i){let{slug:s,environment:o,subnetId:c}=n,u=r({slug:s,environment:o,resourceType:"nat"}),d=t(u);return{natGateway:{Type:"AWS::EC2::NatGateway",Properties:{AllocationId:k.GetAtt(i,"AllocationId"),SubnetId:c,Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:o},{Key:"Warning",Value:"NAT Gateway incurs hourly charges"}]}},logicalId:d}}static createRouteTable(n,i,s,o){let c=r({slug:n,environment:i,resourceType:`rt-${o}`}),u=t(c);return{routeTable:{Type:"AWS::EC2::RouteTable",Properties:{VpcId:k.Ref(s),Tags:[{Key:"Name",Value:c},{Key:"Environment",Value:i},{Key:"Type",Value:o}]}},logicalId:u}}static createRoute(n,i,s){let o=t(`${n}-route-${s.type}`),c={Type:"AWS::EC2::Route",Properties:{RouteTableId:k.Ref(n),DestinationCidrBlock:i}};if(s.type==="igw")c.Properties.GatewayId=k.Ref(s.logicalId);else if(s.type==="nat")c.Properties.NatGatewayId=k.Ref(s.logicalId);else if(s.type==="instance")c.Properties.InstanceId=k.Ref(s.logicalId);return{route:c,logicalId:o}}static associateSubnetWithRouteTable(n,i){let s=t(`${n}-rt-assoc`);return{association:{Type:"AWS::EC2::SubnetRouteTableAssociation",Properties:{SubnetId:k.Ref(n),RouteTableId:k.Ref(i)}},logicalId:s}}static enableFlowLogs(n){let{slug:i,environment:s,resourceId:o,resourceType:c,trafficType:u="ALL",logGroupName:d}=n,f=r({slug:i,environment:s,resourceType:"flowlog"}),h=t(f);return{flowLog:{Type:"AWS::EC2::FlowLog",Properties:{ResourceType:c,ResourceIds:[o],TrafficType:u,LogDestinationType:"cloud-watch-logs",LogGroupName:d||`/aws/vpc/${i}-${s}`,Tags:[{Key:"Name",Value:f},{Key:"Environment",Value:s}]}},logicalId:h}}static calculateSubnetCidrs(n,i,s=3){let[o,c]=n.split("/"),u=Number.parseInt(c,10),d=Math.ceil(Math.log2(i*s)),f=u+d;if(f>28)throw Error("VPC CIDR is too small to accommodate requested subnets");let[h,S,A,T]=o.split(".").map(Number),v=(h<<24)+(S<<16)+(A<<8)+T,R=2**(32-f),P=[];for(let E=0;E<i*s;E++){let I=v+E*R,M=[I>>>24&255,I>>>16&255,I>>>8&255,I&255].join(".");P.push(`${M}/${f}`)}return P}static getAvailabilityZones(n,i){return["a","b","c","d","e","f"].slice(0,i).map((o)=>`${n}${o}`)}static createMultiAzNetwork(n){let{slug:i,environment:s,region:o,cidr:c="10.0.0.0/16",zones:u=3,enableNatGateway:d=!1,singleNatGateway:f=!1,enableFlowLogs:h=!1}=n,S={},A=[],T=[],v=[],{vpc:R,logicalId:P}=y.createVpc({slug:i,environment:s,cidr:c});S[P]=R;let{internetGateway:E,logicalId:I}=y.createInternetGateway(i,s);S[I]=E;let{attachment:M,logicalId:L}=y.attachInternetGateway(P,I);S[L]=M;let{routeTable:x,logicalId:O}=y.createRouteTable(i,s,P,"public");S[O]=x;let{route:B,logicalId:F}=y.createRoute(O,"0.0.0.0/0",{type:"igw",logicalId:I});B.DependsOn=L,S[F]=B;let U=y.calculateSubnetCidrs(c,u,2),j=y.getAvailabilityZones(o,u),H=[];for(let z=0;z<u;z++){let
|
|
580
|
+
`,instanceType:"t3.medium",allowedPorts:[22,6379]})}}class y{static createVpc(n){let{slug:i,environment:s,cidr:o="10.0.0.0/16",enableDnsHostnames:c=!0,enableDnsSupport:u=!0}=n,d=r({slug:i,environment:s,resourceType:"vpc"}),f=t(d);return{vpc:{Type:"AWS::EC2::VPC",Properties:{CidrBlock:o,EnableDnsHostnames:c,EnableDnsSupport:u,Tags:[{Key:"Name",Value:d},{Key:"Environment",Value:s}]}},logicalId:f}}static createSubnet(n){let{slug:i,environment:s,vpcId:o,type:c,cidr:u,availabilityZone:d,mapPublicIp:f=c==="public"}=n,h=r({slug:i,environment:s,resourceType:`subnet-${c}`}),S=t(`${h}-${d}`);return{subnet:{Type:"AWS::EC2::Subnet",Properties:{VpcId:o,CidrBlock:u,AvailabilityZone:d,MapPublicIpOnLaunch:f,Tags:[{Key:"Name",Value:`${h}-${d}`},{Key:"Environment",Value:s},{Key:"Type",Value:c}]}},logicalId:S}}static createInternetGateway(n,i){let s=r({slug:n,environment:i,resourceType:"igw"}),o=t(s);return{internetGateway:{Type:"AWS::EC2::InternetGateway",Properties:{Tags:[{Key:"Name",Value:s},{Key:"Environment",Value:i}]}},logicalId:o}}static attachInternetGateway(n,i){let s=t(`${n}-igw-attachment`);return{attachment:{Type:"AWS::EC2::VPCGatewayAttachment",Properties:{VpcId:k.Ref(n),InternetGatewayId:k.Ref(i)}},logicalId:s}}static createEip(n,i){let s=r({slug:n,environment:i,resourceType:"eip"}),o=t(s);return{eip:{Type:"AWS::EC2::EIP",Properties:{Domain:"vpc",Tags:[{Key:"Name",Value:s},{Key:"Environment",Value:i}]}},logicalId:o}}static createNatGateway(n,i){let{slug:s,environment:o,subnetId:c}=n,u=r({slug:s,environment:o,resourceType:"nat"}),d=t(u);return{natGateway:{Type:"AWS::EC2::NatGateway",Properties:{AllocationId:k.GetAtt(i,"AllocationId"),SubnetId:c,Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:o},{Key:"Warning",Value:"NAT Gateway incurs hourly charges"}]}},logicalId:d}}static createRouteTable(n,i,s,o){let c=r({slug:n,environment:i,resourceType:`rt-${o}`}),u=t(c);return{routeTable:{Type:"AWS::EC2::RouteTable",Properties:{VpcId:k.Ref(s),Tags:[{Key:"Name",Value:c},{Key:"Environment",Value:i},{Key:"Type",Value:o}]}},logicalId:u}}static createRoute(n,i,s){let o=t(`${n}-route-${s.type}`),c={Type:"AWS::EC2::Route",Properties:{RouteTableId:k.Ref(n),DestinationCidrBlock:i}};if(s.type==="igw")c.Properties.GatewayId=k.Ref(s.logicalId);else if(s.type==="nat")c.Properties.NatGatewayId=k.Ref(s.logicalId);else if(s.type==="instance")c.Properties.InstanceId=k.Ref(s.logicalId);return{route:c,logicalId:o}}static associateSubnetWithRouteTable(n,i){let s=t(`${n}-rt-assoc`);return{association:{Type:"AWS::EC2::SubnetRouteTableAssociation",Properties:{SubnetId:k.Ref(n),RouteTableId:k.Ref(i)}},logicalId:s}}static enableFlowLogs(n){let{slug:i,environment:s,resourceId:o,resourceType:c,trafficType:u="ALL",logGroupName:d}=n,f=r({slug:i,environment:s,resourceType:"flowlog"}),h=t(f);return{flowLog:{Type:"AWS::EC2::FlowLog",Properties:{ResourceType:c,ResourceIds:[o],TrafficType:u,LogDestinationType:"cloud-watch-logs",LogGroupName:d||`/aws/vpc/${i}-${s}`,Tags:[{Key:"Name",Value:f},{Key:"Environment",Value:s}]}},logicalId:h}}static calculateSubnetCidrs(n,i,s=3){let[o,c]=n.split("/"),u=Number.parseInt(c,10),d=Math.ceil(Math.log2(i*s)),f=u+d;if(f>28)throw Error("VPC CIDR is too small to accommodate requested subnets");let[h,S,A,T]=o.split(".").map(Number),v=(h<<24)+(S<<16)+(A<<8)+T,R=2**(32-f),P=[];for(let E=0;E<i*s;E++){let I=v+E*R,M=[I>>>24&255,I>>>16&255,I>>>8&255,I&255].join(".");P.push(`${M}/${f}`)}return P}static getAvailabilityZones(n,i){return["a","b","c","d","e","f"].slice(0,i).map((o)=>`${n}${o}`)}static createMultiAzNetwork(n){let{slug:i,environment:s,region:o,cidr:c="10.0.0.0/16",zones:u=3,enableNatGateway:d=!1,singleNatGateway:f=!1,enableFlowLogs:h=!1}=n,S={},A=[],T=[],v=[],{vpc:R,logicalId:P}=y.createVpc({slug:i,environment:s,cidr:c});S[P]=R;let{internetGateway:E,logicalId:I}=y.createInternetGateway(i,s);S[I]=E;let{attachment:M,logicalId:L}=y.attachInternetGateway(P,I);S[L]=M;let{routeTable:x,logicalId:O}=y.createRouteTable(i,s,P,"public");S[O]=x;let{route:B,logicalId:F}=y.createRoute(O,"0.0.0.0/0",{type:"igw",logicalId:I});B.DependsOn=L,S[F]=B;let U=y.calculateSubnetCidrs(c,u,2),j=y.getAvailabilityZones(o,u),H=[];for(let z=0;z<u;z++){let ae=j[z],Te=U[z*2],oe=U[z*2+1],{subnet:pe,logicalId:se}=y.createSubnet({slug:i,environment:s,vpcId:k.Ref(P),type:"public",cidr:Te,availabilityZone:ae});S[se]=pe,A.push(se);let{association:me,logicalId:Ie}=y.associateSubnetWithRouteTable(se,O);S[Ie]=me;let{subnet:Le,logicalId:fe}=y.createSubnet({slug:i,environment:s,vpcId:k.Ref(P),type:"private",cidr:oe,availabilityZone:ae});if(S[fe]=Le,T.push(fe),d&&(!f||z===0)){let{eip:ge,logicalId:he}=y.createEip(`${i}-${ae}`,s);S[he]=ge;let{natGateway:De,logicalId:Se}=y.createNatGateway({slug:`${i}-${ae}`,environment:s,subnetId:k.Ref(se)},he);De.DependsOn=L,S[Se]=De,v.push(Se);let{routeTable:Re,logicalId:$e}=y.createRouteTable(`${i}-${ae}`,s,P,"private");S[$e]=Re,H.push($e);let{route:We,logicalId:G}=y.createRoute($e,"0.0.0.0/0",{type:"nat",logicalId:Se});S[G]=We;let{association:ne,logicalId:ie}=y.associateSubnetWithRouteTable(fe,$e);S[ie]=ne}else if(d&&f&&z>0){let{association:ge,logicalId:he}=y.associateSubnetWithRouteTable(fe,H[0]);S[he]=ge}else{let{routeTable:ge,logicalId:he}=y.createRouteTable(`${i}-${ae}-isolated`,s,P,"private");S[he]=ge;let{association:De,logicalId:Se}=y.associateSubnetWithRouteTable(fe,he);S[Se]=De}}if(h){let{flowLog:z,logicalId:ae}=y.enableFlowLogs({slug:i,environment:s,resourceId:k.Ref(P),resourceType:"VPC"});S[ae]=z}return{resources:S,outputs:{vpcId:P,publicSubnetIds:A,privateSubnetIds:T,natGatewayIds:v.length>0?v:void 0}}}static NatGatewayCostWarning=`
|
|
581
581
|
⚠️ NAT Gateway Cost Warning:
|
|
582
582
|
- Each NAT Gateway costs approximately $32-45/month (hourly charges)
|
|
583
583
|
- Data processing charges: $0.045/GB processed
|
|
@@ -2278,7 +2278,7 @@ function resolveTemplate(template, data) {
|
|
|
2278
2278
|
| fields @timestamp, @message
|
|
2279
2279
|
| filter @message like /ERROR|WARN|Exception/
|
|
2280
2280
|
| sort @timestamp desc
|
|
2281
|
-
| limit 50`,region:o,title:"Recent Errors and Warnings"}}),d+=6;return Lo.createDashboard({slug:i,environment:s,widgets:u})}static DashboardTemplates={staticWebsite:(n)=>({slug:n.slug,environment:n.environment,widgets:[{type:"text",x:0,y:0,width:24,height:1,properties:{markdown:`# ${n.slug.toUpperCase()} Static Website Dashboard`}},{type:"metric",x:0,y:1,width:8,height:6,properties:{title:"CloudFront Requests",region:"us-east-1",metrics:[["AWS/CloudFront","Requests","DistributionId",n.cloudFrontDistributionId,"Region","Global"]],period:300,stat:"Sum"}},{type:"metric",x:8,y:1,width:8,height:6,properties:{title:"Error Rate",region:"us-east-1",metrics:[["AWS/CloudFront","4xxErrorRate","DistributionId",n.cloudFrontDistributionId,"Region","Global",{label:"4XX"}],["AWS/CloudFront","5xxErrorRate","DistributionId",n.cloudFrontDistributionId,"Region","Global",{label:"5XX"}]],period:300,stat:"Average"}},{type:"metric",x:16,y:1,width:8,height:6,properties:{title:"Bytes Downloaded",region:"us-east-1",metrics:[["AWS/CloudFront","BytesDownloaded","DistributionId",n.cloudFrontDistributionId,"Region","Global"]],period:300,stat:"Sum"}},{type:"metric",x:0,y:7,width:12,height:6,properties:{title:"S3 Bucket Size",region:n.region||"us-east-1",metrics:[["AWS/S3","BucketSizeBytes","BucketName",n.s3BucketName,"StorageType","StandardStorage"]],period:86400,stat:"Average"}},{type:"metric",x:12,y:7,width:12,height:6,properties:{title:"S3 Number of Objects",region:n.region||"us-east-1",metrics:[["AWS/S3","NumberOfObjects","BucketName",n.s3BucketName,"StorageType","AllStorageTypes"]],period:86400,stat:"Average"}}]}),serverlessApi:(n)=>({slug:n.slug,environment:n.environment,widgets:[{type:"text",x:0,y:0,width:24,height:1,properties:{markdown:`# ${n.slug.toUpperCase()} Serverless API Dashboard`}},{type:"metric",x:0,y:1,width:8,height:6,properties:{title:"API Requests",region:n.region||"us-east-1",metrics:[["AWS/ApiGateway","Count","ApiName",n.apiGatewayName]],period:60,stat:"Sum"}},{type:"metric",x:8,y:1,width:8,height:6,properties:{title:"API Latency",region:n.region||"us-east-1",metrics:[["AWS/ApiGateway","Latency","ApiName",n.apiGatewayName]],period:60,stat:"Average"}},{type:"metric",x:16,y:1,width:8,height:6,properties:{title:"API Errors",region:n.region||"us-east-1",metrics:[["AWS/ApiGateway","4XXError","ApiName",n.apiGatewayName,{label:"4XX"}],["AWS/ApiGateway","5XXError","ApiName",n.apiGatewayName,{label:"5XX"}]],period:60,stat:"Sum"}},...n.lambdaFunctionNames.map((i,s)=>({type:"metric",x:s%3*8,y:7+Math.floor(s/3)*6,width:8,height:6,properties:{title:`${i} Metrics`,region:n.region||"us-east-1",metrics:[["AWS/Lambda","Invocations","FunctionName",i],["AWS/Lambda","Duration","FunctionName",i],["AWS/Lambda","Errors","FunctionName",i]],period:300,stat:"Sum"}}))]}),containerService:(n)=>({slug:n.slug,environment:n.environment,widgets:[{type:"text",x:0,y:0,width:24,height:1,properties:{markdown:`# ${n.slug.toUpperCase()} Container Service Dashboard`}},{type:"metric",x:0,y:1,width:8,height:6,properties:{title:"ECS CPU",region:n.region||"us-east-1",metrics:[["AWS/ECS","CPUUtilization","ClusterName",n.ecsClusterName,"ServiceName",n.ecsServiceName]],period:60,stat:"Average"}},{type:"metric",x:8,y:1,width:8,height:6,properties:{title:"ECS Memory",region:n.region||"us-east-1",metrics:[["AWS/ECS","MemoryUtilization","ClusterName",n.ecsClusterName,"ServiceName",n.ecsServiceName]],period:60,stat:"Average"}},{type:"metric",x:16,y:1,width:8,height:6,properties:{title:"Running Tasks",region:n.region||"us-east-1",metrics:[["ECS/ContainerInsights","RunningTaskCount","ClusterName",n.ecsClusterName,"ServiceName",n.ecsServiceName]],period:60,stat:"Average"}},{type:"metric",x:0,y:7,width:8,height:6,properties:{title:"ALB Requests",region:n.region||"us-east-1",metrics:[["AWS/ApplicationELB","RequestCount","LoadBalancer",n.albName]],period:60,stat:"Sum"}},{type:"metric",x:8,y:7,width:8,height:6,properties:{title:"Response Time",region:n.region||"us-east-1",metrics:[["AWS/ApplicationELB","TargetResponseTime","LoadBalancer",n.albName]],period:60,stat:"Average"}},{type:"metric",x:16,y:7,width:8,height:6,properties:{title:"Healthy Hosts",region:n.region||"us-east-1",metrics:[["AWS/ApplicationELB","HealthyHostCount","LoadBalancer",n.albName]],period:60,stat:"Average"}},...n.rdsInstanceId?[{type:"metric",x:0,y:13,width:12,height:6,properties:{title:"RDS CPU",region:n.region||"us-east-1",metrics:[["AWS/RDS","CPUUtilization","DBInstanceIdentifier",n.rdsInstanceId]],period:300,stat:"Average"}},{type:"metric",x:12,y:13,width:12,height:6,properties:{title:"RDS Connections",region:n.region||"us-east-1",metrics:[["AWS/RDS","DatabaseConnections","DBInstanceIdentifier",n.rdsInstanceId]],period:60,stat:"Sum"}}]:[]]})};static Config={createAlarmConfig:(n)=>{let{metricName:i,namespace:s,threshold:o,comparisonOperator:c="GreaterThanThreshold",evaluationPeriods:u=1,period:d=300,statistic:f="Average",treatMissingData:h="missing"}=n;return{MetricName:i,Namespace:s,Threshold:o,ComparisonOperator:c,EvaluationPeriods:u,Period:d,Statistic:f,TreatMissingData:h}},namespaces:{ec2:"AWS/EC2",ecs:"AWS/ECS",lambda:"AWS/Lambda",rds:"AWS/RDS",sqs:"AWS/SQS",sns:"AWS/SNS",s3:"AWS/S3",cloudfront:"AWS/CloudFront",alb:"AWS/ApplicationELB",nlb:"AWS/NetworkELB",apiGateway:"AWS/ApiGateway",dynamodb:"AWS/DynamoDB",elasticache:"AWS/ElastiCache"},comparisonOperators:{greaterThan:"GreaterThanThreshold",greaterOrEqual:"GreaterThanOrEqualToThreshold",lessThan:"LessThanThreshold",lessOrEqual:"LessThanOrEqualToThreshold"},metrics:{ec2:{cpu:{metricName:"CPUUtilization",namespace:"AWS/EC2"},networkIn:{metricName:"NetworkIn",namespace:"AWS/EC2"},networkOut:{metricName:"NetworkOut",namespace:"AWS/EC2"},statusCheck:{metricName:"StatusCheckFailed",namespace:"AWS/EC2"}},ecs:{cpu:{metricName:"CPUUtilization",namespace:"AWS/ECS"},memory:{metricName:"MemoryUtilization",namespace:"AWS/ECS"}},lambda:{invocations:{metricName:"Invocations",namespace:"AWS/Lambda"},errors:{metricName:"Errors",namespace:"AWS/Lambda"},duration:{metricName:"Duration",namespace:"AWS/Lambda"},throttles:{metricName:"Throttles",namespace:"AWS/Lambda"},concurrentExecutions:{metricName:"ConcurrentExecutions",namespace:"AWS/Lambda"}},rds:{cpu:{metricName:"CPUUtilization",namespace:"AWS/RDS"},connections:{metricName:"DatabaseConnections",namespace:"AWS/RDS"},freeStorage:{metricName:"FreeStorageSpace",namespace:"AWS/RDS"},readLatency:{metricName:"ReadLatency",namespace:"AWS/RDS"},writeLatency:{metricName:"WriteLatency",namespace:"AWS/RDS"}},alb:{requestCount:{metricName:"RequestCount",namespace:"AWS/ApplicationELB"},responseTime:{metricName:"TargetResponseTime",namespace:"AWS/ApplicationELB"},httpCode4xx:{metricName:"HTTPCode_Target_4XX_Count",namespace:"AWS/ApplicationELB"},httpCode5xx:{metricName:"HTTPCode_Target_5XX_Count",namespace:"AWS/ApplicationELB"},healthyHosts:{metricName:"HealthyHostCount",namespace:"AWS/ApplicationELB"}},sqs:{messagesVisible:{metricName:"ApproximateNumberOfMessagesVisible",namespace:"AWS/SQS"},messagesDelayed:{metricName:"ApproximateNumberOfMessagesDelayed",namespace:"AWS/SQS"},messageAge:{metricName:"ApproximateAgeOfOldestMessage",namespace:"AWS/SQS"}}},presets:{highCpu:(n=80)=>({metricName:"CPUUtilization",threshold:n,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),highMemory:(n=80)=>({metricName:"MemoryUtilization",threshold:n,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),highErrors:(n=10)=>({metricName:"Errors",threshold:n,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:1,period:60,statistic:"Sum"}),highLatency:(n=5000)=>({metricName:"Duration",threshold:n,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),lowHealthyHosts:(n=1)=>({metricName:"HealthyHostCount",namespace:"AWS/ApplicationELB",threshold:n,comparisonOperator:"LessThanThreshold",evaluationPeriods:2,period:60,statistic:"Minimum"}),queueDepth:(n=1000)=>({metricName:"ApproximateNumberOfMessagesVisible",namespace:"AWS/SQS",threshold:n,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),lowStorage:(n=10737418240)=>({metricName:"FreeStorageSpace",namespace:"AWS/RDS",threshold:n,comparisonOperator:"LessThanThreshold",evaluationPeriods:1,period:300,statistic:"Average"})}}}class Y{static createUserPool(n){let{slug:i,environment:s,userPoolName:o,aliasAttributes:c,autoVerifiedAttributes:u,passwordPolicy:d,mfaConfiguration:f,emailConfiguration:h,smsConfiguration:S,lambdaTriggers:A,userPoolAddOns:T,accountRecoverySetting:v}=n,R=o||r({slug:i,environment:s,resourceType:"user-pool"}),P=t(R),E={Type:"AWS::Cognito::UserPool",Properties:{UserPoolName:R,Policies:d?{PasswordPolicy:{MinimumLength:d.minimumLength,RequireLowercase:d.requireLowercase,RequireUppercase:d.requireUppercase,RequireNumbers:d.requireNumbers,RequireSymbols:d.requireSymbols,TemporaryPasswordValidityDays:d.temporaryPasswordValidityDays}}:void 0,MfaConfiguration:f,Schema:[{Name:"email",AttributeDataType:"String",Required:!0,Mutable:!1}]}};if(c&&c.length>0)E.Properties.UsernameAttributes=c;if(u&&u.length>0)E.Properties.AutoVerifiedAttributes=u;if(h)E.Properties.EmailConfiguration={EmailSendingAccount:h.emailSendingAccount,From:h.from,ReplyToEmailAddress:h.replyToEmailAddress,SourceArn:h.sourceArn,ConfigurationSet:h.configurationSet};if(S)E.Properties.SmsConfiguration={ExternalId:S.externalId,SnsCallerArn:S.snsCallerArn};if(A)E.Properties.LambdaConfig={PreSignUp:A.preSignUp,PostConfirmation:A.postConfirmation,PreAuthentication:A.preAuthentication,PostAuthentication:A.postAuthentication,CustomMessage:A.customMessage,DefineAuthChallenge:A.defineAuthChallenge,CreateAuthChallenge:A.createAuthChallenge,VerifyAuthChallengeResponse:A.verifyAuthChallengeResponse,PreTokenGeneration:A.preTokenGeneration,UserMigration:A.userMigration};if(T)E.Properties.UserPoolAddOns={AdvancedSecurityMode:T.advancedSecurityMode};if(v)E.Properties.AccountRecoverySetting={RecoveryMechanisms:v.recoveryMechanisms};return{userPool:E,logicalId:P}}static createUserPoolClient(n,i){let{slug:s,environment:o,clientName:c,generateSecret:u=!1,refreshTokenValidity:d,accessTokenValidity:f,idTokenValidity:h,tokenValidityUnits:S,readAttributes:A,writeAttributes:T,explicitAuthFlows:v,preventUserExistenceErrors:R,enableTokenRevocation:P,callbackURLs:E,logoutURLs:I,allowedOAuthFlows:M,allowedOAuthScopes:L,allowedOAuthFlowsUserPoolClient:x,supportedIdentityProviders:O}=i,B=c||r({slug:s,environment:o,resourceType:"user-pool-client"}),F=t(B);return{client:{Type:"AWS::Cognito::UserPoolClient",Properties:{ClientName:B,UserPoolId:k.Ref(n),GenerateSecret:u,RefreshTokenValidity:d,AccessTokenValidity:f,IdTokenValidity:h,TokenValidityUnits:S,ReadAttributes:A,WriteAttributes:T,ExplicitAuthFlows:v,PreventUserExistenceErrors:R,EnableTokenRevocation:P,CallbackURLs:E,LogoutURLs:I,AllowedOAuthFlows:M,AllowedOAuthScopes:L,AllowedOAuthFlowsUserPoolClient:x,SupportedIdentityProviders:O}},logicalId:F}}static createUserPoolDomain(n,i){let{slug:s,environment:o,domain:c,customDomainConfig:u}=i,d=r({slug:s,environment:o,resourceType:"user-pool-domain"}),f=t(d);return{domain:{Type:"AWS::Cognito::UserPoolDomain",Properties:{Domain:c,UserPoolId:k.Ref(n),CustomDomainConfig:u}},logicalId:f}}static createIdentityPool(n){let{slug:i,environment:s,identityPoolName:o,allowUnauthenticatedIdentities:c=!1,cognitoIdentityProviders:u,supportedLoginProviders:d,samlProviderARNs:f,openIdConnectProviderARNs:h}=n,S=o||r({slug:i,environment:s,resourceType:"identity-pool"}),A=t(S);return{identityPool:{Type:"AWS::Cognito::IdentityPool",Properties:{IdentityPoolName:S,AllowUnauthenticatedIdentities:c,CognitoIdentityProviders:u,SupportedLoginProviders:d,SamlProviderARNs:f,OpenIdConnectProviderARNs:h}},logicalId:A}}static createIdentityPoolRoleAttachment(n,i){let{slug:s,environment:o,authenticatedRole:c,unauthenticatedRole:u,roleMappings:d}=i,f=r({slug:s,environment:o,resourceType:"identity-pool-role-attachment"}),h=t(f),S={authenticated:c};if(u)S.unauthenticated=u;return{attachment:{Type:"AWS::Cognito::IdentityPoolRoleAttachment",Properties:{IdentityPoolId:k.Ref(n),Roles:S,RoleMappings:d}},logicalId:h}}static createAuthenticatedRole(n){let{slug:i,environment:s,identityPoolLogicalId:o}=n,c=r({slug:i,environment:s,resourceType:"cognito-authenticated-role"}),u=t(c);return{role:{Type:"AWS::IAM::Role",Properties:{RoleName:c,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Federated:"cognito-identity.amazonaws.com"},Action:"sts:AssumeRoleWithWebIdentity",Condition:{StringEquals:{"cognito-identity.amazonaws.com:aud":k.Ref(o)},"ForAnyValue:StringLike":{"cognito-identity.amazonaws.com:amr":"authenticated"}}}]},Policies:[{PolicyName:"CognitoAuthenticatedPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["cognito-sync:*","cognito-identity:*"],Resource:"*"}]}}],Tags:[{Key:"Name",Value:c},{Key:"Environment",Value:s}]}},logicalId:u}}static createUnauthenticatedRole(n){let{slug:i,environment:s,identityPoolLogicalId:o}=n,c=r({slug:i,environment:s,resourceType:"cognito-unauthenticated-role"}),u=t(c);return{role:{Type:"AWS::IAM::Role",Properties:{RoleName:c,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Federated:"cognito-identity.amazonaws.com"},Action:"sts:AssumeRoleWithWebIdentity",Condition:{StringEquals:{"cognito-identity.amazonaws.com:aud":k.Ref(o)},"ForAnyValue:StringLike":{"cognito-identity.amazonaws.com:amr":"unauthenticated"}}}]},Policies:[{PolicyName:"CognitoUnauthenticatedPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["cognito-sync:*"],Resource:"*"}]}}],Tags:[{Key:"Name",Value:c},{Key:"Environment",Value:s}]}},logicalId:u}}static PasswordPolicies={relaxed:()=>({minimumLength:8,requireLowercase:!1,requireUppercase:!1,requireNumbers:!1,requireSymbols:!1,temporaryPasswordValidityDays:7}),standard:()=>({minimumLength:8,requireLowercase:!0,requireUppercase:!0,requireNumbers:!0,requireSymbols:!1,temporaryPasswordValidityDays:3}),strict:()=>({minimumLength:12,requireLowercase:!0,requireUppercase:!0,requireNumbers:!0,requireSymbols:!0,temporaryPasswordValidityDays:1})};static AuthFlows={standard:["ALLOW_USER_SRP_AUTH","ALLOW_REFRESH_TOKEN_AUTH"],admin:["ALLOW_ADMIN_USER_PASSWORD_AUTH","ALLOW_REFRESH_TOKEN_AUTH"],custom:["ALLOW_CUSTOM_AUTH","ALLOW_REFRESH_TOKEN_AUTH"],all:["ALLOW_USER_SRP_AUTH","ALLOW_USER_PASSWORD_AUTH","ALLOW_ADMIN_USER_PASSWORD_AUTH","ALLOW_CUSTOM_AUTH","ALLOW_REFRESH_TOKEN_AUTH"]};static OAuthScopes={basic:["openid","email","profile"],all:["openid","email","profile","phone","aws.cognito.signin.user.admin"]};static UseCases={webApp:(n,i,s)=>{let{userPool:o,logicalId:c}=Y.createUserPool({slug:n,environment:i,aliasAttributes:["email"],autoVerifiedAttributes:["email"],passwordPolicy:Y.PasswordPolicies.standard(),mfaConfiguration:"OPTIONAL"}),{client:u,logicalId:d}=Y.createUserPoolClient(c,{slug:n,environment:i,explicitAuthFlows:[...Y.AuthFlows.standard],callbackURLs:[s],allowedOAuthFlows:["code"],allowedOAuthScopes:[...Y.OAuthScopes.basic],allowedOAuthFlowsUserPoolClient:!0});return{userPool:o,poolId:c,client:u,clientId:d}},mobileApp:(n,i)=>{let{userPool:s,logicalId:o}=Y.createUserPool({slug:n,environment:i,aliasAttributes:["email"],autoVerifiedAttributes:["email"],passwordPolicy:Y.PasswordPolicies.standard(),mfaConfiguration:"OPTIONAL"}),{client:c,logicalId:u}=Y.createUserPoolClient(o,{slug:n,environment:i,explicitAuthFlows:[...Y.AuthFlows.standard]}),{identityPool:d,logicalId:f}=Y.createIdentityPool({slug:n,environment:i,allowUnauthenticatedIdentities:!1,cognitoIdentityProviders:[{ClientId:k.Ref(u),ProviderName:k.GetAtt(o,"ProviderName")}]}),{role:h,logicalId:S}=Y.createAuthenticatedRole({slug:n,environment:i,identityPoolLogicalId:f}),{attachment:A,logicalId:T}=Y.createIdentityPoolRoleAttachment(f,{slug:n,environment:i,authenticatedRole:k.GetAtt(S,"Arn")});return{userPool:s,poolId:o,client:c,clientId:u,identityPool:d,identityPoolId:f,authRole:h,authRoleId:S,attachment:A,attachmentId:T}}}}import{createHash as xr}from"node:crypto";import{copyFileSync as kr,existsSync as Et,readdirSync as Mr,readFileSync as it,statSync as Lr,writeFileSync as st}from"node:fs";import{basename as Or,dirname as hn,extname as bn,join as Ue}from"node:path";class Z{static createApplication(n){let{slug:i,environment:s,applicationName:o,computePlatform:c}=n,u=o||r({slug:i,environment:s,resourceType:"deploy-app"}),d=t(u);return{application:{Type:"AWS::CodeDeploy::Application",Properties:{ApplicationName:u,ComputePlatform:c,Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:s}]}},logicalId:d}}static createDeploymentGroup(n,i){let{slug:s,environment:o,deploymentGroupName:c,serviceRoleArn:u,autoScalingGroups:d,ec2TagFilters:f,deploymentConfigName:h,autoRollbackConfiguration:S,alarmConfiguration:A,loadBalancerInfo:T,blueGreenDeploymentConfiguration:v}=i,R=c||r({slug:s,environment:o,resourceType:"deploy-group"}),P=t(R);return{deploymentGroup:{Type:"AWS::CodeDeploy::DeploymentGroup",Properties:{ApplicationName:k.Ref(n),DeploymentGroupName:R,ServiceRoleArn:u,AutoScalingGroups:d,Ec2TagFilters:f?.map((I)=>({Key:I.key,Value:I.value,Type:I.type})),DeploymentConfigName:h,AutoRollbackConfiguration:S?{Enabled:S.enabled,Events:S.events}:void 0,AlarmConfiguration:A?{Enabled:A.enabled,Alarms:A.alarms?.map((I)=>({Name:I.name})),IgnorePollAlarmFailure:A.ignorePollAlarmFailure}:void 0,LoadBalancerInfo:T?{TargetGroupInfoList:T.targetGroupInfoList?.map((I)=>({Name:I.name})),ElbInfoList:T.elbInfoList?.map((I)=>({Name:I.name}))}:void 0,BlueGreenDeploymentConfiguration:v?{TerminateBlueInstancesOnDeploymentSuccess:v.terminateBlueInstancesOnDeploymentSuccess?{Action:v.terminateBlueInstancesOnDeploymentSuccess.action,TerminationWaitTimeInMinutes:v.terminateBlueInstancesOnDeploymentSuccess.terminationWaitTimeInMinutes}:void 0,DeploymentReadyOption:v.deploymentReadyOption?{ActionOnTimeout:v.deploymentReadyOption.actionOnTimeout,WaitTimeInMinutes:v.deploymentReadyOption.waitTimeInMinutes}:void 0,GreenFleetProvisioningOption:v.greenFleetProvisioningOption?{Action:v.greenFleetProvisioningOption.action}:void 0}:void 0,Tags:[{Key:"Name",Value:R},{Key:"Environment",Value:o}]}},logicalId:P}}static createDeploymentConfig(n){let{slug:i,environment:s,deploymentConfigName:o,minimumHealthyHosts:c,trafficRoutingConfig:u}=n,d=o||r({slug:i,environment:s,resourceType:"deploy-config"}),f=t(d);return{deploymentConfig:{Type:"AWS::CodeDeploy::DeploymentConfig",Properties:{DeploymentConfigName:d,MinimumHealthyHosts:c?{Type:c.type,Value:c.value}:void 0,TrafficRoutingConfig:u?{Type:u.type,TimeBasedCanary:u.timeBasedCanary?{CanaryPercentage:u.timeBasedCanary.canaryPercentage,CanaryInterval:u.timeBasedCanary.canaryInterval}:void 0,TimeBasedLinear:u.timeBasedLinear?{LinearPercentage:u.timeBasedLinear.linearPercentage,LinearInterval:u.timeBasedLinear.linearInterval}:void 0}:void 0}},logicalId:f}}static DeploymentConfigs={allAtOnce:()=>({type:"FLEET_PERCENT",value:0}),halfAtATime:()=>({type:"FLEET_PERCENT",value:50}),oneAtATime:()=>({type:"HOST_COUNT",value:1}),custom:(n,i)=>({type:n,value:i})};static TrafficRouting={allAtOnce:()=>({type:"AllAtOnce"}),canary:(n,i)=>({type:"TimeBasedCanary",timeBasedCanary:{canaryPercentage:n,canaryInterval:i}}),linear:(n,i)=>({type:"TimeBasedLinear",timeBasedLinear:{linearPercentage:n,linearInterval:i}})};static RollbackConfigs={onFailure:()=>({enabled:!0,events:["DEPLOYMENT_FAILURE"]}),onAlarmOrFailure:()=>({enabled:!0,events:["DEPLOYMENT_FAILURE","DEPLOYMENT_STOP_ON_ALARM"]}),onAllEvents:()=>({enabled:!0,events:["DEPLOYMENT_FAILURE","DEPLOYMENT_STOP_ON_ALARM","DEPLOYMENT_STOP_ON_REQUEST"]}),disabled:()=>({enabled:!1})};static BlueGreenConfigs={standard:()=>({terminateBlueInstancesOnDeploymentSuccess:{action:"TERMINATE",terminationWaitTimeInMinutes:5},deploymentReadyOption:{actionOnTimeout:"CONTINUE_DEPLOYMENT",waitTimeInMinutes:0},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}}),withDelay:(n)=>({terminateBlueInstancesOnDeploymentSuccess:{action:"TERMINATE",terminationWaitTimeInMinutes:n},deploymentReadyOption:{actionOnTimeout:"CONTINUE_DEPLOYMENT",waitTimeInMinutes:0},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}}),withManualApproval:(n)=>({terminateBlueInstancesOnDeploymentSuccess:{action:"TERMINATE",terminationWaitTimeInMinutes:5},deploymentReadyOption:{actionOnTimeout:"STOP_DEPLOYMENT",waitTimeInMinutes:n},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}}),keepBlue:()=>({terminateBlueInstancesOnDeploymentSuccess:{action:"KEEP_ALIVE"},deploymentReadyOption:{actionOnTimeout:"CONTINUE_DEPLOYMENT",waitTimeInMinutes:0},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}})};static UseCases={ec2Deployment:(n,i,s,o)=>{let{application:c,logicalId:u}=Z.createApplication({slug:n,environment:i,computePlatform:"Server"}),{deploymentGroup:d,logicalId:f}=Z.createDeploymentGroup(u,{slug:n,environment:i,serviceRoleArn:s,autoScalingGroups:o,deploymentConfigName:"CodeDeployDefault.OneAtATime",autoRollbackConfiguration:Z.RollbackConfigs.onFailure()});return{application:c,appId:u,deploymentGroup:d,groupId:f}},lambdaCanaryDeployment:(n,i,s,o=10,c=5)=>{let{application:u,logicalId:d}=Z.createApplication({slug:n,environment:i,computePlatform:"Lambda"}),{deploymentConfig:f,logicalId:h}=Z.createDeploymentConfig({slug:n,environment:i,trafficRoutingConfig:Z.TrafficRouting.canary(o,c)}),{deploymentGroup:S,logicalId:A}=Z.createDeploymentGroup(d,{slug:n,environment:i,serviceRoleArn:s,deploymentConfigName:k.Ref(h),autoRollbackConfiguration:Z.RollbackConfigs.onAlarmOrFailure()});return{application:u,appId:d,deploymentConfig:f,configId:h,deploymentGroup:S,groupId:A}},ecsBlueGreenDeployment:(n,i,s,o)=>{let{application:c,logicalId:u}=Z.createApplication({slug:n,environment:i,computePlatform:"ECS"}),{deploymentGroup:d,logicalId:f}=Z.createDeploymentGroup(u,{slug:n,environment:i,serviceRoleArn:s,loadBalancerInfo:{targetGroupInfoList:[{name:o}]},blueGreenDeploymentConfiguration:Z.BlueGreenConfigs.standard(),autoRollbackConfiguration:Z.RollbackConfigs.onFailure()});return{application:c,appId:u,deploymentGroup:d,groupId:f}}};static Strategies={rolling:(n=25)=>({type:"rolling",batchPercentage:n}),blueGreen:()=>({type:"blue-green"}),canary:(n=10,i=5)=>({type:"canary",canaryPercentage:n,canaryInterval:i}),allAtOnce:()=>({type:"all-at-once"})}}class _{static ContentTypes={".html":"text/html",".htm":"text/html",".css":"text/css",".js":"application/javascript",".mjs":"application/javascript",".json":"application/json",".xml":"application/xml",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject",".pdf":"application/pdf",".txt":"text/plain",".md":"text/markdown",".map":"application/json"};static NoHashPatterns=[/^index\.html$/,/^favicon\.ico$/,/^robots\.txt$/,/^sitemap\.xml$/,/^manifest\.json$/,/^\.well-known\//,/^_redirects$/,/^_headers$/];static computeFileHash(n,i="md5"){let s=it(n);return xr(i).update(s).digest("hex")}static computeShortHash(n){return _.computeFileHash(n).slice(0,8)}static getContentType(n){let i=bn(n).toLowerCase();return _.ContentTypes[i]||"application/octet-stream"}static shouldHashFile(n,i){return![..._.NoHashPatterns,...i||[]].some((o)=>o.test(n))}static generateHashedFilename(n,i){let s=bn(n),o=Or(n,s),c=hn(n);if(c===".")return`${o}.${i}${s}`;return Ue(c,`${o}.${i}${s}`)}static collectFiles(n,i){let s=[],o=i||n;if(!Et(n))return s;let c=Mr(n,{withFileTypes:!0});for(let u of c){let d=Ue(n,u.name);if(u.isDirectory())s.push(..._.collectFiles(d,o));else if(u.isFile())s.push(d)}return s}static hashDirectory(n){let{sourceDir:i,outputDir:s,excludePatterns:o=[],hashAlgorithm:c="md5",copyUnhashed:u=!0}=n,d=_.collectFiles(i),f=[],h={};for(let A of d){let T=A.replace(i,"").replace(/^[/\\]/,""),v=_.shouldHashFile(T,o),R=Lr(A),P=v?_.computeFileHash(A,c).slice(0,8):"",E=v?_.generateHashedFilename(T,P):T,I={originalPath:T,hashedPath:E,hash:P,size:R.size,contentType:_.getContentType(A)};if(f.push(I),h[T]=E,s){let M=Ue(s,E),L=hn(M);if(!Et(L)){let{mkdirSync:x}=nt("node:fs");x(L,{recursive:!0})}if(v||u)kr(A,M)}}let S={version:"1.0",timestamp:new Date().toISOString(),assets:f,hashMap:h};if(s){let A=Ue(s,"asset-manifest.json");st(A,JSON.stringify(S,null,2))}return S}static getInvalidationPaths(n,i){let s=[];if(!n)return["/*"];let o=n.hashMap,c=i.hashMap;for(let[u,d]of Object.entries(c)){let f=o[u];if(!f||f!==d){if(s.push(`/${u}`),f&&f!==d)s.push(`/${f}`)}}for(let[u,d]of Object.entries(o))if(!c[u])s.push(`/${u}`),s.push(`/${d}`);if(s.length>100)return["/*"];return[...new Set(s)]}static updateHtmlReferences(n){let{htmlDir:i,manifest:s,basePath:o=""}=n,c=_.collectFiles(i).filter((u)=>u.endsWith(".html")||u.endsWith(".htm"));for(let u of c){let d=it(u,"utf-8");for(let[f,h]of Object.entries(s.hashMap)){if(f===h)continue;let S=[new RegExp(`(src|href)=["']${o}/?${_.escapeRegExp(f)}["']`,"g"),new RegExp(`url\\(["']?${o}/?${_.escapeRegExp(f)}["']?\\)`,"g")];for(let A of S)d=d.replace(A,(T)=>T.replace(f,h))}st(u,d)}}static updateCssReferences(n){let{cssDir:i,manifest:s,basePath:o=""}=n,c=_.collectFiles(i).filter((u)=>u.endsWith(".css"));for(let u of c){let d=it(u,"utf-8");for(let[f,h]of Object.entries(s.hashMap)){if(f===h)continue;let S=new RegExp(`url\\(["']?${o}/?${_.escapeRegExp(f)}["']?\\)`,"g");d=d.replace(S,`url(${o}/${h})`)}st(u,d)}}static escapeRegExp(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}static generateS3DeploymentManifest(n){let{sourceDir:i,keyPrefix:s="",excludePatterns:o=[],cacheControl:c={hashed:"public, max-age=31536000, immutable",unhashed:"public, max-age=3600",html:"public, max-age=0, must-revalidate"}}=n;return _.hashDirectory({sourceDir:i,excludePatterns:o}).assets.map((d)=>{let f=d.hash!=="",h=d.contentType==="text/html",S=c.unhashed||"public, max-age=3600";if(h)S=c.html||"public, max-age=0, must-revalidate";else if(f)S=c.hashed||"public, max-age=31536000, immutable";return{localPath:Ue(i,d.originalPath),s3Key:s?`${s}/${d.hashedPath}`:d.hashedPath,contentType:d.contentType,cacheControl:S,hash:d.hash}})}static compareManifests(n,i){let s={added:[],removed:[],changed:[],unchanged:[]},o=new Set(Object.keys(n.hashMap)),c=new Set(Object.keys(i.hashMap));for(let u of c)if(!o.has(u))s.added.push(u);for(let u of o)if(!c.has(u))s.removed.push(u);for(let u of c)if(o.has(u))if(n.hashMap[u]!==i.hashMap[u])s.changed.push(u);else s.unchanged.push(u);return s}static loadManifest(n){if(!Et(n))return null;try{let i=it(n,"utf-8");return JSON.parse(i)}catch{return null}}static saveManifest(n,i){st(i,JSON.stringify(n,null,2))}}class Vi{static createSecret(n){let{slug:i,environment:s,secretName:o,description:c,secretString:u,kmsKeyId:d,tags:f}=n,h=o||r({slug:i,environment:s,resourceType:"secret"}),S=t(h),A={Type:"AWS::SecretsManager::Secret",Properties:{Name:h,Description:c,SecretString:u,Tags:[{Key:"Name",Value:h},{Key:"Environment",Value:s},...f?Object.entries(f).map(([T,v])=>({Key:T,Value:v})):[]]}};if(d)A.Properties.KmsKeyId=d;return{secret:A,logicalId:S}}static createGeneratedSecret(n){let{slug:i,environment:s,secretName:o,description:c,excludeCharacters:u,excludeLowercase:d,excludeNumbers:f,excludePunctuation:h,excludeUppercase:S,passwordLength:A,requireEachIncludedType:T,kmsKeyId:v,tags:R}=n,P=o||r({slug:i,environment:s,resourceType:"secret"}),E=t(P),I={Type:"AWS::SecretsManager::Secret",Properties:{Name:P,Description:c,GenerateSecretString:{ExcludeCharacters:u,ExcludeLowercase:d,ExcludeNumbers:f,ExcludePunctuation:h,ExcludeUppercase:S,PasswordLength:A||32,RequireEachIncludedType:T!==!1},Tags:[{Key:"Name",Value:P},{Key:"Environment",Value:s},...R?Object.entries(R).map(([M,L])=>({Key:M,Value:L})):[]]}};if(v)I.Properties.KmsKeyId=v;return{secret:I,logicalId:E}}static createDatabaseSecret(n){let{slug:i,environment:s,secretName:o,username:c,dbname:u,engine:d,host:f,port:h,kmsKeyId:S}=n,A=o||r({slug:i,environment:s,resourceType:"db-secret"}),T=t(A),v={username:c};if(u)v.dbname=u;if(d)v.engine=d;if(f)v.host=f;if(h)v.port=h;let R={Type:"AWS::SecretsManager::Secret",Properties:{Name:A,Description:`Database credentials for ${c}`,GenerateSecretString:{SecretStringTemplate:JSON.stringify(v),GenerateStringKey:"password",PasswordLength:32,ExcludeCharacters:'"@/\\',RequireEachIncludedType:!0},Tags:[{Key:"Name",Value:A},{Key:"Environment",Value:s},{Key:"Type",Value:"database"}]}};if(S)R.Properties.KmsKeyId=S;return{secret:R,logicalId:T}}static attachToDatabase(n){let{slug:i,environment:s,secretId:o,targetId:c,targetType:u}=n,d=r({slug:i,environment:s,resourceType:"secret-attachment"}),f=t(d);return{attachment:{Type:"AWS::SecretsManager::SecretTargetAttachment",Properties:{SecretId:o,TargetId:c,TargetType:u}},logicalId:f}}static enableRotation(n){let{slug:i,environment:s,secretId:o,rotationLambdaArn:c,automaticallyAfterDays:u,rotationType:d,kmsKeyArn:f,vpcSecurityGroupIds:h,vpcSubnetIds:S}=n,A=r({slug:i,environment:s,resourceType:"secret-rotation"}),T=t(A),v={Type:"AWS::SecretsManager::RotationSchedule",Properties:{SecretId:o,RotationRules:{AutomaticallyAfterDays:u||30}}};if(c)v.Properties.RotationLambdaARN=c;else if(d)v.Properties.HostedRotationLambda={RotationType:d,KmsKeyArn:f,VpcSecurityGroupIds:h,VpcSubnetIds:S};return{rotation:v,logicalId:T}}static SecretTypes={apiKey:(n,i,s)=>Vi.createGeneratedSecret({slug:n,environment:i,secretName:`${n}-${i}-${s}-api-key`,description:`API key for ${s}`,passwordLength:32,excludePunctuation:!0,excludeLowercase:!1,excludeUppercase:!1,excludeNumbers:!1}),oauthClientSecret:(n,i,s)=>Vi.createGeneratedSecret({slug:n,environment:i,secretName:`${n}-${i}-${s}-oauth-secret`,description:`OAuth client secret for ${s}`,passwordLength:64,excludeCharacters:"\"'`\\/@",requireEachIncludedType:!0}),jwtSecret:(n,i)=>Vi.createGeneratedSecret({slug:n,environment:i,secretName:`${n}-${i}-jwt-secret`,description:"JWT signing secret",passwordLength:64,excludePunctuation:!0}),encryptionKey:(n,i)=>Vi.createGeneratedSecret({slug:n,environment:i,secretName:`${n}-${i}-encryption-key`,description:"Data encryption key",passwordLength:64,excludeCharacters:"+/=",excludePunctuation:!0})};static RotationTypes={MySQLSingleUser:"MySQLSingleUser",MySQLMultiUser:"MySQLMultiUser",PostgreSQLSingleUser:"PostgreSQLSingleUser",PostgreSQLMultiUser:"PostgreSQLMultiUser",OracleSingleUser:"OracleSingleUser",OracleMultiUser:"OracleMultiUser",MariaDBSingleUser:"MariaDBSingleUser",MariaDBMultiUser:"MariaDBMultiUser",SQLServerSingleUser:"SQLServerSingleUser",SQLServerMultiUser:"SQLServerMultiUser",RedshiftSingleUser:"RedshiftSingleUser",RedshiftMultiUser:"RedshiftMultiUser",MongoDBSingleUser:"MongoDBSingleUser",MongoDBMultiUser:"MongoDBMultiUser"}}class D{static createParameter(n){let{slug:i,environment:s,parameterName:o,value:c,type:u="String",description:d,tier:f="Standard",tags:h}=n,S=o||r({slug:i,environment:s,resourceType:"parameter"}),A=t(S);return{parameter:{Type:"AWS::SSM::Parameter",Properties:{Name:`/${i}/${s}/${S}`,Type:u,Value:c,Description:d,Tier:f,Tags:{Name:S,Environment:s,...h}}},logicalId:A}}static createString(n,i,s,o,c){return D.createParameter({slug:n,environment:i,parameterName:s,value:o,type:"String",description:c})}static createSecureString(n,i,s,o,c){return D.createParameter({slug:n,environment:i,parameterName:s,value:o,type:"SecureString",description:c})}static createStringList(n,i,s,o,c){return D.createParameter({slug:n,environment:i,parameterName:s,value:o.join(","),type:"StringList",description:c})}static Parameters={databaseUrl:(n,i,s)=>D.createSecureString(n,i,"database-url",s,"Database connection URL"),apiEndpoint:(n,i,s)=>D.createString(n,i,"api-endpoint",s,"API endpoint URL"),appVersion:(n,i,s)=>D.createString(n,i,"app-version",s,"Application version"),featureFlags:(n,i,s)=>D.createStringList(n,i,"feature-flags",s,"Enabled feature flags"),apiKey:(n,i,s,o)=>D.createSecureString(n,i,`${s}-api-key`,o,`API key for ${s}`),oauthCredentials:(n,i,s,o)=>{let c=D.createString(n,i,"oauth-client-id",s,"OAuth client ID"),u=D.createSecureString(n,i,"oauth-client-secret",o,"OAuth client secret");return{clientId:c,clientSecret:u}},smtpCredentials:(n,i,s,o,c,u)=>{let d=D.createString(n,i,"smtp-username",s,"SMTP username"),f=D.createSecureString(n,i,"smtp-password",o,"SMTP password"),h=D.createString(n,i,"smtp-host",c,"SMTP host"),S=D.createString(n,i,"smtp-port",u.toString(),"SMTP port");return{username:d,password:f,host:h,port:S}},redisUrl:(n,i,s)=>D.createSecureString(n,i,"redis-url",s,"Redis connection URL"),s3Bucket:(n,i,s)=>D.createString(n,i,"s3-bucket",s,"S3 bucket name"),cloudFrontDistribution:(n,i,s)=>D.createString(n,i,"cloudfront-distribution-id",s,"CloudFront distribution ID")}}class ar{static createDomain(n){let{slug:i,environment:s,domainName:o,engineVersion:c="OpenSearch_2.11",instanceType:u="t3.small.search",instanceCount:d=1,volumeSize:f=10,volumeType:h="gp3",dedicatedMaster:S=!1,dedicatedMasterType:A,dedicatedMasterCount:T=3,multiAz:v=!1,availabilityZoneCount:R=2,vpc:P,encryption:E,enforceHttps:I=!0,tlsSecurityPolicy:M="Policy-Min-TLS-1-2-2019-07",advancedSecurity:L,autoSnapshotHour:x=0,autoTune:O=!0,tags:B={}}=n,F=o||r({slug:i,environment:s,resourceType:"search"}),U=t(F);return{domain:{Type:"AWS::OpenSearchService::Domain",Properties:{DomainName:F,EngineVersion:c,ClusterConfig:{InstanceType:u,InstanceCount:d,DedicatedMasterEnabled:S,...S&&{DedicatedMasterType:A||u,DedicatedMasterCount:T},ZoneAwarenessEnabled:v,...v&&{ZoneAwarenessConfig:{AvailabilityZoneCount:R}}},EBSOptions:{EBSEnabled:!0,VolumeType:h,VolumeSize:f},DomainEndpointOptions:{EnforceHTTPS:I,TLSSecurityPolicy:M},SnapshotOptions:{AutomatedSnapshotStartHour:x},...P&&{VPCOptions:{SubnetIds:P.subnetIds,SecurityGroupIds:P.securityGroupIds}},...E&&{EncryptionAtRestOptions:{Enabled:E.atRest??!0,...E.kmsKeyId&&{KmsKeyId:E.kmsKeyId}},NodeToNodeEncryptionOptions:{Enabled:E.nodeToNode??!0}},...L&&{AdvancedSecurityOptions:{Enabled:L.enabled,InternalUserDatabaseEnabled:L.internalUserDatabase??!0,...L.masterUserName&&L.masterUserPassword&&{MasterUserOptions:{MasterUserName:L.masterUserName,MasterUserPassword:L.masterUserPassword}},...L.masterUserArn&&{MasterUserOptions:{MasterUserARN:L.masterUserArn}}}},...O&&{AutoTuneOptions:{DesiredState:"ENABLED"}},Tags:[{Key:"Name",Value:F},{Key:"Environment",Value:s},...Object.entries(B).map(([H,z])=>({Key:H,Value:z}))]}},logicalId:U}}static createAccessPolicy(n,i){let{ipAddresses:s,iamPrincipalArns:o,allowAll:c,vpcEndpoint:u}=i;if(c)return{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:"*"},Action:"es:*",Resource:n}]};let d=[];if(o&&o.length>0)d.push({Effect:"Allow",Principal:{AWS:o},Action:"es:*",Resource:n});if(s&&s.length>0)d.push({Effect:"Allow",Principal:{AWS:"*"},Action:"es:*",Resource:n,Condition:{IpAddress:{"aws:SourceIp":s}}});if(u)return{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:"*"},Action:"es:*",Resource:n}]};return{Version:"2012-10-17",Statement:d}}static DomainPresets={development:(n,i)=>ar.createDomain({slug:n,environment:i,instanceType:"t3.small.search",instanceCount:1,volumeSize:10,multiAz:!1,dedicatedMaster:!1,encryption:{atRest:!0,nodeToNode:!0},autoTune:!1}),production:(n,i,s)=>ar.createDomain({slug:n,environment:i,instanceType:"m6g.large.search",instanceCount:3,volumeSize:100,volumeType:"gp3",multiAz:!0,availabilityZoneCount:3,dedicatedMaster:!0,dedicatedMasterType:"m6g.large.search",dedicatedMasterCount:3,vpc:s,encryption:{atRest:!0,nodeToNode:!0},advancedSecurity:{enabled:!0,internalUserDatabase:!0},autoTune:!0}),costOptimized:(n,i)=>ar.createDomain({slug:n,environment:i,instanceType:"t3.medium.search",instanceCount:2,volumeSize:20,volumeType:"gp3",multiAz:!0,dedicatedMaster:!1,encryption:{atRest:!0,nodeToNode:!0},autoTune:!0}),highPerformance:(n,i,s)=>ar.createDomain({slug:n,environment:i,instanceType:"r6g.2xlarge.search",instanceCount:6,volumeSize:500,volumeType:"gp3",multiAz:!0,availabilityZoneCount:3,dedicatedMaster:!0,dedicatedMasterType:"c6g.xlarge.search",dedicatedMasterCount:3,vpc:s,encryption:{atRest:!0,nodeToNode:!0},advancedSecurity:{enabled:!0,internalUserDatabase:!1},autoTune:!0})};static InstanceTypes={"t3.small.search":"t3.small.search","t3.medium.search":"t3.medium.search","m6g.large.search":"m6g.large.search","m6g.xlarge.search":"m6g.xlarge.search","m6g.2xlarge.search":"m6g.2xlarge.search","r6g.large.search":"r6g.large.search","r6g.xlarge.search":"r6g.xlarge.search","r6g.2xlarge.search":"r6g.2xlarge.search","r6g.4xlarge.search":"r6g.4xlarge.search","c6g.large.search":"c6g.large.search","c6g.xlarge.search":"c6g.xlarge.search","c6g.2xlarge.search":"c6g.2xlarge.search"};static EngineVersions={"OpenSearch_2.11":"OpenSearch_2.11","OpenSearch_2.9":"OpenSearch_2.9","OpenSearch_2.7":"OpenSearch_2.7","OpenSearch_1.3":"OpenSearch_1.3","Elasticsearch_7.10":"Elasticsearch_7.10"}}class Dt{static createDomainRedirectBucket(n){let{slug:i,environment:s,sourceDomain:o,targetDomain:c,protocol:u="https"}=n,d=r({slug:i,environment:s,resourceType:"s3",suffix:"redirect"}),f=t(d),h=t(`${d}-policy`),S={Type:"AWS::S3::Bucket",Properties:{BucketName:o,WebsiteConfiguration:{RedirectAllRequestsTo:{HostName:c,Protocol:u}},PublicAccessBlockConfiguration:{BlockPublicAcls:!1,BlockPublicPolicy:!1,IgnorePublicAcls:!1,RestrictPublicBuckets:!1},Tags:[{Key:"Name",Value:d},{Key:"Environment",Value:s},{Key:"Purpose",Value:"Domain Redirect"}]}},A={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:k.Ref(f),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadForRedirect",Effect:"Allow",Principal:"*",Action:["s3:GetObject"],Resource:[k.Join("",[k.GetAtt(f,"Arn"),"/*"])]}]}}};return{bucket:S,bucketPolicy:A,logicalId:f,policyLogicalId:h}}static createPathRedirectFunction(n){let{slug:i,environment:s,rules:o}=n,c=r({slug:i,environment:s,resourceType:"cf-redirect"}),u=t(c),d=Dt.generateRedirectFunctionCode(o);return{function:{Type:"AWS::CloudFront::Function",Properties:{Name:c,AutoPublish:!0,FunctionConfig:{Comment:`Path redirect function for ${i} (${s})`,Runtime:"cloudfront-js-2.0"},FunctionCode:d}},logicalId:u,functionCode:d}}static generateRedirectFunctionCode(n){return`function handler(event) {
|
|
2281
|
+
| limit 50`,region:o,title:"Recent Errors and Warnings"}}),d+=6;return Lo.createDashboard({slug:i,environment:s,widgets:u})}static DashboardTemplates={staticWebsite:(n)=>({slug:n.slug,environment:n.environment,widgets:[{type:"text",x:0,y:0,width:24,height:1,properties:{markdown:`# ${n.slug.toUpperCase()} Static Website Dashboard`}},{type:"metric",x:0,y:1,width:8,height:6,properties:{title:"CloudFront Requests",region:"us-east-1",metrics:[["AWS/CloudFront","Requests","DistributionId",n.cloudFrontDistributionId,"Region","Global"]],period:300,stat:"Sum"}},{type:"metric",x:8,y:1,width:8,height:6,properties:{title:"Error Rate",region:"us-east-1",metrics:[["AWS/CloudFront","4xxErrorRate","DistributionId",n.cloudFrontDistributionId,"Region","Global",{label:"4XX"}],["AWS/CloudFront","5xxErrorRate","DistributionId",n.cloudFrontDistributionId,"Region","Global",{label:"5XX"}]],period:300,stat:"Average"}},{type:"metric",x:16,y:1,width:8,height:6,properties:{title:"Bytes Downloaded",region:"us-east-1",metrics:[["AWS/CloudFront","BytesDownloaded","DistributionId",n.cloudFrontDistributionId,"Region","Global"]],period:300,stat:"Sum"}},{type:"metric",x:0,y:7,width:12,height:6,properties:{title:"S3 Bucket Size",region:n.region||"us-east-1",metrics:[["AWS/S3","BucketSizeBytes","BucketName",n.s3BucketName,"StorageType","StandardStorage"]],period:86400,stat:"Average"}},{type:"metric",x:12,y:7,width:12,height:6,properties:{title:"S3 Number of Objects",region:n.region||"us-east-1",metrics:[["AWS/S3","NumberOfObjects","BucketName",n.s3BucketName,"StorageType","AllStorageTypes"]],period:86400,stat:"Average"}}]}),serverlessApi:(n)=>({slug:n.slug,environment:n.environment,widgets:[{type:"text",x:0,y:0,width:24,height:1,properties:{markdown:`# ${n.slug.toUpperCase()} Serverless API Dashboard`}},{type:"metric",x:0,y:1,width:8,height:6,properties:{title:"API Requests",region:n.region||"us-east-1",metrics:[["AWS/ApiGateway","Count","ApiName",n.apiGatewayName]],period:60,stat:"Sum"}},{type:"metric",x:8,y:1,width:8,height:6,properties:{title:"API Latency",region:n.region||"us-east-1",metrics:[["AWS/ApiGateway","Latency","ApiName",n.apiGatewayName]],period:60,stat:"Average"}},{type:"metric",x:16,y:1,width:8,height:6,properties:{title:"API Errors",region:n.region||"us-east-1",metrics:[["AWS/ApiGateway","4XXError","ApiName",n.apiGatewayName,{label:"4XX"}],["AWS/ApiGateway","5XXError","ApiName",n.apiGatewayName,{label:"5XX"}]],period:60,stat:"Sum"}},...n.lambdaFunctionNames.map((i,s)=>({type:"metric",x:s%3*8,y:7+Math.floor(s/3)*6,width:8,height:6,properties:{title:`${i} Metrics`,region:n.region||"us-east-1",metrics:[["AWS/Lambda","Invocations","FunctionName",i],["AWS/Lambda","Duration","FunctionName",i],["AWS/Lambda","Errors","FunctionName",i]],period:300,stat:"Sum"}}))]}),containerService:(n)=>({slug:n.slug,environment:n.environment,widgets:[{type:"text",x:0,y:0,width:24,height:1,properties:{markdown:`# ${n.slug.toUpperCase()} Container Service Dashboard`}},{type:"metric",x:0,y:1,width:8,height:6,properties:{title:"ECS CPU",region:n.region||"us-east-1",metrics:[["AWS/ECS","CPUUtilization","ClusterName",n.ecsClusterName,"ServiceName",n.ecsServiceName]],period:60,stat:"Average"}},{type:"metric",x:8,y:1,width:8,height:6,properties:{title:"ECS Memory",region:n.region||"us-east-1",metrics:[["AWS/ECS","MemoryUtilization","ClusterName",n.ecsClusterName,"ServiceName",n.ecsServiceName]],period:60,stat:"Average"}},{type:"metric",x:16,y:1,width:8,height:6,properties:{title:"Running Tasks",region:n.region||"us-east-1",metrics:[["ECS/ContainerInsights","RunningTaskCount","ClusterName",n.ecsClusterName,"ServiceName",n.ecsServiceName]],period:60,stat:"Average"}},{type:"metric",x:0,y:7,width:8,height:6,properties:{title:"ALB Requests",region:n.region||"us-east-1",metrics:[["AWS/ApplicationELB","RequestCount","LoadBalancer",n.albName]],period:60,stat:"Sum"}},{type:"metric",x:8,y:7,width:8,height:6,properties:{title:"Response Time",region:n.region||"us-east-1",metrics:[["AWS/ApplicationELB","TargetResponseTime","LoadBalancer",n.albName]],period:60,stat:"Average"}},{type:"metric",x:16,y:7,width:8,height:6,properties:{title:"Healthy Hosts",region:n.region||"us-east-1",metrics:[["AWS/ApplicationELB","HealthyHostCount","LoadBalancer",n.albName]],period:60,stat:"Average"}},...n.rdsInstanceId?[{type:"metric",x:0,y:13,width:12,height:6,properties:{title:"RDS CPU",region:n.region||"us-east-1",metrics:[["AWS/RDS","CPUUtilization","DBInstanceIdentifier",n.rdsInstanceId]],period:300,stat:"Average"}},{type:"metric",x:12,y:13,width:12,height:6,properties:{title:"RDS Connections",region:n.region||"us-east-1",metrics:[["AWS/RDS","DatabaseConnections","DBInstanceIdentifier",n.rdsInstanceId]],period:60,stat:"Sum"}}]:[]]})};static Config={createAlarmConfig:(n)=>{let{metricName:i,namespace:s,threshold:o,comparisonOperator:c="GreaterThanThreshold",evaluationPeriods:u=1,period:d=300,statistic:f="Average",treatMissingData:h="missing"}=n;return{MetricName:i,Namespace:s,Threshold:o,ComparisonOperator:c,EvaluationPeriods:u,Period:d,Statistic:f,TreatMissingData:h}},namespaces:{ec2:"AWS/EC2",ecs:"AWS/ECS",lambda:"AWS/Lambda",rds:"AWS/RDS",sqs:"AWS/SQS",sns:"AWS/SNS",s3:"AWS/S3",cloudfront:"AWS/CloudFront",alb:"AWS/ApplicationELB",nlb:"AWS/NetworkELB",apiGateway:"AWS/ApiGateway",dynamodb:"AWS/DynamoDB",elasticache:"AWS/ElastiCache"},comparisonOperators:{greaterThan:"GreaterThanThreshold",greaterOrEqual:"GreaterThanOrEqualToThreshold",lessThan:"LessThanThreshold",lessOrEqual:"LessThanOrEqualToThreshold"},metrics:{ec2:{cpu:{metricName:"CPUUtilization",namespace:"AWS/EC2"},networkIn:{metricName:"NetworkIn",namespace:"AWS/EC2"},networkOut:{metricName:"NetworkOut",namespace:"AWS/EC2"},statusCheck:{metricName:"StatusCheckFailed",namespace:"AWS/EC2"}},ecs:{cpu:{metricName:"CPUUtilization",namespace:"AWS/ECS"},memory:{metricName:"MemoryUtilization",namespace:"AWS/ECS"}},lambda:{invocations:{metricName:"Invocations",namespace:"AWS/Lambda"},errors:{metricName:"Errors",namespace:"AWS/Lambda"},duration:{metricName:"Duration",namespace:"AWS/Lambda"},throttles:{metricName:"Throttles",namespace:"AWS/Lambda"},concurrentExecutions:{metricName:"ConcurrentExecutions",namespace:"AWS/Lambda"}},rds:{cpu:{metricName:"CPUUtilization",namespace:"AWS/RDS"},connections:{metricName:"DatabaseConnections",namespace:"AWS/RDS"},freeStorage:{metricName:"FreeStorageSpace",namespace:"AWS/RDS"},readLatency:{metricName:"ReadLatency",namespace:"AWS/RDS"},writeLatency:{metricName:"WriteLatency",namespace:"AWS/RDS"}},alb:{requestCount:{metricName:"RequestCount",namespace:"AWS/ApplicationELB"},responseTime:{metricName:"TargetResponseTime",namespace:"AWS/ApplicationELB"},httpCode4xx:{metricName:"HTTPCode_Target_4XX_Count",namespace:"AWS/ApplicationELB"},httpCode5xx:{metricName:"HTTPCode_Target_5XX_Count",namespace:"AWS/ApplicationELB"},healthyHosts:{metricName:"HealthyHostCount",namespace:"AWS/ApplicationELB"}},sqs:{messagesVisible:{metricName:"ApproximateNumberOfMessagesVisible",namespace:"AWS/SQS"},messagesDelayed:{metricName:"ApproximateNumberOfMessagesDelayed",namespace:"AWS/SQS"},messageAge:{metricName:"ApproximateAgeOfOldestMessage",namespace:"AWS/SQS"}}},presets:{highCpu:(n=80)=>({metricName:"CPUUtilization",threshold:n,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),highMemory:(n=80)=>({metricName:"MemoryUtilization",threshold:n,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),highErrors:(n=10)=>({metricName:"Errors",threshold:n,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:1,period:60,statistic:"Sum"}),highLatency:(n=5000)=>({metricName:"Duration",threshold:n,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),lowHealthyHosts:(n=1)=>({metricName:"HealthyHostCount",namespace:"AWS/ApplicationELB",threshold:n,comparisonOperator:"LessThanThreshold",evaluationPeriods:2,period:60,statistic:"Minimum"}),queueDepth:(n=1000)=>({metricName:"ApproximateNumberOfMessagesVisible",namespace:"AWS/SQS",threshold:n,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),lowStorage:(n=10737418240)=>({metricName:"FreeStorageSpace",namespace:"AWS/RDS",threshold:n,comparisonOperator:"LessThanThreshold",evaluationPeriods:1,period:300,statistic:"Average"})}}}class Y{static createUserPool(n){let{slug:i,environment:s,userPoolName:o,aliasAttributes:c,autoVerifiedAttributes:u,passwordPolicy:d,mfaConfiguration:f,emailConfiguration:h,smsConfiguration:S,lambdaTriggers:A,userPoolAddOns:T,accountRecoverySetting:v}=n,R=o||r({slug:i,environment:s,resourceType:"user-pool"}),P=t(R),E={Type:"AWS::Cognito::UserPool",Properties:{UserPoolName:R,Policies:d?{PasswordPolicy:{MinimumLength:d.minimumLength,RequireLowercase:d.requireLowercase,RequireUppercase:d.requireUppercase,RequireNumbers:d.requireNumbers,RequireSymbols:d.requireSymbols,TemporaryPasswordValidityDays:d.temporaryPasswordValidityDays}}:void 0,MfaConfiguration:f,Schema:[{Name:"email",AttributeDataType:"String",Required:!0,Mutable:!1}]}};if(c&&c.length>0)E.Properties.UsernameAttributes=c;if(u&&u.length>0)E.Properties.AutoVerifiedAttributes=u;if(h)E.Properties.EmailConfiguration={EmailSendingAccount:h.emailSendingAccount,From:h.from,ReplyToEmailAddress:h.replyToEmailAddress,SourceArn:h.sourceArn,ConfigurationSet:h.configurationSet};if(S)E.Properties.SmsConfiguration={ExternalId:S.externalId,SnsCallerArn:S.snsCallerArn};if(A)E.Properties.LambdaConfig={PreSignUp:A.preSignUp,PostConfirmation:A.postConfirmation,PreAuthentication:A.preAuthentication,PostAuthentication:A.postAuthentication,CustomMessage:A.customMessage,DefineAuthChallenge:A.defineAuthChallenge,CreateAuthChallenge:A.createAuthChallenge,VerifyAuthChallengeResponse:A.verifyAuthChallengeResponse,PreTokenGeneration:A.preTokenGeneration,UserMigration:A.userMigration};if(T)E.Properties.UserPoolAddOns={AdvancedSecurityMode:T.advancedSecurityMode};if(v)E.Properties.AccountRecoverySetting={RecoveryMechanisms:v.recoveryMechanisms};return{userPool:E,logicalId:P}}static createUserPoolClient(n,i){let{slug:s,environment:o,clientName:c,generateSecret:u=!1,refreshTokenValidity:d,accessTokenValidity:f,idTokenValidity:h,tokenValidityUnits:S,readAttributes:A,writeAttributes:T,explicitAuthFlows:v,preventUserExistenceErrors:R,enableTokenRevocation:P,callbackURLs:E,logoutURLs:I,allowedOAuthFlows:M,allowedOAuthScopes:L,allowedOAuthFlowsUserPoolClient:x,supportedIdentityProviders:O}=i,B=c||r({slug:s,environment:o,resourceType:"user-pool-client"}),F=t(B);return{client:{Type:"AWS::Cognito::UserPoolClient",Properties:{ClientName:B,UserPoolId:k.Ref(n),GenerateSecret:u,RefreshTokenValidity:d,AccessTokenValidity:f,IdTokenValidity:h,TokenValidityUnits:S,ReadAttributes:A,WriteAttributes:T,ExplicitAuthFlows:v,PreventUserExistenceErrors:R,EnableTokenRevocation:P,CallbackURLs:E,LogoutURLs:I,AllowedOAuthFlows:M,AllowedOAuthScopes:L,AllowedOAuthFlowsUserPoolClient:x,SupportedIdentityProviders:O}},logicalId:F}}static createUserPoolDomain(n,i){let{slug:s,environment:o,domain:c,customDomainConfig:u}=i,d=r({slug:s,environment:o,resourceType:"user-pool-domain"}),f=t(d);return{domain:{Type:"AWS::Cognito::UserPoolDomain",Properties:{Domain:c,UserPoolId:k.Ref(n),CustomDomainConfig:u}},logicalId:f}}static createIdentityPool(n){let{slug:i,environment:s,identityPoolName:o,allowUnauthenticatedIdentities:c=!1,cognitoIdentityProviders:u,supportedLoginProviders:d,samlProviderARNs:f,openIdConnectProviderARNs:h}=n,S=o||r({slug:i,environment:s,resourceType:"identity-pool"}),A=t(S);return{identityPool:{Type:"AWS::Cognito::IdentityPool",Properties:{IdentityPoolName:S,AllowUnauthenticatedIdentities:c,CognitoIdentityProviders:u,SupportedLoginProviders:d,SamlProviderARNs:f,OpenIdConnectProviderARNs:h}},logicalId:A}}static createIdentityPoolRoleAttachment(n,i){let{slug:s,environment:o,authenticatedRole:c,unauthenticatedRole:u,roleMappings:d}=i,f=r({slug:s,environment:o,resourceType:"identity-pool-role-attachment"}),h=t(f),S={authenticated:c};if(u)S.unauthenticated=u;return{attachment:{Type:"AWS::Cognito::IdentityPoolRoleAttachment",Properties:{IdentityPoolId:k.Ref(n),Roles:S,RoleMappings:d}},logicalId:h}}static createAuthenticatedRole(n){let{slug:i,environment:s,identityPoolLogicalId:o}=n,c=r({slug:i,environment:s,resourceType:"cognito-authenticated-role"}),u=t(c);return{role:{Type:"AWS::IAM::Role",Properties:{RoleName:c,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Federated:"cognito-identity.amazonaws.com"},Action:"sts:AssumeRoleWithWebIdentity",Condition:{StringEquals:{"cognito-identity.amazonaws.com:aud":k.Ref(o)},"ForAnyValue:StringLike":{"cognito-identity.amazonaws.com:amr":"authenticated"}}}]},Policies:[{PolicyName:"CognitoAuthenticatedPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["cognito-sync:*","cognito-identity:*"],Resource:"*"}]}}],Tags:[{Key:"Name",Value:c},{Key:"Environment",Value:s}]}},logicalId:u}}static createUnauthenticatedRole(n){let{slug:i,environment:s,identityPoolLogicalId:o}=n,c=r({slug:i,environment:s,resourceType:"cognito-unauthenticated-role"}),u=t(c);return{role:{Type:"AWS::IAM::Role",Properties:{RoleName:c,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Federated:"cognito-identity.amazonaws.com"},Action:"sts:AssumeRoleWithWebIdentity",Condition:{StringEquals:{"cognito-identity.amazonaws.com:aud":k.Ref(o)},"ForAnyValue:StringLike":{"cognito-identity.amazonaws.com:amr":"unauthenticated"}}}]},Policies:[{PolicyName:"CognitoUnauthenticatedPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["cognito-sync:*"],Resource:"*"}]}}],Tags:[{Key:"Name",Value:c},{Key:"Environment",Value:s}]}},logicalId:u}}static PasswordPolicies={relaxed:()=>({minimumLength:8,requireLowercase:!1,requireUppercase:!1,requireNumbers:!1,requireSymbols:!1,temporaryPasswordValidityDays:7}),standard:()=>({minimumLength:8,requireLowercase:!0,requireUppercase:!0,requireNumbers:!0,requireSymbols:!1,temporaryPasswordValidityDays:3}),strict:()=>({minimumLength:12,requireLowercase:!0,requireUppercase:!0,requireNumbers:!0,requireSymbols:!0,temporaryPasswordValidityDays:1})};static AuthFlows={standard:["ALLOW_USER_SRP_AUTH","ALLOW_REFRESH_TOKEN_AUTH"],admin:["ALLOW_ADMIN_USER_PASSWORD_AUTH","ALLOW_REFRESH_TOKEN_AUTH"],custom:["ALLOW_CUSTOM_AUTH","ALLOW_REFRESH_TOKEN_AUTH"],all:["ALLOW_USER_SRP_AUTH","ALLOW_USER_PASSWORD_AUTH","ALLOW_ADMIN_USER_PASSWORD_AUTH","ALLOW_CUSTOM_AUTH","ALLOW_REFRESH_TOKEN_AUTH"]};static OAuthScopes={basic:["openid","email","profile"],all:["openid","email","profile","phone","aws.cognito.signin.user.admin"]};static UseCases={webApp:(n,i,s)=>{let{userPool:o,logicalId:c}=Y.createUserPool({slug:n,environment:i,aliasAttributes:["email"],autoVerifiedAttributes:["email"],passwordPolicy:Y.PasswordPolicies.standard(),mfaConfiguration:"OPTIONAL"}),{client:u,logicalId:d}=Y.createUserPoolClient(c,{slug:n,environment:i,explicitAuthFlows:[...Y.AuthFlows.standard],callbackURLs:[s],allowedOAuthFlows:["code"],allowedOAuthScopes:[...Y.OAuthScopes.basic],allowedOAuthFlowsUserPoolClient:!0});return{userPool:o,poolId:c,client:u,clientId:d}},mobileApp:(n,i)=>{let{userPool:s,logicalId:o}=Y.createUserPool({slug:n,environment:i,aliasAttributes:["email"],autoVerifiedAttributes:["email"],passwordPolicy:Y.PasswordPolicies.standard(),mfaConfiguration:"OPTIONAL"}),{client:c,logicalId:u}=Y.createUserPoolClient(o,{slug:n,environment:i,explicitAuthFlows:[...Y.AuthFlows.standard]}),{identityPool:d,logicalId:f}=Y.createIdentityPool({slug:n,environment:i,allowUnauthenticatedIdentities:!1,cognitoIdentityProviders:[{ClientId:k.Ref(u),ProviderName:k.GetAtt(o,"ProviderName")}]}),{role:h,logicalId:S}=Y.createAuthenticatedRole({slug:n,environment:i,identityPoolLogicalId:f}),{attachment:A,logicalId:T}=Y.createIdentityPoolRoleAttachment(f,{slug:n,environment:i,authenticatedRole:k.GetAtt(S,"Arn")});return{userPool:s,poolId:o,client:c,clientId:u,identityPool:d,identityPoolId:f,authRole:h,authRoleId:S,attachment:A,attachmentId:T}}}}import{createHash as xr}from"node:crypto";import{copyFileSync as kr,existsSync as Et,readdirSync as Mr,readFileSync as ot,statSync as Lr,writeFileSync as ct}from"node:fs";import{basename as Or,dirname as hn,extname as bn,join as Ke}from"node:path";class Z{static createApplication(n){let{slug:i,environment:s,applicationName:o,computePlatform:c}=n,u=o||r({slug:i,environment:s,resourceType:"deploy-app"}),d=t(u);return{application:{Type:"AWS::CodeDeploy::Application",Properties:{ApplicationName:u,ComputePlatform:c,Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:s}]}},logicalId:d}}static createDeploymentGroup(n,i){let{slug:s,environment:o,deploymentGroupName:c,serviceRoleArn:u,autoScalingGroups:d,ec2TagFilters:f,deploymentConfigName:h,autoRollbackConfiguration:S,alarmConfiguration:A,loadBalancerInfo:T,blueGreenDeploymentConfiguration:v}=i,R=c||r({slug:s,environment:o,resourceType:"deploy-group"}),P=t(R);return{deploymentGroup:{Type:"AWS::CodeDeploy::DeploymentGroup",Properties:{ApplicationName:k.Ref(n),DeploymentGroupName:R,ServiceRoleArn:u,AutoScalingGroups:d,Ec2TagFilters:f?.map((I)=>({Key:I.key,Value:I.value,Type:I.type})),DeploymentConfigName:h,AutoRollbackConfiguration:S?{Enabled:S.enabled,Events:S.events}:void 0,AlarmConfiguration:A?{Enabled:A.enabled,Alarms:A.alarms?.map((I)=>({Name:I.name})),IgnorePollAlarmFailure:A.ignorePollAlarmFailure}:void 0,LoadBalancerInfo:T?{TargetGroupInfoList:T.targetGroupInfoList?.map((I)=>({Name:I.name})),ElbInfoList:T.elbInfoList?.map((I)=>({Name:I.name}))}:void 0,BlueGreenDeploymentConfiguration:v?{TerminateBlueInstancesOnDeploymentSuccess:v.terminateBlueInstancesOnDeploymentSuccess?{Action:v.terminateBlueInstancesOnDeploymentSuccess.action,TerminationWaitTimeInMinutes:v.terminateBlueInstancesOnDeploymentSuccess.terminationWaitTimeInMinutes}:void 0,DeploymentReadyOption:v.deploymentReadyOption?{ActionOnTimeout:v.deploymentReadyOption.actionOnTimeout,WaitTimeInMinutes:v.deploymentReadyOption.waitTimeInMinutes}:void 0,GreenFleetProvisioningOption:v.greenFleetProvisioningOption?{Action:v.greenFleetProvisioningOption.action}:void 0}:void 0,Tags:[{Key:"Name",Value:R},{Key:"Environment",Value:o}]}},logicalId:P}}static createDeploymentConfig(n){let{slug:i,environment:s,deploymentConfigName:o,minimumHealthyHosts:c,trafficRoutingConfig:u}=n,d=o||r({slug:i,environment:s,resourceType:"deploy-config"}),f=t(d);return{deploymentConfig:{Type:"AWS::CodeDeploy::DeploymentConfig",Properties:{DeploymentConfigName:d,MinimumHealthyHosts:c?{Type:c.type,Value:c.value}:void 0,TrafficRoutingConfig:u?{Type:u.type,TimeBasedCanary:u.timeBasedCanary?{CanaryPercentage:u.timeBasedCanary.canaryPercentage,CanaryInterval:u.timeBasedCanary.canaryInterval}:void 0,TimeBasedLinear:u.timeBasedLinear?{LinearPercentage:u.timeBasedLinear.linearPercentage,LinearInterval:u.timeBasedLinear.linearInterval}:void 0}:void 0}},logicalId:f}}static DeploymentConfigs={allAtOnce:()=>({type:"FLEET_PERCENT",value:0}),halfAtATime:()=>({type:"FLEET_PERCENT",value:50}),oneAtATime:()=>({type:"HOST_COUNT",value:1}),custom:(n,i)=>({type:n,value:i})};static TrafficRouting={allAtOnce:()=>({type:"AllAtOnce"}),canary:(n,i)=>({type:"TimeBasedCanary",timeBasedCanary:{canaryPercentage:n,canaryInterval:i}}),linear:(n,i)=>({type:"TimeBasedLinear",timeBasedLinear:{linearPercentage:n,linearInterval:i}})};static RollbackConfigs={onFailure:()=>({enabled:!0,events:["DEPLOYMENT_FAILURE"]}),onAlarmOrFailure:()=>({enabled:!0,events:["DEPLOYMENT_FAILURE","DEPLOYMENT_STOP_ON_ALARM"]}),onAllEvents:()=>({enabled:!0,events:["DEPLOYMENT_FAILURE","DEPLOYMENT_STOP_ON_ALARM","DEPLOYMENT_STOP_ON_REQUEST"]}),disabled:()=>({enabled:!1})};static BlueGreenConfigs={standard:()=>({terminateBlueInstancesOnDeploymentSuccess:{action:"TERMINATE",terminationWaitTimeInMinutes:5},deploymentReadyOption:{actionOnTimeout:"CONTINUE_DEPLOYMENT",waitTimeInMinutes:0},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}}),withDelay:(n)=>({terminateBlueInstancesOnDeploymentSuccess:{action:"TERMINATE",terminationWaitTimeInMinutes:n},deploymentReadyOption:{actionOnTimeout:"CONTINUE_DEPLOYMENT",waitTimeInMinutes:0},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}}),withManualApproval:(n)=>({terminateBlueInstancesOnDeploymentSuccess:{action:"TERMINATE",terminationWaitTimeInMinutes:5},deploymentReadyOption:{actionOnTimeout:"STOP_DEPLOYMENT",waitTimeInMinutes:n},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}}),keepBlue:()=>({terminateBlueInstancesOnDeploymentSuccess:{action:"KEEP_ALIVE"},deploymentReadyOption:{actionOnTimeout:"CONTINUE_DEPLOYMENT",waitTimeInMinutes:0},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}})};static UseCases={ec2Deployment:(n,i,s,o)=>{let{application:c,logicalId:u}=Z.createApplication({slug:n,environment:i,computePlatform:"Server"}),{deploymentGroup:d,logicalId:f}=Z.createDeploymentGroup(u,{slug:n,environment:i,serviceRoleArn:s,autoScalingGroups:o,deploymentConfigName:"CodeDeployDefault.OneAtATime",autoRollbackConfiguration:Z.RollbackConfigs.onFailure()});return{application:c,appId:u,deploymentGroup:d,groupId:f}},lambdaCanaryDeployment:(n,i,s,o=10,c=5)=>{let{application:u,logicalId:d}=Z.createApplication({slug:n,environment:i,computePlatform:"Lambda"}),{deploymentConfig:f,logicalId:h}=Z.createDeploymentConfig({slug:n,environment:i,trafficRoutingConfig:Z.TrafficRouting.canary(o,c)}),{deploymentGroup:S,logicalId:A}=Z.createDeploymentGroup(d,{slug:n,environment:i,serviceRoleArn:s,deploymentConfigName:k.Ref(h),autoRollbackConfiguration:Z.RollbackConfigs.onAlarmOrFailure()});return{application:u,appId:d,deploymentConfig:f,configId:h,deploymentGroup:S,groupId:A}},ecsBlueGreenDeployment:(n,i,s,o)=>{let{application:c,logicalId:u}=Z.createApplication({slug:n,environment:i,computePlatform:"ECS"}),{deploymentGroup:d,logicalId:f}=Z.createDeploymentGroup(u,{slug:n,environment:i,serviceRoleArn:s,loadBalancerInfo:{targetGroupInfoList:[{name:o}]},blueGreenDeploymentConfiguration:Z.BlueGreenConfigs.standard(),autoRollbackConfiguration:Z.RollbackConfigs.onFailure()});return{application:c,appId:u,deploymentGroup:d,groupId:f}}};static Strategies={rolling:(n=25)=>({type:"rolling",batchPercentage:n}),blueGreen:()=>({type:"blue-green"}),canary:(n=10,i=5)=>({type:"canary",canaryPercentage:n,canaryInterval:i}),allAtOnce:()=>({type:"all-at-once"})}}class _{static ContentTypes={".html":"text/html",".htm":"text/html",".css":"text/css",".js":"application/javascript",".mjs":"application/javascript",".json":"application/json",".xml":"application/xml",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject",".pdf":"application/pdf",".txt":"text/plain",".md":"text/markdown",".map":"application/json"};static NoHashPatterns=[/^index\.html$/,/^favicon\.ico$/,/^robots\.txt$/,/^sitemap\.xml$/,/^manifest\.json$/,/^\.well-known\//,/^_redirects$/,/^_headers$/];static computeFileHash(n,i="md5"){let s=ot(n);return xr(i).update(s).digest("hex")}static computeShortHash(n){return _.computeFileHash(n).slice(0,8)}static getContentType(n){let i=bn(n).toLowerCase();return _.ContentTypes[i]||"application/octet-stream"}static shouldHashFile(n,i){return![..._.NoHashPatterns,...i||[]].some((o)=>o.test(n))}static generateHashedFilename(n,i){let s=bn(n),o=Or(n,s),c=hn(n);if(c===".")return`${o}.${i}${s}`;return Ke(c,`${o}.${i}${s}`)}static collectFiles(n,i){let s=[],o=i||n;if(!Et(n))return s;let c=Mr(n,{withFileTypes:!0});for(let u of c){let d=Ke(n,u.name);if(u.isDirectory())s.push(..._.collectFiles(d,o));else if(u.isFile())s.push(d)}return s}static hashDirectory(n){let{sourceDir:i,outputDir:s,excludePatterns:o=[],hashAlgorithm:c="md5",copyUnhashed:u=!0}=n,d=_.collectFiles(i),f=[],h={};for(let A of d){let T=A.replace(i,"").replace(/^[/\\]/,""),v=_.shouldHashFile(T,o),R=Lr(A),P=v?_.computeFileHash(A,c).slice(0,8):"",E=v?_.generateHashedFilename(T,P):T,I={originalPath:T,hashedPath:E,hash:P,size:R.size,contentType:_.getContentType(A)};if(f.push(I),h[T]=E,s){let M=Ke(s,E),L=hn(M);if(!Et(L)){let{mkdirSync:x}=nt("node:fs");x(L,{recursive:!0})}if(v||u)kr(A,M)}}let S={version:"1.0",timestamp:new Date().toISOString(),assets:f,hashMap:h};if(s){let A=Ke(s,"asset-manifest.json");ct(A,JSON.stringify(S,null,2))}return S}static getInvalidationPaths(n,i){let s=[];if(!n)return["/*"];let o=n.hashMap,c=i.hashMap;for(let[u,d]of Object.entries(c)){let f=o[u];if(!f||f!==d){if(s.push(`/${u}`),f&&f!==d)s.push(`/${f}`)}}for(let[u,d]of Object.entries(o))if(!c[u])s.push(`/${u}`),s.push(`/${d}`);if(s.length>100)return["/*"];return[...new Set(s)]}static updateHtmlReferences(n){let{htmlDir:i,manifest:s,basePath:o=""}=n,c=_.collectFiles(i).filter((u)=>u.endsWith(".html")||u.endsWith(".htm"));for(let u of c){let d=ot(u,"utf-8");for(let[f,h]of Object.entries(s.hashMap)){if(f===h)continue;let S=[new RegExp(`(src|href)=["']${o}/?${_.escapeRegExp(f)}["']`,"g"),new RegExp(`url\\(["']?${o}/?${_.escapeRegExp(f)}["']?\\)`,"g")];for(let A of S)d=d.replace(A,(T)=>T.replace(f,h))}ct(u,d)}}static updateCssReferences(n){let{cssDir:i,manifest:s,basePath:o=""}=n,c=_.collectFiles(i).filter((u)=>u.endsWith(".css"));for(let u of c){let d=ot(u,"utf-8");for(let[f,h]of Object.entries(s.hashMap)){if(f===h)continue;let S=new RegExp(`url\\(["']?${o}/?${_.escapeRegExp(f)}["']?\\)`,"g");d=d.replace(S,`url(${o}/${h})`)}ct(u,d)}}static escapeRegExp(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}static generateS3DeploymentManifest(n){let{sourceDir:i,keyPrefix:s="",excludePatterns:o=[],cacheControl:c={hashed:"public, max-age=31536000, immutable",unhashed:"public, max-age=3600",html:"public, max-age=0, must-revalidate"}}=n;return _.hashDirectory({sourceDir:i,excludePatterns:o}).assets.map((d)=>{let f=d.hash!=="",h=d.contentType==="text/html",S=c.unhashed||"public, max-age=3600";if(h)S=c.html||"public, max-age=0, must-revalidate";else if(f)S=c.hashed||"public, max-age=31536000, immutable";return{localPath:Ke(i,d.originalPath),s3Key:s?`${s}/${d.hashedPath}`:d.hashedPath,contentType:d.contentType,cacheControl:S,hash:d.hash}})}static compareManifests(n,i){let s={added:[],removed:[],changed:[],unchanged:[]},o=new Set(Object.keys(n.hashMap)),c=new Set(Object.keys(i.hashMap));for(let u of c)if(!o.has(u))s.added.push(u);for(let u of o)if(!c.has(u))s.removed.push(u);for(let u of c)if(o.has(u))if(n.hashMap[u]!==i.hashMap[u])s.changed.push(u);else s.unchanged.push(u);return s}static loadManifest(n){if(!Et(n))return null;try{let i=ot(n,"utf-8");return JSON.parse(i)}catch{return null}}static saveManifest(n,i){ct(i,JSON.stringify(n,null,2))}}class Vi{static createSecret(n){let{slug:i,environment:s,secretName:o,description:c,secretString:u,kmsKeyId:d,tags:f}=n,h=o||r({slug:i,environment:s,resourceType:"secret"}),S=t(h),A={Type:"AWS::SecretsManager::Secret",Properties:{Name:h,Description:c,SecretString:u,Tags:[{Key:"Name",Value:h},{Key:"Environment",Value:s},...f?Object.entries(f).map(([T,v])=>({Key:T,Value:v})):[]]}};if(d)A.Properties.KmsKeyId=d;return{secret:A,logicalId:S}}static createGeneratedSecret(n){let{slug:i,environment:s,secretName:o,description:c,excludeCharacters:u,excludeLowercase:d,excludeNumbers:f,excludePunctuation:h,excludeUppercase:S,passwordLength:A,requireEachIncludedType:T,kmsKeyId:v,tags:R}=n,P=o||r({slug:i,environment:s,resourceType:"secret"}),E=t(P),I={Type:"AWS::SecretsManager::Secret",Properties:{Name:P,Description:c,GenerateSecretString:{ExcludeCharacters:u,ExcludeLowercase:d,ExcludeNumbers:f,ExcludePunctuation:h,ExcludeUppercase:S,PasswordLength:A||32,RequireEachIncludedType:T!==!1},Tags:[{Key:"Name",Value:P},{Key:"Environment",Value:s},...R?Object.entries(R).map(([M,L])=>({Key:M,Value:L})):[]]}};if(v)I.Properties.KmsKeyId=v;return{secret:I,logicalId:E}}static createDatabaseSecret(n){let{slug:i,environment:s,secretName:o,username:c,dbname:u,engine:d,host:f,port:h,kmsKeyId:S}=n,A=o||r({slug:i,environment:s,resourceType:"db-secret"}),T=t(A),v={username:c};if(u)v.dbname=u;if(d)v.engine=d;if(f)v.host=f;if(h)v.port=h;let R={Type:"AWS::SecretsManager::Secret",Properties:{Name:A,Description:`Database credentials for ${c}`,GenerateSecretString:{SecretStringTemplate:JSON.stringify(v),GenerateStringKey:"password",PasswordLength:32,ExcludeCharacters:'"@/\\',RequireEachIncludedType:!0},Tags:[{Key:"Name",Value:A},{Key:"Environment",Value:s},{Key:"Type",Value:"database"}]}};if(S)R.Properties.KmsKeyId=S;return{secret:R,logicalId:T}}static attachToDatabase(n){let{slug:i,environment:s,secretId:o,targetId:c,targetType:u}=n,d=r({slug:i,environment:s,resourceType:"secret-attachment"}),f=t(d);return{attachment:{Type:"AWS::SecretsManager::SecretTargetAttachment",Properties:{SecretId:o,TargetId:c,TargetType:u}},logicalId:f}}static enableRotation(n){let{slug:i,environment:s,secretId:o,rotationLambdaArn:c,automaticallyAfterDays:u,rotationType:d,kmsKeyArn:f,vpcSecurityGroupIds:h,vpcSubnetIds:S}=n,A=r({slug:i,environment:s,resourceType:"secret-rotation"}),T=t(A),v={Type:"AWS::SecretsManager::RotationSchedule",Properties:{SecretId:o,RotationRules:{AutomaticallyAfterDays:u||30}}};if(c)v.Properties.RotationLambdaARN=c;else if(d)v.Properties.HostedRotationLambda={RotationType:d,KmsKeyArn:f,VpcSecurityGroupIds:h,VpcSubnetIds:S};return{rotation:v,logicalId:T}}static SecretTypes={apiKey:(n,i,s)=>Vi.createGeneratedSecret({slug:n,environment:i,secretName:`${n}-${i}-${s}-api-key`,description:`API key for ${s}`,passwordLength:32,excludePunctuation:!0,excludeLowercase:!1,excludeUppercase:!1,excludeNumbers:!1}),oauthClientSecret:(n,i,s)=>Vi.createGeneratedSecret({slug:n,environment:i,secretName:`${n}-${i}-${s}-oauth-secret`,description:`OAuth client secret for ${s}`,passwordLength:64,excludeCharacters:"\"'`\\/@",requireEachIncludedType:!0}),jwtSecret:(n,i)=>Vi.createGeneratedSecret({slug:n,environment:i,secretName:`${n}-${i}-jwt-secret`,description:"JWT signing secret",passwordLength:64,excludePunctuation:!0}),encryptionKey:(n,i)=>Vi.createGeneratedSecret({slug:n,environment:i,secretName:`${n}-${i}-encryption-key`,description:"Data encryption key",passwordLength:64,excludeCharacters:"+/=",excludePunctuation:!0})};static RotationTypes={MySQLSingleUser:"MySQLSingleUser",MySQLMultiUser:"MySQLMultiUser",PostgreSQLSingleUser:"PostgreSQLSingleUser",PostgreSQLMultiUser:"PostgreSQLMultiUser",OracleSingleUser:"OracleSingleUser",OracleMultiUser:"OracleMultiUser",MariaDBSingleUser:"MariaDBSingleUser",MariaDBMultiUser:"MariaDBMultiUser",SQLServerSingleUser:"SQLServerSingleUser",SQLServerMultiUser:"SQLServerMultiUser",RedshiftSingleUser:"RedshiftSingleUser",RedshiftMultiUser:"RedshiftMultiUser",MongoDBSingleUser:"MongoDBSingleUser",MongoDBMultiUser:"MongoDBMultiUser"}}class D{static createParameter(n){let{slug:i,environment:s,parameterName:o,value:c,type:u="String",description:d,tier:f="Standard",tags:h}=n,S=o||r({slug:i,environment:s,resourceType:"parameter"}),A=t(S);return{parameter:{Type:"AWS::SSM::Parameter",Properties:{Name:`/${i}/${s}/${S}`,Type:u,Value:c,Description:d,Tier:f,Tags:{Name:S,Environment:s,...h}}},logicalId:A}}static createString(n,i,s,o,c){return D.createParameter({slug:n,environment:i,parameterName:s,value:o,type:"String",description:c})}static createSecureString(n,i,s,o,c){return D.createParameter({slug:n,environment:i,parameterName:s,value:o,type:"SecureString",description:c})}static createStringList(n,i,s,o,c){return D.createParameter({slug:n,environment:i,parameterName:s,value:o.join(","),type:"StringList",description:c})}static Parameters={databaseUrl:(n,i,s)=>D.createSecureString(n,i,"database-url",s,"Database connection URL"),apiEndpoint:(n,i,s)=>D.createString(n,i,"api-endpoint",s,"API endpoint URL"),appVersion:(n,i,s)=>D.createString(n,i,"app-version",s,"Application version"),featureFlags:(n,i,s)=>D.createStringList(n,i,"feature-flags",s,"Enabled feature flags"),apiKey:(n,i,s,o)=>D.createSecureString(n,i,`${s}-api-key`,o,`API key for ${s}`),oauthCredentials:(n,i,s,o)=>{let c=D.createString(n,i,"oauth-client-id",s,"OAuth client ID"),u=D.createSecureString(n,i,"oauth-client-secret",o,"OAuth client secret");return{clientId:c,clientSecret:u}},smtpCredentials:(n,i,s,o,c,u)=>{let d=D.createString(n,i,"smtp-username",s,"SMTP username"),f=D.createSecureString(n,i,"smtp-password",o,"SMTP password"),h=D.createString(n,i,"smtp-host",c,"SMTP host"),S=D.createString(n,i,"smtp-port",u.toString(),"SMTP port");return{username:d,password:f,host:h,port:S}},redisUrl:(n,i,s)=>D.createSecureString(n,i,"redis-url",s,"Redis connection URL"),s3Bucket:(n,i,s)=>D.createString(n,i,"s3-bucket",s,"S3 bucket name"),cloudFrontDistribution:(n,i,s)=>D.createString(n,i,"cloudfront-distribution-id",s,"CloudFront distribution ID")}}class ar{static createDomain(n){let{slug:i,environment:s,domainName:o,engineVersion:c="OpenSearch_2.11",instanceType:u="t3.small.search",instanceCount:d=1,volumeSize:f=10,volumeType:h="gp3",dedicatedMaster:S=!1,dedicatedMasterType:A,dedicatedMasterCount:T=3,multiAz:v=!1,availabilityZoneCount:R=2,vpc:P,encryption:E,enforceHttps:I=!0,tlsSecurityPolicy:M="Policy-Min-TLS-1-2-2019-07",advancedSecurity:L,autoSnapshotHour:x=0,autoTune:O=!0,tags:B={}}=n,F=o||r({slug:i,environment:s,resourceType:"search"}),U=t(F);return{domain:{Type:"AWS::OpenSearchService::Domain",Properties:{DomainName:F,EngineVersion:c,ClusterConfig:{InstanceType:u,InstanceCount:d,DedicatedMasterEnabled:S,...S&&{DedicatedMasterType:A||u,DedicatedMasterCount:T},ZoneAwarenessEnabled:v,...v&&{ZoneAwarenessConfig:{AvailabilityZoneCount:R}}},EBSOptions:{EBSEnabled:!0,VolumeType:h,VolumeSize:f},DomainEndpointOptions:{EnforceHTTPS:I,TLSSecurityPolicy:M},SnapshotOptions:{AutomatedSnapshotStartHour:x},...P&&{VPCOptions:{SubnetIds:P.subnetIds,SecurityGroupIds:P.securityGroupIds}},...E&&{EncryptionAtRestOptions:{Enabled:E.atRest??!0,...E.kmsKeyId&&{KmsKeyId:E.kmsKeyId}},NodeToNodeEncryptionOptions:{Enabled:E.nodeToNode??!0}},...L&&{AdvancedSecurityOptions:{Enabled:L.enabled,InternalUserDatabaseEnabled:L.internalUserDatabase??!0,...L.masterUserName&&L.masterUserPassword&&{MasterUserOptions:{MasterUserName:L.masterUserName,MasterUserPassword:L.masterUserPassword}},...L.masterUserArn&&{MasterUserOptions:{MasterUserARN:L.masterUserArn}}}},...O&&{AutoTuneOptions:{DesiredState:"ENABLED"}},Tags:[{Key:"Name",Value:F},{Key:"Environment",Value:s},...Object.entries(B).map(([H,z])=>({Key:H,Value:z}))]}},logicalId:U}}static createAccessPolicy(n,i){let{ipAddresses:s,iamPrincipalArns:o,allowAll:c,vpcEndpoint:u}=i;if(c)return{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:"*"},Action:"es:*",Resource:n}]};let d=[];if(o&&o.length>0)d.push({Effect:"Allow",Principal:{AWS:o},Action:"es:*",Resource:n});if(s&&s.length>0)d.push({Effect:"Allow",Principal:{AWS:"*"},Action:"es:*",Resource:n,Condition:{IpAddress:{"aws:SourceIp":s}}});if(u)return{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:"*"},Action:"es:*",Resource:n}]};return{Version:"2012-10-17",Statement:d}}static DomainPresets={development:(n,i)=>ar.createDomain({slug:n,environment:i,instanceType:"t3.small.search",instanceCount:1,volumeSize:10,multiAz:!1,dedicatedMaster:!1,encryption:{atRest:!0,nodeToNode:!0},autoTune:!1}),production:(n,i,s)=>ar.createDomain({slug:n,environment:i,instanceType:"m6g.large.search",instanceCount:3,volumeSize:100,volumeType:"gp3",multiAz:!0,availabilityZoneCount:3,dedicatedMaster:!0,dedicatedMasterType:"m6g.large.search",dedicatedMasterCount:3,vpc:s,encryption:{atRest:!0,nodeToNode:!0},advancedSecurity:{enabled:!0,internalUserDatabase:!0},autoTune:!0}),costOptimized:(n,i)=>ar.createDomain({slug:n,environment:i,instanceType:"t3.medium.search",instanceCount:2,volumeSize:20,volumeType:"gp3",multiAz:!0,dedicatedMaster:!1,encryption:{atRest:!0,nodeToNode:!0},autoTune:!0}),highPerformance:(n,i,s)=>ar.createDomain({slug:n,environment:i,instanceType:"r6g.2xlarge.search",instanceCount:6,volumeSize:500,volumeType:"gp3",multiAz:!0,availabilityZoneCount:3,dedicatedMaster:!0,dedicatedMasterType:"c6g.xlarge.search",dedicatedMasterCount:3,vpc:s,encryption:{atRest:!0,nodeToNode:!0},advancedSecurity:{enabled:!0,internalUserDatabase:!1},autoTune:!0})};static InstanceTypes={"t3.small.search":"t3.small.search","t3.medium.search":"t3.medium.search","m6g.large.search":"m6g.large.search","m6g.xlarge.search":"m6g.xlarge.search","m6g.2xlarge.search":"m6g.2xlarge.search","r6g.large.search":"r6g.large.search","r6g.xlarge.search":"r6g.xlarge.search","r6g.2xlarge.search":"r6g.2xlarge.search","r6g.4xlarge.search":"r6g.4xlarge.search","c6g.large.search":"c6g.large.search","c6g.xlarge.search":"c6g.xlarge.search","c6g.2xlarge.search":"c6g.2xlarge.search"};static EngineVersions={"OpenSearch_2.11":"OpenSearch_2.11","OpenSearch_2.9":"OpenSearch_2.9","OpenSearch_2.7":"OpenSearch_2.7","OpenSearch_1.3":"OpenSearch_1.3","Elasticsearch_7.10":"Elasticsearch_7.10"}}class Dt{static createDomainRedirectBucket(n){let{slug:i,environment:s,sourceDomain:o,targetDomain:c,protocol:u="https"}=n,d=r({slug:i,environment:s,resourceType:"s3",suffix:"redirect"}),f=t(d),h=t(`${d}-policy`),S={Type:"AWS::S3::Bucket",Properties:{BucketName:o,WebsiteConfiguration:{RedirectAllRequestsTo:{HostName:c,Protocol:u}},PublicAccessBlockConfiguration:{BlockPublicAcls:!1,BlockPublicPolicy:!1,IgnorePublicAcls:!1,RestrictPublicBuckets:!1},Tags:[{Key:"Name",Value:d},{Key:"Environment",Value:s},{Key:"Purpose",Value:"Domain Redirect"}]}},A={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:k.Ref(f),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadForRedirect",Effect:"Allow",Principal:"*",Action:["s3:GetObject"],Resource:[k.Join("",[k.GetAtt(f,"Arn"),"/*"])]}]}}};return{bucket:S,bucketPolicy:A,logicalId:f,policyLogicalId:h}}static createPathRedirectFunction(n){let{slug:i,environment:s,rules:o}=n,c=r({slug:i,environment:s,resourceType:"cf-redirect"}),u=t(c),d=Dt.generateRedirectFunctionCode(o);return{function:{Type:"AWS::CloudFront::Function",Properties:{Name:c,AutoPublish:!0,FunctionConfig:{Comment:`Path redirect function for ${i} (${s})`,Runtime:"cloudfront-js-2.0"},FunctionCode:d}},logicalId:u,functionCode:d}}static generateRedirectFunctionCode(n){return`function handler(event) {
|
|
2282
2282
|
const request = event.request;
|
|
2283
2283
|
const uri = request.uri;
|
|
2284
2284
|
const querystring = request.querystring;
|
|
@@ -2430,7 +2430,7 @@ exports.handler = async (event) => {
|
|
|
2430
2430
|
console.log('Receive SMS:', JSON.stringify(event, null, 2));
|
|
2431
2431
|
// Process inbound SMS, handle opt-out keywords
|
|
2432
2432
|
return { statusCode: 200 };
|
|
2433
|
-
};`}var e={ref:(n)=>({Ref:n}),getAtt:(n,i)=>({"Fn::GetAtt":[n,i]}),join:(n,i)=>({"Fn::Join":[n,i]}),sub:(n,i)=>i?{"Fn::Sub":[n,i]}:{"Fn::Sub":n},select:(n,i)=>({"Fn::Select":[n,i]}),split:(n,i)=>({"Fn::Split":[n,i]}),getAZs:(n="")=>({"Fn::GetAZs":n}),importValue:(n)=>({"Fn::ImportValue":n}),findInMap:(n,i,s)=>({"Fn::FindInMap":[n,i,s]}),base64:(n)=>({"Fn::Base64":n}),cidr:(n,i,s)=>({"Fn::Cidr":[n,i,s]}),equals:(n,i)=>({"Fn::Equals":[n,i]}),if:(n,i,s)=>({"Fn::If":[n,i,s]}),not:(n)=>({"Fn::Not":[n]}),and:(...n)=>({"Fn::And":n}),or:(...n)=>({"Fn::Or":n})},cn={s3Bucket:(n)=>e.sub(`arn:aws:s3:::${n}`),s3Object:(n,i="*")=>e.sub(`arn:aws:s3:::${n}/${i}`),lambda:(n,i,s)=>e.sub(`arn:aws:lambda:\${AWS::Region}:\${AWS::AccountId}:function:${n}`,i&&s?{"AWS::Region":i,"AWS::AccountId":s}:void 0),dynamodb:(n)=>e.sub(`arn:aws:dynamodb:\${AWS::Region}:\${AWS::AccountId}:table/${n}`),sqs:(n)=>e.sub(`arn:aws:sqs:\${AWS::Region}:\${AWS::AccountId}:${n}`),sns:(n)=>e.sub(`arn:aws:sns:\${AWS::Region}:\${AWS::AccountId}:${n}`),kinesis:(n)=>e.sub(`arn:aws:kinesis:\${AWS::Region}:\${AWS::AccountId}:stream/${n}`),iam:(n,i)=>e.sub(`arn:aws:iam::\${AWS::AccountId}:${n}/${i}`),secretsManager:(n)=>e.sub(`arn:aws:secretsmanager:\${AWS::Region}:\${AWS::AccountId}:secret:${n}`),cloudwatch:(n)=>e.sub(`arn:aws:logs:\${AWS::Region}:\${AWS::AccountId}:log-group:${n}`)},$I={ACCOUNT_ID:{Ref:"AWS::AccountId"},NOTIFICATION_ARNS:{Ref:"AWS::NotificationARNs"},NO_VALUE:{Ref:"AWS::NoValue"},PARTITION:{Ref:"AWS::Partition"},REGION:{Ref:"AWS::Region"},STACK_ID:{Ref:"AWS::StackId"},STACK_NAME:{Ref:"AWS::StackName"},URL_SUFFIX:{Ref:"AWS::URLSuffix"}};function Sn(n,i){if(i.type==="http")$r(n,i);else if(i.type==="rest")Br(n,i);else if(i.type==="websocket")Fr(n,i)}function $r(n,i){let s={Name:e.sub("${AWS::StackName}-http-api"),ProtocolType:"HTTP"};if(i.cors)s.CorsConfiguration={AllowOrigins:i.cors.allowOrigins,AllowMethods:i.cors.allowMethods,AllowHeaders:i.cors.allowHeaders||["*"],MaxAge:i.cors.maxAge||300};if(n.addResource("HttpApi","AWS::ApiGatewayV2::Api",s),n.addResource("HttpApiStage","AWS::ApiGatewayV2::Stage",{ApiId:e.ref("HttpApi"),StageName:"$default",AutoDeploy:!0,DefaultRouteSettings:i.throttling?{ThrottlingBurstLimit:i.throttling.burstLimit,ThrottlingRateLimit:i.throttling.rateLimit}:void 0,AccessLogSettings:{DestinationArn:e.getAtt("ApiLogGroup","Arn"),Format:"$context.requestId $context.error.message $context.error.messageString"}},{dependsOn:["HttpApi","ApiLogGroup"]}),n.addResource("ApiLogGroup","AWS::Logs::LogGroup",{LogGroupName:e.sub("/aws/apigateway/${AWS::StackName}-http-api"),RetentionInDays:14}),i.authorizer)Gr(n,"HttpApi",i.authorizer);if(i.customDomain)It(n,"HttpApi",i.customDomain,"HTTP");n.addOutputs({HttpApiId:{Description:"HTTP API ID",Value:e.ref("HttpApi"),Export:{Name:e.sub("${AWS::StackName}-http-api-id")}},HttpApiEndpoint:{Description:"HTTP API endpoint",Value:e.getAtt("HttpApi","ApiEndpoint"),Export:{Name:e.sub("${AWS::StackName}-http-api-endpoint")}}})}function Br(n,i){n.addResource("RestApi","AWS::ApiGateway::RestApi",{Name:e.sub("${AWS::StackName}-rest-api"),Description:e.sub("REST API for ${AWS::StackName}"),EndpointConfiguration:{Types:["REGIONAL"]}}),n.addResource("ApiGatewayAccount","AWS::ApiGateway::Account",{CloudWatchRoleArn:e.getAtt("ApiGatewayCloudWatchRole","Arn")},{dependsOn:"ApiGatewayCloudWatchRole"}),n.addResource("ApiGatewayCloudWatchRole","AWS::IAM::Role",{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"apigateway.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs"]}),n.addResource("RestApiDeployment","AWS::ApiGateway::Deployment",{RestApiId:e.ref("RestApi"),Description:"Initial deployment"},{dependsOn:"RestApi"});let s={RestApiId:e.ref("RestApi"),DeploymentId:e.ref("RestApiDeployment"),StageName:"prod",Description:"Production stage",MethodSettings:[{ResourcePath:"/*",HttpMethod:"*",LoggingLevel:"INFO",DataTraceEnabled:!0,MetricsEnabled:!0}]};if(i.throttling)s.MethodSettings[0].ThrottlingBurstLimit=i.throttling.burstLimit,s.MethodSettings[0].ThrottlingRateLimit=i.throttling.rateLimit;if(n.addResource("RestApiStage","AWS::ApiGateway::Stage",s,{dependsOn:["RestApi","RestApiDeployment"]}),i.customDomain)It(n,"RestApi",i.customDomain,"REST");n.addOutputs({RestApiId:{Description:"REST API ID",Value:e.ref("RestApi"),Export:{Name:e.sub("${AWS::StackName}-rest-api-id")}},RestApiEndpoint:{Description:"REST API endpoint",Value:e.sub("https://${RestApi}.execute-api.${AWS::Region}.amazonaws.com/prod"),Export:{Name:e.sub("${AWS::StackName}-rest-api-endpoint")}}})}function Fr(n,i){if(n.addResource("WebSocketApi","AWS::ApiGatewayV2::Api",{Name:e.sub("${AWS::StackName}-websocket-api"),ProtocolType:"WEBSOCKET",RouteSelectionExpression:"$request.body.action"}),i.routes){if(i.routes.connect)at(n,"$connect",i.routes.connect.functionName);if(i.routes.disconnect)at(n,"$disconnect",i.routes.disconnect.functionName);if(i.routes.default)at(n,"$default",i.routes.default.functionName);if(i.routes.custom)i.routes.custom.forEach((s)=>{at(n,s.routeKey,s.functionName)})}if(n.addResource("WebSocketApiStage","AWS::ApiGatewayV2::Stage",{ApiId:e.ref("WebSocketApi"),StageName:"prod",AutoDeploy:!0,DefaultRouteSettings:i.throttling?{ThrottlingBurstLimit:i.throttling.burstLimit,ThrottlingRateLimit:i.throttling.rateLimit}:void 0},{dependsOn:"WebSocketApi"}),i.customDomain)It(n,"WebSocketApi",i.customDomain,"WEBSOCKET");n.addOutputs({WebSocketApiId:{Description:"WebSocket API ID",Value:e.ref("WebSocketApi"),Export:{Name:e.sub("${AWS::StackName}-websocket-api-id")}},WebSocketApiEndpoint:{Description:"WebSocket API endpoint",Value:e.getAtt("WebSocketApi","ApiEndpoint"),Export:{Name:e.sub("${AWS::StackName}-websocket-api-endpoint")}}})}function at(n,i,s){let o=n.toLogicalId(`websocket-route-${i}`),c=n.toLogicalId(`websocket-integration-${i}`),u=n.toLogicalId(`${s}-function`);n.addResource(c,"AWS::ApiGatewayV2::Integration",{ApiId:e.ref("WebSocketApi"),IntegrationType:"AWS_PROXY",IntegrationUri:e.sub(`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${u}.Arn}/invocations`)},{dependsOn:["WebSocketApi",u]}),n.addResource(o,"AWS::ApiGatewayV2::Route",{ApiId:e.ref("WebSocketApi"),RouteKey:i,Target:e.join("/",["integrations",e.ref(c)])},{dependsOn:["WebSocketApi",c]}),n.addResource(`${o}Permission`,"AWS::Lambda::Permission",{FunctionName:e.ref(u),Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:e.sub("arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${WebSocketApi}/*")},{dependsOn:[u,"WebSocketApi"]})}function It(n,i,s,o){let c={DomainName:s.domain};if(o==="REST")c.CertificateArn=s.certificateArn,c.EndpointConfiguration={Types:["REGIONAL"]},n.addResource("ApiCustomDomain","AWS::ApiGateway::DomainName",c),n.addResource("ApiBasePathMapping","AWS::ApiGateway::BasePathMapping",{DomainName:e.ref("ApiCustomDomain"),RestApiId:e.ref(i),Stage:e.ref("RestApiStage")},{dependsOn:["ApiCustomDomain",i,"RestApiStage"]});else c.DomainNameConfigurations=[{CertificateArn:s.certificateArn,EndpointType:"REGIONAL"}],n.addResource("ApiCustomDomain","AWS::ApiGatewayV2::DomainName",c),n.addResource("ApiMapping","AWS::ApiGatewayV2::ApiMapping",{ApiId:e.ref(i),DomainName:e.ref("ApiCustomDomain"),Stage:o==="HTTP"?e.ref("HttpApiStage"):e.ref("WebSocketApiStage")},{dependsOn:["ApiCustomDomain",i]});if(s.dnsProvider!=="external")n.addResource("ApiDNSRecord","AWS::Route53::RecordSet",{HostedZoneName:e.sub(`${_r(s.domain)}.`),Name:s.domain,Type:"A",AliasTarget:{HostedZoneId:e.getAtt("ApiCustomDomain","RegionalHostedZoneId"),DNSName:e.getAtt("ApiCustomDomain","RegionalDomainName"),EvaluateTargetHealth:!1}},{dependsOn:"ApiCustomDomain"});n.addOutputs({ApiCustomDomainName:{Description:"Configured API custom domain",Value:s.domain},ApiCustomDomainTarget:{Description:"DNS target for Route53 or an external DNS provider",Value:e.getAtt("ApiCustomDomain","RegionalDomainName")},ApiCustomDomainHostedZoneId:{Description:"Regional API Gateway hosted zone ID",Value:e.getAtt("ApiCustomDomain","RegionalHostedZoneId")}})}function Gr(n,i,s){if(!s)return;if(s.type==="jwt")n.addResource("ApiAuthorizer","AWS::ApiGatewayV2::Authorizer",{ApiId:e.ref(i),AuthorizerType:"JWT",IdentitySource:[s.identitySource||"$request.header.Authorization"],JwtConfiguration:{Issuer:s.issuer,Audience:s.audience},Name:"JWTAuthorizer"},{dependsOn:i});else if(s.type==="lambda")n.addResource("ApiAuthorizer","AWS::ApiGatewayV2::Authorizer",{ApiId:e.ref(i),AuthorizerType:"REQUEST",AuthorizerUri:s.authorizerUri,IdentitySource:[s.identitySource||"$request.header.Authorization"],Name:"LambdaAuthorizer"},{dependsOn:i})}function _r(n){let i=n.split(".");if(i.length>=2)return i.slice(-2).join(".");return n}function An(n,i){if(i.redis)Wr(n,i.redis);if(i.memcached)Vr(n,i.memcached);if(i.elasticache)Ur(n,i.elasticache)}function Wr(n,i){if(!i)return;if(n.addResource("CacheSubnetGroup","AWS::ElastiCache::SubnetGroup",{Description:"Subnet group for ElastiCache Redis cluster",SubnetIds:[e.ref("PrivateSubnet1"),e.ref("PrivateSubnet2")],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-cache-subnet-group")}]},{dependsOn:["PrivateSubnet1","PrivateSubnet2"]}),n.addResource("CacheSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for ElastiCache Redis",VpcId:e.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:i.port||6379,ToPort:i.port||6379,SourceSecurityGroupId:e.ref("AppSecurityGroup")}],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-cache-sg")}]},{dependsOn:["VPC","AppSecurityGroup"]}),i.parameterGroup&&Object.keys(i.parameterGroup).length>0)n.addResource("CacheParameterGroup","AWS::ElastiCache::ParameterGroup",{Description:"Parameter group for Redis",CacheParameterGroupFamily:`redis${i.engineVersion.split(".")[0]}`,Properties:i.parameterGroup});if(i.numCacheNodes>1||i.automaticFailoverEnabled)n.addResource("RedisReplicationGroup","AWS::ElastiCache::ReplicationGroup",{ReplicationGroupDescription:"Redis replication group",ReplicationGroupId:e.sub("${AWS::StackName}-redis"),Engine:"redis",EngineVersion:i.engineVersion,CacheNodeType:i.nodeType,NumCacheClusters:i.numCacheNodes,AutomaticFailoverEnabled:i.automaticFailoverEnabled||!1,MultiAZEnabled:i.automaticFailoverEnabled||!1,Port:i.port||6379,CacheSubnetGroupName:e.ref("CacheSubnetGroup"),SecurityGroupIds:[e.ref("CacheSecurityGroup")],CacheParameterGroupName:i.parameterGroup?e.ref("CacheParameterGroup"):void 0,SnapshotRetentionLimit:i.snapshotRetentionLimit||5,SnapshotWindow:i.snapshotWindow||"03:00-05:00",PreferredMaintenanceWindow:"sun:05:00-sun:06:00",AtRestEncryptionEnabled:!0,TransitEncryptionEnabled:!0,Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-redis")}]},{dependsOn:i.parameterGroup?["CacheSubnetGroup","CacheSecurityGroup","CacheParameterGroup"]:["CacheSubnetGroup","CacheSecurityGroup"],deletionPolicy:"Snapshot",updateReplacePolicy:"Snapshot"}),n.addOutputs({RedisEndpoint:{Description:"Redis primary endpoint",Value:e.getAtt("RedisReplicationGroup","PrimaryEndPoint.Address"),Export:{Name:e.sub("${AWS::StackName}-redis-endpoint")}},RedisPort:{Description:"Redis port",Value:e.getAtt("RedisReplicationGroup","PrimaryEndPoint.Port"),Export:{Name:e.sub("${AWS::StackName}-redis-port")}}});else n.addResource("RedisCacheCluster","AWS::ElastiCache::CacheCluster",{ClusterName:e.sub("${AWS::StackName}-redis"),Engine:"redis",EngineVersion:i.engineVersion,CacheNodeType:i.nodeType,NumCacheNodes:1,Port:i.port||6379,CacheSubnetGroupName:e.ref("CacheSubnetGroup"),VpcSecurityGroupIds:[e.ref("CacheSecurityGroup")],CacheParameterGroupName:i.parameterGroup?e.ref("CacheParameterGroup"):void 0,SnapshotRetentionLimit:i.snapshotRetentionLimit||5,SnapshotWindow:i.snapshotWindow||"03:00-05:00",PreferredMaintenanceWindow:"sun:05:00-sun:06:00",Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-redis")}]},{dependsOn:i.parameterGroup?["CacheSubnetGroup","CacheSecurityGroup","CacheParameterGroup"]:["CacheSubnetGroup","CacheSecurityGroup"],deletionPolicy:"Snapshot",updateReplacePolicy:"Snapshot"}),n.addOutputs({RedisEndpoint:{Description:"Redis endpoint",Value:e.getAtt("RedisCacheCluster","RedisEndpoint.Address"),Export:{Name:e.sub("${AWS::StackName}-redis-endpoint")}},RedisPort:{Description:"Redis port",Value:e.getAtt("RedisCacheCluster","RedisEndpoint.Port"),Export:{Name:e.sub("${AWS::StackName}-redis-port")}}})}function Vr(n,i){if(!i)return;if(!n.hasResource("CacheSubnetGroup"))n.addResource("CacheSubnetGroup","AWS::ElastiCache::SubnetGroup",{Description:"Subnet group for ElastiCache",SubnetIds:[e.ref("PrivateSubnet1"),e.ref("PrivateSubnet2")]},{dependsOn:["PrivateSubnet1","PrivateSubnet2"]});if(!n.hasResource("CacheSecurityGroup"))n.addResource("CacheSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for ElastiCache Memcached",VpcId:e.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:i.port||11211,ToPort:i.port||11211,SourceSecurityGroupId:e.ref("AppSecurityGroup")}],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-cache-sg")}]},{dependsOn:["VPC","AppSecurityGroup"]});n.addResource("MemcachedCacheCluster","AWS::ElastiCache::CacheCluster",{ClusterName:e.sub("${AWS::StackName}-memcached"),Engine:"memcached",EngineVersion:i.engineVersion,CacheNodeType:i.nodeType,NumCacheNodes:i.numCacheNodes,Port:i.port||11211,CacheSubnetGroupName:e.ref("CacheSubnetGroup"),VpcSecurityGroupIds:[e.ref("CacheSecurityGroup")],PreferredMaintenanceWindow:"sun:05:00-sun:06:00",Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-memcached")}]},{dependsOn:["CacheSubnetGroup","CacheSecurityGroup"]}),n.addOutputs({MemcachedEndpoint:{Description:"Memcached configuration endpoint",Value:e.getAtt("MemcachedCacheCluster","ConfigurationEndpoint.Address"),Export:{Name:e.sub("${AWS::StackName}-memcached-endpoint")}},MemcachedPort:{Description:"Memcached port",Value:e.getAtt("MemcachedCacheCluster","ConfigurationEndpoint.Port"),Export:{Name:e.sub("${AWS::StackName}-memcached-port")}}})}function Ur(n,i){if(!i)return;let s=i.engine==="redis";if(!n.hasResource("CacheSubnetGroup"))n.addResource("CacheSubnetGroup","AWS::ElastiCache::SubnetGroup",{Description:"Subnet group for ElastiCache",SubnetIds:[e.ref("PrivateSubnet1"),e.ref("PrivateSubnet2")]},{dependsOn:["PrivateSubnet1","PrivateSubnet2"]});if(!n.hasResource("CacheSecurityGroup"))n.addResource("CacheSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for ElastiCache",VpcId:e.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:s?6379:11211,ToPort:s?6379:11211,SourceSecurityGroupId:e.ref("AppSecurityGroup")}],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-cache-sg")}]},{dependsOn:["VPC","AppSecurityGroup"]});n.addResource("CacheCluster","AWS::ElastiCache::CacheCluster",{ClusterName:e.sub(`\${AWS::StackName}-${i.engine}`),Engine:i.engine,EngineVersion:i.engineVersion,CacheNodeType:i.nodeType,NumCacheNodes:i.numCacheNodes,CacheSubnetGroupName:e.ref("CacheSubnetGroup"),VpcSecurityGroupIds:[e.ref("CacheSecurityGroup")],Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${i.engine}`)}]},{dependsOn:["CacheSubnetGroup","CacheSecurityGroup"]})}function Cn(n,i){if(!i.enabled)return;n.addResource("CloudFrontOriginAccessIdentity","AWS::CloudFront::CloudFrontOriginAccessIdentity",{CloudFrontOriginAccessIdentityConfig:{Comment:e.sub("${AWS::StackName} CloudFront OAI")}});let s=[],o=[];if(!i.origins||i.origins.length===0)s.push({Id:"S3Origin",DomainName:e.getAtt("StaticBucket","DomainName"),S3OriginConfig:{OriginAccessIdentity:e.sub("origin-access-identity/cloudfront/${CloudFrontOriginAccessIdentity}")}});else i.origins.forEach((d,f)=>{let h={Id:d.id,DomainName:d.domainName};if(d.originPath)h.OriginPath=d.originPath;if(d.domainName.includes("s3"))h.S3OriginConfig={OriginAccessIdentity:e.sub("origin-access-identity/cloudfront/${CloudFrontOriginAccessIdentity}")};else h.CustomOriginConfig={HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only",OriginSSLProtocols:["TLSv1.2"]};if(s.push(h),f>0||d.pathPattern)o.push({PathPattern:d.pathPattern||`/${d.id}/*`,TargetOriginId:d.id,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD"],Compress:i.compress!==!1,ForwardedValues:{QueryString:!0,Cookies:{Forward:"none"}},MinTTL:i.cachePolicy?.minTTL||0,DefaultTTL:i.cachePolicy?.defaultTTL||86400,MaxTTL:i.cachePolicy?.maxTTL||31536000})});let c={TargetOriginId:s[0].Id,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD"],Compress:i.compress!==!1,ForwardedValues:{QueryString:!0,Cookies:{Forward:"none"}},MinTTL:i.cachePolicy?.minTTL||0,DefaultTTL:i.cachePolicy?.defaultTTL||86400,MaxTTL:i.cachePolicy?.maxTTL||31536000};if(i.edgeFunctions&&i.edgeFunctions.length>0)c.LambdaFunctionAssociations=i.edgeFunctions.map((d)=>({EventType:d.eventType,LambdaFunctionARN:d.functionArn}));let u={Enabled:!0,HttpVersion:i.http3?"http3":"http2",IPV6Enabled:!0,Origins:s,DefaultCacheBehavior:c,PriceClass:i.priceClass||"PriceClass_100",ViewerCertificate:{}};if(o.length>0)u.CacheBehaviors=o;if(i.customDomain)u.Aliases=[i.customDomain.domain],u.ViewerCertificate={AcmCertificateArn:i.customDomain.certificateArn,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};else u.ViewerCertificate={CloudFrontDefaultCertificate:!0};if(i.errorPages)u.CustomErrorResponses=Object.entries(i.errorPages).map(([d,f])=>({ErrorCode:Number.parseInt(d),ResponseCode:200,ResponsePagePath:f,ErrorCachingMinTTL:300}));if(u.DefaultRootObject="index.html",u.Comment=e.sub("${AWS::StackName} CloudFront Distribution"),n.addResource("CloudFrontDistribution","AWS::CloudFront::Distribution",{DistributionConfig:u},{dependsOn:"CloudFrontOriginAccessIdentity"}),!i.origins||i.origins.length===0)n.addResource("StaticBucketPolicyForCloudFront","AWS::S3::BucketPolicy",{Bucket:e.ref("StaticBucket"),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontAccess",Effect:"Allow",Principal:{CanonicalUser:e.getAtt("CloudFrontOriginAccessIdentity","S3CanonicalUserId")},Action:"s3:GetObject",Resource:e.join("",[e.getAtt("StaticBucket","Arn"),"/*"])}]}},{dependsOn:["StaticBucket","CloudFrontOriginAccessIdentity"]});if(i.customDomain)n.addResource("CloudFrontDNSRecord","AWS::Route53::RecordSet",{HostedZoneName:e.sub(`${Hr(i.customDomain.domain)}.`),Name:i.customDomain.domain,Type:"A",AliasTarget:{HostedZoneId:"Z2FDTNDATAQYW2",DNSName:e.getAtt("CloudFrontDistribution","DomainName"),EvaluateTargetHealth:!1}},{dependsOn:"CloudFrontDistribution"});if(n.addOutputs({CloudFrontDistributionId:{Description:"CloudFront distribution ID",Value:e.ref("CloudFrontDistribution"),Export:{Name:e.sub("${AWS::StackName}-cloudfront-id")}},CloudFrontDomainName:{Description:"CloudFront distribution domain name",Value:e.getAtt("CloudFrontDistribution","DomainName"),Export:{Name:e.sub("${AWS::StackName}-cloudfront-domain")}}}),i.customDomain)n.addOutputs({CloudFrontURL:{Description:"CloudFront custom domain URL",Value:e.sub(`https://${i.customDomain.domain}`)}})}function Hr(n){let i=n.split(".");if(i.length>=2)return i.slice(-2).join(".");return n}function Tn(n,i){if(i.server)jr(n,i.server);if(i.fargate)vn(n,"app",i.fargate);if(i.services)i.services.forEach((s)=>{if(s.type==="fargate")vn(n,s.name,{taskDefinition:s.taskDefinition,service:s.service})})}function jr(n,i){if(!i)return;n.addResource("AppSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for application instances",VpcId:e.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:3000,ToPort:3000,SourceSecurityGroupId:e.ref("ALBSecurityGroup")},{IpProtocol:"tcp",FromPort:22,ToPort:22,CidrIp:"0.0.0.0/0"}],SecurityGroupEgress:[{IpProtocol:"-1",CidrIp:"0.0.0.0/0"}],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-app-sg")}]},{dependsOn:"VPC"}),n.addResource("EC2InstanceRole","AWS::IAM::Role",{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ec2.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore","arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy"],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-ec2-role")}]}),n.addResource("EC2InstanceProfile","AWS::IAM::InstanceProfile",{Roles:[e.ref("EC2InstanceRole")]},{dependsOn:"EC2InstanceRole"});let s=i.userData||`#!/bin/bash
|
|
2433
|
+
};`}var e={ref:(n)=>({Ref:n}),getAtt:(n,i)=>({"Fn::GetAtt":[n,i]}),join:(n,i)=>({"Fn::Join":[n,i]}),sub:(n,i)=>i?{"Fn::Sub":[n,i]}:{"Fn::Sub":n},select:(n,i)=>({"Fn::Select":[n,i]}),split:(n,i)=>({"Fn::Split":[n,i]}),getAZs:(n="")=>({"Fn::GetAZs":n}),importValue:(n)=>({"Fn::ImportValue":n}),findInMap:(n,i,s)=>({"Fn::FindInMap":[n,i,s]}),base64:(n)=>({"Fn::Base64":n}),cidr:(n,i,s)=>({"Fn::Cidr":[n,i,s]}),equals:(n,i)=>({"Fn::Equals":[n,i]}),if:(n,i,s)=>({"Fn::If":[n,i,s]}),not:(n)=>({"Fn::Not":[n]}),and:(...n)=>({"Fn::And":n}),or:(...n)=>({"Fn::Or":n})},cn={s3Bucket:(n)=>e.sub(`arn:aws:s3:::${n}`),s3Object:(n,i="*")=>e.sub(`arn:aws:s3:::${n}/${i}`),lambda:(n,i,s)=>e.sub(`arn:aws:lambda:\${AWS::Region}:\${AWS::AccountId}:function:${n}`,i&&s?{"AWS::Region":i,"AWS::AccountId":s}:void 0),dynamodb:(n)=>e.sub(`arn:aws:dynamodb:\${AWS::Region}:\${AWS::AccountId}:table/${n}`),sqs:(n)=>e.sub(`arn:aws:sqs:\${AWS::Region}:\${AWS::AccountId}:${n}`),sns:(n)=>e.sub(`arn:aws:sns:\${AWS::Region}:\${AWS::AccountId}:${n}`),kinesis:(n)=>e.sub(`arn:aws:kinesis:\${AWS::Region}:\${AWS::AccountId}:stream/${n}`),iam:(n,i)=>e.sub(`arn:aws:iam::\${AWS::AccountId}:${n}/${i}`),secretsManager:(n)=>e.sub(`arn:aws:secretsmanager:\${AWS::Region}:\${AWS::AccountId}:secret:${n}`),cloudwatch:(n)=>e.sub(`arn:aws:logs:\${AWS::Region}:\${AWS::AccountId}:log-group:${n}`)},$I={ACCOUNT_ID:{Ref:"AWS::AccountId"},NOTIFICATION_ARNS:{Ref:"AWS::NotificationARNs"},NO_VALUE:{Ref:"AWS::NoValue"},PARTITION:{Ref:"AWS::Partition"},REGION:{Ref:"AWS::Region"},STACK_ID:{Ref:"AWS::StackId"},STACK_NAME:{Ref:"AWS::StackName"},URL_SUFFIX:{Ref:"AWS::URLSuffix"}};function Sn(n,i){if(i.type==="http")$r(n,i);else if(i.type==="rest")Br(n,i);else if(i.type==="websocket")Fr(n,i)}function $r(n,i){let s={Name:e.sub("${AWS::StackName}-http-api"),ProtocolType:"HTTP"};if(i.cors)s.CorsConfiguration={AllowOrigins:i.cors.allowOrigins,AllowMethods:i.cors.allowMethods,AllowHeaders:i.cors.allowHeaders||["*"],MaxAge:i.cors.maxAge||300};if(n.addResource("HttpApi","AWS::ApiGatewayV2::Api",s),n.addResource("HttpApiStage","AWS::ApiGatewayV2::Stage",{ApiId:e.ref("HttpApi"),StageName:"$default",AutoDeploy:!0,DefaultRouteSettings:i.throttling?{ThrottlingBurstLimit:i.throttling.burstLimit,ThrottlingRateLimit:i.throttling.rateLimit}:void 0,AccessLogSettings:{DestinationArn:e.getAtt("ApiLogGroup","Arn"),Format:"$context.requestId $context.error.message $context.error.messageString"}},{dependsOn:["HttpApi","ApiLogGroup"]}),n.addResource("ApiLogGroup","AWS::Logs::LogGroup",{LogGroupName:e.sub("/aws/apigateway/${AWS::StackName}-http-api"),RetentionInDays:14}),i.authorizer)Gr(n,"HttpApi",i.authorizer);if(i.customDomain)It(n,"HttpApi",i.customDomain,"HTTP");n.addOutputs({HttpApiId:{Description:"HTTP API ID",Value:e.ref("HttpApi"),Export:{Name:e.sub("${AWS::StackName}-http-api-id")}},HttpApiEndpoint:{Description:"HTTP API endpoint",Value:e.getAtt("HttpApi","ApiEndpoint"),Export:{Name:e.sub("${AWS::StackName}-http-api-endpoint")}}})}function Br(n,i){n.addResource("RestApi","AWS::ApiGateway::RestApi",{Name:e.sub("${AWS::StackName}-rest-api"),Description:e.sub("REST API for ${AWS::StackName}"),EndpointConfiguration:{Types:["REGIONAL"]}}),n.addResource("ApiGatewayAccount","AWS::ApiGateway::Account",{CloudWatchRoleArn:e.getAtt("ApiGatewayCloudWatchRole","Arn")},{dependsOn:"ApiGatewayCloudWatchRole"}),n.addResource("ApiGatewayCloudWatchRole","AWS::IAM::Role",{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"apigateway.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs"]}),n.addResource("RestApiDeployment","AWS::ApiGateway::Deployment",{RestApiId:e.ref("RestApi"),Description:"Initial deployment"},{dependsOn:"RestApi"});let s={RestApiId:e.ref("RestApi"),DeploymentId:e.ref("RestApiDeployment"),StageName:"prod",Description:"Production stage",MethodSettings:[{ResourcePath:"/*",HttpMethod:"*",LoggingLevel:"INFO",DataTraceEnabled:!0,MetricsEnabled:!0}]};if(i.throttling)s.MethodSettings[0].ThrottlingBurstLimit=i.throttling.burstLimit,s.MethodSettings[0].ThrottlingRateLimit=i.throttling.rateLimit;if(n.addResource("RestApiStage","AWS::ApiGateway::Stage",s,{dependsOn:["RestApi","RestApiDeployment"]}),i.customDomain)It(n,"RestApi",i.customDomain,"REST");n.addOutputs({RestApiId:{Description:"REST API ID",Value:e.ref("RestApi"),Export:{Name:e.sub("${AWS::StackName}-rest-api-id")}},RestApiEndpoint:{Description:"REST API endpoint",Value:e.sub("https://${RestApi}.execute-api.${AWS::Region}.amazonaws.com/prod"),Export:{Name:e.sub("${AWS::StackName}-rest-api-endpoint")}}})}function Fr(n,i){if(n.addResource("WebSocketApi","AWS::ApiGatewayV2::Api",{Name:e.sub("${AWS::StackName}-websocket-api"),ProtocolType:"WEBSOCKET",RouteSelectionExpression:"$request.body.action"}),i.routes){if(i.routes.connect)lt(n,"$connect",i.routes.connect.functionName);if(i.routes.disconnect)lt(n,"$disconnect",i.routes.disconnect.functionName);if(i.routes.default)lt(n,"$default",i.routes.default.functionName);if(i.routes.custom)i.routes.custom.forEach((s)=>{lt(n,s.routeKey,s.functionName)})}if(n.addResource("WebSocketApiStage","AWS::ApiGatewayV2::Stage",{ApiId:e.ref("WebSocketApi"),StageName:"prod",AutoDeploy:!0,DefaultRouteSettings:i.throttling?{ThrottlingBurstLimit:i.throttling.burstLimit,ThrottlingRateLimit:i.throttling.rateLimit}:void 0},{dependsOn:"WebSocketApi"}),i.customDomain)It(n,"WebSocketApi",i.customDomain,"WEBSOCKET");n.addOutputs({WebSocketApiId:{Description:"WebSocket API ID",Value:e.ref("WebSocketApi"),Export:{Name:e.sub("${AWS::StackName}-websocket-api-id")}},WebSocketApiEndpoint:{Description:"WebSocket API endpoint",Value:e.getAtt("WebSocketApi","ApiEndpoint"),Export:{Name:e.sub("${AWS::StackName}-websocket-api-endpoint")}}})}function lt(n,i,s){let o=n.toLogicalId(`websocket-route-${i}`),c=n.toLogicalId(`websocket-integration-${i}`),u=n.toLogicalId(`${s}-function`);n.addResource(c,"AWS::ApiGatewayV2::Integration",{ApiId:e.ref("WebSocketApi"),IntegrationType:"AWS_PROXY",IntegrationUri:e.sub(`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${u}.Arn}/invocations`)},{dependsOn:["WebSocketApi",u]}),n.addResource(o,"AWS::ApiGatewayV2::Route",{ApiId:e.ref("WebSocketApi"),RouteKey:i,Target:e.join("/",["integrations",e.ref(c)])},{dependsOn:["WebSocketApi",c]}),n.addResource(`${o}Permission`,"AWS::Lambda::Permission",{FunctionName:e.ref(u),Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:e.sub("arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${WebSocketApi}/*")},{dependsOn:[u,"WebSocketApi"]})}function It(n,i,s,o){let c={DomainName:s.domain};if(o==="REST")c.CertificateArn=s.certificateArn,c.EndpointConfiguration={Types:["REGIONAL"]},n.addResource("ApiCustomDomain","AWS::ApiGateway::DomainName",c),n.addResource("ApiBasePathMapping","AWS::ApiGateway::BasePathMapping",{DomainName:e.ref("ApiCustomDomain"),RestApiId:e.ref(i),Stage:e.ref("RestApiStage")},{dependsOn:["ApiCustomDomain",i,"RestApiStage"]});else c.DomainNameConfigurations=[{CertificateArn:s.certificateArn,EndpointType:"REGIONAL"}],n.addResource("ApiCustomDomain","AWS::ApiGatewayV2::DomainName",c),n.addResource("ApiMapping","AWS::ApiGatewayV2::ApiMapping",{ApiId:e.ref(i),DomainName:e.ref("ApiCustomDomain"),Stage:o==="HTTP"?e.ref("HttpApiStage"):e.ref("WebSocketApiStage")},{dependsOn:["ApiCustomDomain",i]});if(s.dnsProvider!=="external")n.addResource("ApiDNSRecord","AWS::Route53::RecordSet",{HostedZoneName:e.sub(`${_r(s.domain)}.`),Name:s.domain,Type:"A",AliasTarget:{HostedZoneId:e.getAtt("ApiCustomDomain","RegionalHostedZoneId"),DNSName:e.getAtt("ApiCustomDomain","RegionalDomainName"),EvaluateTargetHealth:!1}},{dependsOn:"ApiCustomDomain"});n.addOutputs({ApiCustomDomainName:{Description:"Configured API custom domain",Value:s.domain},ApiCustomDomainTarget:{Description:"DNS target for Route53 or an external DNS provider",Value:e.getAtt("ApiCustomDomain","RegionalDomainName")},ApiCustomDomainHostedZoneId:{Description:"Regional API Gateway hosted zone ID",Value:e.getAtt("ApiCustomDomain","RegionalHostedZoneId")}})}function Gr(n,i,s){if(!s)return;if(s.type==="jwt")n.addResource("ApiAuthorizer","AWS::ApiGatewayV2::Authorizer",{ApiId:e.ref(i),AuthorizerType:"JWT",IdentitySource:[s.identitySource||"$request.header.Authorization"],JwtConfiguration:{Issuer:s.issuer,Audience:s.audience},Name:"JWTAuthorizer"},{dependsOn:i});else if(s.type==="lambda")n.addResource("ApiAuthorizer","AWS::ApiGatewayV2::Authorizer",{ApiId:e.ref(i),AuthorizerType:"REQUEST",AuthorizerUri:s.authorizerUri,IdentitySource:[s.identitySource||"$request.header.Authorization"],Name:"LambdaAuthorizer"},{dependsOn:i})}function _r(n){let i=n.split(".");if(i.length>=2)return i.slice(-2).join(".");return n}function An(n,i){if(i.redis)Wr(n,i.redis);if(i.memcached)Vr(n,i.memcached);if(i.elasticache)Ur(n,i.elasticache)}function Wr(n,i){if(!i)return;if(n.addResource("CacheSubnetGroup","AWS::ElastiCache::SubnetGroup",{Description:"Subnet group for ElastiCache Redis cluster",SubnetIds:[e.ref("PrivateSubnet1"),e.ref("PrivateSubnet2")],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-cache-subnet-group")}]},{dependsOn:["PrivateSubnet1","PrivateSubnet2"]}),n.addResource("CacheSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for ElastiCache Redis",VpcId:e.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:i.port||6379,ToPort:i.port||6379,SourceSecurityGroupId:e.ref("AppSecurityGroup")}],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-cache-sg")}]},{dependsOn:["VPC","AppSecurityGroup"]}),i.parameterGroup&&Object.keys(i.parameterGroup).length>0)n.addResource("CacheParameterGroup","AWS::ElastiCache::ParameterGroup",{Description:"Parameter group for Redis",CacheParameterGroupFamily:`redis${i.engineVersion.split(".")[0]}`,Properties:i.parameterGroup});if(i.numCacheNodes>1||i.automaticFailoverEnabled)n.addResource("RedisReplicationGroup","AWS::ElastiCache::ReplicationGroup",{ReplicationGroupDescription:"Redis replication group",ReplicationGroupId:e.sub("${AWS::StackName}-redis"),Engine:"redis",EngineVersion:i.engineVersion,CacheNodeType:i.nodeType,NumCacheClusters:i.numCacheNodes,AutomaticFailoverEnabled:i.automaticFailoverEnabled||!1,MultiAZEnabled:i.automaticFailoverEnabled||!1,Port:i.port||6379,CacheSubnetGroupName:e.ref("CacheSubnetGroup"),SecurityGroupIds:[e.ref("CacheSecurityGroup")],CacheParameterGroupName:i.parameterGroup?e.ref("CacheParameterGroup"):void 0,SnapshotRetentionLimit:i.snapshotRetentionLimit||5,SnapshotWindow:i.snapshotWindow||"03:00-05:00",PreferredMaintenanceWindow:"sun:05:00-sun:06:00",AtRestEncryptionEnabled:!0,TransitEncryptionEnabled:!0,Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-redis")}]},{dependsOn:i.parameterGroup?["CacheSubnetGroup","CacheSecurityGroup","CacheParameterGroup"]:["CacheSubnetGroup","CacheSecurityGroup"],deletionPolicy:"Snapshot",updateReplacePolicy:"Snapshot"}),n.addOutputs({RedisEndpoint:{Description:"Redis primary endpoint",Value:e.getAtt("RedisReplicationGroup","PrimaryEndPoint.Address"),Export:{Name:e.sub("${AWS::StackName}-redis-endpoint")}},RedisPort:{Description:"Redis port",Value:e.getAtt("RedisReplicationGroup","PrimaryEndPoint.Port"),Export:{Name:e.sub("${AWS::StackName}-redis-port")}}});else n.addResource("RedisCacheCluster","AWS::ElastiCache::CacheCluster",{ClusterName:e.sub("${AWS::StackName}-redis"),Engine:"redis",EngineVersion:i.engineVersion,CacheNodeType:i.nodeType,NumCacheNodes:1,Port:i.port||6379,CacheSubnetGroupName:e.ref("CacheSubnetGroup"),VpcSecurityGroupIds:[e.ref("CacheSecurityGroup")],CacheParameterGroupName:i.parameterGroup?e.ref("CacheParameterGroup"):void 0,SnapshotRetentionLimit:i.snapshotRetentionLimit||5,SnapshotWindow:i.snapshotWindow||"03:00-05:00",PreferredMaintenanceWindow:"sun:05:00-sun:06:00",Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-redis")}]},{dependsOn:i.parameterGroup?["CacheSubnetGroup","CacheSecurityGroup","CacheParameterGroup"]:["CacheSubnetGroup","CacheSecurityGroup"],deletionPolicy:"Snapshot",updateReplacePolicy:"Snapshot"}),n.addOutputs({RedisEndpoint:{Description:"Redis endpoint",Value:e.getAtt("RedisCacheCluster","RedisEndpoint.Address"),Export:{Name:e.sub("${AWS::StackName}-redis-endpoint")}},RedisPort:{Description:"Redis port",Value:e.getAtt("RedisCacheCluster","RedisEndpoint.Port"),Export:{Name:e.sub("${AWS::StackName}-redis-port")}}})}function Vr(n,i){if(!i)return;if(!n.hasResource("CacheSubnetGroup"))n.addResource("CacheSubnetGroup","AWS::ElastiCache::SubnetGroup",{Description:"Subnet group for ElastiCache",SubnetIds:[e.ref("PrivateSubnet1"),e.ref("PrivateSubnet2")]},{dependsOn:["PrivateSubnet1","PrivateSubnet2"]});if(!n.hasResource("CacheSecurityGroup"))n.addResource("CacheSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for ElastiCache Memcached",VpcId:e.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:i.port||11211,ToPort:i.port||11211,SourceSecurityGroupId:e.ref("AppSecurityGroup")}],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-cache-sg")}]},{dependsOn:["VPC","AppSecurityGroup"]});n.addResource("MemcachedCacheCluster","AWS::ElastiCache::CacheCluster",{ClusterName:e.sub("${AWS::StackName}-memcached"),Engine:"memcached",EngineVersion:i.engineVersion,CacheNodeType:i.nodeType,NumCacheNodes:i.numCacheNodes,Port:i.port||11211,CacheSubnetGroupName:e.ref("CacheSubnetGroup"),VpcSecurityGroupIds:[e.ref("CacheSecurityGroup")],PreferredMaintenanceWindow:"sun:05:00-sun:06:00",Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-memcached")}]},{dependsOn:["CacheSubnetGroup","CacheSecurityGroup"]}),n.addOutputs({MemcachedEndpoint:{Description:"Memcached configuration endpoint",Value:e.getAtt("MemcachedCacheCluster","ConfigurationEndpoint.Address"),Export:{Name:e.sub("${AWS::StackName}-memcached-endpoint")}},MemcachedPort:{Description:"Memcached port",Value:e.getAtt("MemcachedCacheCluster","ConfigurationEndpoint.Port"),Export:{Name:e.sub("${AWS::StackName}-memcached-port")}}})}function Ur(n,i){if(!i)return;let s=i.engine==="redis";if(!n.hasResource("CacheSubnetGroup"))n.addResource("CacheSubnetGroup","AWS::ElastiCache::SubnetGroup",{Description:"Subnet group for ElastiCache",SubnetIds:[e.ref("PrivateSubnet1"),e.ref("PrivateSubnet2")]},{dependsOn:["PrivateSubnet1","PrivateSubnet2"]});if(!n.hasResource("CacheSecurityGroup"))n.addResource("CacheSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for ElastiCache",VpcId:e.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:s?6379:11211,ToPort:s?6379:11211,SourceSecurityGroupId:e.ref("AppSecurityGroup")}],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-cache-sg")}]},{dependsOn:["VPC","AppSecurityGroup"]});n.addResource("CacheCluster","AWS::ElastiCache::CacheCluster",{ClusterName:e.sub(`\${AWS::StackName}-${i.engine}`),Engine:i.engine,EngineVersion:i.engineVersion,CacheNodeType:i.nodeType,NumCacheNodes:i.numCacheNodes,CacheSubnetGroupName:e.ref("CacheSubnetGroup"),VpcSecurityGroupIds:[e.ref("CacheSecurityGroup")],Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${i.engine}`)}]},{dependsOn:["CacheSubnetGroup","CacheSecurityGroup"]})}function Cn(n,i){if(!i.enabled)return;n.addResource("CloudFrontOriginAccessIdentity","AWS::CloudFront::CloudFrontOriginAccessIdentity",{CloudFrontOriginAccessIdentityConfig:{Comment:e.sub("${AWS::StackName} CloudFront OAI")}});let s=[],o=[];if(!i.origins||i.origins.length===0)s.push({Id:"S3Origin",DomainName:e.getAtt("StaticBucket","DomainName"),S3OriginConfig:{OriginAccessIdentity:e.sub("origin-access-identity/cloudfront/${CloudFrontOriginAccessIdentity}")}});else i.origins.forEach((d,f)=>{let h={Id:d.id,DomainName:d.domainName};if(d.originPath)h.OriginPath=d.originPath;if(d.domainName.includes("s3"))h.S3OriginConfig={OriginAccessIdentity:e.sub("origin-access-identity/cloudfront/${CloudFrontOriginAccessIdentity}")};else h.CustomOriginConfig={HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only",OriginSSLProtocols:["TLSv1.2"]};if(s.push(h),f>0||d.pathPattern)o.push({PathPattern:d.pathPattern||`/${d.id}/*`,TargetOriginId:d.id,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD"],Compress:i.compress!==!1,ForwardedValues:{QueryString:!0,Cookies:{Forward:"none"}},MinTTL:i.cachePolicy?.minTTL||0,DefaultTTL:i.cachePolicy?.defaultTTL||86400,MaxTTL:i.cachePolicy?.maxTTL||31536000})});let c={TargetOriginId:s[0].Id,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD"],Compress:i.compress!==!1,ForwardedValues:{QueryString:!0,Cookies:{Forward:"none"}},MinTTL:i.cachePolicy?.minTTL||0,DefaultTTL:i.cachePolicy?.defaultTTL||86400,MaxTTL:i.cachePolicy?.maxTTL||31536000};if(i.edgeFunctions&&i.edgeFunctions.length>0)c.LambdaFunctionAssociations=i.edgeFunctions.map((d)=>({EventType:d.eventType,LambdaFunctionARN:d.functionArn}));let u={Enabled:!0,HttpVersion:i.http3?"http3":"http2",IPV6Enabled:!0,Origins:s,DefaultCacheBehavior:c,PriceClass:i.priceClass||"PriceClass_100",ViewerCertificate:{}};if(o.length>0)u.CacheBehaviors=o;if(i.customDomain)u.Aliases=[i.customDomain.domain],u.ViewerCertificate={AcmCertificateArn:i.customDomain.certificateArn,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};else u.ViewerCertificate={CloudFrontDefaultCertificate:!0};if(i.errorPages)u.CustomErrorResponses=Object.entries(i.errorPages).map(([d,f])=>({ErrorCode:Number.parseInt(d),ResponseCode:200,ResponsePagePath:f,ErrorCachingMinTTL:300}));if(u.DefaultRootObject="index.html",u.Comment=e.sub("${AWS::StackName} CloudFront Distribution"),n.addResource("CloudFrontDistribution","AWS::CloudFront::Distribution",{DistributionConfig:u},{dependsOn:"CloudFrontOriginAccessIdentity"}),!i.origins||i.origins.length===0)n.addResource("StaticBucketPolicyForCloudFront","AWS::S3::BucketPolicy",{Bucket:e.ref("StaticBucket"),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontAccess",Effect:"Allow",Principal:{CanonicalUser:e.getAtt("CloudFrontOriginAccessIdentity","S3CanonicalUserId")},Action:"s3:GetObject",Resource:e.join("",[e.getAtt("StaticBucket","Arn"),"/*"])}]}},{dependsOn:["StaticBucket","CloudFrontOriginAccessIdentity"]});if(i.customDomain)n.addResource("CloudFrontDNSRecord","AWS::Route53::RecordSet",{HostedZoneName:e.sub(`${Hr(i.customDomain.domain)}.`),Name:i.customDomain.domain,Type:"A",AliasTarget:{HostedZoneId:"Z2FDTNDATAQYW2",DNSName:e.getAtt("CloudFrontDistribution","DomainName"),EvaluateTargetHealth:!1}},{dependsOn:"CloudFrontDistribution"});if(n.addOutputs({CloudFrontDistributionId:{Description:"CloudFront distribution ID",Value:e.ref("CloudFrontDistribution"),Export:{Name:e.sub("${AWS::StackName}-cloudfront-id")}},CloudFrontDomainName:{Description:"CloudFront distribution domain name",Value:e.getAtt("CloudFrontDistribution","DomainName"),Export:{Name:e.sub("${AWS::StackName}-cloudfront-domain")}}}),i.customDomain)n.addOutputs({CloudFrontURL:{Description:"CloudFront custom domain URL",Value:e.sub(`https://${i.customDomain.domain}`)}})}function Hr(n){let i=n.split(".");if(i.length>=2)return i.slice(-2).join(".");return n}function Tn(n,i){if(i.server)jr(n,i.server);if(i.fargate)vn(n,"app",i.fargate);if(i.services)i.services.forEach((s)=>{if(s.type==="fargate")vn(n,s.name,{taskDefinition:s.taskDefinition,service:s.service})})}function jr(n,i){if(!i)return;n.addResource("AppSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for application instances",VpcId:e.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:3000,ToPort:3000,SourceSecurityGroupId:e.ref("ALBSecurityGroup")},{IpProtocol:"tcp",FromPort:22,ToPort:22,CidrIp:"0.0.0.0/0"}],SecurityGroupEgress:[{IpProtocol:"-1",CidrIp:"0.0.0.0/0"}],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-app-sg")}]},{dependsOn:"VPC"}),n.addResource("EC2InstanceRole","AWS::IAM::Role",{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ec2.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore","arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy"],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-ec2-role")}]}),n.addResource("EC2InstanceProfile","AWS::IAM::InstanceProfile",{Roles:[e.ref("EC2InstanceRole")]},{dependsOn:"EC2InstanceRole"});let s=i.userData||`#!/bin/bash
|
|
2434
2434
|
set -e
|
|
2435
2435
|
# Update system
|
|
2436
2436
|
yum update -y || apt-get update -y
|
|
@@ -2451,13 +2451,13 @@ rpm -U ./amazon-cloudwatch-agent.rpm || true
|
|
|
2451
2451
|
};`},Environment:i.environment?{Variables:i.environment}:void 0,Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${i.name}`)}]};if(s!=="edge")u.VpcConfig={SubnetIds:[e.ref("PrivateSubnet1"),e.ref("PrivateSubnet2")],SecurityGroupIds:[e.ref("AppSecurityGroup")]};if(n.addResource(o,"AWS::Lambda::Function",u,{dependsOn:c}),n.addResource(`${o}LogGroup`,"AWS::Logs::LogGroup",{LogGroupName:e.sub(`/aws/lambda/\${AWS::StackName}-${i.name}`),RetentionInDays:14}),i.events)i.events.forEach((d,f)=>{Qr(n,o,d,f)});n.addOutputs({[`${o}Arn`]:{Description:`${i.name} function ARN`,Value:e.getAtt(o,"Arn"),Export:{Name:e.sub(`\${AWS::StackName}-${i.name}-function-arn`)}}})}function Qr(n,i,s,o){let c=`${i}EventSource${o}`;switch(s.type){case"http":break;case"s3":if(s.bucket){let u=n.toLogicalId(`${s.bucket}-bucket`);n.addResource(`${c}Permission`,"AWS::Lambda::Permission",{FunctionName:e.ref(i),Action:"lambda:InvokeFunction",Principal:"s3.amazonaws.com",SourceArn:cn.s3Bucket(e.ref(u))},{dependsOn:[i,u]})}break;case"sqs":if(s.queueName){let u=n.toLogicalId(`${s.queueName}-queue`);n.addResource(c,"AWS::Lambda::EventSourceMapping",{EventSourceArn:e.getAtt(u,"Arn"),FunctionName:e.ref(i),BatchSize:s.batchSize||10},{dependsOn:[i,u]})}break;case"kinesis":if(s.streamName){let u=n.toLogicalId(`${s.streamName}-stream`);n.addResource(c,"AWS::Lambda::EventSourceMapping",{EventSourceArn:e.getAtt(u,"Arn"),FunctionName:e.ref(i),BatchSize:s.batchSize||100,StartingPosition:s.startingPosition||"LATEST",ParallelizationFactor:s.parallelizationFactor||1},{dependsOn:[i,u]})}break;case"dynamodb-stream":if(s.tableName){let u=n.toLogicalId(`${s.tableName}-table`);n.addResource(c,"AWS::Lambda::EventSourceMapping",{EventSourceArn:e.getAtt(u,"StreamArn"),FunctionName:e.ref(i),BatchSize:s.batchSize||100,StartingPosition:s.startingPosition||"LATEST"},{dependsOn:[i,u]})}break;case"schedule":if(s.expression)n.addResource(`${c}Rule`,"AWS::Events::Rule",{ScheduleExpression:s.expression,State:"ENABLED",Targets:[{Arn:e.getAtt(i,"Arn"),Id:`${i}Target`}]},{dependsOn:i}),n.addResource(`${c}Permission`,"AWS::Lambda::Permission",{FunctionName:e.ref(i),Action:"lambda:InvokeFunction",Principal:"events.amazonaws.com",SourceArn:e.getAtt(`${c}Rule`,"Arn")},{dependsOn:[i,`${c}Rule`]});break}}function Jr(n){let i=[];if(!n)return i;if(n.forEach((s)=>{switch(s.type){case"s3":i.push({Effect:"Allow",Action:["s3:GetObject","s3:GetObjectVersion"],Resource:s.bucket?`arn:aws:s3:::${s.bucket}/*`:"arn:aws:s3:::*/*"});break;case"sqs":i.push({Effect:"Allow",Action:["sqs:ReceiveMessage","sqs:DeleteMessage","sqs:GetQueueAttributes"],Resource:s.queueName?cn.sqs(s.queueName):"arn:aws:sqs:*:*:*"});break;case"kinesis":i.push({Effect:"Allow",Action:["kinesis:GetRecords","kinesis:GetShardIterator","kinesis:DescribeStream","kinesis:ListStreams"],Resource:s.streamName?cn.kinesis(s.streamName):"arn:aws:kinesis:*:*:stream/*"});break;case"dynamodb-stream":i.push({Effect:"Allow",Action:["dynamodb:GetRecords","dynamodb:GetShardIterator","dynamodb:DescribeStream","dynamodb:ListStreams"],Resource:s.tableName?e.sub(`arn:aws:dynamodb:\${AWS::Region}:\${AWS::AccountId}:table/${s.tableName}/stream/*`):"arn:aws:dynamodb:*:*:table/*/stream/*"});break}}),i.length===0)i.push({Effect:"Allow",Action:["logs:CreateLogGroup","logs:CreateLogStream","logs:PutLogEvents"],Resource:"arn:aws:logs:*:*:*"});return i}function wn(n,i){if(i.topics)i.topics.forEach((s)=>{Yr(n,s)})}function Yr(n,i){let s=n.toLogicalId(`${i.name}-topic`);if(n.addResource(s,"AWS::SNS::Topic",{TopicName:e.sub(`\${AWS::StackName}-${i.name}`),DisplayName:i.displayName||i.name,Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${i.name}`)}]}),n.addResource(`${s}Policy`,"AWS::SNS::TopicPolicy",{Topics:[e.ref(s)],PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:["events.amazonaws.com","cloudwatch.amazonaws.com","s3.amazonaws.com"]},Action:"sns:Publish",Resource:e.ref(s)},{Effect:"Allow",Principal:{AWS:e.sub("arn:aws:iam::${AWS::AccountId}:root")},Action:["sns:Subscribe","sns:Publish","sns:Receive"],Resource:e.ref(s)}]}},{dependsOn:s}),i.subscriptions)i.subscriptions.forEach((o,c)=>{let u=`${s}Subscription${c+1}`,d={Protocol:o.protocol,TopicArn:e.ref(s),Endpoint:o.endpoint};if(o.filterPolicy)d.FilterPolicy=o.filterPolicy;if(o.protocol==="sqs"){let f=n.toLogicalId(`${o.endpoint}-queue`);d.Endpoint=e.getAtt(f,"Arn")}if(o.protocol==="lambda"){let f=n.toLogicalId(o.endpoint);d.Endpoint=e.getAtt(f,"Arn"),n.addResource(`${u}Permission`,"AWS::Lambda::Permission",{FunctionName:e.ref(f),Action:"lambda:InvokeFunction",Principal:"sns.amazonaws.com",SourceArn:e.ref(s)},{dependsOn:[f,s]})}n.addResource(u,"AWS::SNS::Subscription",d,{dependsOn:s})});n.addOutputs({[`${s}Arn`]:{Description:`${i.name} topic ARN`,Value:e.ref(s),Export:{Name:e.sub(`\${AWS::StackName}-${i.name}-topic-arn`)}}})}function In(n,i){if(i.alarms&&i.alarms.length>0)n.addResource("AlarmTopic","AWS::SNS::Topic",{TopicName:e.sub("${AWS::StackName}-alarms"),DisplayName:"CloudWatch Alarms",Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-alarms")}]}),i.alarms.forEach((s,o)=>{Zr(n,s,o)});if(i.dashboard)Xr(n,i.dashboard);if(i.logs?.groups)i.logs.groups.forEach((s)=>{ei(n,s,i.logs?.retention)})}function Zr(n,i,s){let o=n.toLogicalId(`alarm-${i.name||i.metric}-${s}`),c={AlarmName:i.name||e.sub(`\${AWS::StackName}-${i.metric}`),AlarmDescription:`Alarm for ${i.metric}`,MetricName:i.metric,Namespace:i.namespace||Nt(i.metric,i.service),Statistic:i.statistic||"Average",Period:i.period||300,EvaluationPeriods:i.evaluationPeriods||1,Threshold:i.threshold,ComparisonOperator:i.comparisonOperator||"GreaterThanThreshold",TreatMissingData:i.treatMissingData||"notBreaching",AlarmActions:[e.ref("AlarmTopic")],OKActions:[e.ref("AlarmTopic")]};if(i.dimensions)c.Dimensions=Object.entries(i.dimensions).map(([u,d])=>({Name:u,Value:d}));else if(i.service)c.Dimensions=ti(i.service);n.addResource(o,"AWS::CloudWatch::Alarm",c,{dependsOn:"AlarmTopic"})}function Xr(n,i){if(!i)return;let s=[],o=0,c=0;i.widgets?.forEach((u)=>{let d=u.width||12,f=u.height||6;if(u.type==="metric"&&u.metrics){let h=u.metrics.map((S)=>{if(typeof S==="string")return[Nt(S),S];else return[Nt(S.metric,S.service),S.metric]});s.push({type:"metric",x:o,y:c,width:d,height:f,properties:{metrics:h,period:300,stat:"Average",region:e.ref("AWS::Region"),title:u.metrics.length>1?"Multiple Metrics":typeof u.metrics[0]==="string"?u.metrics[0]:u.metrics[0].metric}})}else if(u.type==="log"&&u.logGroup)s.push({type:"log",x:o,y:c,width:d,height:f,properties:{query:`SOURCE '${u.logGroup}'
|
|
2452
2452
|
| fields @timestamp, @message
|
|
2453
2453
|
| sort @timestamp desc
|
|
2454
|
-
| limit 20`,region:e.ref("AWS::Region"),title:`Logs: ${u.logGroup}`}});else if(u.type==="text"&&u.text)s.push({type:"text",x:o,y:c,width:d,height:f,properties:{markdown:u.text}});if(o+=d,o>=24)o=0,c+=f}),n.addResource("CloudWatchDashboard","AWS::CloudWatch::Dashboard",{DashboardName:e.sub(`\${AWS::StackName}-${i.name}`),DashboardBody:JSON.stringify({widgets:s})}),n.addOutputs({DashboardURL:{Description:"CloudWatch Dashboard URL",Value:e.sub("https://console.aws.amazon.com/cloudwatch/home?region=${AWS::Region}#dashboards:name=${CloudWatchDashboard}")}})}function ei(n,i,s){let o=n.toLogicalId(`${i}-log-group`);n.addResource(o,"AWS::Logs::LogGroup",{LogGroupName:e.sub(`/aws/\${AWS::StackName}/${i}`),RetentionInDays:s||14,Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${i}`)}]})}function Nt(n,i){if(i)return{ec2:"AWS/EC2",ecs:"AWS/ECS",lambda:"AWS/Lambda",rds:"AWS/RDS",dynamodb:"AWS/DynamoDB",s3:"AWS/S3",cloudfront:"AWS/CloudFront",alb:"AWS/ApplicationELB",nlb:"AWS/NetworkELB",apigateway:"AWS/ApiGateway",sqs:"AWS/SQS",sns:"AWS/SNS",kinesis:"AWS/Kinesis",elasticache:"AWS/ElastiCache"}[i.toLowerCase()]||"AWS/CloudWatch";let s=n.toLowerCase();if(s.includes("cpu")||s.includes("memory")||s.includes("network"))return"AWS/EC2";if(s.includes("lambda")||s.includes("invocation")||s.includes("duration"))return"AWS/Lambda";if(s.includes("request")||s.includes("latency")||s.includes("target"))return"AWS/ApplicationELB";if(s.includes("database")||s.includes("connection"))return"AWS/RDS";if(s.includes("read")||s.includes("write")||s.includes("consumed"))return"AWS/DynamoDB";return"AWS/CloudWatch"}function ti(n){return{ec2:[{Name:"InstanceId",Value:e.ref("EC2Instance")}],ecs:[{Name:"ClusterName",Value:e.ref("ECSCluster")},{Name:"ServiceName",Value:e.getAtt("ECSService","Name")}],lambda:[{Name:"FunctionName",Value:e.ref("LambdaFunction")}],rds:[{Name:"DBInstanceIdentifier",Value:e.ref("Database")}],dynamodb:[{Name:"TableName",Value:e.ref("DynamoDBTable")}],alb:[{Name:"LoadBalancer",Value:e.getAtt("LoadBalancer","LoadBalancerFullName")}],apigateway:[{Name:"ApiName",Value:e.ref("HttpApi")}]}[n.toLowerCase()]||[]}function Dn(n,i){if(!i.vpc)return;let{cidr:s="10.0.0.0/16",availabilityZones:o=2,natGateways:c=1,enableDnsHostnames:u=!0,enableDnsSupport:d=!0}=i.vpc;n.addResource("VPC","AWS::EC2::VPC",{CidrBlock:s,EnableDnsHostnames:u,EnableDnsSupport:d,Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-vpc")}]}),n.addResource("InternetGateway","AWS::EC2::InternetGateway",{Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-igw")}]}),n.addResource("VPCGatewayAttachment","AWS::EC2::VPCGatewayAttachment",{VpcId:e.ref("VPC"),InternetGatewayId:e.ref("InternetGateway")},{dependsOn:["VPC","InternetGateway"]});let f=[];for(let T=0;T<o;T++){let v=`PublicSubnet${T+1}`;f.push(v),n.addResource(v,"AWS::EC2::Subnet",{VpcId:e.ref("VPC"),CidrBlock:e.select(T,e.cidr(e.getAtt("VPC","CidrBlock"),o*2,8)),AvailabilityZone:e.select(T,e.getAZs()),MapPublicIpOnLaunch:!0,Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-public-${T+1}`)},{Key:"Type",Value:"public"}]},{dependsOn:"VPC"})}let h=[];for(let T=0;T<o;T++){let v=`PrivateSubnet${T+1}`;h.push(v),n.addResource(v,"AWS::EC2::Subnet",{VpcId:e.ref("VPC"),CidrBlock:e.select(T+o,e.cidr(e.getAtt("VPC","CidrBlock"),o*2,8)),AvailabilityZone:e.select(T,e.getAZs()),MapPublicIpOnLaunch:!1,Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-private-${T+1}`)},{Key:"Type",Value:"private"}]},{dependsOn:"VPC"})}let S=[];for(let T=0;T<c;T++){let v=`NatEIP${T+1}`;S.push(v),n.addResource(v,"AWS::EC2::EIP",{Domain:"vpc",Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-nat-eip-${T+1}`)}]},{dependsOn:"VPCGatewayAttachment"})}let A=[];for(let T=0;T<c;T++){let v=`NatGateway${T+1}`;A.push(v);let R=T%o;n.addResource(v,"AWS::EC2::NatGateway",{AllocationId:e.getAtt(S[T],"AllocationId"),SubnetId:e.ref(f[R]),Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-nat-${T+1}`)}]},{dependsOn:[S[T],f[R]]})}n.addResource("PublicRouteTable","AWS::EC2::RouteTable",{VpcId:e.ref("VPC"),Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-public-rt")}]},{dependsOn:"VPC"}),n.addResource("PublicRoute","AWS::EC2::Route",{RouteTableId:e.ref("PublicRouteTable"),DestinationCidrBlock:"0.0.0.0/0",GatewayId:e.ref("InternetGateway")},{dependsOn:["PublicRouteTable","VPCGatewayAttachment"]}),f.forEach((T,v)=>{n.addResource(`PublicSubnetRouteTableAssociation${v+1}`,"AWS::EC2::SubnetRouteTableAssociation",{SubnetId:e.ref(T),RouteTableId:e.ref("PublicRouteTable")},{dependsOn:[T,"PublicRouteTable"]})}),h.forEach((T,v)=>{let R=`PrivateRouteTable${v+1}`,P=v%c;n.addResource(R,"AWS::EC2::RouteTable",{VpcId:e.ref("VPC"),Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-private-rt-${v+1}`)}]},{dependsOn:"VPC"}),n.addResource(`PrivateRoute${v+1}`,"AWS::EC2::Route",{RouteTableId:e.ref(R),DestinationCidrBlock:"0.0.0.0/0",NatGatewayId:e.ref(A[P])},{dependsOn:[R,A[P]]}),n.addResource(`PrivateSubnetRouteTableAssociation${v+1}`,"AWS::EC2::SubnetRouteTableAssociation",{SubnetId:e.ref(T),RouteTableId:e.ref(R)},{dependsOn:[T,R]})}),n.addResource("S3VPCEndpoint","AWS::EC2::VPCEndpoint",{VpcId:e.ref("VPC"),ServiceName:e.sub("com.amazonaws.${AWS::Region}.s3"),VpcEndpointType:"Gateway",RouteTableIds:[e.ref("PublicRouteTable"),...Array.from({length:o},(T,v)=>e.ref(`PrivateRouteTable${v+1}`))]},{dependsOn:"VPC"}),n.addResource("NetworkAcl","AWS::EC2::NetworkAcl",{VpcId:e.ref("VPC"),Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-nacl")}]},{dependsOn:"VPC"}),n.addResource("NetworkAclEntryInbound","AWS::EC2::NetworkAclEntry",{NetworkAclId:e.ref("NetworkAcl"),RuleNumber:100,Protocol:-1,RuleAction:"allow",CidrBlock:"0.0.0.0/0"},{dependsOn:"NetworkAcl"}),n.addResource("NetworkAclEntryOutbound","AWS::EC2::NetworkAclEntry",{NetworkAclId:e.ref("NetworkAcl"),RuleNumber:100,Protocol:-1,Egress:!0,RuleAction:"allow",CidrBlock:"0.0.0.0/0"},{dependsOn:"NetworkAcl"}),n.addOutputs({VPCId:{Description:"VPC ID",Value:e.ref("VPC"),Export:{Name:e.sub("${AWS::StackName}-VPC")}},PublicSubnets:{Description:"Public subnet IDs",Value:e.join(",",f.map((T)=>e.ref(T))),Export:{Name:e.sub("${AWS::StackName}-PublicSubnets")}},PrivateSubnets:{Description:"Private subnet IDs",Value:e.join(",",h.map((T)=>e.ref(T))),Export:{Name:e.sub("${AWS::StackName}-PrivateSubnets")}}})}function Nn(n,i){for(let[s,o]of Object.entries(i))ni(n,s,o)}function ni(n,i,s){let o=n.toLogicalId(`${i}-queue`),c=s.fifo||!1,u;if(s.deadLetterQueue){let f=`${o}DLQ`;n.addResource(f,"AWS::SQS::Queue",{QueueName:c?e.sub(`\${AWS::StackName}-${i}-dlq.fifo`):e.sub(`\${AWS::StackName}-${i}-dlq`),FifoQueue:c,MessageRetentionPeriod:1209600,Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${i}-dlq`)}]},{deletionPolicy:"Retain",updateReplacePolicy:"Retain"}),u=e.getAtt(f,"Arn")}let d={QueueName:c?e.sub(`\${AWS::StackName}-${i}.fifo`):e.sub(`\${AWS::StackName}-${i}`),FifoQueue:c,VisibilityTimeout:s.visibilityTimeout||30,MessageRetentionPeriod:s.messageRetentionPeriod||345600,ReceiveMessageWaitTimeSeconds:s.receiveMessageWaitTime||0,Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${i}`)}]};if(c&&s.contentBasedDeduplication)d.ContentBasedDeduplication=!0;if(s.deadLetterQueue&&u)d.RedrivePolicy={deadLetterTargetArn:u,maxReceiveCount:s.maxReceiveCount||3};if(n.addResource(o,"AWS::SQS::Queue",d,{dependsOn:s.deadLetterQueue?`${o}DLQ`:void 0,deletionPolicy:"Retain",updateReplacePolicy:"Retain"}),n.addResource(`${o}Policy`,"AWS::SQS::QueuePolicy",{Queues:[e.ref(o)],PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:["lambda.amazonaws.com","events.amazonaws.com","sns.amazonaws.com"]},Action:"sqs:SendMessage",Resource:e.getAtt(o,"Arn"),Condition:{ArnEquals:{"aws:SourceArn":e.sub("arn:aws:*:${AWS::Region}:${AWS::AccountId}:*")}}}]}},{dependsOn:o}),n.addOutputs({[`${o}Url`]:{Description:`${i} queue URL`,Value:e.ref(o),Export:{Name:e.sub(`\${AWS::StackName}-${i}-queue-url`)}},[`${o}Arn`]:{Description:`${i} queue ARN`,Value:e.getAtt(o,"Arn"),Export:{Name:e.sub(`\${AWS::StackName}-${i}-queue-arn`)}}}),s.deadLetterQueue)n.addOutputs({[`${o}DLQUrl`]:{Description:`${i} dead letter queue URL`,Value:e.ref(`${o}DLQ`),Export:{Name:e.sub(`\${AWS::StackName}-${i}-dlq-url`)}}})}function xn(n,i){if(i.certificate)ri(n,i.certificate);if(i.waf?.enabled)ii(n,i.waf);if(i.securityGroups)for(let[s,o]of Object.entries(i.securityGroups))si(n,s,o)}function ri(n,i){if(!i)return;let s=[i.domain];if(i.subdomains)s.push(...i.subdomains);n.addResource("Certificate","AWS::CertificateManager::Certificate",{DomainName:i.domain,SubjectAlternativeNames:i.subdomains,ValidationMethod:i.validationMethod||"DNS",DomainValidationOptions:s.map((o)=>({DomainName:o,HostedZoneId:e.ref("HostedZone")})),Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-certificate")}]}),n.addOutputs({CertificateArn:{Description:"ACM Certificate ARN",Value:e.ref("Certificate"),Export:{Name:e.sub("${AWS::StackName}-certificate-arn")}}})}function ii(n,i){if(!i)return;let s=[],o=i.rules||["rateLimit","sqlInjection","xss"];if(o.includes("rateLimit"))s.push({Name:"RateLimitRule",Priority:1,Statement:{RateBasedStatement:{Limit:i.rateLimit||2000,AggregateKeyType:"IP"}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"RateLimitRule"}});let c=s.length+1;if(o.includes("sqlInjection"))s.push({Name:"AWSManagedRulesSQLi",Priority:c++,Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:"AWSManagedRulesSQLiRuleSet"}},OverrideAction:{None:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"AWSManagedRulesSQLi"}});if(o.includes("xss"))s.push({Name:"AWSManagedRulesXSS",Priority:c++,Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:"AWSManagedRulesKnownBadInputsRuleSet"}},OverrideAction:{None:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"AWSManagedRulesXSS"}});if(o.includes("knownBadInputs"))s.push({Name:"AWSManagedRulesKnownBadInputs",Priority:c++,Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:"AWSManagedRulesKnownBadInputsRuleSet"}},OverrideAction:{None:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"AWSManagedRulesKnownBadInputs"}});if(o.includes("coreRuleSet"))s.push({Name:"AWSManagedRulesCoreRuleSet",Priority:c++,Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:"AWSManagedRulesCommonRuleSet"}},OverrideAction:{None:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"AWSManagedRulesCoreRuleSet"}});if(o.includes("linuxRuleSet"))s.push({Name:"AWSManagedRulesLinuxRuleSet",Priority:c++,Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:"AWSManagedRulesLinuxRuleSet"}},OverrideAction:{None:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"AWSManagedRulesLinuxRuleSet"}});if(o.includes("apiProtection"))s.push({Name:"AWSManagedRulesAPIProtection",Priority:c++,Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:"AWSManagedRulesAmazonIpReputationList"}},OverrideAction:{None:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"AWSManagedRulesAPIProtection"}});if(o.includes("geoBlock"))s.push({Name:"GeoBlockRule",Priority:c++,Statement:{GeoMatchStatement:{CountryCodes:["CN","RU"]}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"GeoBlockRule"}});if(o.includes("connectionLimit"))s.push({Name:"ConnectionLimitRule",Priority:c++,Statement:{RateBasedStatement:{Limit:100,AggregateKeyType:"IP"}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"ConnectionLimitRule"}});if(n.addResource("WebACL","AWS::WAFv2::WebACL",{Name:e.sub("${AWS::StackName}-waf"),Scope:i.scope||"REGIONAL",DefaultAction:{Allow:{}},Rules:s,VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:e.sub("${AWS::StackName}-waf")},Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-waf")}]}),n.hasResource("LoadBalancer"))n.addResource("WebACLAssociation","AWS::WAFv2::WebACLAssociation",{ResourceArn:e.ref("LoadBalancer"),WebACLArn:e.getAtt("WebACL","Arn")},{dependsOn:["WebACL","LoadBalancer"]});n.addOutputs({WebACLId:{Description:"WAF Web ACL ID",Value:e.ref("WebACL"),Export:{Name:e.sub("${AWS::StackName}-waf-id")}},WebACLArn:{Description:"WAF Web ACL ARN",Value:e.getAtt("WebACL","Arn"),Export:{Name:e.sub("${AWS::StackName}-waf-arn")}}})}function si(n,i,s){if(!s)return;let o=n.toLogicalId(`${i}-security-group`),c=s.ingress?.map((d)=>({IpProtocol:d.protocol,FromPort:d.port,ToPort:d.port,CidrIp:d.cidr,SourceSecurityGroupId:d.source?e.ref(d.source):void 0}))||[],u=s.egress?.map((d)=>({IpProtocol:d.protocol,FromPort:d.port,ToPort:d.port,CidrIp:d.cidr||"0.0.0.0/0"}))||[{IpProtocol:"-1",CidrIp:"0.0.0.0/0"}];n.addResource(o,"AWS::EC2::SecurityGroup",{GroupDescription:`Security group for ${i}`,VpcId:e.ref("VPC"),SecurityGroupIngress:c,SecurityGroupEgress:u,Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${i}-sg`)}]},{dependsOn:"VPC"}),n.addOutputs({[`${o}Id`]:{Description:`${i} security group ID`,Value:e.ref(o),Export:{Name:e.sub(`\${AWS::StackName}-${i}-sg-id`)}}})}function kn(n,i){for(let[s,o]of Object.entries(i)){if(o.type==="efs"){oi(n,s,o);continue}ai(n,s,o)}}function ai(n,i,s){let o=n.toLogicalId(`${i}-bucket`),c={BucketName:e.sub(`\${AWS::StackName}-${i}`),Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${i}`)}]};if(s.versioning)c.VersioningConfiguration={Status:"Enabled"};if(s.encryption)c.BucketEncryption={ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]};if(!s.public)c.PublicAccessBlockConfiguration={BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0};if(s.website)c.WebsiteConfiguration={IndexDocument:"index.html",ErrorDocument:"index.html"};if(s.cors&&s.cors.length>0)c.CorsConfiguration={CorsRules:s.cors.map((u)=>({AllowedOrigins:u.allowedOrigins,AllowedMethods:u.allowedMethods,AllowedHeaders:u.allowedHeaders||["*"],MaxAge:u.maxAge||3600}))};if(s.lifecycleRules&&s.lifecycleRules.length>0)c.LifecycleConfiguration={Rules:s.lifecycleRules.map((u)=>({Id:u.id,Status:u.enabled?"Enabled":"Disabled",ExpirationInDays:u.expirationDays,Transitions:u.transitions?.map((d)=>({TransitionInDays:d.days,StorageClass:d.storageClass}))}))};if(s.intelligentTiering)c.IntelligentTieringConfigurations=[{Id:"EntireBucket",Status:"Enabled",Tierings:[{AccessTier:"ARCHIVE_ACCESS",Days:90},{AccessTier:"DEEP_ARCHIVE_ACCESS",Days:180}]}];if(n.addResource(o,"AWS::S3::Bucket",c,{deletionPolicy:s.versioning?"Retain":"Delete"}),s.public)n.addResource(`${o}Policy`,"AWS::S3::BucketPolicy",{Bucket:e.ref(o),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadGetObject",Effect:"Allow",Principal:"*",Action:"s3:GetObject",Resource:e.join("",[cn.s3Bucket(e.ref(o)),"/*"])}]}},{dependsOn:o});if(n.addOutputs({[`${o}Name`]:{Description:`${i} bucket name`,Value:e.ref(o),Export:{Name:e.sub(`\${AWS::StackName}-${i}-bucket`)}},[`${o}Arn`]:{Description:`${i} bucket ARN`,Value:e.getAtt(o,"Arn"),Export:{Name:e.sub(`\${AWS::StackName}-${i}-bucket-arn`)}}}),s.website)n.addOutputs({[`${o}WebsiteURL`]:{Description:`${i} website URL`,Value:e.getAtt(o,"WebsiteURL")}})}function oi(n,i,s){let o=n.toLogicalId(`${i}-efs`),c={Encrypted:s.encryption!==!1,PerformanceMode:s.performanceMode||"generalPurpose",ThroughputMode:s.throughputMode||"bursting",FileSystemTags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${i}`)}]};if(s.lifecyclePolicy){if(c.LifecyclePolicies=[],s.lifecyclePolicy.transitionToIA)c.LifecyclePolicies.push({TransitionToIA:`AFTER_${s.lifecyclePolicy.transitionToIA}_DAYS`});if(s.lifecyclePolicy.transitionToPrimaryStorageClass)c.LifecyclePolicies.push({TransitionToPrimaryStorageClass:"AFTER_1_ACCESS"})}n.addResource(o,"AWS::EFS::FileSystem",c,{deletionPolicy:"Retain"});let u=2;for(let d=0;d<u;d++)n.addResource(`${o}MountTarget${d+1}`,"AWS::EFS::MountTarget",{FileSystemId:e.ref(o),SubnetId:e.ref(`PrivateSubnet${d+1}`),SecurityGroups:[e.ref("EFSSecurityGroup")]},{dependsOn:[o,`PrivateSubnet${d+1}`]});n.addResource("EFSSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for EFS mount targets",VpcId:e.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:2049,ToPort:2049,SourceSecurityGroupId:e.ref("AppSecurityGroup")}],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-efs-sg")}]},{dependsOn:"VPC"}),n.addOutputs({[`${o}Id`]:{Description:`${i} EFS file system ID`,Value:e.ref(o),Export:{Name:e.sub(`\${AWS::StackName}-${i}-efs`)}}})}class Am{template;config;resourceDependencies;constructor(n){this.config=n,this.resourceDependencies=new Map,this.template={AWSTemplateFormatVersion:"2010-09-09",Description:`Infrastructure for ${n.project.name} (${n.project.slug})`,Resources:{}}}build(){return this.addParameters(),this.addMappings(),this.addConditions(),this.addResources(),this.initializeOutputs(),this.resolveDependencies(),this.template}addParameters(){this.template.Parameters={Environment:{Type:"String",Default:"production",AllowedValues:["development","staging","production"],Description:"Environment name"}}}addMappings(){this.template.Mappings={RegionMap:{"us-east-1":{AMI:"ami-0f3caa1cf4417e51b"},"us-west-2":{AMI:"ami-0d1cd67c26f5fca19"},"eu-west-1":{AMI:"ami-0bbc25e23a7640b9b"}}}}addConditions(){this.template.Conditions={IsProduction:e.equals(e.ref("Environment"),"production"),HasDomain:e.not([e.equals(this.config.environments?.production?.domain||"","")])}}addResources(){let{infrastructure:n}=this.config;if(!n)return;if(n.network)this.addNetworkResources(n.network);if(n.storage)this.addStorageResources(n.storage);if(n.compute)this.addComputeResources(n.compute);if(n.databases)this.addDatabaseResources(n.databases);if(n.cache)this.addCacheResources(n.cache);if(n.cdn)this.addCDNResources(n.cdn);if(n.apiGateway)this.addApiGatewayResources(n.apiGateway);if(n.functions)this.addFunctionResources(n.functions);if(n.queues)this.addQueueResources(n.queues);if(n.messaging)this.addMessagingResources(n.messaging);if(n.monitoring)this.addMonitoringResources(n.monitoring);if(n.security)this.addSecurityResources(n.security)}initializeOutputs(){let n=this.template.Outputs||{};if(this.template.Outputs={StackName:{Description:"Stack name",Value:e.ref("AWS::StackName"),Export:{Name:e.sub("${AWS::StackName}-Name")}},Region:{Description:"AWS Region",Value:e.ref("AWS::Region"),Export:{Name:e.sub("${AWS::StackName}-Region")}},...n},this.config.environments?.production?.domain)this.template.Outputs.Domain={Description:"Production domain",Value:this.config.environments.production.domain,Condition:"HasDomain"}}addResource(n,i,s,o){let c={Type:i,Properties:s};if(o?.dependsOn)c.DependsOn=o.dependsOn,this.trackDependency(n,o.dependsOn);if(o?.condition)c.Condition=o.condition;if(o?.deletionPolicy)c.DeletionPolicy=o.deletionPolicy;if(o?.updateReplacePolicy)c.UpdateReplacePolicy=o.updateReplacePolicy;this.template.Resources[n]=c}addOutputs(n){this.template.Outputs={...this.template.Outputs,...n}}getOutputs(){return this.template.Outputs||{}}hasResource(n){return n in this.template.Resources}getResource(n){return this.template.Resources[n]}trackDependency(n,i){if(!this.resourceDependencies.has(n))this.resourceDependencies.set(n,new Set);(Array.isArray(i)?i:[i]).forEach((o)=>this.resourceDependencies.get(n).add(o))}resolveDependencies(){let n=new Set,i=new Set,s=(o)=>{if(i.has(o))throw Error(`Circular dependency detected involving resource: ${o}`);if(n.has(o))return!0;n.add(o),i.add(o);let c=this.resourceDependencies.get(o);if(c)for(let u of c)s(u);return i.delete(o),!0};for(let o of this.resourceDependencies.keys())s(o)}toLogicalId(n){return n.split(/[-_\s]/).map((i)=>i.charAt(0).toUpperCase()+i.slice(1).toLowerCase()).join("")}addNetworkResources(n){Dn(this,n)}addStorageResources(n){kn(this,n)}addComputeResources(n){Tn(this,n)}addDatabaseResources(n){Pn(this,n)}addFunctionResources(n){En(this,n)}addCacheResources(n){An(this,n)}addQueueResources(n){Nn(this,n)}addMessagingResources(n){wn(this,n)}addCDNResources(n){Cn(this,n)}addApiGatewayResources(n){Sn(this,n)}addMonitoringResources(n){In(this,n)}addSecurityResources(n){xn(this,n)}}function il(n){return new Am(n).build()}function MI(n){let{name:i,slug:s,domain:o,subdomain:c}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:c&&o?`${c}.${o}`:o}},infrastructure:{storage:{assets:{public:!0,versioning:!1,website:!0,encryption:!1,cors:[{allowedOrigins:["*"],allowedMethods:["GET","HEAD"],allowedHeaders:["*"],maxAge:3600}]}},cdn:{enabled:!0,customDomain:o?{domain:c&&o?`${c}.${o}`:o,certificateArn:"TO_BE_GENERATED"}:void 0,cachePolicy:{minTTL:0,defaultTTL:86400,maxTTL:31536000},compress:!0,http3:!0,errorPages:{404:"/index.html",403:"/index.html"}}}}}function FI(n){let{name:i,slug:s,domain:o,instanceType:c="t3.small",minInstances:u=2,maxInstances:d=10}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"server",environments:{production:{type:"production",domain:o}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:2,natGateways:1}},compute:{server:{instanceType:c,ami:"ubuntu-22.04",keyPair:`${s}-key`,autoScaling:{min:u,max:d,desired:u,targetCPU:70},loadBalancer:{type:"application",healthCheck:{path:"/health",interval:30,timeout:5,healthyThreshold:2,unhealthyThreshold:3}},userData:{packages:["nodejs","npm","nginx"],commands:["curl -fsSL https://bun.sh/install | bash","npm install -g pm2"]}}},databases:{postgres:{engine:"postgres",version:"15",instanceClass:"db.t3.micro",allocatedStorage:20,multiAZ:!0,backupRetentionDays:7,deletionProtection:!0}},cache:{redis:{nodeType:"cache.t3.micro",numCacheNodes:1,engine:"redis",engineVersion:"7.0"}},security:{certificate:o?{domain:o,subdomains:[`*.${o}`],validationMethod:"DNS"}:void 0}}}}function UI(n){let{name:i,slug:s,domain:o,taskCpu:c="256",taskMemory:u="512",desiredCount:d=2}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:o}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:2,natGateways:0}},compute:{fargate:{taskDefinition:{cpu:c,memory:u,containerDefinitions:[{name:"app",image:`${s}-app:latest`,portMappings:[{containerPort:3000}],environment:[],secrets:[]}]},service:{desiredCount:d,healthCheck:{path:"/health",interval:30,timeout:5,healthyThreshold:2,unhealthyThreshold:3},autoScaling:{min:d,max:d*5,targetCPU:70,targetMemory:80}},loadBalancer:{type:"application"}}},databases:{dynamodb:{tables:{[`${s}-main`]:{partitionKey:{name:"id",type:"S"},sortKey:{name:"createdAt",type:"S"},billingMode:"PAY_PER_REQUEST",streamEnabled:!0,pointInTimeRecovery:!0}}}},functions:{"process-queue":{runtime:"nodejs20.x",handler:"dist/workers/queue.handler",memory:512,timeout:60,events:[{type:"sqs",queueName:`${s}-queue`}]}},security:{certificate:o?{domain:o,subdomains:[`*.${o}`],validationMethod:"DNS"}:void 0}}}}function QI(n){let{name:i,slug:s,entry:o,domain:c,runtime:u="nodejs20.x",memory:d=1024,build:f,deploy:h,assets:S,queues:A=!0,scheduler:T="on",region:v="us-east-1"}=n;return{project:{name:i,slug:s,region:v},mode:"serverless",environments:{production:{type:"production",domain:c,app:{kind:"node",runtime:u,entry:o,memory:d,build:f,deploy:h,assets:S,queues:A,scheduler:T,domain:c}}}}}function sl(n){let i=n.database!==!1,s=n.cache!==!1,o=n.queue!==!1;return{project:{name:n.name,slug:n.slug,region:"us-east-1"},mode:"server",environments:{production:{type:"production",domain:n.domain}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:2,natGateways:1}},compute:{fargate:{taskDefinition:{cpu:"256",memory:"512",containerDefinitions:[{name:"api",image:n.imageUri,portMappings:[{containerPort:3000}],environment:[{name:"NODE_ENV",value:"production"},{name:"PORT",value:"3000"},{name:"AWS_REGION",value:e.ref("AWS::Region")},...i?[{name:"DB_HOST",value:e.getAtt("PostgresDb","Endpoint.Address")},{name:"DB_PORT",value:e.getAtt("PostgresDb","Endpoint.Port")}]:[],...s?[{name:"REDIS_HOST",value:e.getAtt("RedisReplicationGroup","PrimaryEndPoint.Address")},{name:"REDIS_PORT",value:e.getAtt("RedisReplicationGroup","PrimaryEndPoint.Port")},{name:"REDIS_TLS",value:"true"}]:[],...o?[{name:"QUEUE_URL",value:e.ref("JobsQueue")}]:[],{name:"MAIL_TRANSPORT",value:"ses"}],secrets:i?[{name:"DB_USERNAME",valueFrom:e.sub("${DBSecret}:username::")},{name:"DB_PASSWORD",valueFrom:e.sub("${DBSecret}:password::")}]:[]}]},service:{desiredCount:n.desiredCount||1,healthCheck:{path:"/api/health",interval:30,timeout:5},autoScaling:{min:n.desiredCount||1,max:6,targetCPU:70}},loadBalancer:{type:"application",...n.certificateArn?{customDomain:{domain:n.domain,certificateArn:n.certificateArn}}:{},...n.originVerifySecret?{originVerifyHeader:{name:"X-Origin-Verify",value:n.originVerifySecret}}:{}}}},...i?{databases:{postgres:{engine:"postgres",version:"16",instanceClass:"db.t4g.micro",allocatedStorage:20,maxAllocatedStorage:100,multiAZ:!1,backupRetentionDays:7,deletionProtection:!0}}}:{},...s?{cache:{redis:{nodeType:"cache.t4g.micro",numCacheNodes:2,engine:"redis",engineVersion:"7.1",automaticFailoverEnabled:!0,snapshotRetentionLimit:5}}}:{},...o?{queues:{jobs:{fifo:!1,visibilityTimeout:300,messageRetentionPeriod:345600,deadLetterQueue:!0,maxReceiveCount:3,receiveMessageWaitTime:20}}}:{}}}}function HI(n){let{name:i,slug:s,domain:o,apiSubdomain:c="api"}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"server",environments:{production:{type:"production",domain:o}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:2,natGateways:1}},storage:{frontend:{public:!0,versioning:!0,website:!0,encryption:!1}},cdn:{enabled:!0,customDomain:{domain:o,certificateArn:"TO_BE_GENERATED"},cachePolicy:{minTTL:0,defaultTTL:86400,maxTTL:31536000},compress:!0,http3:!0,errorPages:{404:"/index.html"}},compute:{fargate:{taskDefinition:{cpu:"512",memory:"1024",containerDefinitions:[{name:"api",image:`${s}-api:latest`,portMappings:[{containerPort:3000}]}]},service:{desiredCount:2,healthCheck:{path:"/api/health",interval:30},autoScaling:{min:2,max:10,targetCPU:70}},loadBalancer:{type:"application",customDomain:{domain:`${c}.${o}`,certificateArn:"TO_BE_GENERATED"}}}},databases:{postgres:{engine:"postgres",version:"15",instanceClass:"db.t3.small",allocatedStorage:50,multiAZ:!0,backupRetentionDays:14,deletionProtection:!0}},cache:{redis:{nodeType:"cache.t3.small",numCacheNodes:2,engine:"redis",engineVersion:"7.0"}},queues:{jobs:{fifo:!1,visibilityTimeout:300,messageRetentionPeriod:345600,deadLetterQueue:!0}},security:{certificate:{domain:o,subdomains:[`*.${o}`],validationMethod:"DNS"},waf:{enabled:!0,rules:["rateLimit","sqlInjection","xss"]}}}}}function GI(n){let{name:i,slug:s,domain:o}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:o}},infrastructure:{apiGateway:{type:"HTTP",cors:{allowOrigins:["*"],allowMethods:["GET","POST","PUT","DELETE","PATCH"],allowHeaders:["Content-Type","Authorization"],maxAge:3600},customDomain:o?{domain:o,certificateArn:"TO_BE_GENERATED"}:void 0,throttling:{rateLimit:1e4,burstLimit:5000},authorizer:{type:"JWT",identitySource:"$request.header.Authorization"}},functions:{users:{runtime:"nodejs20.x",handler:"dist/api/users.handler",memory:512,timeout:30,events:[{type:"http",path:"/users",method:"GET"},{type:"http",path:"/users",method:"POST"}]},products:{runtime:"nodejs20.x",handler:"dist/api/products.handler",memory:512,timeout:30,events:[{type:"http",path:"/products",method:"GET"}]}},databases:{dynamodb:{tables:{[`${s}-users`]:{partitionKey:{name:"userId",type:"S"},billingMode:"PAY_PER_REQUEST",streamEnabled:!0,pointInTimeRecovery:!0,globalSecondaryIndexes:[{name:"EmailIndex",partitionKey:{name:"email",type:"S"},projection:"ALL"}]},[`${s}-products`]:{partitionKey:{name:"productId",type:"S"},sortKey:{name:"category",type:"S"},billingMode:"PAY_PER_REQUEST",streamEnabled:!1}}}},cache:{elasticache:{nodeType:"cache.t3.micro",numCacheNodes:1,engine:"redis",engineVersion:"7.0"}},security:{certificate:o?{domain:o,validationMethod:"DNS"}:void 0,waf:{enabled:!0,rules:["rateLimit","sqlInjection"]}},monitoring:{alarms:[{metric:"Errors",threshold:10,period:300,evaluationPeriods:1},{metric:"Duration",threshold:3000,period:300,evaluationPeriods:2}]}}}}function VI(n){let{name:i,slug:s,domain:o,instanceType:c="t3.small"}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"server",environments:{production:{type:"production",domain:o}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:2,natGateways:1}},compute:{server:{instanceType:c,ami:"ubuntu-22.04",keyPair:`${s}-key`,autoScaling:{min:2,max:6,desired:2,targetCPU:75},loadBalancer:{type:"application",healthCheck:{path:"/wp-admin/install.php",interval:30}},userData:{packages:["nginx","php8.1-fpm","php8.1-mysql","php8.1-curl","php8.1-gd","php8.1-mbstring","php8.1-xml","php8.1-zip"],commands:["cd /var/www","wget https://wordpress.org/latest.tar.gz","tar -xzf latest.tar.gz","chown -R www-data:www-data wordpress","rm /etc/nginx/sites-enabled/default","systemctl restart nginx","systemctl restart php8.1-fpm"]}}},fileSystem:{uploads:{performanceMode:"generalPurpose",throughputMode:"bursting",encrypted:!0,lifecyclePolicy:{transitionToIA:30},mountPath:"/var/www/wordpress/wp-content/uploads"}},databases:{mysql:{engine:"mysql",version:"8.0",instanceClass:"db.t3.small",allocatedStorage:50,multiAZ:!0,backupRetentionDays:7,deletionProtection:!0,databaseName:"wordpress"}},cache:{redis:{nodeType:"cache.t3.micro",numCacheNodes:1,engine:"redis",engineVersion:"7.0"}},cdn:{enabled:!0,customDomain:{domain:o,certificateArn:"TO_BE_GENERATED"},cachePolicy:{minTTL:0,defaultTTL:86400,maxTTL:31536000},compress:!0,origins:[{type:"alb",pathPattern:"/wp-content/*"}]},security:{certificate:{domain:o,subdomains:[`www.${o}`],validationMethod:"DNS"},waf:{enabled:!0,rules:["rateLimit","sqlInjection","xss","wordpressRules"]}}}}}function qI(n){let{name:i,slug:s,domain:o,apiDomain:c}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:o}},infrastructure:{storage:{static:{public:!0,versioning:!0,website:!0,encryption:!1,cors:[{allowedOrigins:["*"],allowedMethods:["GET","HEAD"]}],lifecycleRules:[{id:"DeleteOldVersions",enabled:!0,expirationDays:90}]}},cdn:{enabled:!0,customDomain:{domain:o,certificateArn:"TO_BE_GENERATED"},cachePolicy:{minTTL:0,defaultTTL:0,maxTTL:31536000},compress:!0,http3:!0,errorPages:{404:"/404.html",500:"/500.html"},edgeFunctions:[{eventType:"origin-request",functionArn:"TO_BE_CREATED",name:"ssr-handler"}]},functions:{ssr:{runtime:"nodejs20.x",handler:"dist/edge/ssr.handler",memory:512,timeout:5},...c?{api:{runtime:"nodejs20.x",handler:"dist/api/index.handler",memory:1024,timeout:30,events:[{type:"http",path:"/{proxy+}",method:"ANY"}]}}:{}},apiGateway:c?{type:"HTTP",customDomain:{domain:c,certificateArn:"TO_BE_GENERATED"},cors:{allowOrigins:[o],allowMethods:["GET","POST","PUT","DELETE"],allowHeaders:["Content-Type","Authorization"]}}:void 0,databases:{dynamodb:{tables:{content:{partitionKey:{name:"id",type:"S"},sortKey:{name:"type",type:"S"},billingMode:"PAY_PER_REQUEST",streamEnabled:!1}}}},security:{certificate:{domain:o,subdomains:c?[c]:[],validationMethod:"DNS"},waf:{enabled:!0,rules:["rateLimit","geoBlock"]}}}}}function jI(n){let{name:i,slug:s,domain:o,services:c}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:o}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:3,natGateways:2}},compute:{services:c.map((u)=>({name:u.name,type:"fargate",taskDefinition:{cpu:u.cpu||"256",memory:u.memory||"512",containerDefinitions:[{name:u.name,image:`${s}-${u.name}:latest`,portMappings:[{containerPort:u.port}],healthCheck:{command:["CMD-SHELL",`curl -f http://localhost:${u.port}/health || exit 1`],interval:30,timeout:5,retries:3}}]},service:{desiredCount:u.desiredCount||2,serviceDiscovery:{enabled:!0,namespace:`${s}.local`},autoScaling:{min:2,max:10,targetCPU:70}}}))},apiGateway:{type:"HTTP",customDomain:{domain:o,certificateArn:"TO_BE_GENERATED"},cors:{allowOrigins:["*"],allowMethods:["GET","POST","PUT","DELETE","PATCH"]},routes:c.map((u)=>({path:`/${u.name}/{proxy+}`,integration:{type:"vpc-link",service:u.name}}))},databases:{dynamodb:{tables:Object.fromEntries(c.map((u)=>[`${s}-${u.name}`,{partitionKey:{name:"id",type:"S"},billingMode:"PAY_PER_REQUEST",streamEnabled:!0,pointInTimeRecovery:!0}]))}},queues:{events:{fifo:!1,visibilityTimeout:300,messageRetentionPeriod:345600,deadLetterQueue:!0}},messaging:{topics:{events:{name:`${s}-events`,subscriptions:c.map((u)=>({protocol:"sqs",endpoint:`${s}-${u.name}-queue`,filterPolicy:{service:[u.name]}}))}}},monitoring:{dashboard:{name:`${s}-microservices`,widgets:c.map((u)=>({type:"metric",metrics:[{service:u.name,metric:"CPUUtilization"},{service:u.name,metric:"MemoryUtilization"},{service:u.name,metric:"RequestCount"}]}))},alarms:c.flatMap((u)=>[{name:`${u.name}-high-cpu`,metric:"CPUUtilization",threshold:80,service:u.name},{name:`${u.name}-errors`,metric:"Errors",threshold:10,service:u.name}])},security:{certificate:{domain:o,validationMethod:"DNS"},waf:{enabled:!0,rules:["rateLimit","sqlInjection"]}}}}}function zI(n){let{name:i,slug:s,domain:o}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:o}},infrastructure:{apiGateway:{type:"websocket",customDomain:o?{domain:o,certificateArn:"TO_BE_GENERATED"}:void 0,routes:[{path:"$connect",method:"WEBSOCKET",integration:"websocket-connect"},{path:"$disconnect",method:"WEBSOCKET",integration:"websocket-disconnect"},{path:"$default",method:"WEBSOCKET",integration:"websocket-default"},{path:"sendMessage",method:"WEBSOCKET",integration:"websocket-send-message"},{path:"joinRoom",method:"WEBSOCKET",integration:"websocket-join-room"}]},functions:{connect:{runtime:"nodejs20.x",handler:"dist/websocket/connect.handler",memory:512,timeout:30},disconnect:{runtime:"nodejs20.x",handler:"dist/websocket/disconnect.handler",memory:512,timeout:30},default:{runtime:"nodejs20.x",handler:"dist/websocket/default.handler",memory:512,timeout:30},"send-message":{runtime:"nodejs20.x",handler:"dist/websocket/sendMessage.handler",memory:512,timeout:30},"join-room":{runtime:"nodejs20.x",handler:"dist/websocket/joinRoom.handler",memory:512,timeout:30},broadcast:{runtime:"nodejs20.x",handler:"dist/streams/broadcast.handler",memory:1024,timeout:60,events:[{type:"dynamodb-stream",tableName:`${s}-messages`,startingPosition:"LATEST",batchSize:100}]}},databases:{dynamodb:{tables:{[`${s}-connections`]:{partitionKey:{name:"connectionId",type:"S"},billingMode:"PAY_PER_REQUEST",globalSecondaryIndexes:[{name:"RoomIndex",partitionKey:{name:"roomId",type:"S"},sortKey:{name:"connectionId",type:"S"},projection:"ALL"}]},[`${s}-messages`]:{partitionKey:{name:"roomId",type:"S"},sortKey:{name:"timestamp",type:"S"},billingMode:"PAY_PER_REQUEST",streamEnabled:!0,pointInTimeRecovery:!0,globalSecondaryIndexes:[{name:"UserIndex",partitionKey:{name:"userId",type:"S"},sortKey:{name:"timestamp",type:"S"},projection:"ALL"}]},[`${s}-rooms`]:{partitionKey:{name:"roomId",type:"S"},billingMode:"PAY_PER_REQUEST"}}}},cache:{elasticache:{nodeType:"cache.t3.small",numCacheNodes:2,engine:"redis",engineVersion:"7.0"}},monitoring:{alarms:[{metric:"WebSocketConnections",threshold:1e4,evaluationPeriods:1},{metric:"IntegrationLatency",threshold:1000,evaluationPeriods:2}],dashboard:{name:`${s}-realtime`,widgets:[{type:"metric",metrics:["WebSocketConnections","MessagesSent","IntegrationLatency"]}]}},security:{certificate:o?{domain:o,validationMethod:"DNS"}:void 0,waf:{enabled:!0,rules:["rateLimit","connectionLimit"]}}}}}function KI(n){let{name:i,slug:s,retentionDays:o=7}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"serverless",infrastructure:{streaming:{dataStream:{name:`${s}-stream`,shardCount:2,retentionPeriod:o*24,encryption:!0}},storage:{raw:{public:!1,versioning:!0,encryption:!0,intelligentTiering:!0,lifecycleRules:[{id:"ArchiveOldData",enabled:!0,transitions:[{days:30,storageClass:"GLACIER"},{days:90,storageClass:"DEEP_ARCHIVE"}]}]},processed:{public:!1,versioning:!0,encryption:!0,intelligentTiering:!0}},functions:{"stream-processor":{runtime:"nodejs20.x",handler:"dist/processors/stream.handler",memory:2048,timeout:300,events:[{type:"kinesis",streamName:`${s}-stream`,batchSize:1000,startingPosition:"LATEST",parallelizationFactor:10}]},transformer:{runtime:"nodejs20.x",handler:"dist/processors/transform.handler",memory:3008,timeout:900,events:[{type:"s3",bucket:`${s}-raw`,prefix:"incoming/"}]},aggregator:{runtime:"nodejs20.x",handler:"dist/processors/aggregate.handler",memory:2048,timeout:600,events:[{type:"schedule",expression:"cron(0 * * * ? *)"}]}},analytics:{athena:{database:`${s}_analytics`,workgroup:`${s}-workgroup`,outputBucket:`${s}-query-results`,tables:[{name:"raw_events",location:`s3://${s}-raw/events/`,format:"parquet",partitionKeys:["year","month","day"]},{name:"processed_events",location:`s3://${s}-processed/events/`,format:"parquet",partitionKeys:["year","month","day"]}]},glue:{crawlers:[{name:`${s}-crawler`,databaseName:`${s}_analytics`,s3Targets:[`s3://${s}-raw/`,`s3://${s}-processed/`],schedule:"cron(0 2 * * ? *)"}],jobs:[{name:`${s}-etl-job`,scriptLocation:`s3://${s}-scripts/etl.py`,role:`${s}-glue-role`,maxCapacity:10,timeout:120}]}},databases:{dynamodb:{tables:{[`${s}-metadata`]:{partitionKey:{name:"pipelineId",type:"S"},sortKey:{name:"timestamp",type:"S"},billingMode:"PAY_PER_REQUEST"}}}},queues:{failedJobs:{fifo:!1,visibilityTimeout:900,messageRetentionPeriod:1209600,deadLetterQueue:!0,maxReceiveCount:3}},workflow:{pipelines:[{name:`${s}-daily-pipeline`,type:"stepFunctions",definition:{StartAt:"ExtractData",States:{ExtractData:{Type:"Task",Resource:"arn:aws:states:::lambda:invoke",Next:"TransformData"},TransformData:{Type:"Task",Resource:"arn:aws:states:::lambda:invoke",Next:"LoadData"},LoadData:{Type:"Task",Resource:"arn:aws:states:::lambda:invoke",End:!0}}},schedule:"cron(0 0 * * ? *)"}]},monitoring:{dashboard:{name:`${s}-pipeline`,widgets:[{type:"metric",metrics:["KinesisIncomingRecords","LambdaInvocations","S3ObjectsCreated","GlueJobsSucceeded"]}]},alarms:[{metric:"LambdaErrors",threshold:10,evaluationPeriods:1},{metric:"KinesisIteratorAge",threshold:60000,evaluationPeriods:2}]}}}}function WI(n){let{name:i,slug:s,domain:o,modelS3Path:c=`s3://${s}-models/`,instanceType:u="ml.t3.medium"}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:o}},infrastructure:{storage:{models:{public:!1,versioning:!0,encryption:!0,intelligentTiering:!0},datasets:{public:!1,versioning:!0,encryption:!0,lifecycleRules:[{id:"ArchiveOldDatasets",enabled:!0,transitions:[{days:90,storageClass:"GLACIER"}]}]},predictions:{public:!1,versioning:!1,encryption:!0,lifecycleRules:[{id:"DeleteOldPredictions",enabled:!0,expirationDays:30}]}},machineLearning:{sagemaker:{endpoints:[{name:`${s}-inference`,modelS3Path:c,instanceType:u,initialInstanceCount:1,autoScaling:{minInstances:1,maxInstances:5,targetInvocationsPerInstance:1000}}],trainingJobs:[{name:`${s}-training`,algorithmSpecification:{trainingImage:"TO_BE_SPECIFIED",trainingInputMode:"File"},instanceType:"ml.p3.2xlarge",instanceCount:1,volumeSizeInGB:50,maxRuntimeInSeconds:86400}]}},apiGateway:{type:"HTTP",customDomain:o?{domain:o,certificateArn:"TO_BE_GENERATED"}:void 0,cors:{allowOrigins:["*"],allowMethods:["POST"],allowHeaders:["Content-Type","Authorization"]},throttling:{rateLimit:1000,burstLimit:500}},functions:{predict:{runtime:"python3.11",handler:"handlers/predict.handler",memory:2048,timeout:60,events:[{type:"http",path:"/predict",method:"POST"}],environment:{SAGEMAKER_ENDPOINT:`${s}-inference`,MODEL_BUCKET:`${s}-models`}},"batch-predict":{runtime:"python3.11",handler:"handlers/batchPredict.handler",memory:3008,timeout:900,events:[{type:"s3",bucket:`${s}-datasets`,suffix:".csv"}]},"trigger-training":{runtime:"python3.11",handler:"handlers/training.handler",memory:1024,timeout:300,events:[{type:"schedule",expression:"cron(0 2 * * ? *)"}]}},databases:{dynamodb:{tables:{[`${s}-predictions`]:{partitionKey:{name:"requestId",type:"S"},sortKey:{name:"timestamp",type:"S"},billingMode:"PAY_PER_REQUEST",streamEnabled:!0},[`${s}-models`]:{partitionKey:{name:"modelId",type:"S"},sortKey:{name:"version",type:"S"},billingMode:"PAY_PER_REQUEST"}}}},queues:{predictions:{fifo:!1,visibilityTimeout:300,messageRetentionPeriod:86400,deadLetterQueue:!0}},monitoring:{dashboard:{name:`${s}-ml`,widgets:[{type:"metric",metrics:["SageMakerInvocations","SageMakerModelLatency","APIGatewayRequests","LambdaErrors"]}]},alarms:[{metric:"SageMakerModelLatency",threshold:1000,evaluationPeriods:2},{metric:"SageMakerInvocationErrors",threshold:10,evaluationPeriods:1}]},security:{certificate:o?{domain:o,validationMethod:"DNS"}:void 0,waf:{enabled:!0,rules:["rateLimit","apiProtection"]}}}}}function JI(n){let{name:i,slug:s,domain:o,instanceType:c="t3.medium",minInstances:u=2,maxInstances:d=10,databaseEngine:f="mysql",sessionStore:h="redis"}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"server",environments:{production:{type:"production",domain:o}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:2,natGateways:2}},compute:{server:{instanceType:c,ami:"ubuntu-22.04",autoScaling:{min:u,max:d,targetCPU:70,scaleUpCooldown:300,scaleDownCooldown:300},loadBalancer:{type:"application",healthCheck:{path:"/health",interval:30,timeout:5,healthyThreshold:2,unhealthyThreshold:3},stickySession:{enabled:!0,duration:86400}},userData:`#!/bin/bash
|
|
2454
|
+
| limit 20`,region:e.ref("AWS::Region"),title:`Logs: ${u.logGroup}`}});else if(u.type==="text"&&u.text)s.push({type:"text",x:o,y:c,width:d,height:f,properties:{markdown:u.text}});if(o+=d,o>=24)o=0,c+=f}),n.addResource("CloudWatchDashboard","AWS::CloudWatch::Dashboard",{DashboardName:e.sub(`\${AWS::StackName}-${i.name}`),DashboardBody:JSON.stringify({widgets:s})}),n.addOutputs({DashboardURL:{Description:"CloudWatch Dashboard URL",Value:e.sub("https://console.aws.amazon.com/cloudwatch/home?region=${AWS::Region}#dashboards:name=${CloudWatchDashboard}")}})}function ei(n,i,s){let o=n.toLogicalId(`${i}-log-group`);n.addResource(o,"AWS::Logs::LogGroup",{LogGroupName:e.sub(`/aws/\${AWS::StackName}/${i}`),RetentionInDays:s||14,Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${i}`)}]})}function Nt(n,i){if(i)return{ec2:"AWS/EC2",ecs:"AWS/ECS",lambda:"AWS/Lambda",rds:"AWS/RDS",dynamodb:"AWS/DynamoDB",s3:"AWS/S3",cloudfront:"AWS/CloudFront",alb:"AWS/ApplicationELB",nlb:"AWS/NetworkELB",apigateway:"AWS/ApiGateway",sqs:"AWS/SQS",sns:"AWS/SNS",kinesis:"AWS/Kinesis",elasticache:"AWS/ElastiCache"}[i.toLowerCase()]||"AWS/CloudWatch";let s=n.toLowerCase();if(s.includes("cpu")||s.includes("memory")||s.includes("network"))return"AWS/EC2";if(s.includes("lambda")||s.includes("invocation")||s.includes("duration"))return"AWS/Lambda";if(s.includes("request")||s.includes("latency")||s.includes("target"))return"AWS/ApplicationELB";if(s.includes("database")||s.includes("connection"))return"AWS/RDS";if(s.includes("read")||s.includes("write")||s.includes("consumed"))return"AWS/DynamoDB";return"AWS/CloudWatch"}function ti(n){return{ec2:[{Name:"InstanceId",Value:e.ref("EC2Instance")}],ecs:[{Name:"ClusterName",Value:e.ref("ECSCluster")},{Name:"ServiceName",Value:e.getAtt("ECSService","Name")}],lambda:[{Name:"FunctionName",Value:e.ref("LambdaFunction")}],rds:[{Name:"DBInstanceIdentifier",Value:e.ref("Database")}],dynamodb:[{Name:"TableName",Value:e.ref("DynamoDBTable")}],alb:[{Name:"LoadBalancer",Value:e.getAtt("LoadBalancer","LoadBalancerFullName")}],apigateway:[{Name:"ApiName",Value:e.ref("HttpApi")}]}[n.toLowerCase()]||[]}function Dn(n,i){if(!i.vpc)return;let{cidr:s="10.0.0.0/16",availabilityZones:o=2,natGateways:c=1,enableDnsHostnames:u=!0,enableDnsSupport:d=!0}=i.vpc;n.addResource("VPC","AWS::EC2::VPC",{CidrBlock:s,EnableDnsHostnames:u,EnableDnsSupport:d,Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-vpc")}]}),n.addResource("InternetGateway","AWS::EC2::InternetGateway",{Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-igw")}]}),n.addResource("VPCGatewayAttachment","AWS::EC2::VPCGatewayAttachment",{VpcId:e.ref("VPC"),InternetGatewayId:e.ref("InternetGateway")},{dependsOn:["VPC","InternetGateway"]});let f=[];for(let T=0;T<o;T++){let v=`PublicSubnet${T+1}`;f.push(v),n.addResource(v,"AWS::EC2::Subnet",{VpcId:e.ref("VPC"),CidrBlock:e.select(T,e.cidr(e.getAtt("VPC","CidrBlock"),o*2,8)),AvailabilityZone:e.select(T,e.getAZs()),MapPublicIpOnLaunch:!0,Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-public-${T+1}`)},{Key:"Type",Value:"public"}]},{dependsOn:"VPC"})}let h=[];for(let T=0;T<o;T++){let v=`PrivateSubnet${T+1}`;h.push(v),n.addResource(v,"AWS::EC2::Subnet",{VpcId:e.ref("VPC"),CidrBlock:e.select(T+o,e.cidr(e.getAtt("VPC","CidrBlock"),o*2,8)),AvailabilityZone:e.select(T,e.getAZs()),MapPublicIpOnLaunch:!1,Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-private-${T+1}`)},{Key:"Type",Value:"private"}]},{dependsOn:"VPC"})}let S=[];for(let T=0;T<c;T++){let v=`NatEIP${T+1}`;S.push(v),n.addResource(v,"AWS::EC2::EIP",{Domain:"vpc",Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-nat-eip-${T+1}`)}]},{dependsOn:"VPCGatewayAttachment"})}let A=[];for(let T=0;T<c;T++){let v=`NatGateway${T+1}`;A.push(v);let R=T%o;n.addResource(v,"AWS::EC2::NatGateway",{AllocationId:e.getAtt(S[T],"AllocationId"),SubnetId:e.ref(f[R]),Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-nat-${T+1}`)}]},{dependsOn:[S[T],f[R]]})}n.addResource("PublicRouteTable","AWS::EC2::RouteTable",{VpcId:e.ref("VPC"),Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-public-rt")}]},{dependsOn:"VPC"}),n.addResource("PublicRoute","AWS::EC2::Route",{RouteTableId:e.ref("PublicRouteTable"),DestinationCidrBlock:"0.0.0.0/0",GatewayId:e.ref("InternetGateway")},{dependsOn:["PublicRouteTable","VPCGatewayAttachment"]}),f.forEach((T,v)=>{n.addResource(`PublicSubnetRouteTableAssociation${v+1}`,"AWS::EC2::SubnetRouteTableAssociation",{SubnetId:e.ref(T),RouteTableId:e.ref("PublicRouteTable")},{dependsOn:[T,"PublicRouteTable"]})}),h.forEach((T,v)=>{let R=`PrivateRouteTable${v+1}`,P=v%c;n.addResource(R,"AWS::EC2::RouteTable",{VpcId:e.ref("VPC"),Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-private-rt-${v+1}`)}]},{dependsOn:"VPC"}),n.addResource(`PrivateRoute${v+1}`,"AWS::EC2::Route",{RouteTableId:e.ref(R),DestinationCidrBlock:"0.0.0.0/0",NatGatewayId:e.ref(A[P])},{dependsOn:[R,A[P]]}),n.addResource(`PrivateSubnetRouteTableAssociation${v+1}`,"AWS::EC2::SubnetRouteTableAssociation",{SubnetId:e.ref(T),RouteTableId:e.ref(R)},{dependsOn:[T,R]})}),n.addResource("S3VPCEndpoint","AWS::EC2::VPCEndpoint",{VpcId:e.ref("VPC"),ServiceName:e.sub("com.amazonaws.${AWS::Region}.s3"),VpcEndpointType:"Gateway",RouteTableIds:[e.ref("PublicRouteTable"),...Array.from({length:o},(T,v)=>e.ref(`PrivateRouteTable${v+1}`))]},{dependsOn:"VPC"}),n.addResource("NetworkAcl","AWS::EC2::NetworkAcl",{VpcId:e.ref("VPC"),Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-nacl")}]},{dependsOn:"VPC"}),n.addResource("NetworkAclEntryInbound","AWS::EC2::NetworkAclEntry",{NetworkAclId:e.ref("NetworkAcl"),RuleNumber:100,Protocol:-1,RuleAction:"allow",CidrBlock:"0.0.0.0/0"},{dependsOn:"NetworkAcl"}),n.addResource("NetworkAclEntryOutbound","AWS::EC2::NetworkAclEntry",{NetworkAclId:e.ref("NetworkAcl"),RuleNumber:100,Protocol:-1,Egress:!0,RuleAction:"allow",CidrBlock:"0.0.0.0/0"},{dependsOn:"NetworkAcl"}),n.addOutputs({VPCId:{Description:"VPC ID",Value:e.ref("VPC"),Export:{Name:e.sub("${AWS::StackName}-VPC")}},PublicSubnets:{Description:"Public subnet IDs",Value:e.join(",",f.map((T)=>e.ref(T))),Export:{Name:e.sub("${AWS::StackName}-PublicSubnets")}},PrivateSubnets:{Description:"Private subnet IDs",Value:e.join(",",h.map((T)=>e.ref(T))),Export:{Name:e.sub("${AWS::StackName}-PrivateSubnets")}}})}function Nn(n,i){for(let[s,o]of Object.entries(i))ni(n,s,o)}function ni(n,i,s){let o=n.toLogicalId(`${i}-queue`),c=s.fifo||!1,u;if(s.deadLetterQueue){let f=`${o}DLQ`;n.addResource(f,"AWS::SQS::Queue",{QueueName:c?e.sub(`\${AWS::StackName}-${i}-dlq.fifo`):e.sub(`\${AWS::StackName}-${i}-dlq`),FifoQueue:c,MessageRetentionPeriod:1209600,Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${i}-dlq`)}]},{deletionPolicy:"Retain",updateReplacePolicy:"Retain"}),u=e.getAtt(f,"Arn")}let d={QueueName:c?e.sub(`\${AWS::StackName}-${i}.fifo`):e.sub(`\${AWS::StackName}-${i}`),FifoQueue:c,VisibilityTimeout:s.visibilityTimeout||30,MessageRetentionPeriod:s.messageRetentionPeriod||345600,ReceiveMessageWaitTimeSeconds:s.receiveMessageWaitTime||0,Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${i}`)}]};if(c&&s.contentBasedDeduplication)d.ContentBasedDeduplication=!0;if(s.deadLetterQueue&&u)d.RedrivePolicy={deadLetterTargetArn:u,maxReceiveCount:s.maxReceiveCount||3};if(n.addResource(o,"AWS::SQS::Queue",d,{dependsOn:s.deadLetterQueue?`${o}DLQ`:void 0,deletionPolicy:"Retain",updateReplacePolicy:"Retain"}),n.addResource(`${o}Policy`,"AWS::SQS::QueuePolicy",{Queues:[e.ref(o)],PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:["lambda.amazonaws.com","events.amazonaws.com","sns.amazonaws.com"]},Action:"sqs:SendMessage",Resource:e.getAtt(o,"Arn"),Condition:{ArnEquals:{"aws:SourceArn":e.sub("arn:aws:*:${AWS::Region}:${AWS::AccountId}:*")}}}]}},{dependsOn:o}),n.addOutputs({[`${o}Url`]:{Description:`${i} queue URL`,Value:e.ref(o),Export:{Name:e.sub(`\${AWS::StackName}-${i}-queue-url`)}},[`${o}Arn`]:{Description:`${i} queue ARN`,Value:e.getAtt(o,"Arn"),Export:{Name:e.sub(`\${AWS::StackName}-${i}-queue-arn`)}}}),s.deadLetterQueue)n.addOutputs({[`${o}DLQUrl`]:{Description:`${i} dead letter queue URL`,Value:e.ref(`${o}DLQ`),Export:{Name:e.sub(`\${AWS::StackName}-${i}-dlq-url`)}}})}function xn(n,i){if(i.certificate)ri(n,i.certificate);if(i.waf?.enabled)ii(n,i.waf);if(i.securityGroups)for(let[s,o]of Object.entries(i.securityGroups))ai(n,s,o)}function ri(n,i){if(!i)return;let s=[i.domain];if(i.subdomains)s.push(...i.subdomains);n.addResource("Certificate","AWS::CertificateManager::Certificate",{DomainName:i.domain,SubjectAlternativeNames:i.subdomains,ValidationMethod:i.validationMethod||"DNS",DomainValidationOptions:s.map((o)=>({DomainName:o,HostedZoneId:e.ref("HostedZone")})),Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-certificate")}]}),n.addOutputs({CertificateArn:{Description:"ACM Certificate ARN",Value:e.ref("Certificate"),Export:{Name:e.sub("${AWS::StackName}-certificate-arn")}}})}function ii(n,i){if(!i)return;let s=[],o=i.rules||["rateLimit","sqlInjection","xss"];if(o.includes("rateLimit"))s.push({Name:"RateLimitRule",Priority:1,Statement:{RateBasedStatement:{Limit:i.rateLimit||2000,AggregateKeyType:"IP"}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"RateLimitRule"}});let c=s.length+1;if(o.includes("sqlInjection"))s.push({Name:"AWSManagedRulesSQLi",Priority:c++,Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:"AWSManagedRulesSQLiRuleSet"}},OverrideAction:{None:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"AWSManagedRulesSQLi"}});if(o.includes("xss"))s.push({Name:"AWSManagedRulesXSS",Priority:c++,Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:"AWSManagedRulesKnownBadInputsRuleSet"}},OverrideAction:{None:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"AWSManagedRulesXSS"}});if(o.includes("knownBadInputs"))s.push({Name:"AWSManagedRulesKnownBadInputs",Priority:c++,Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:"AWSManagedRulesKnownBadInputsRuleSet"}},OverrideAction:{None:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"AWSManagedRulesKnownBadInputs"}});if(o.includes("coreRuleSet"))s.push({Name:"AWSManagedRulesCoreRuleSet",Priority:c++,Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:"AWSManagedRulesCommonRuleSet"}},OverrideAction:{None:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"AWSManagedRulesCoreRuleSet"}});if(o.includes("linuxRuleSet"))s.push({Name:"AWSManagedRulesLinuxRuleSet",Priority:c++,Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:"AWSManagedRulesLinuxRuleSet"}},OverrideAction:{None:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"AWSManagedRulesLinuxRuleSet"}});if(o.includes("apiProtection"))s.push({Name:"AWSManagedRulesAPIProtection",Priority:c++,Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:"AWSManagedRulesAmazonIpReputationList"}},OverrideAction:{None:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"AWSManagedRulesAPIProtection"}});if(o.includes("geoBlock"))s.push({Name:"GeoBlockRule",Priority:c++,Statement:{GeoMatchStatement:{CountryCodes:["CN","RU"]}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"GeoBlockRule"}});if(o.includes("connectionLimit"))s.push({Name:"ConnectionLimitRule",Priority:c++,Statement:{RateBasedStatement:{Limit:100,AggregateKeyType:"IP"}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"ConnectionLimitRule"}});if(n.addResource("WebACL","AWS::WAFv2::WebACL",{Name:e.sub("${AWS::StackName}-waf"),Scope:i.scope||"REGIONAL",DefaultAction:{Allow:{}},Rules:s,VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:e.sub("${AWS::StackName}-waf")},Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-waf")}]}),n.hasResource("LoadBalancer"))n.addResource("WebACLAssociation","AWS::WAFv2::WebACLAssociation",{ResourceArn:e.ref("LoadBalancer"),WebACLArn:e.getAtt("WebACL","Arn")},{dependsOn:["WebACL","LoadBalancer"]});n.addOutputs({WebACLId:{Description:"WAF Web ACL ID",Value:e.ref("WebACL"),Export:{Name:e.sub("${AWS::StackName}-waf-id")}},WebACLArn:{Description:"WAF Web ACL ARN",Value:e.getAtt("WebACL","Arn"),Export:{Name:e.sub("${AWS::StackName}-waf-arn")}}})}function ai(n,i,s){if(!s)return;let o=n.toLogicalId(`${i}-security-group`),c=s.ingress?.map((d)=>({IpProtocol:d.protocol,FromPort:d.port,ToPort:d.port,CidrIp:d.cidr,SourceSecurityGroupId:d.source?e.ref(d.source):void 0}))||[],u=s.egress?.map((d)=>({IpProtocol:d.protocol,FromPort:d.port,ToPort:d.port,CidrIp:d.cidr||"0.0.0.0/0"}))||[{IpProtocol:"-1",CidrIp:"0.0.0.0/0"}];n.addResource(o,"AWS::EC2::SecurityGroup",{GroupDescription:`Security group for ${i}`,VpcId:e.ref("VPC"),SecurityGroupIngress:c,SecurityGroupEgress:u,Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${i}-sg`)}]},{dependsOn:"VPC"}),n.addOutputs({[`${o}Id`]:{Description:`${i} security group ID`,Value:e.ref(o),Export:{Name:e.sub(`\${AWS::StackName}-${i}-sg-id`)}}})}function kn(n,i){for(let[s,o]of Object.entries(i)){if(o.type==="efs"){oi(n,s,o);continue}si(n,s,o)}}function si(n,i,s){let o=n.toLogicalId(`${i}-bucket`),c={BucketName:e.sub(`\${AWS::StackName}-${i}`),Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${i}`)}]};if(s.versioning)c.VersioningConfiguration={Status:"Enabled"};if(s.encryption)c.BucketEncryption={ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]};if(!s.public)c.PublicAccessBlockConfiguration={BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0};if(s.website)c.WebsiteConfiguration={IndexDocument:"index.html",ErrorDocument:"index.html"};if(s.cors&&s.cors.length>0)c.CorsConfiguration={CorsRules:s.cors.map((u)=>({AllowedOrigins:u.allowedOrigins,AllowedMethods:u.allowedMethods,AllowedHeaders:u.allowedHeaders||["*"],MaxAge:u.maxAge||3600}))};if(s.lifecycleRules&&s.lifecycleRules.length>0)c.LifecycleConfiguration={Rules:s.lifecycleRules.map((u)=>({Id:u.id,Status:u.enabled?"Enabled":"Disabled",ExpirationInDays:u.expirationDays,Transitions:u.transitions?.map((d)=>({TransitionInDays:d.days,StorageClass:d.storageClass}))}))};if(s.intelligentTiering)c.IntelligentTieringConfigurations=[{Id:"EntireBucket",Status:"Enabled",Tierings:[{AccessTier:"ARCHIVE_ACCESS",Days:90},{AccessTier:"DEEP_ARCHIVE_ACCESS",Days:180}]}];if(n.addResource(o,"AWS::S3::Bucket",c,{deletionPolicy:s.versioning?"Retain":"Delete"}),s.public)n.addResource(`${o}Policy`,"AWS::S3::BucketPolicy",{Bucket:e.ref(o),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadGetObject",Effect:"Allow",Principal:"*",Action:"s3:GetObject",Resource:e.join("",[cn.s3Bucket(e.ref(o)),"/*"])}]}},{dependsOn:o});if(n.addOutputs({[`${o}Name`]:{Description:`${i} bucket name`,Value:e.ref(o),Export:{Name:e.sub(`\${AWS::StackName}-${i}-bucket`)}},[`${o}Arn`]:{Description:`${i} bucket ARN`,Value:e.getAtt(o,"Arn"),Export:{Name:e.sub(`\${AWS::StackName}-${i}-bucket-arn`)}}}),s.website)n.addOutputs({[`${o}WebsiteURL`]:{Description:`${i} website URL`,Value:e.getAtt(o,"WebsiteURL")}})}function oi(n,i,s){let o=n.toLogicalId(`${i}-efs`),c={Encrypted:s.encryption!==!1,PerformanceMode:s.performanceMode||"generalPurpose",ThroughputMode:s.throughputMode||"bursting",FileSystemTags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${i}`)}]};if(s.lifecyclePolicy){if(c.LifecyclePolicies=[],s.lifecyclePolicy.transitionToIA)c.LifecyclePolicies.push({TransitionToIA:`AFTER_${s.lifecyclePolicy.transitionToIA}_DAYS`});if(s.lifecyclePolicy.transitionToPrimaryStorageClass)c.LifecyclePolicies.push({TransitionToPrimaryStorageClass:"AFTER_1_ACCESS"})}n.addResource(o,"AWS::EFS::FileSystem",c,{deletionPolicy:"Retain"});let u=2;for(let d=0;d<u;d++)n.addResource(`${o}MountTarget${d+1}`,"AWS::EFS::MountTarget",{FileSystemId:e.ref(o),SubnetId:e.ref(`PrivateSubnet${d+1}`),SecurityGroups:[e.ref("EFSSecurityGroup")]},{dependsOn:[o,`PrivateSubnet${d+1}`]});n.addResource("EFSSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for EFS mount targets",VpcId:e.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:2049,ToPort:2049,SourceSecurityGroupId:e.ref("AppSecurityGroup")}],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-efs-sg")}]},{dependsOn:"VPC"}),n.addOutputs({[`${o}Id`]:{Description:`${i} EFS file system ID`,Value:e.ref(o),Export:{Name:e.sub(`\${AWS::StackName}-${i}-efs`)}}})}class Am{template;config;resourceDependencies;constructor(n){this.config=n,this.resourceDependencies=new Map,this.template={AWSTemplateFormatVersion:"2010-09-09",Description:`Infrastructure for ${n.project.name} (${n.project.slug})`,Resources:{}}}build(){return this.addParameters(),this.addMappings(),this.addConditions(),this.addResources(),this.initializeOutputs(),this.resolveDependencies(),this.template}addParameters(){this.template.Parameters={Environment:{Type:"String",Default:"production",AllowedValues:["development","staging","production"],Description:"Environment name"}}}addMappings(){this.template.Mappings={RegionMap:{"us-east-1":{AMI:"ami-0f3caa1cf4417e51b"},"us-west-2":{AMI:"ami-0d1cd67c26f5fca19"},"eu-west-1":{AMI:"ami-0bbc25e23a7640b9b"}}}}addConditions(){this.template.Conditions={IsProduction:e.equals(e.ref("Environment"),"production"),HasDomain:e.not([e.equals(this.config.environments?.production?.domain||"","")])}}addResources(){let{infrastructure:n}=this.config;if(!n)return;if(n.network)this.addNetworkResources(n.network);if(n.storage)this.addStorageResources(n.storage);if(n.compute)this.addComputeResources(n.compute);if(n.databases)this.addDatabaseResources(n.databases);if(n.cache)this.addCacheResources(n.cache);if(n.cdn)this.addCDNResources(n.cdn);if(n.apiGateway)this.addApiGatewayResources(n.apiGateway);if(n.functions)this.addFunctionResources(n.functions);if(n.queues)this.addQueueResources(n.queues);if(n.messaging)this.addMessagingResources(n.messaging);if(n.monitoring)this.addMonitoringResources(n.monitoring);if(n.security)this.addSecurityResources(n.security)}initializeOutputs(){let n=this.template.Outputs||{};if(this.template.Outputs={StackName:{Description:"Stack name",Value:e.ref("AWS::StackName"),Export:{Name:e.sub("${AWS::StackName}-Name")}},Region:{Description:"AWS Region",Value:e.ref("AWS::Region"),Export:{Name:e.sub("${AWS::StackName}-Region")}},...n},this.config.environments?.production?.domain)this.template.Outputs.Domain={Description:"Production domain",Value:this.config.environments.production.domain,Condition:"HasDomain"}}addResource(n,i,s,o){let c={Type:i,Properties:s};if(o?.dependsOn)c.DependsOn=o.dependsOn,this.trackDependency(n,o.dependsOn);if(o?.condition)c.Condition=o.condition;if(o?.deletionPolicy)c.DeletionPolicy=o.deletionPolicy;if(o?.updateReplacePolicy)c.UpdateReplacePolicy=o.updateReplacePolicy;this.template.Resources[n]=c}addOutputs(n){this.template.Outputs={...this.template.Outputs,...n}}getOutputs(){return this.template.Outputs||{}}hasResource(n){return n in this.template.Resources}getResource(n){return this.template.Resources[n]}trackDependency(n,i){if(!this.resourceDependencies.has(n))this.resourceDependencies.set(n,new Set);(Array.isArray(i)?i:[i]).forEach((o)=>this.resourceDependencies.get(n).add(o))}resolveDependencies(){let n=new Set,i=new Set,s=(o)=>{if(i.has(o))throw Error(`Circular dependency detected involving resource: ${o}`);if(n.has(o))return!0;n.add(o),i.add(o);let c=this.resourceDependencies.get(o);if(c)for(let u of c)s(u);return i.delete(o),!0};for(let o of this.resourceDependencies.keys())s(o)}toLogicalId(n){return n.split(/[-_\s]/).map((i)=>i.charAt(0).toUpperCase()+i.slice(1).toLowerCase()).join("")}addNetworkResources(n){Dn(this,n)}addStorageResources(n){kn(this,n)}addComputeResources(n){Tn(this,n)}addDatabaseResources(n){Pn(this,n)}addFunctionResources(n){En(this,n)}addCacheResources(n){An(this,n)}addQueueResources(n){Nn(this,n)}addMessagingResources(n){wn(this,n)}addCDNResources(n){Cn(this,n)}addApiGatewayResources(n){Sn(this,n)}addMonitoringResources(n){In(this,n)}addSecurityResources(n){xn(this,n)}}function il(n){return new Am(n).build()}function MI(n){let{name:i,slug:s,domain:o,subdomain:c}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:c&&o?`${c}.${o}`:o}},infrastructure:{storage:{assets:{public:!0,versioning:!1,website:!0,encryption:!1,cors:[{allowedOrigins:["*"],allowedMethods:["GET","HEAD"],allowedHeaders:["*"],maxAge:3600}]}},cdn:{enabled:!0,customDomain:o?{domain:c&&o?`${c}.${o}`:o,certificateArn:"TO_BE_GENERATED"}:void 0,cachePolicy:{minTTL:0,defaultTTL:86400,maxTTL:31536000},compress:!0,http3:!0,errorPages:{404:"/index.html",403:"/index.html"}}}}}function FI(n){let{name:i,slug:s,domain:o,instanceType:c="t3.small",minInstances:u=2,maxInstances:d=10}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"server",environments:{production:{type:"production",domain:o}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:2,natGateways:1}},compute:{server:{instanceType:c,ami:"ubuntu-22.04",keyPair:`${s}-key`,autoScaling:{min:u,max:d,desired:u,targetCPU:70},loadBalancer:{type:"application",healthCheck:{path:"/health",interval:30,timeout:5,healthyThreshold:2,unhealthyThreshold:3}},userData:{packages:["nodejs","npm","nginx"],commands:["curl -fsSL https://bun.sh/install | bash","npm install -g pm2"]}}},databases:{postgres:{engine:"postgres",version:"15",instanceClass:"db.t3.micro",allocatedStorage:20,multiAZ:!0,backupRetentionDays:7,deletionProtection:!0}},cache:{redis:{nodeType:"cache.t3.micro",numCacheNodes:1,engine:"redis",engineVersion:"7.0"}},security:{certificate:o?{domain:o,subdomains:[`*.${o}`],validationMethod:"DNS"}:void 0}}}}function UI(n){let{name:i,slug:s,domain:o,taskCpu:c="256",taskMemory:u="512",desiredCount:d=2}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:o}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:2,natGateways:0}},compute:{fargate:{taskDefinition:{cpu:c,memory:u,containerDefinitions:[{name:"app",image:`${s}-app:latest`,portMappings:[{containerPort:3000}],environment:[],secrets:[]}]},service:{desiredCount:d,healthCheck:{path:"/health",interval:30,timeout:5,healthyThreshold:2,unhealthyThreshold:3},autoScaling:{min:d,max:d*5,targetCPU:70,targetMemory:80}},loadBalancer:{type:"application"}}},databases:{dynamodb:{tables:{[`${s}-main`]:{partitionKey:{name:"id",type:"S"},sortKey:{name:"createdAt",type:"S"},billingMode:"PAY_PER_REQUEST",streamEnabled:!0,pointInTimeRecovery:!0}}}},functions:{"process-queue":{runtime:"nodejs20.x",handler:"dist/workers/queue.handler",memory:512,timeout:60,events:[{type:"sqs",queueName:`${s}-queue`}]}},security:{certificate:o?{domain:o,subdomains:[`*.${o}`],validationMethod:"DNS"}:void 0}}}}function QI(n){let{name:i,slug:s,entry:o,domain:c,runtime:u="nodejs20.x",memory:d=1024,build:f,deploy:h,assets:S,queues:A=!0,scheduler:T="on",region:v="us-east-1"}=n;return{project:{name:i,slug:s,region:v},mode:"serverless",environments:{production:{type:"production",domain:c,app:{kind:"node",runtime:u,entry:o,memory:d,build:f,deploy:h,assets:S,queues:A,scheduler:T,domain:c}}}}}function sl(n){let i=n.database!==!1,s=n.cache!==!1,o=n.queue!==!1;return{project:{name:n.name,slug:n.slug,region:"us-east-1"},mode:"server",environments:{production:{type:"production",domain:n.domain}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:2,natGateways:1}},compute:{fargate:{taskDefinition:{cpu:"256",memory:"512",containerDefinitions:[{name:"api",image:n.imageUri,portMappings:[{containerPort:3000}],environment:[{name:"NODE_ENV",value:"production"},{name:"PORT",value:"3000"},{name:"AWS_REGION",value:e.ref("AWS::Region")},...i?[{name:"DB_HOST",value:e.getAtt("PostgresDb","Endpoint.Address")},{name:"DB_PORT",value:e.getAtt("PostgresDb","Endpoint.Port")}]:[],...s?[{name:"REDIS_HOST",value:e.getAtt("RedisReplicationGroup","PrimaryEndPoint.Address")},{name:"REDIS_PORT",value:e.getAtt("RedisReplicationGroup","PrimaryEndPoint.Port")},{name:"REDIS_TLS",value:"true"}]:[],...o?[{name:"QUEUE_URL",value:e.ref("JobsQueue")}]:[],{name:"MAIL_TRANSPORT",value:"ses"}],secrets:i?[{name:"DB_USERNAME",valueFrom:e.sub("${DBSecret}:username::")},{name:"DB_PASSWORD",valueFrom:e.sub("${DBSecret}:password::")}]:[]}]},service:{desiredCount:n.desiredCount||1,healthCheck:{path:"/api/health",interval:30,timeout:5},autoScaling:{min:n.desiredCount||1,max:6,targetCPU:70}},loadBalancer:{type:"application",...n.certificateArn?{customDomain:{domain:n.domain,certificateArn:n.certificateArn}}:{},...n.originVerifySecret?{originVerifyHeader:{name:"X-Origin-Verify",value:n.originVerifySecret}}:{}}}},...i?{databases:{postgres:{engine:"postgres",version:"16",instanceClass:"db.t4g.micro",allocatedStorage:20,maxAllocatedStorage:100,multiAZ:!1,backupRetentionDays:7,deletionProtection:!0}}}:{},...s?{cache:{redis:{nodeType:"cache.t4g.micro",numCacheNodes:2,engine:"redis",engineVersion:"7.1",automaticFailoverEnabled:!0,snapshotRetentionLimit:5}}}:{},...o?{queues:{jobs:{fifo:!1,visibilityTimeout:300,messageRetentionPeriod:345600,deadLetterQueue:!0,maxReceiveCount:3,receiveMessageWaitTime:20}}}:{}}}}function HI(n){let{name:i,slug:s,domain:o,apiSubdomain:c="api"}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"server",environments:{production:{type:"production",domain:o}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:2,natGateways:1}},storage:{frontend:{public:!0,versioning:!0,website:!0,encryption:!1}},cdn:{enabled:!0,customDomain:{domain:o,certificateArn:"TO_BE_GENERATED"},cachePolicy:{minTTL:0,defaultTTL:86400,maxTTL:31536000},compress:!0,http3:!0,errorPages:{404:"/index.html"}},compute:{fargate:{taskDefinition:{cpu:"512",memory:"1024",containerDefinitions:[{name:"api",image:`${s}-api:latest`,portMappings:[{containerPort:3000}]}]},service:{desiredCount:2,healthCheck:{path:"/api/health",interval:30},autoScaling:{min:2,max:10,targetCPU:70}},loadBalancer:{type:"application",customDomain:{domain:`${c}.${o}`,certificateArn:"TO_BE_GENERATED"}}}},databases:{postgres:{engine:"postgres",version:"15",instanceClass:"db.t3.small",allocatedStorage:50,multiAZ:!0,backupRetentionDays:14,deletionProtection:!0}},cache:{redis:{nodeType:"cache.t3.small",numCacheNodes:2,engine:"redis",engineVersion:"7.0"}},queues:{jobs:{fifo:!1,visibilityTimeout:300,messageRetentionPeriod:345600,deadLetterQueue:!0}},security:{certificate:{domain:o,subdomains:[`*.${o}`],validationMethod:"DNS"},waf:{enabled:!0,rules:["rateLimit","sqlInjection","xss"]}}}}}function GI(n){let{name:i,slug:s,domain:o}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:o}},infrastructure:{apiGateway:{type:"HTTP",cors:{allowOrigins:["*"],allowMethods:["GET","POST","PUT","DELETE","PATCH"],allowHeaders:["Content-Type","Authorization"],maxAge:3600},customDomain:o?{domain:o,certificateArn:"TO_BE_GENERATED"}:void 0,throttling:{rateLimit:1e4,burstLimit:5000},authorizer:{type:"JWT",identitySource:"$request.header.Authorization"}},functions:{users:{runtime:"nodejs20.x",handler:"dist/api/users.handler",memory:512,timeout:30,events:[{type:"http",path:"/users",method:"GET"},{type:"http",path:"/users",method:"POST"}]},products:{runtime:"nodejs20.x",handler:"dist/api/products.handler",memory:512,timeout:30,events:[{type:"http",path:"/products",method:"GET"}]}},databases:{dynamodb:{tables:{[`${s}-users`]:{partitionKey:{name:"userId",type:"S"},billingMode:"PAY_PER_REQUEST",streamEnabled:!0,pointInTimeRecovery:!0,globalSecondaryIndexes:[{name:"EmailIndex",partitionKey:{name:"email",type:"S"},projection:"ALL"}]},[`${s}-products`]:{partitionKey:{name:"productId",type:"S"},sortKey:{name:"category",type:"S"},billingMode:"PAY_PER_REQUEST",streamEnabled:!1}}}},cache:{elasticache:{nodeType:"cache.t3.micro",numCacheNodes:1,engine:"redis",engineVersion:"7.0"}},security:{certificate:o?{domain:o,validationMethod:"DNS"}:void 0,waf:{enabled:!0,rules:["rateLimit","sqlInjection"]}},monitoring:{alarms:[{metric:"Errors",threshold:10,period:300,evaluationPeriods:1},{metric:"Duration",threshold:3000,period:300,evaluationPeriods:2}]}}}}function VI(n){let{name:i,slug:s,domain:o,instanceType:c="t3.small"}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"server",environments:{production:{type:"production",domain:o}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:2,natGateways:1}},compute:{server:{instanceType:c,ami:"ubuntu-22.04",keyPair:`${s}-key`,autoScaling:{min:2,max:6,desired:2,targetCPU:75},loadBalancer:{type:"application",healthCheck:{path:"/wp-admin/install.php",interval:30}},userData:{packages:["nginx","php8.1-fpm","php8.1-mysql","php8.1-curl","php8.1-gd","php8.1-mbstring","php8.1-xml","php8.1-zip"],commands:["cd /var/www","wget https://wordpress.org/latest.tar.gz","tar -xzf latest.tar.gz","chown -R www-data:www-data wordpress","rm /etc/nginx/sites-enabled/default","systemctl restart nginx","systemctl restart php8.1-fpm"]}}},fileSystem:{uploads:{performanceMode:"generalPurpose",throughputMode:"bursting",encrypted:!0,lifecyclePolicy:{transitionToIA:30},mountPath:"/var/www/wordpress/wp-content/uploads"}},databases:{mysql:{engine:"mysql",version:"8.0",instanceClass:"db.t3.small",allocatedStorage:50,multiAZ:!0,backupRetentionDays:7,deletionProtection:!0,databaseName:"wordpress"}},cache:{redis:{nodeType:"cache.t3.micro",numCacheNodes:1,engine:"redis",engineVersion:"7.0"}},cdn:{enabled:!0,customDomain:{domain:o,certificateArn:"TO_BE_GENERATED"},cachePolicy:{minTTL:0,defaultTTL:86400,maxTTL:31536000},compress:!0,origins:[{type:"alb",pathPattern:"/wp-content/*"}]},security:{certificate:{domain:o,subdomains:[`www.${o}`],validationMethod:"DNS"},waf:{enabled:!0,rules:["rateLimit","sqlInjection","xss","wordpressRules"]}}}}}function qI(n){let{name:i,slug:s,domain:o,apiDomain:c}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:o}},infrastructure:{storage:{static:{public:!0,versioning:!0,website:!0,encryption:!1,cors:[{allowedOrigins:["*"],allowedMethods:["GET","HEAD"]}],lifecycleRules:[{id:"DeleteOldVersions",enabled:!0,expirationDays:90}]}},cdn:{enabled:!0,customDomain:{domain:o,certificateArn:"TO_BE_GENERATED"},cachePolicy:{minTTL:0,defaultTTL:0,maxTTL:31536000},compress:!0,http3:!0,errorPages:{404:"/404.html",500:"/500.html"},edgeFunctions:[{eventType:"origin-request",functionArn:"TO_BE_CREATED",name:"ssr-handler"}]},functions:{ssr:{runtime:"nodejs20.x",handler:"dist/edge/ssr.handler",memory:512,timeout:5},...c?{api:{runtime:"nodejs20.x",handler:"dist/api/index.handler",memory:1024,timeout:30,events:[{type:"http",path:"/{proxy+}",method:"ANY"}]}}:{}},apiGateway:c?{type:"HTTP",customDomain:{domain:c,certificateArn:"TO_BE_GENERATED"},cors:{allowOrigins:[o],allowMethods:["GET","POST","PUT","DELETE"],allowHeaders:["Content-Type","Authorization"]}}:void 0,databases:{dynamodb:{tables:{content:{partitionKey:{name:"id",type:"S"},sortKey:{name:"type",type:"S"},billingMode:"PAY_PER_REQUEST",streamEnabled:!1}}}},security:{certificate:{domain:o,subdomains:c?[c]:[],validationMethod:"DNS"},waf:{enabled:!0,rules:["rateLimit","geoBlock"]}}}}}function jI(n){let{name:i,slug:s,domain:o,services:c}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:o}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:3,natGateways:2}},compute:{services:c.map((u)=>({name:u.name,type:"fargate",taskDefinition:{cpu:u.cpu||"256",memory:u.memory||"512",containerDefinitions:[{name:u.name,image:`${s}-${u.name}:latest`,portMappings:[{containerPort:u.port}],healthCheck:{command:["CMD-SHELL",`curl -f http://localhost:${u.port}/health || exit 1`],interval:30,timeout:5,retries:3}}]},service:{desiredCount:u.desiredCount||2,serviceDiscovery:{enabled:!0,namespace:`${s}.local`},autoScaling:{min:2,max:10,targetCPU:70}}}))},apiGateway:{type:"HTTP",customDomain:{domain:o,certificateArn:"TO_BE_GENERATED"},cors:{allowOrigins:["*"],allowMethods:["GET","POST","PUT","DELETE","PATCH"]},routes:c.map((u)=>({path:`/${u.name}/{proxy+}`,integration:{type:"vpc-link",service:u.name}}))},databases:{dynamodb:{tables:Object.fromEntries(c.map((u)=>[`${s}-${u.name}`,{partitionKey:{name:"id",type:"S"},billingMode:"PAY_PER_REQUEST",streamEnabled:!0,pointInTimeRecovery:!0}]))}},queues:{events:{fifo:!1,visibilityTimeout:300,messageRetentionPeriod:345600,deadLetterQueue:!0}},messaging:{topics:{events:{name:`${s}-events`,subscriptions:c.map((u)=>({protocol:"sqs",endpoint:`${s}-${u.name}-queue`,filterPolicy:{service:[u.name]}}))}}},monitoring:{dashboard:{name:`${s}-microservices`,widgets:c.map((u)=>({type:"metric",metrics:[{service:u.name,metric:"CPUUtilization"},{service:u.name,metric:"MemoryUtilization"},{service:u.name,metric:"RequestCount"}]}))},alarms:c.flatMap((u)=>[{name:`${u.name}-high-cpu`,metric:"CPUUtilization",threshold:80,service:u.name},{name:`${u.name}-errors`,metric:"Errors",threshold:10,service:u.name}])},security:{certificate:{domain:o,validationMethod:"DNS"},waf:{enabled:!0,rules:["rateLimit","sqlInjection"]}}}}}function zI(n){let{name:i,slug:s,domain:o}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:o}},infrastructure:{apiGateway:{type:"websocket",customDomain:o?{domain:o,certificateArn:"TO_BE_GENERATED"}:void 0,routes:[{path:"$connect",method:"WEBSOCKET",integration:"websocket-connect"},{path:"$disconnect",method:"WEBSOCKET",integration:"websocket-disconnect"},{path:"$default",method:"WEBSOCKET",integration:"websocket-default"},{path:"sendMessage",method:"WEBSOCKET",integration:"websocket-send-message"},{path:"joinRoom",method:"WEBSOCKET",integration:"websocket-join-room"}]},functions:{connect:{runtime:"nodejs20.x",handler:"dist/websocket/connect.handler",memory:512,timeout:30},disconnect:{runtime:"nodejs20.x",handler:"dist/websocket/disconnect.handler",memory:512,timeout:30},default:{runtime:"nodejs20.x",handler:"dist/websocket/default.handler",memory:512,timeout:30},"send-message":{runtime:"nodejs20.x",handler:"dist/websocket/sendMessage.handler",memory:512,timeout:30},"join-room":{runtime:"nodejs20.x",handler:"dist/websocket/joinRoom.handler",memory:512,timeout:30},broadcast:{runtime:"nodejs20.x",handler:"dist/streams/broadcast.handler",memory:1024,timeout:60,events:[{type:"dynamodb-stream",tableName:`${s}-messages`,startingPosition:"LATEST",batchSize:100}]}},databases:{dynamodb:{tables:{[`${s}-connections`]:{partitionKey:{name:"connectionId",type:"S"},billingMode:"PAY_PER_REQUEST",globalSecondaryIndexes:[{name:"RoomIndex",partitionKey:{name:"roomId",type:"S"},sortKey:{name:"connectionId",type:"S"},projection:"ALL"}]},[`${s}-messages`]:{partitionKey:{name:"roomId",type:"S"},sortKey:{name:"timestamp",type:"S"},billingMode:"PAY_PER_REQUEST",streamEnabled:!0,pointInTimeRecovery:!0,globalSecondaryIndexes:[{name:"UserIndex",partitionKey:{name:"userId",type:"S"},sortKey:{name:"timestamp",type:"S"},projection:"ALL"}]},[`${s}-rooms`]:{partitionKey:{name:"roomId",type:"S"},billingMode:"PAY_PER_REQUEST"}}}},cache:{elasticache:{nodeType:"cache.t3.small",numCacheNodes:2,engine:"redis",engineVersion:"7.0"}},monitoring:{alarms:[{metric:"WebSocketConnections",threshold:1e4,evaluationPeriods:1},{metric:"IntegrationLatency",threshold:1000,evaluationPeriods:2}],dashboard:{name:`${s}-realtime`,widgets:[{type:"metric",metrics:["WebSocketConnections","MessagesSent","IntegrationLatency"]}]}},security:{certificate:o?{domain:o,validationMethod:"DNS"}:void 0,waf:{enabled:!0,rules:["rateLimit","connectionLimit"]}}}}}function KI(n){let{name:i,slug:s,retentionDays:o=7}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"serverless",infrastructure:{streaming:{dataStream:{name:`${s}-stream`,shardCount:2,retentionPeriod:o*24,encryption:!0}},storage:{raw:{public:!1,versioning:!0,encryption:!0,intelligentTiering:!0,lifecycleRules:[{id:"ArchiveOldData",enabled:!0,transitions:[{days:30,storageClass:"GLACIER"},{days:90,storageClass:"DEEP_ARCHIVE"}]}]},processed:{public:!1,versioning:!0,encryption:!0,intelligentTiering:!0}},functions:{"stream-processor":{runtime:"nodejs20.x",handler:"dist/processors/stream.handler",memory:2048,timeout:300,events:[{type:"kinesis",streamName:`${s}-stream`,batchSize:1000,startingPosition:"LATEST",parallelizationFactor:10}]},transformer:{runtime:"nodejs20.x",handler:"dist/processors/transform.handler",memory:3008,timeout:900,events:[{type:"s3",bucket:`${s}-raw`,prefix:"incoming/"}]},aggregator:{runtime:"nodejs20.x",handler:"dist/processors/aggregate.handler",memory:2048,timeout:600,events:[{type:"schedule",expression:"cron(0 * * * ? *)"}]}},analytics:{athena:{database:`${s}_analytics`,workgroup:`${s}-workgroup`,outputBucket:`${s}-query-results`,tables:[{name:"raw_events",location:`s3://${s}-raw/events/`,format:"parquet",partitionKeys:["year","month","day"]},{name:"processed_events",location:`s3://${s}-processed/events/`,format:"parquet",partitionKeys:["year","month","day"]}]},glue:{crawlers:[{name:`${s}-crawler`,databaseName:`${s}_analytics`,s3Targets:[`s3://${s}-raw/`,`s3://${s}-processed/`],schedule:"cron(0 2 * * ? *)"}],jobs:[{name:`${s}-etl-job`,scriptLocation:`s3://${s}-scripts/etl.py`,role:`${s}-glue-role`,maxCapacity:10,timeout:120}]}},databases:{dynamodb:{tables:{[`${s}-metadata`]:{partitionKey:{name:"pipelineId",type:"S"},sortKey:{name:"timestamp",type:"S"},billingMode:"PAY_PER_REQUEST"}}}},queues:{failedJobs:{fifo:!1,visibilityTimeout:900,messageRetentionPeriod:1209600,deadLetterQueue:!0,maxReceiveCount:3}},workflow:{pipelines:[{name:`${s}-daily-pipeline`,type:"stepFunctions",definition:{StartAt:"ExtractData",States:{ExtractData:{Type:"Task",Resource:"arn:aws:states:::lambda:invoke",Next:"TransformData"},TransformData:{Type:"Task",Resource:"arn:aws:states:::lambda:invoke",Next:"LoadData"},LoadData:{Type:"Task",Resource:"arn:aws:states:::lambda:invoke",End:!0}}},schedule:"cron(0 0 * * ? *)"}]},monitoring:{dashboard:{name:`${s}-pipeline`,widgets:[{type:"metric",metrics:["KinesisIncomingRecords","LambdaInvocations","S3ObjectsCreated","GlueJobsSucceeded"]}]},alarms:[{metric:"LambdaErrors",threshold:10,evaluationPeriods:1},{metric:"KinesisIteratorAge",threshold:60000,evaluationPeriods:2}]}}}}function WI(n){let{name:i,slug:s,domain:o,modelS3Path:c=`s3://${s}-models/`,instanceType:u="ml.t3.medium"}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:o}},infrastructure:{storage:{models:{public:!1,versioning:!0,encryption:!0,intelligentTiering:!0},datasets:{public:!1,versioning:!0,encryption:!0,lifecycleRules:[{id:"ArchiveOldDatasets",enabled:!0,transitions:[{days:90,storageClass:"GLACIER"}]}]},predictions:{public:!1,versioning:!1,encryption:!0,lifecycleRules:[{id:"DeleteOldPredictions",enabled:!0,expirationDays:30}]}},machineLearning:{sagemaker:{endpoints:[{name:`${s}-inference`,modelS3Path:c,instanceType:u,initialInstanceCount:1,autoScaling:{minInstances:1,maxInstances:5,targetInvocationsPerInstance:1000}}],trainingJobs:[{name:`${s}-training`,algorithmSpecification:{trainingImage:"TO_BE_SPECIFIED",trainingInputMode:"File"},instanceType:"ml.p3.2xlarge",instanceCount:1,volumeSizeInGB:50,maxRuntimeInSeconds:86400}]}},apiGateway:{type:"HTTP",customDomain:o?{domain:o,certificateArn:"TO_BE_GENERATED"}:void 0,cors:{allowOrigins:["*"],allowMethods:["POST"],allowHeaders:["Content-Type","Authorization"]},throttling:{rateLimit:1000,burstLimit:500}},functions:{predict:{runtime:"python3.11",handler:"handlers/predict.handler",memory:2048,timeout:60,events:[{type:"http",path:"/predict",method:"POST"}],environment:{SAGEMAKER_ENDPOINT:`${s}-inference`,MODEL_BUCKET:`${s}-models`}},"batch-predict":{runtime:"python3.11",handler:"handlers/batchPredict.handler",memory:3008,timeout:900,events:[{type:"s3",bucket:`${s}-datasets`,suffix:".csv"}]},"trigger-training":{runtime:"python3.11",handler:"handlers/training.handler",memory:1024,timeout:300,events:[{type:"schedule",expression:"cron(0 2 * * ? *)"}]}},databases:{dynamodb:{tables:{[`${s}-predictions`]:{partitionKey:{name:"requestId",type:"S"},sortKey:{name:"timestamp",type:"S"},billingMode:"PAY_PER_REQUEST",streamEnabled:!0},[`${s}-models`]:{partitionKey:{name:"modelId",type:"S"},sortKey:{name:"version",type:"S"},billingMode:"PAY_PER_REQUEST"}}}},queues:{predictions:{fifo:!1,visibilityTimeout:300,messageRetentionPeriod:86400,deadLetterQueue:!0}},monitoring:{dashboard:{name:`${s}-ml`,widgets:[{type:"metric",metrics:["SageMakerInvocations","SageMakerModelLatency","APIGatewayRequests","LambdaErrors"]}]},alarms:[{metric:"SageMakerModelLatency",threshold:1000,evaluationPeriods:2},{metric:"SageMakerInvocationErrors",threshold:10,evaluationPeriods:1}]},security:{certificate:o?{domain:o,validationMethod:"DNS"}:void 0,waf:{enabled:!0,rules:["rateLimit","apiProtection"]}}}}}function JI(n){let{name:i,slug:s,domain:o,instanceType:c="t3.medium",minInstances:u=2,maxInstances:d=10,databaseEngine:f="mysql",sessionStore:h="redis"}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"server",environments:{production:{type:"production",domain:o}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:2,natGateways:2}},compute:{server:{instanceType:c,ami:"ubuntu-22.04",autoScaling:{min:u,max:d,targetCPU:70,scaleUpCooldown:300,scaleDownCooldown:300},loadBalancer:{type:"application",healthCheck:{path:"/health",interval:30,timeout:5,healthyThreshold:2,unhealthyThreshold:3},stickySession:{enabled:!0,duration:86400}},userData:`#!/bin/bash
|
|
2455
2455
|
# Install Node.js or PHP/Python based on app needs
|
|
2456
2456
|
# Configure application server (PM2, Nginx, Apache)
|
|
2457
2457
|
# Mount EFS for shared file storage
|
|
2458
2458
|
`}},storage:{uploads:{type:"efs",performanceMode:"generalPurpose",throughputMode:"bursting",encrypted:!0,lifecyclePolicy:{transitionToIA:30}},backups:{public:!1,versioning:!0,encryption:!0,lifecycleRules:[{id:"ArchiveOldBackups",enabled:!0,transitions:[{days:90,storageClass:"GLACIER"}]}]},static:{public:!0,versioning:!1,encryption:!1,cors:[{allowedOrigins:[o||"*"],allowedMethods:["GET","HEAD"]}]}},cdn:{enabled:!0,origins:[{originId:"static-assets",domainName:`${s}-static.s3.amazonaws.com`,pathPattern:"/static/*"}],customDomain:o?{domain:o,certificateArn:"TO_BE_GENERATED"}:void 0,cachePolicy:{minTTL:0,defaultTTL:86400,maxTTL:31536000},compress:!0,http3:!0},databases:f==="mysql"?{mysql:{engine:"mysql",version:"8.0",instanceClass:"db.t3.medium",allocatedStorage:100,maxAllocatedStorage:500,multiAZ:!0,backupRetentionDays:14,preferredBackupWindow:"03:00-04:00",preferredMaintenanceWindow:"sun:04:00-sun:05:00",enablePerformanceInsights:!0,performanceInsightsRetention:7,deletionProtection:!0,parameters:{max_connections:"500",innodb_buffer_pool_size:"{DBInstanceClassMemory*3/4}",slow_query_log:"1",long_query_time:"2"}}}:{postgres:{engine:"postgres",version:"15",instanceClass:"db.t3.medium",allocatedStorage:100,maxAllocatedStorage:500,multiAZ:!0,backupRetentionDays:14,preferredBackupWindow:"03:00-04:00",preferredMaintenanceWindow:"sun:04:00-sun:05:00",enablePerformanceInsights:!0,performanceInsightsRetention:7,deletionProtection:!0,parameters:{max_connections:"500",shared_buffers:"{DBInstanceClassMemory/4}",log_min_duration_statement:"2000"}}},cache:h==="redis"?{redis:{nodeType:"cache.t3.medium",numCacheNodes:2,engine:"redis",engineVersion:"7.0",port:6379,parameterGroup:{maxmemoryPolicy:"allkeys-lru",timeout:"300"},snapshotRetentionLimit:5,snapshotWindow:"03:00-05:00",automaticFailoverEnabled:!0}}:void 0,queues:{jobs:{fifo:!1,visibilityTimeout:900,messageRetentionPeriod:345600,receiveMessageWaitTime:20,deadLetterQueue:!0,maxReceiveCount:3},emails:{fifo:!1,visibilityTimeout:300,messageRetentionPeriod:86400,deadLetterQueue:!0}},functions:{"job-worker":{runtime:"nodejs20.x",handler:"dist/workers/jobs.handler",memory:2048,timeout:900,events:[{type:"sqs",queueName:`${s}-jobs`,batchSize:10}]},"email-sender":{runtime:"nodejs20.x",handler:"dist/workers/email.handler",memory:512,timeout:60,events:[{type:"sqs",queueName:`${s}-emails`,batchSize:10}]},cleanup:{runtime:"nodejs20.x",handler:"dist/tasks/cleanup.handler",memory:512,timeout:300,events:[{type:"schedule",expression:"cron(0 2 * * ? *)"}]}},monitoring:{dashboard:{name:`${s}-web-app`,widgets:[{type:"metric",metrics:["EC2CPUUtilization","ALBRequestCount","ALBTargetResponseTime","RDSCPUUtilization","RDSDatabaseConnections","RDSReadLatency","RDSWriteLatency"]}]},alarms:[{metric:"EC2CPUUtilization",threshold:80,evaluationPeriods:2},{metric:"RDSCPUUtilization",threshold:80,evaluationPeriods:2},{metric:"RDSDatabaseConnections",threshold:400,evaluationPeriods:1},{metric:"ALBTargetResponseTime",threshold:2000,evaluationPeriods:2},{metric:"ALBUnhealthyHostCount",threshold:1,evaluationPeriods:1}],logs:{retention:14,groups:[`${s}-app`,`${s}-nginx`,`${s}-workers`]}},security:{certificate:o?{domain:o,validationMethod:"DNS"}:void 0,waf:{enabled:!0,rules:["rateLimit","sqlInjection","xss","knownBadInputs"]},securityGroups:{alb:{ingress:[{port:80,protocol:"tcp",cidr:"0.0.0.0/0"},{port:443,protocol:"tcp",cidr:"0.0.0.0/0"}]},app:{ingress:[{port:3000,protocol:"tcp",source:"alb-sg"}]},database:{ingress:[{port:f==="mysql"?3306:5432,protocol:"tcp",source:"app-sg"}]},...h==="redis"&&{cache:{ingress:[{port:6379,protocol:"tcp",source:"app-sg"}]}}}}}}}function XI(n){let{name:i,slug:s,domain:o,repository:c,phpVersion:u="8.3",size:d="small",database:f=s.replace(/-/g,"_"),databasePassword:h,sslEmail:S,deployStrategy:A="push",provider:T="hetzner"}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"server",cloud:{provider:T},environments:{production:{type:"production",domain:o}},infrastructure:{compute:{mode:"server",size:d,runtime:"php",webServer:"nginx",php:{versions:[u],default:u},managedServices:{mysql:!0,redis:!0},firewall:{enabled:!0},autoUpdates:!0,monitoring:!0,backups:{enabled:!0,schedule:"0 2 * * *",retentionCount:7}},appDatabase:{engine:"mysql",name:f,username:f,password:h}},sites:{main:{root:".",type:"laravel",domain:o,phpVersion:u,repository:{...c,strategy:A},scheduler:!0,queues:[{connection:"redis",queue:"default",processes:1}],ssl:{provider:"letsencrypt",email:S}}}}}function YI(n){let{name:i,slug:s,domain:o,layers:c,phpVersion:u="8.3",architecture:d="x86_64",memory:f=1024,build:h,deploy:S=["migrate --force"],cache:A="dynamodb",scheduler:T="on",region:v="us-east-1"}=n;return{project:{name:i,slug:s,region:v},mode:"serverless",environments:{production:{type:"production",domain:o,app:{kind:"php",runtime:"provided.al2023",phpVersion:u,architecture:d,layers:c,memory:f,build:h,deploy:S,assets:"public",queues:!0,scheduler:T,cache:{driver:A},domain:o}}}}}function ZI(n){return{root:n.root??"packages/ui/dist",deploy:"server",type:"static",domain:n.domain,build:n.build??"cd packages/ui && bun install && bun run build",ssl:{provider:"letsencrypt"},auth:{username:n.username??"admin",password:n.password}}}var WA=qd,JA="./node_modules/@stacksjs/ts-cloud/dist/bin/dashboard-server.js";function ci(n){let i=n.split(".").filter(Boolean);return i.length<=2?n:i.slice(-2).join(".")}function li(n){let i=2166136261;for(let s=0;s<n.length;s++)i^=n.charCodeAt(s),i=Math.imul(i,16777619);return i>>>0}var XA=20000,YA=12000;function ZA(n){return XA+li(n)%YA}function Mn(n,i){let s=ci(n);if(s===n)return`dashboard.${s}`;for(let o of i)if(o===s)return`dashboard.${s}`;return`dashboard.${n}`}function Ln(n,i){let s=[],o=n.infrastructure?.dns?.domain;if(o&&!n.cloud?.attachTo)s.push(o);if(i&&n.environments?.[i]?.domain)s.push(n.environments[i].domain);for(let c of Object.values(n.sites??{})){let u=c;if(!u||u.redirect)continue;let d=u.domain;if(typeof d==="string")s.push(d);else if(Array.isArray(d))s.push(...d.filter((f)=>typeof f==="string"))}return s.filter((c)=>c&&!c.startsWith("dashboard."))}function ey(n,i,s){if(s)return s;let o=Ln(n,i),c=o[0];if(!c)return null;return Mn(c,o)}function ty(n,i,s){if(s)return[s];let o=Ln(n,i),c=[];for(let u of o){let d=Mn(u,o);if(!c.includes(d))c.push(d)}return c}function cr(n){return Object.entries(n.sites??{}).some(([i,s])=>{if(!s)return!1;let o=s.root??"";return dr(i)||o==="ui/dist"||o.endsWith("/ui/dist")||o.endsWith("/dist/ui")})}var ym="dashboard-";function Sm(n){return ym+n.replace(/^dashboard\./,"").replace(/\./g,"-")}function dr(n){return n==="dashboard"||n.startsWith(ym)}function qi(n,i,s){if(cr(n))return[];if(n.cloud?.attachTo)return[];let o=s.password?{auth:{username:s.username||"admin",password:s.password,realm:s.realm}}:{},c=s.build===!1||s.build===void 0?{}:{build:s.build};if(s.live!==!1){let d=ey(n,i,s.domain);if(!d)return[];let f=s.port??ZA(d),h=n.infrastructure?.appDatabase??n.infrastructure?.compute?.database,S={root:s.uiRoot,deploy:"server",domain:d,preStart:["bun install --production --no-save"],start:`bun ${JA} --box --host 127.0.0.1 --port ${f}`,port:f,cpuWeight:10,ioWeight:10,tasksMax:128,env:{APP_ENV:"production",NODE_ENV:"production",TS_CLOUD_DASHBOARD_TELEMETRY:"1",...h?.password?{TS_CLOUD_DASHBOARD_DB_PASSWORD:h.password}:{}},zeroDowntime:!1,sharedPaths:[WA],healthCheck:{path:"/login"},ssl:{provider:"letsencrypt"}};return[{name:Sm(d),site:S}]}return ty(n,i,s.domain).map((d)=>({name:Sm(d),site:{root:s.uiRoot,deploy:"server",type:"static",domain:d,ssl:{provider:"letsencrypt"},...c,...o}}))}function eb(n,i,s){return qi(n,i,s)[0]??null}function xt(n,i){let s={...n};for(let o in i){let c=i[o],u=s[o];if(c===void 0)continue;if(Array.isArray(c)&&Array.isArray(u))s[o]=[...u,...c];else if(typeof c==="object"&&c!==null&&!Array.isArray(c)&&typeof u==="object"&&u!==null&&!Array.isArray(u))s[o]=xt(u,c);else s[o]=c}return s}function Im(n,i){return xt(n,i)}function tb(...n){return n.reduce((i,s)=>xt(i,s),{})}function rb(n,i){return(s)=>{let o=n(s);if(typeof i==="function")return Im(o,i(o,s));return Im(o,i)}}function dn(n){return{infrastructure:n}}function nb(n){return dn({monitoring:n})}function ib(n){return dn({security:n})}function sb(n){return dn({databases:n})}function ob(n){return dn({cache:n})}function ab(n){return dn({cdn:n})}function cb(n){return dn({queues:n})}import{existsSync as On,readFileSync as kt}from"node:fs";import{homedir as $n}from"node:os";import{join as Bn}from"node:path";function ry(){let n=process.env.AWS_ACCESS_KEY_ID,i=process.env.AWS_SECRET_ACCESS_KEY;if(!n||!i)return null;return{accessKeyId:n,secretAccessKey:i,sessionToken:process.env.AWS_SESSION_TOKEN}}function ny(n){let i=n?.profile||process.env.AWS_PROFILE||"default",s=n?.credentialsFile||Bn($n(),".aws","credentials");if(!On(s))return null;try{let o=kt(s,"utf-8");return ui(o,i)}catch{return null}}function ui(n,i){let s=n.split(`
|
|
2459
|
-
`),o=null,c,u,d;for(let f of s){let h=f.trim();if(!h||h.startsWith("#")||h.startsWith(";"))continue;let S=h.match(/^\[([^\]]+)\]$/);if(S){if(o===i&&c&&u)return{accessKeyId:c,secretAccessKey:u,sessionToken:d};o=S[1],c=void 0,u=void 0,d=void 0;continue}if(o===i){let[A,...T]=h.split("="),v=T.join("=").trim();switch(A.trim().toLowerCase()){case"aws_access_key_id":c=v;break;case"aws_secret_access_key":u=v;break;case"aws_session_token":d=v;break}}}if(o===i&&c&&u)return{accessKeyId:c,secretAccessKey:u,sessionToken:d};return null}async function iy(n){let i=n?.timeout??1000,s="http://169.254.169.254";try{let o=await
|
|
2460
|
-
`),f=!1;for(let h of d){let S=h.trim();if(S.startsWith("[")){f=S===u;continue}if(f&&S.startsWith("region")){let[,A]=S.split("=");if(A)return A.trim()}}}catch{}return"us-east-1"}async function bm(n){let i=n||await ji(),s=ay(),{signRequest:o}=await import("./chunk-09d6pdgx.js"),c=s.startsWith("us-gov")?`https://sts.${s}.amazonaws.com`:s==="us-east-1"?"https://sts.amazonaws.com":`https://sts.${s}.amazonaws.com`,u="Action=GetCallerIdentity&Version=2011-06-15",d=o({method:"POST",url:c,body:"Action=GetCallerIdentity&Version=2011-06-15",headers:{"Content-Type":"application/x-www-form-urlencoded"},...i,service:"sts",region:s}),f=await fetch(d.url,{method:d.method,headers:d.headers,body:d.body});if(!f.ok)throw Error(`Failed to get account ID: ${await f.text()}`);let h=await f.text(),S=He(h,"Account");if(!S)throw Error("Failed to parse account ID from response");return S}var mi=5242880,Mt=5242880;var pi=5242880;class Lt{region;endpoint;forcePathStyle;credentials;credentialOptions;retryOptions;constructor(n={}){this.region=n.region||process.env.AWS_REGION||"us-east-1",this.endpoint=n.endpoint||`https://s3.${this.region}.amazonaws.com`,this.forcePathStyle=n.forcePathStyle||!1,this.credentials=n.credentials,this.credentialOptions=n.credentialOptions,this.retryOptions=n.retryOptions||{}}async getCredentials(){if(this.credentials)return this.credentials;return ji(this.credentialOptions)}buildUrl(n,i){let s=i?encodeURIComponent(i).replace(/%2F/g,"/"):"";if(this.forcePathStyle)return i?`${this.endpoint}/${n}/${s}`:`${this.endpoint}/${n}`;let o=new URL(this.endpoint);return o.hostname=`${n}.${o.hostname}`,i?`${o.origin}/${s}`:o.origin}async get(n,i,s={}){let o=await this.getCredentials(),c=this.buildUrl(n,i),u={};if(s.range)u.Range=s.range;if(s.ifModifiedSince)u["If-Modified-Since"]=s.ifModifiedSince.toUTCString();if(s.ifMatch)u["If-Match"]=s.ifMatch;if(s.ifNoneMatch)u["If-None-Match"]=s.ifNoneMatch;let d=new URL(c);if(s.responseContentType)d.searchParams.set("response-content-type",s.responseContentType);if(s.responseContentDisposition)d.searchParams.set("response-content-disposition",s.responseContentDisposition);let f=N({method:"GET",url:d.toString(),headers:u,...o,service:"s3",region:this.region}),h=await fetch(f.url,{method:f.method,headers:f.headers});if(!h.ok&&h.status!==304){let S=await h.text();throw new V(`Failed to get object: ${S}`,h.status,n,i)}return h}async getText(n,i,s={}){return(await this.get(n,i,s)).text()}async getJSON(n,i,s={}){return(await this.get(n,i,s)).json()}async getBuffer(n,i,s={}){return(await this.get(n,i,s)).arrayBuffer()}async put(n,i,s,o={}){let c,u;if(typeof s==="string")c=new TextEncoder().encode(s).length,u=s;else if(s instanceof ArrayBuffer)c=s.byteLength,u=s;else if(s instanceof Uint8Array)c=s.byteLength,u=s;else if(s instanceof Blob)c=s.size,u=s;else return this.uploadMultipart(n,i,s,{...o,partSize:Mt});if(c>pi){let d=fi(u).stream();return this.uploadMultipart(n,i,d,{...o,partSize:Mt})}return this.putSimple(n,i,u,c,o)}async putSimple(n,i,s,o,c){let u=await this.getCredentials(),d=this.buildUrl(n,i),f={"Content-Length":String(o),"Content-Type":c.contentType||Fn(i)};if(c.contentEncoding)f["Content-Encoding"]=c.contentEncoding;if(c.cacheControl)f["Cache-Control"]=c.cacheControl;if(c.contentDisposition)f["Content-Disposition"]=c.contentDisposition;if(c.storageClass)f["x-amz-storage-class"]=c.storageClass;if(c.serverSideEncryption)f["x-amz-server-side-encryption"]=c.serverSideEncryption;if(c.acl)f["x-amz-acl"]=c.acl;if(c.tagging)f["x-amz-tagging"]=c.tagging;if(c.metadata)for(let[v,R]of Object.entries(c.metadata))f[`x-amz-meta-${v.toLowerCase()}`]=R;let h;if(typeof s==="string")h=s;else if(s instanceof Blob)h=await s.text();else h=new TextDecoder().decode(s instanceof ArrayBuffer?new Uint8Array(s):s);let S=N({method:"PUT",url:d,headers:f,body:h,...u,service:"s3",region:this.region}),A=await fetch(S.url,{method:S.method,headers:S.headers,body:s});if(!A.ok){let v=await A.text();throw new V(`Failed to put object: ${v}`,A.status,n,i)}return{etag:(A.headers.get("ETag")||"").replace(/"/g,"")}}async delete(n,i){let s=await this.getCredentials(),o=this.buildUrl(n,i),c=N({method:"DELETE",url:o,...s,service:"s3",region:this.region}),u=await fetch(c.url,{method:c.method,headers:c.headers});if(!u.ok&&u.status!==204){let d=await u.text();throw new V(`Failed to delete object: ${d}`,u.status,n,i)}}async deleteMany(n,i){let s=await this.getCredentials(),o=`${this.buildUrl(n)}?delete`,u=`<?xml version="1.0" encoding="UTF-8"?><Delete><Quiet>false</Quiet>${i.map((P)=>`<Object><Key>${yi(P)}</Key></Object>`).join("")}</Delete>`,d=N({method:"POST",url:o,headers:{"Content-Type":"application/xml"},body:u,...s,service:"s3",region:this.region}),f=await fetch(d.url,{method:d.method,headers:d.headers,body:u});if(!f.ok){let P=await f.text();throw new V(`Failed to delete objects: ${P}`,f.status,n)}let h=await f.text(),S=[],A=[],T=/<Deleted><Key>([^<]+)<\/Key>/g,v;while((v=T.exec(h))!==null)S.push(v[1]);let R=/<Error><Key>([^<]+)<\/Key><Code>([^<]+)<\/Code><Message>([^<]+)<\/Message>/g;while((v=R.exec(h))!==null)A.push({key:v[1],error:`${v[2]}: ${v[3]}`});return{deleted:S,errors:A}}async list(n,i={}){let s=await this.getCredentials(),o=new URL(this.buildUrl(n));if(o.searchParams.set("list-type","2"),i.prefix)o.searchParams.set("prefix",i.prefix);if(i.delimiter)o.searchParams.set("delimiter",i.delimiter);if(i.maxKeys)o.searchParams.set("max-keys",String(i.maxKeys));if(i.continuationToken)o.searchParams.set("continuation-token",i.continuationToken);if(i.startAfter)o.searchParams.set("start-after",i.startAfter);let c=N({method:"GET",url:o.toString(),...s,service:"s3",region:this.region}),u=await fetch(c.url,{method:c.method,headers:c.headers});if(!u.ok){let f=await u.text();throw new V(`Failed to list objects: ${f}`,u.status,n)}let d=await u.text();return gi(d)}async*listAll(n,i={}){let s;do{let o=await this.list(n,{...i,continuationToken:s});for(let c of o.contents)yield c;s=o.nextContinuationToken}while(s)}async head(n,i){let s=await this.getCredentials(),o=this.buildUrl(n,i),c=N({method:"HEAD",url:o,...s,service:"s3",region:this.region}),u=await fetch(c.url,{method:c.method,headers:c.headers});if(u.status===404)return null;if(!u.ok){let f=await u.text();throw new V(`Failed to head object: ${f}`,u.status,n,i)}let d={};return u.headers.forEach((f,h)=>{if(h.toLowerCase().startsWith("x-amz-meta-"))d[h.slice(11)]=f}),{contentLength:Number(u.headers.get("Content-Length")||0),contentType:u.headers.get("Content-Type")||"application/octet-stream",etag:(u.headers.get("ETag")||"").replace(/"/g,""),lastModified:new Date(u.headers.get("Last-Modified")||0),metadata:d,storageClass:u.headers.get("x-amz-storage-class")||void 0,serverSideEncryption:u.headers.get("x-amz-server-side-encryption")||void 0}}async exists(n,i){return await this.head(n,i)!==null}async copy(n,i,s,o,c={}){let u=await this.getCredentials(),d=this.buildUrl(s,o),f={"x-amz-copy-source":`/${n}/${encodeURIComponent(i)}`};if(c.metadataDirective)f["x-amz-metadata-directive"]=c.metadataDirective;if(c.contentType)f["Content-Type"]=c.contentType;if(c.storageClass)f["x-amz-storage-class"]=c.storageClass;if(c.acl)f["x-amz-acl"]=c.acl;if(c.metadata)for(let[R,P]of Object.entries(c.metadata))f[`x-amz-meta-${R.toLowerCase()}`]=P;let h=N({method:"PUT",url:d,headers:f,...u,service:"s3",region:this.region}),S=await fetch(h.url,{method:h.method,headers:h.headers});if(!S.ok){let R=await S.text();throw new V(`Failed to copy object: ${R}`,S.status,s,o)}let T=(await S.text()).match(/<ETag>"?([^"<]+)"?<\/ETag>/);return{etag:T?T[1]:""}}async getPresignedUrl(n,i,s={}){let o=await this.getCredentials(),c=this.buildUrl(n,i);return zo({url:c,method:s.method||"GET",expiresIn:s.expiresIn||3600,...o,service:"s3",region:this.region})}async uploadMultipart(n,i,s,o={}){let c=await this.getCredentials(),u=Math.max(o.partSize||Mt,mi),d,f;if(s instanceof ReadableStream)d=s;else if(s instanceof Blob)d=s.stream(),f=s.size;else{let A=new Blob([s]);d=A.stream(),f=A.size}let{uploadId:h,baseUrl:S}=await this.initiateMultipartUpload(n,i,o);try{let A=await this.uploadParts(n,i,S,h,d,u,c,f,o.concurrency||4,o.onProgress);return await this.completeMultipartUpload(n,i,S,h,A)}catch(A){throw await this.abortMultipartUpload(n,i,h,S).catch(()=>{}),A}}async initiateMultipartUpload(n,i,s){let o=await this.getCredentials(),c=this.buildUrl(n,i),u=`${c}?uploads`,d={"Content-Type":s.contentType||Fn(i)};if(s.storageClass)d["x-amz-storage-class"]=s.storageClass;if(s.serverSideEncryption)d["x-amz-server-side-encryption"]=s.serverSideEncryption;if(s.acl)d["x-amz-acl"]=s.acl;if(s.metadata)for(let[v,R]of Object.entries(s.metadata))d[`x-amz-meta-${v.toLowerCase()}`]=R;let f=N({method:"POST",url:u,headers:d,...o,service:"s3",region:this.region}),h=await fetch(f.url,{method:f.method,headers:f.headers});if(!h.ok){let v=await h.text();throw new V(`Failed to initiate multipart upload: ${v}`,h.status,n,i)}let A=(await h.text()).match(/<UploadId>([^<]+)<\/UploadId>/);if(!A)throw new V("Failed to parse upload ID from response",0,n,i);let T=c;if(h.url)try{let v=new URL(h.url);v.search="",T=v.toString()}catch{}return{uploadId:A[1],baseUrl:T}}async uploadParts(n,i,s,o,c,u,d,f,h,S){let A=[],T=c.getReader(),v=1,R=new Uint8Array(0),P=0,E=f?Math.ceil(f/u):void 0,I=new Map,M=async(x,O)=>{let B=`${s}?partNumber=${O}&uploadId=${encodeURIComponent(o)}`,F={"Content-Length":String(x.byteLength),"x-amz-content-sha256":"UNSIGNED-PAYLOAD"},U=N({method:"PUT",url:B,headers:F,...d,service:"s3",region:this.region}),j=await fetch(U.url,{method:U.method,headers:U.headers,body:x,redirect:"error"});if(!j.ok){let z=await j.text();throw new V(`Failed to upload part ${O}: ${z}`,j.status,n,i)}let H=(j.headers.get("ETag")||"").replace(/"/g,"");if(!H)throw new V(`Missing ETag for part ${O}`,j.status,n,i);return{partNumber:O,etag:H}},L=async()=>{let x=await Promise.race(I.values());I.delete(x.partNumber),A.push(x)};while(!0){let{done:x,value:O}=await T.read();if(O){let B=new Uint8Array(R.length+O.length);B.set(R),B.set(O,R.length),R=B}while(R.length>=u||x&&R.length>0){let B=R.slice(0,u);R=R.slice(u);let F=v++;if(I.size>=h)await L();if(I.set(F,M(B,F)),P+=B.byteLength,S)S({loaded:P,total:f||P,part:F,totalParts:E||F})}if(x)break}while(I.size>0)await L();return A.sort((x,O)=>x.partNumber-O.partNumber),A}async completeMultipartUpload(n,i,s,o,c){let u=await this.getCredentials(),d=`${s}?uploadId=${encodeURIComponent(o)}`,h=`<?xml version="1.0" encoding="UTF-8"?><CompleteMultipartUpload>${c.map((P)=>`<Part><PartNumber>${P.partNumber}</PartNumber><ETag>"${P.etag}"</ETag></Part>`).join("")}</CompleteMultipartUpload>`,S=N({method:"POST",url:d,headers:{"Content-Type":"application/xml"},body:h,...u,service:"s3",region:this.region}),A=await fetch(S.url,{method:S.method,headers:S.headers,body:h});if(!A.ok){let P=await A.text();throw new V(`Failed to complete multipart upload: ${P}`,A.status,n,i)}let v=(await A.text()).match(/<ETag>"?([^"<]+)"?<\/ETag>/);return{etag:v?v[1]:""}}async abortMultipartUpload(n,i,s,o){let c=await this.getCredentials(),u=`${o??this.buildUrl(n,i)}?uploadId=${encodeURIComponent(s)}`,d=N({method:"DELETE",url:u,...c,service:"s3",region:this.region});await fetch(d.url,{method:d.method,headers:d.headers})}async emptyAndDeleteBucket(n){let s=[];for await(let d of this.listAll(n,{}))if(s.push(d.key),s.length>=1000)await this.deleteMany(n,s),s=[];if(s.length>0)await this.deleteMany(n,s);let o=await this.getCredentials(),c=this.buildUrl(n),u=N({method:"DELETE",url:c,...o,service:"s3",region:this.region});await fetch(u.url,{method:u.method,headers:u.headers})}}class V extends Error{statusCode;bucket;key;constructor(n,i,s,o){super(n);this.statusCode=i;this.bucket=s;this.key=o;this.name="S3Error"}}function gi(n){let i=[],s=[],o=/<Contents>([\s\S]*?)<\/Contents>/g,c;while((c=o.exec(n))!==null){let d=c[1];i.push({key:oe(d,"Key")||"",lastModified:new Date(oe(d,"LastModified")||0),etag:(oe(d,"ETag")||"").replace(/"/g,""),size:Number(oe(d,"Size")||0),storageClass:oe(d,"StorageClass")||"STANDARD"})}let u=/<CommonPrefixes><Prefix>([^<]+)<\/Prefix><\/CommonPrefixes>/g;while((c=u.exec(n))!==null)s.push(c[1]);return{contents:i,commonPrefixes:s,isTruncated:oe(n,"IsTruncated")==="true",continuationToken:oe(n,"ContinuationToken")||void 0,nextContinuationToken:oe(n,"NextContinuationToken")||void 0,keyCount:Number(oe(n,"KeyCount")||0),maxKeys:Number(oe(n,"MaxKeys")||1000),prefix:oe(n,"Prefix")||void 0,delimiter:oe(n,"Delimiter")||void 0}}function oe(n,i){let s=new RegExp(`<${i}>([^<]*)</${i}>`),o=n.match(s);return o?o[1]:null}function yi(n){return n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Fn(n){let i=n.split(".").pop()?.toLowerCase();return{html:"text/html",htm:"text/html",css:"text/css",js:"application/javascript",mjs:"application/javascript",json:"application/json",xml:"application/xml",txt:"text/plain",md:"text/markdown",csv:"text/csv",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",ico:"image/x-icon",avif:"image/avif",mp4:"video/mp4",webm:"video/webm",mov:"video/quicktime",avi:"video/x-msvideo",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",zip:"application/zip",gz:"application/gzip",tar:"application/x-tar",rar:"application/vnd.rar","7z":"application/x-7z-compressed",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",otf:"font/otf",eot:"application/vnd.ms-fontobject",wasm:"application/wasm"}[i||""]||"application/octet-stream"}function fi(n){if(n instanceof Blob)return n;if(typeof n==="string")return new Blob([n],{type:"text/plain"});return new Blob([n])}function cy(n){return new Lt(n)}class tt extends Error{code;solution;details;constructor(n,i,s,o){super(n);this.code=i;this.solution=s;this.details=o;this.name="CloudError",Error.captureStackTrace?.(this,tt)}toString(){let n=`${this.name} [${this.code}]: ${this.message}`;if(this.solution)n+=`
|
|
2459
|
+
`),o=null,c,u,d;for(let f of s){let h=f.trim();if(!h||h.startsWith("#")||h.startsWith(";"))continue;let S=h.match(/^\[([^\]]+)\]$/);if(S){if(o===i&&c&&u)return{accessKeyId:c,secretAccessKey:u,sessionToken:d};o=S[1],c=void 0,u=void 0,d=void 0;continue}if(o===i){let[A,...T]=h.split("="),v=T.join("=").trim();switch(A.trim().toLowerCase()){case"aws_access_key_id":c=v;break;case"aws_secret_access_key":u=v;break;case"aws_session_token":d=v;break}}}if(o===i&&c&&u)return{accessKeyId:c,secretAccessKey:u,sessionToken:d};return null}async function iy(n){let i=n?.timeout??1000,s="http://169.254.169.254";try{let o=await ze("http://169.254.169.254/latest/api/token",{method:"PUT",headers:{"X-aws-ec2-metadata-token-ttl-seconds":"21600"}},i);if(!o.ok)return null;let c=await o.text(),u=await ze("http://169.254.169.254/latest/meta-data/iam/security-credentials/",{headers:{"X-aws-ec2-metadata-token":c}},i);if(!u.ok)return null;let d=(await u.text()).trim(),f=await ze(`http://169.254.169.254/latest/meta-data/iam/security-credentials/${d}`,{headers:{"X-aws-ec2-metadata-token":c}},i);if(!f.ok)return null;let h=await f.json();return{accessKeyId:h.AccessKeyId,secretAccessKey:h.SecretAccessKey,sessionToken:h.Token,expiration:new Date(h.Expiration)}}catch{return null}}async function sy(n){let i=n?.timeout??1000,s=process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI,o=process.env.AWS_CONTAINER_CREDENTIALS_FULL_URI,c=null;if(s)c=`http://169.254.170.2${s}`;else if(o)c=o;if(!c)return null;try{let u={},d=process.env.AWS_CONTAINER_AUTHORIZATION_TOKEN;if(d)u.Authorization=d;let f=await ze(c,{headers:u},i);if(!f.ok)return null;let h=await f.json();return{accessKeyId:h.AccessKeyId,secretAccessKey:h.SecretAccessKey,sessionToken:h.Token,expiration:new Date(h.Expiration)}}catch{return null}}async function oy(n){let i=n?.timeout??5000,s=process.env.AWS_WEB_IDENTITY_TOKEN_FILE,o=process.env.AWS_ROLE_ARN,c=process.env.AWS_ROLE_SESSION_NAME||"ts-cloud-session";if(!s||!o)return null;try{let u=kt(s,"utf-8").trim(),d=process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||"us-east-1",f=d.startsWith("us-gov")?`https://sts.${d}.amazonaws.com`:d==="us-east-1"?"https://sts.amazonaws.com":`https://sts.${d}.amazonaws.com`,h=new URLSearchParams({Action:"AssumeRoleWithWebIdentity",Version:"2011-06-15",RoleArn:o,RoleSessionName:c,WebIdentityToken:u}),S=await ze(`${f}/?${h.toString()}`,{method:"POST"},i);if(!S.ok)return null;let A=await S.text(),T=qe(A,"AccessKeyId"),v=qe(A,"SecretAccessKey"),R=qe(A,"SessionToken"),P=qe(A,"Expiration");if(!T||!v)return null;return{accessKeyId:T,secretAccessKey:v,sessionToken:R??void 0,expiration:P?new Date(P):void 0}}catch{return null}}async function ji(n){let i=ry();if(i)return i;let s=ny(n);if(s)return s;let o=await oy(n);if(o)return o;let c=await sy(n);if(c)return c;let u=await iy(n);if(u)return u;throw Error("Could not find AWS credentials. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables, or configure ~/.aws/credentials, or run on an EC2 instance with an IAM role.")}function db(n){let i=null,s=null;return async()=>{if(i){if(!i.expiration)return i;let o=300000;if(i.expiration.getTime()-Date.now()>o)return i}if(s)return s;return s=ji(n).then((o)=>(i=o,s=null,o)).catch((o)=>{throw s=null,o}),s}}async function ze(n,i,s){let o=new AbortController,c=setTimeout(()=>o.abort(),s);try{let u=await fetch(n,{...i,signal:o.signal});return clearTimeout(c),u}catch(u){throw clearTimeout(c),u}}function qe(n,i){let s=new RegExp(`<${i}>([^<]+)</${i}>`),o=n.match(s);return o?o[1]:null}async function $o(n){return ji({profile:n})}function ay(n){let i=process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION;if(i)return i;let s=Bn($n(),".aws","config");if(On(s))try{let o=kt(s,"utf-8"),c=n||process.env.AWS_PROFILE||"default",u=c==="default"?"[default]":`[profile ${c}]`,d=o.split(`
|
|
2460
|
+
`),f=!1;for(let h of d){let S=h.trim();if(S.startsWith("[")){f=S===u;continue}if(f&&S.startsWith("region")){let[,A]=S.split("=");if(A)return A.trim()}}}catch{}return"us-east-1"}async function bm(n){let i=n||await ji(),s=ay(),{signRequest:o}=await import("./chunk-09d6pdgx.js"),c=s.startsWith("us-gov")?`https://sts.${s}.amazonaws.com`:s==="us-east-1"?"https://sts.amazonaws.com":`https://sts.${s}.amazonaws.com`,u="Action=GetCallerIdentity&Version=2011-06-15",d=o({method:"POST",url:c,body:"Action=GetCallerIdentity&Version=2011-06-15",headers:{"Content-Type":"application/x-www-form-urlencoded"},...i,service:"sts",region:s}),f=await fetch(d.url,{method:d.method,headers:d.headers,body:d.body});if(!f.ok)throw Error(`Failed to get account ID: ${await f.text()}`);let h=await f.text(),S=qe(h,"Account");if(!S)throw Error("Failed to parse account ID from response");return S}var mi=5242880,Mt=5242880;var pi=5242880;class Lt{region;endpoint;forcePathStyle;credentials;credentialOptions;retryOptions;constructor(n={}){this.region=n.region||process.env.AWS_REGION||"us-east-1",this.endpoint=n.endpoint||`https://s3.${this.region}.amazonaws.com`,this.forcePathStyle=n.forcePathStyle||!1,this.credentials=n.credentials,this.credentialOptions=n.credentialOptions,this.retryOptions=n.retryOptions||{}}async getCredentials(){if(this.credentials)return this.credentials;return ji(this.credentialOptions)}buildUrl(n,i){let s=i?encodeURIComponent(i).replace(/%2F/g,"/"):"";if(this.forcePathStyle)return i?`${this.endpoint}/${n}/${s}`:`${this.endpoint}/${n}`;let o=new URL(this.endpoint);return o.hostname=`${n}.${o.hostname}`,i?`${o.origin}/${s}`:o.origin}async get(n,i,s={}){let o=await this.getCredentials(),c=this.buildUrl(n,i),u={};if(s.range)u.Range=s.range;if(s.ifModifiedSince)u["If-Modified-Since"]=s.ifModifiedSince.toUTCString();if(s.ifMatch)u["If-Match"]=s.ifMatch;if(s.ifNoneMatch)u["If-None-Match"]=s.ifNoneMatch;let d=new URL(c);if(s.responseContentType)d.searchParams.set("response-content-type",s.responseContentType);if(s.responseContentDisposition)d.searchParams.set("response-content-disposition",s.responseContentDisposition);let f=N({method:"GET",url:d.toString(),headers:u,...o,service:"s3",region:this.region}),h=await fetch(f.url,{method:f.method,headers:f.headers});if(!h.ok&&h.status!==304){let S=await h.text();throw new V(`Failed to get object: ${S}`,h.status,n,i)}return h}async getText(n,i,s={}){return(await this.get(n,i,s)).text()}async getJSON(n,i,s={}){return(await this.get(n,i,s)).json()}async getBuffer(n,i,s={}){return(await this.get(n,i,s)).arrayBuffer()}async put(n,i,s,o={}){let c,u;if(typeof s==="string")c=new TextEncoder().encode(s).length,u=s;else if(s instanceof ArrayBuffer)c=s.byteLength,u=s;else if(s instanceof Uint8Array)c=s.byteLength,u=s;else if(s instanceof Blob)c=s.size,u=s;else return this.uploadMultipart(n,i,s,{...o,partSize:Mt});if(c>pi){let d=fi(u).stream();return this.uploadMultipart(n,i,d,{...o,partSize:Mt})}return this.putSimple(n,i,u,c,o)}async putSimple(n,i,s,o,c){let u=await this.getCredentials(),d=this.buildUrl(n,i),f={"Content-Length":String(o),"Content-Type":c.contentType||Fn(i)};if(c.contentEncoding)f["Content-Encoding"]=c.contentEncoding;if(c.cacheControl)f["Cache-Control"]=c.cacheControl;if(c.contentDisposition)f["Content-Disposition"]=c.contentDisposition;if(c.storageClass)f["x-amz-storage-class"]=c.storageClass;if(c.serverSideEncryption)f["x-amz-server-side-encryption"]=c.serverSideEncryption;if(c.acl)f["x-amz-acl"]=c.acl;if(c.tagging)f["x-amz-tagging"]=c.tagging;if(c.metadata)for(let[v,R]of Object.entries(c.metadata))f[`x-amz-meta-${v.toLowerCase()}`]=R;let h;if(typeof s==="string")h=s;else if(s instanceof Blob)h=await s.text();else h=new TextDecoder().decode(s instanceof ArrayBuffer?new Uint8Array(s):s);let S=N({method:"PUT",url:d,headers:f,body:h,...u,service:"s3",region:this.region}),A=await fetch(S.url,{method:S.method,headers:S.headers,body:s});if(!A.ok){let v=await A.text();throw new V(`Failed to put object: ${v}`,A.status,n,i)}return{etag:(A.headers.get("ETag")||"").replace(/"/g,"")}}async delete(n,i){let s=await this.getCredentials(),o=this.buildUrl(n,i),c=N({method:"DELETE",url:o,...s,service:"s3",region:this.region}),u=await fetch(c.url,{method:c.method,headers:c.headers});if(!u.ok&&u.status!==204){let d=await u.text();throw new V(`Failed to delete object: ${d}`,u.status,n,i)}}async deleteMany(n,i){let s=await this.getCredentials(),o=`${this.buildUrl(n)}?delete`,u=`<?xml version="1.0" encoding="UTF-8"?><Delete><Quiet>false</Quiet>${i.map((P)=>`<Object><Key>${yi(P)}</Key></Object>`).join("")}</Delete>`,d=N({method:"POST",url:o,headers:{"Content-Type":"application/xml"},body:u,...s,service:"s3",region:this.region}),f=await fetch(d.url,{method:d.method,headers:d.headers,body:u});if(!f.ok){let P=await f.text();throw new V(`Failed to delete objects: ${P}`,f.status,n)}let h=await f.text(),S=[],A=[],T=/<Deleted><Key>([^<]+)<\/Key>/g,v;while((v=T.exec(h))!==null)S.push(v[1]);let R=/<Error><Key>([^<]+)<\/Key><Code>([^<]+)<\/Code><Message>([^<]+)<\/Message>/g;while((v=R.exec(h))!==null)A.push({key:v[1],error:`${v[2]}: ${v[3]}`});return{deleted:S,errors:A}}async list(n,i={}){let s=await this.getCredentials(),o=new URL(this.buildUrl(n));if(o.searchParams.set("list-type","2"),i.prefix)o.searchParams.set("prefix",i.prefix);if(i.delimiter)o.searchParams.set("delimiter",i.delimiter);if(i.maxKeys)o.searchParams.set("max-keys",String(i.maxKeys));if(i.continuationToken)o.searchParams.set("continuation-token",i.continuationToken);if(i.startAfter)o.searchParams.set("start-after",i.startAfter);let c=N({method:"GET",url:o.toString(),...s,service:"s3",region:this.region}),u=await fetch(c.url,{method:c.method,headers:c.headers});if(!u.ok){let f=await u.text();throw new V(`Failed to list objects: ${f}`,u.status,n)}let d=await u.text();return gi(d)}async*listAll(n,i={}){let s;do{let o=await this.list(n,{...i,continuationToken:s});for(let c of o.contents)yield c;s=o.nextContinuationToken}while(s)}async head(n,i){let s=await this.getCredentials(),o=this.buildUrl(n,i),c=N({method:"HEAD",url:o,...s,service:"s3",region:this.region}),u=await fetch(c.url,{method:c.method,headers:c.headers});if(u.status===404)return null;if(!u.ok){let f=await u.text();throw new V(`Failed to head object: ${f}`,u.status,n,i)}let d={};return u.headers.forEach((f,h)=>{if(h.toLowerCase().startsWith("x-amz-meta-"))d[h.slice(11)]=f}),{contentLength:Number(u.headers.get("Content-Length")||0),contentType:u.headers.get("Content-Type")||"application/octet-stream",etag:(u.headers.get("ETag")||"").replace(/"/g,""),lastModified:new Date(u.headers.get("Last-Modified")||0),metadata:d,storageClass:u.headers.get("x-amz-storage-class")||void 0,serverSideEncryption:u.headers.get("x-amz-server-side-encryption")||void 0}}async exists(n,i){return await this.head(n,i)!==null}async copy(n,i,s,o,c={}){let u=await this.getCredentials(),d=this.buildUrl(s,o),f={"x-amz-copy-source":`/${n}/${encodeURIComponent(i)}`};if(c.metadataDirective)f["x-amz-metadata-directive"]=c.metadataDirective;if(c.contentType)f["Content-Type"]=c.contentType;if(c.storageClass)f["x-amz-storage-class"]=c.storageClass;if(c.acl)f["x-amz-acl"]=c.acl;if(c.metadata)for(let[R,P]of Object.entries(c.metadata))f[`x-amz-meta-${R.toLowerCase()}`]=P;let h=N({method:"PUT",url:d,headers:f,...u,service:"s3",region:this.region}),S=await fetch(h.url,{method:h.method,headers:h.headers});if(!S.ok){let R=await S.text();throw new V(`Failed to copy object: ${R}`,S.status,s,o)}let T=(await S.text()).match(/<ETag>"?([^"<]+)"?<\/ETag>/);return{etag:T?T[1]:""}}async getPresignedUrl(n,i,s={}){let o=await this.getCredentials(),c=this.buildUrl(n,i);return zo({url:c,method:s.method||"GET",expiresIn:s.expiresIn||3600,...o,service:"s3",region:this.region})}async uploadMultipart(n,i,s,o={}){let c=await this.getCredentials(),u=Math.max(o.partSize||Mt,mi),d,f;if(s instanceof ReadableStream)d=s;else if(s instanceof Blob)d=s.stream(),f=s.size;else{let A=new Blob([s]);d=A.stream(),f=A.size}let{uploadId:h,baseUrl:S}=await this.initiateMultipartUpload(n,i,o);try{let A=await this.uploadParts(n,i,S,h,d,u,c,f,o.concurrency||4,o.onProgress);return await this.completeMultipartUpload(n,i,S,h,A)}catch(A){throw await this.abortMultipartUpload(n,i,h,S).catch(()=>{}),A}}async initiateMultipartUpload(n,i,s){let o=await this.getCredentials(),c=this.buildUrl(n,i),u=`${c}?uploads`,d={"Content-Type":s.contentType||Fn(i)};if(s.storageClass)d["x-amz-storage-class"]=s.storageClass;if(s.serverSideEncryption)d["x-amz-server-side-encryption"]=s.serverSideEncryption;if(s.acl)d["x-amz-acl"]=s.acl;if(s.metadata)for(let[v,R]of Object.entries(s.metadata))d[`x-amz-meta-${v.toLowerCase()}`]=R;let f=N({method:"POST",url:u,headers:d,...o,service:"s3",region:this.region}),h=await fetch(f.url,{method:f.method,headers:f.headers});if(!h.ok){let v=await h.text();throw new V(`Failed to initiate multipart upload: ${v}`,h.status,n,i)}let A=(await h.text()).match(/<UploadId>([^<]+)<\/UploadId>/);if(!A)throw new V("Failed to parse upload ID from response",0,n,i);let T=c;if(h.url)try{let v=new URL(h.url);v.search="",T=v.toString()}catch{}return{uploadId:A[1],baseUrl:T}}async uploadParts(n,i,s,o,c,u,d,f,h,S){let A=[],T=c.getReader(),v=1,R=new Uint8Array(0),P=0,E=f?Math.ceil(f/u):void 0,I=new Map,M=async(x,O)=>{let B=`${s}?partNumber=${O}&uploadId=${encodeURIComponent(o)}`,F={"Content-Length":String(x.byteLength),"x-amz-content-sha256":"UNSIGNED-PAYLOAD"},U=N({method:"PUT",url:B,headers:F,...d,service:"s3",region:this.region}),j=await fetch(U.url,{method:U.method,headers:U.headers,body:x,redirect:"error"});if(!j.ok){let z=await j.text();throw new V(`Failed to upload part ${O}: ${z}`,j.status,n,i)}let H=(j.headers.get("ETag")||"").replace(/"/g,"");if(!H)throw new V(`Missing ETag for part ${O}`,j.status,n,i);return{partNumber:O,etag:H}},L=async()=>{let x=await Promise.race(I.values());I.delete(x.partNumber),A.push(x)};while(!0){let{done:x,value:O}=await T.read();if(O){let B=new Uint8Array(R.length+O.length);B.set(R),B.set(O,R.length),R=B}while(R.length>=u||x&&R.length>0){let B=R.slice(0,u);R=R.slice(u);let F=v++;if(I.size>=h)await L();if(I.set(F,M(B,F)),P+=B.byteLength,S)S({loaded:P,total:f||P,part:F,totalParts:E||F})}if(x)break}while(I.size>0)await L();return A.sort((x,O)=>x.partNumber-O.partNumber),A}async completeMultipartUpload(n,i,s,o,c){let u=await this.getCredentials(),d=`${s}?uploadId=${encodeURIComponent(o)}`,h=`<?xml version="1.0" encoding="UTF-8"?><CompleteMultipartUpload>${c.map((P)=>`<Part><PartNumber>${P.partNumber}</PartNumber><ETag>"${P.etag}"</ETag></Part>`).join("")}</CompleteMultipartUpload>`,S=N({method:"POST",url:d,headers:{"Content-Type":"application/xml"},body:h,...u,service:"s3",region:this.region}),A=await fetch(S.url,{method:S.method,headers:S.headers,body:h});if(!A.ok){let P=await A.text();throw new V(`Failed to complete multipart upload: ${P}`,A.status,n,i)}let v=(await A.text()).match(/<ETag>"?([^"<]+)"?<\/ETag>/);return{etag:v?v[1]:""}}async abortMultipartUpload(n,i,s,o){let c=await this.getCredentials(),u=`${o??this.buildUrl(n,i)}?uploadId=${encodeURIComponent(s)}`,d=N({method:"DELETE",url:u,...c,service:"s3",region:this.region});await fetch(d.url,{method:d.method,headers:d.headers})}async emptyAndDeleteBucket(n){let s=[];for await(let d of this.listAll(n,{}))if(s.push(d.key),s.length>=1000)await this.deleteMany(n,s),s=[];if(s.length>0)await this.deleteMany(n,s);let o=await this.getCredentials(),c=this.buildUrl(n),u=N({method:"DELETE",url:c,...o,service:"s3",region:this.region});await fetch(u.url,{method:u.method,headers:u.headers})}}class V extends Error{statusCode;bucket;key;constructor(n,i,s,o){super(n);this.statusCode=i;this.bucket=s;this.key=o;this.name="S3Error"}}function gi(n){let i=[],s=[],o=/<Contents>([\s\S]*?)<\/Contents>/g,c;while((c=o.exec(n))!==null){let d=c[1];i.push({key:ue(d,"Key")||"",lastModified:new Date(ue(d,"LastModified")||0),etag:(ue(d,"ETag")||"").replace(/"/g,""),size:Number(ue(d,"Size")||0),storageClass:ue(d,"StorageClass")||"STANDARD"})}let u=/<CommonPrefixes><Prefix>([^<]+)<\/Prefix><\/CommonPrefixes>/g;while((c=u.exec(n))!==null)s.push(c[1]);return{contents:i,commonPrefixes:s,isTruncated:ue(n,"IsTruncated")==="true",continuationToken:ue(n,"ContinuationToken")||void 0,nextContinuationToken:ue(n,"NextContinuationToken")||void 0,keyCount:Number(ue(n,"KeyCount")||0),maxKeys:Number(ue(n,"MaxKeys")||1000),prefix:ue(n,"Prefix")||void 0,delimiter:ue(n,"Delimiter")||void 0}}function ue(n,i){let s=new RegExp(`<${i}>([^<]*)</${i}>`),o=n.match(s);return o?o[1]:null}function yi(n){return n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Fn(n){let i=n.split(".").pop()?.toLowerCase();return{html:"text/html",htm:"text/html",css:"text/css",js:"application/javascript",mjs:"application/javascript",json:"application/json",xml:"application/xml",txt:"text/plain",md:"text/markdown",csv:"text/csv",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",ico:"image/x-icon",avif:"image/avif",mp4:"video/mp4",webm:"video/webm",mov:"video/quicktime",avi:"video/x-msvideo",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",zip:"application/zip",gz:"application/gzip",tar:"application/x-tar",rar:"application/vnd.rar","7z":"application/x-7z-compressed",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",otf:"font/otf",eot:"application/vnd.ms-fontobject",wasm:"application/wasm"}[i||""]||"application/octet-stream"}function fi(n){if(n instanceof Blob)return n;if(typeof n==="string")return new Blob([n],{type:"text/plain"});return new Blob([n])}function cy(n){return new Lt(n)}class tt extends Error{code;solution;details;constructor(n,i,s,o){super(n);this.code=i;this.solution=s;this.details=o;this.name="CloudError",Error.captureStackTrace?.(this,tt)}toString(){let n=`${this.name} [${this.code}]: ${this.message}`;if(this.solution)n+=`
|
|
2461
2461
|
|
|
2462
2462
|
\uD83D\uDCA1 Solution: ${this.solution}`;if(this.details&&Object.keys(this.details).length>0){n+=`
|
|
2463
2463
|
|
|
@@ -2472,8 +2472,8 @@ Stack trace:`),console.error(i.stack)}}static success(n){console.log(`✔ ${n}`)
|
|
|
2472
2472
|
`,s=n.reduce((o,c)=>{if(!o[c.service])o[c.service]=[];return o[c.service].push(c),o},{});for(let[o,c]of Object.entries(s)){i+=`${o}:
|
|
2473
2473
|
`;for(let u of c){let d=u.warning?"⚠":"✓";i+=` ${d} ${u.quotaName}: ${u.currentValue}/${u.limit} (${u.percentage.toFixed(1)}%)
|
|
2474
2474
|
`}i+=`
|
|
2475
|
-
`}return i}function Ab(n){let i=[];for(let s of n)if(s.percentage>=100)i.push(`Request quota increase for ${s.service} - ${s.quotaName} (currently ${s.limit})`);else if(s.warning)i.push(`Consider requesting quota increase for ${s.service} - ${s.quotaName} (${s.percentage.toFixed(1)}% used)`);return i}import{createHash as Wn}from"node:crypto";import{existsSync as
|
|
2476
|
-
`);return Tm(s)}function bb(n){let i=
|
|
2475
|
+
`}return i}function Ab(n){let i=[];for(let s of n)if(s.percentage>=100)i.push(`Request quota increase for ${s.service} - ${s.quotaName} (currently ${s.limit})`);else if(s.warning)i.push(`Consider requesting quota increase for ${s.service} - ${s.quotaName} (${s.percentage.toFixed(1)}% used)`);return i}import{createHash as Wn}from"node:crypto";import{existsSync as ut,mkdirSync as hi,readdirSync as Gn,readFileSync as _n,unlinkSync as Qe,writeFileSync as bi}from"node:fs";import{join as Ot}from"node:path";class ol{cacheDir;ttl;constructor(n,i={}){this.cacheDir=n,this.ttl=i.ttl||86400000}ensureCacheDir(){if(!ut(this.cacheDir))hi(this.cacheDir,{recursive:!0})}getCachePath(n){let i=Wn("sha256").update(n).digest("hex");return Ot(this.cacheDir,`${i}.json`)}get(n){let i=this.getCachePath(n);if(!ut(i))return;try{let s=_n(i,"utf-8"),o=JSON.parse(s);if(Date.now()-o.timestamp>this.ttl){Qe(i);return}return o.value}catch{Qe(i);return}}set(n,i,s){this.ensureCacheDir();let o=this.getCachePath(n),c={value:i,timestamp:Date.now(),hash:s};bi(o,JSON.stringify(c),"utf-8")}has(n){return this.get(n)!==void 0}clear(){if(!ut(this.cacheDir))return;let n=Gn(this.cacheDir);for(let i of n)Qe(Ot(this.cacheDir,i))}prune(){if(!ut(this.cacheDir))return;let n=Gn(this.cacheDir),i=Date.now();for(let s of n){let o=Ot(this.cacheDir,s);try{let c=_n(o,"utf-8"),u=JSON.parse(c);if(i-u.timestamp>this.ttl)Qe(o)}catch{Qe(o)}}}}class al{cache;constructor(n=Q("cache","templates")){this.cache=new ol(n,{ttl:86400000})}getTemplate(n){return this.cache.get(`template:${n}`)}setTemplate(n,i){let s=this.hashTemplate(i);this.cache.set(`template:${n}`,i,s)}hasChanged(n,i){let s=this.cache.get(`template:${n}`);if(!s)return!0;let o=this.hashTemplate(s),c=this.hashTemplate(i);return o!==c}hashTemplate(n){return Wn("sha256").update(n).digest("hex")}clear(){this.cache.clear()}prune(){this.cache.prune()}}var $t=null;function my(){if(!$t)$t=new al;return $t}import{createHash as Bt}from"node:crypto";import{createReadStream as Si,readdirSync as Ai,statSync as dt}from"node:fs";import{join as Ci,relative as vi}from"node:path";async function vm(n,i={}){let s=i.algorithm||"sha256",o=i.chunkSize||65536;return new Promise((c,u)=>{let d=Bt(s),f=Si(n,{highWaterMark:o});f.on("data",(h)=>d.update(h)),f.on("end",()=>c(d.digest("hex"))),f.on("error",u)})}function Tm(n,i="sha256"){return Bt(i).update(n).digest("hex")}function yb(n,i="sha256"){return Bt(i).update(n).digest("hex")}async function Sb(n,i={}){let s=i.ignorePatterns||["node_modules",".git","dist","build",sn()],o=[];async function c(u){let d=Ai(u,{withFileTypes:!0});for(let f of d){let h=Ci(u,f.name),S=vi(n,h);if(s.some((A)=>S.includes(A)))continue;if(f.isDirectory())await c(h);else if(f.isFile()){let A=dt(h),T=await vm(h,i);o.push({path:S,hash:T,size:A.size,mtime:A.mtimeMs})}}}return await c(n),o}function Ib(n){let s=[...n].sort((o,c)=>o.path.localeCompare(c.path)).map((o)=>`${o.path}:${o.hash}`).join(`
|
|
2476
|
+
`);return Tm(s)}function bb(n){let i=dt(n);return Tm(`${n}:${i.size}:${i.mtimeMs}`)}function Cb(n,i){let s=new Map(n.map((f)=>[f.path,f])),o=new Map(i.map((f)=>[f.path,f])),c=[],u=[],d=[];for(let[f,h]of o){let S=s.get(f);if(!S)c.push(h);else if(S.hash!==h.hash)u.push(h)}for(let[f,h]of s)if(!o.has(f))d.push(h);return{added:c,modified:u,deleted:d}}class fy{cache;constructor(){this.cache=new Map}get(n){let i=dt(n),s=this.cache.get(n);if(s&&s.mtime===i.mtimeMs&&s.size===i.size)return s.hash;return}set(n,i){let s=dt(n);this.cache.set(n,{hash:i,mtime:s.mtimeMs,size:s.size})}async getOrCompute(n,i={}){let s=this.get(n);if(s)return s;let o=await vm(n,i);return this.set(n,o),o}clear(){this.cache.clear()}}async function cl(n,i={}){let s=i.concurrency||5,o=i.stopOnError??!0,c=[],u=[],d=Date.now(),f=[...n],h=[];async function S(v,R){try{let P=await v();c[R]=P}catch(P){let E=P instanceof Error?P:Error(String(P));if(u.push(E),o)throw f.length=0,E}}let A=0;while(f.length>0||h.length>0){while(h.length<s&&f.length>0){let v=f.shift(),R=A++,P=S(v,R);h.push(P)}if(h.length>0){await Promise.race(h);for(let v=h.length-1;v>=0;v--)if(await Promise.race([h[v].then(()=>!0),Promise.resolve(!1)]))h.splice(v,1)}if(o&&u.length>0)break}let T=Date.now()-d;return{results:c.filter((v)=>v!==void 0),errors:u,duration:T}}async function Eb(n,i,s={}){let o=n.map((c)=>()=>i(c));return cl(o,s)}async function vb(n,i,s=5){let o=n.map((u,d)=>()=>i(u,d)),c=await cl(o,{concurrency:s,stopOnError:!1});if(c.errors.length>0)throw AggregateError(c.errors,"Parallel map failed");return c.results}async function Tb(n,i={}){let s=i.retries||3,o=i.retryDelay||1000,c=n.map((u)=>async()=>{let d;for(let f=0;f<=s;f++)try{return await u()}catch(h){if(d=h instanceof Error?h:Error(String(h)),f<s)await Vn(o*(f+1))}throw d});return cl(c,i)}async function wb(n){let i=[];for(let s of n){let o=await s();i.push(o)}return i}function Vn(n){return new Promise((i)=>setTimeout(i,n))}async function Rb(n,i,s="Operation timed out"){return Promise.race([n(),new Promise((o,c)=>setTimeout(()=>c(Error(s)),i))])}class hy{maxConcurrent;minInterval;queue=[];running=0;lastExecution=0;constructor(n=5,i=100){this.maxConcurrent=n;this.minInterval=i}async execute(n){await this.waitForSlot(),this.running++,this.lastExecution=Date.now();try{return await n()}finally{this.running--,this.processQueue()}}waitForSlot(){if(this.running<this.maxConcurrent){let n=Date.now()-this.lastExecution;if(n>=this.minInterval)return Promise.resolve();return Vn(this.minInterval-n)}return new Promise((n)=>this.queue.push(n))}processQueue(){if(this.queue.length>0&&this.running<this.maxConcurrent)this.queue.shift()()}stats(){return{running:this.running,queued:this.queue.length}}}function Ay(n,i){let s=[];for(let o=0;o<n.length;o+=i)s.push(n.slice(o,o+i));return s}async function Db(n,i,s){let o=Ay(n,i),c=[];for(let u of o){let d=await s(u);c.push(...d)}return c}function Pb(n,i){let s=[],o=[],c=[],u=[],d=n.Resources||{},f=i.Resources||{},h=new Set(Object.keys(d)),S=new Set(Object.keys(f));for(let v of S)if(!h.has(v))s.push(v);for(let v of h)if(!S.has(v))c.push(v);for(let v of S)if(h.has(v)){let R=d[v],P=f[v];if(JSON.stringify(R)!==JSON.stringify(P))o.push(v);else u.push(v)}let A=JSON.stringify(n.Parameters||{})!==JSON.stringify(i.Parameters||{}),T=JSON.stringify(n.Outputs||{})!==JSON.stringify(i.Outputs||{});return{added:s,modified:o,deleted:c,unchanged:u,parametersChanged:A,outputsChanged:T,hasChanges:s.length>0||o.length>0||c.length>0||A||T}}function Nb(n){let i=[];if(!n.hasChanges)return"No changes detected";if(n.added.length>0){i.push(`Added resources (${n.added.length}):`);for(let s of n.added)i.push(` + ${s}`)}if(n.modified.length>0){i.push(`Modified resources (${n.modified.length}):`);for(let s of n.modified)i.push(` ~ ${s}`)}if(n.deleted.length>0){i.push(`Deleted resources (${n.deleted.length}):`);for(let s of n.deleted)i.push(` - ${s}`)}if(n.parametersChanged)i.push("Parameters changed");if(n.outputsChanged)i.push("Outputs changed");return i.join(`
|
|
2477
2477
|
`)}function kb(n,i,s){if(n.deleted.length>0)return!0;for(let o of n.modified){let c=i.Resources[o],u=s.Resources[o];if(c.Type!==u.Type)return!0;let d=Ti(u.Type);for(let f of d){let h=c.Properties?.[f],S=u.Properties?.[f];if(JSON.stringify(h)!==JSON.stringify(S))return!0}}return!1}function Ti(n){return{"AWS::S3::Bucket":["BucketName"],"AWS::EC2::Instance":["ImageId","InstanceType","KeyName"],"AWS::RDS::DBInstance":["DBInstanceIdentifier","Engine"],"AWS::DynamoDB::Table":["TableName","KeySchema"],"AWS::Lambda::Function":["FunctionName"],"AWS::ECS::Service":["ServiceName"],"AWS::ElasticLoadBalancingV2::LoadBalancer":["Name","Type"]}[n]||[]}function Bb(n){let i=[],s=[],o=[];i.push(...n.added);for(let c of n.modified)s.push(c);return o.push(...n.deleted),{safe:i,caution:s,dangerous:o}}function xb(n){if(!n.hasChanges)return{strategy:"skip",reason:"No changes detected"};if(n.deleted.length>0)return{strategy:"replace",reason:"Resources will be deleted"};if(n.added.length>0&&n.modified.length===0)return{strategy:"update",reason:"Only new resources added"};return{strategy:"update",reason:"Resources will be updated"}}function Ob(n){let i=n.added.length+n.modified.length+n.deleted.length+n.unchanged.length,s=n.added.length+n.modified.length+n.deleted.length,o=i>0?s/i*100:0;return{total:i,added:n.added.length,modified:n.modified.length,deleted:n.deleted.length,unchanged:n.unchanged.length,changePercentage:o}}var yy={$schema:"http://json-schema.org/draft-07/schema#",title:"ts-cloud Configuration",description:"Configuration schema for ts-cloud infrastructure-as-code",type:"object",required:["project"],properties:{project:{type:"object",description:"Project configuration",required:["name","slug"],properties:{name:{type:"string",description:"Human-readable project name",minLength:1},slug:{type:"string",description:"URL-safe project identifier (lowercase, alphanumeric, hyphens only)",pattern:"^[a-z0-9-]+$",minLength:1,maxLength:63},region:{type:"string",description:"Default AWS region",enum:["us-east-1","us-east-2","us-west-1","us-west-2","eu-west-1","eu-west-2","eu-west-3","eu-central-1","ap-southeast-1","ap-southeast-2","ap-northeast-1","ap-northeast-2","sa-east-1","ca-central-1"]}}},mode:{type:"string",description:"Deployment mode (server and serverless are mutually exclusive; auto-detected when omitted)",enum:["server","serverless"]},environments:{type:"object",description:"Environment-specific configurations",properties:{production:{$ref:"#/definitions/environment"},staging:{$ref:"#/definitions/environment"},development:{$ref:"#/definitions/environment"}}},infrastructure:{type:"object",description:"Infrastructure configuration",properties:{network:{$ref:"#/definitions/network"},storage:{type:"object",description:"S3 storage configuration",additionalProperties:{$ref:"#/definitions/storage"}},compute:{$ref:"#/definitions/compute"},database:{$ref:"#/definitions/database"},cache:{$ref:"#/definitions/cache"},cdn:{$ref:"#/definitions/cdn"},sftp:{$ref:"#/definitions/sftp"},functions:{type:"object",description:"Lambda functions configuration",additionalProperties:{type:"array",items:{$ref:"#/definitions/function"}}},monitoring:{$ref:"#/definitions/monitoring"},security:{$ref:"#/definitions/security"},queue:{type:"object",description:"SQS queue configuration",additionalProperties:{$ref:"#/definitions/queue"}}}}},definitions:{environment:{type:"object",properties:{domain:{type:"string",description:"Custom domain for this environment"},region:{type:"string",description:"AWS region override for this environment"},app:{type:"object",description:"Serverless application manifest (Laravel-Vapor-equivalent). Defining this opts the environment into the serverless app deploy pipeline (http/queue/cli Lambda functions, assets, build/deploy hooks).",properties:{runtime:{type:"string",description:"Lambda runtime override (usually derived from kind + runtimeVersion)"},runtimeVersion:{type:"string",description:"Node major (18/20/22 managed, 24+ custom layer) or Bun release for node/bun apps"},kind:{type:"string",enum:["node","bun","php"],description:"Application kind (drives packaging + runtime)"},entry:{type:"string",description:"Entry file exporting the request handler"},memory:{type:"number",description:"HTTP function memory in MB"},timeout:{type:"number",description:"HTTP request timeout in seconds"},gatewayVersion:{type:"number",enum:[1,2],description:"API Gateway version (2 = HTTP API, 1 = REST)"},warm:{type:"number",description:"Keep-warm / provisioned concurrency count"},lambdaInsights:{type:"object",description:"CloudWatch Lambda Insights extension configuration for zip deployments",required:["layerArn"],properties:{layerArn:{type:"string",description:"Region- and architecture-specific Lambda Insights extension layer ARN"}}},queues:{description:"Queue names (true = single default queue, false = disabled)"},scheduler:{type:"string",enum:["off","on","sub-minute"],description:"Task scheduler mode"},build:{type:"array",items:{type:"string"},description:"Commands run locally before packaging"},deploy:{type:"array",items:{type:"string"},description:"Commands run remotely after activation (e.g. migrations)"},octane:{type:"boolean",description:"Persistent application mode (Laravel Octane)"},packaging:{type:"string",enum:["zip","image"],description:"Deployment package format (zip or container image)"},phpVersion:{type:"string",description:"PHP version for the runtime layer (kind: php)"},architecture:{type:"string",enum:["x86_64","arm64"],description:"CPU architecture"}}}}},network:{type:"object",properties:{vpc:{type:"object",properties:{cidr:{type:"string",description:"VPC CIDR block",pattern:"^([0-9]{1,3}\\.){3}[0-9]{1,3}/[0-9]{1,2}$",default:"10.0.0.0/16"},availabilityZones:{type:"number",description:"Number of availability zones",minimum:1,maximum:3,default:2},natGateways:{type:"number",description:"Number of NAT gateways (0 for no NAT, saves cost)",minimum:0,maximum:3,default:1}}}}},storage:{type:"object",properties:{public:{type:"boolean",description:"Allow public access",default:!1},versioning:{type:"boolean",description:"Enable versioning",default:!1},encryption:{type:"boolean",description:"Enable server-side encryption",default:!0},website:{type:"boolean",description:"Enable static website hosting",default:!1},cors:{type:"object",description:"CORS configuration",properties:{allowedOrigins:{type:"array",items:{type:"string"}},allowedMethods:{type:"array",items:{type:"string",enum:["GET","PUT","POST","DELETE","HEAD"]}}}}}},compute:{type:"object",properties:{server:{type:"object",description:"EC2 server configuration",properties:{instanceType:{type:"string",description:"EC2 instance type",enum:["t3.micro","t3.small","t3.medium","t3.large","t3.xlarge","t3.2xlarge"]},autoScaling:{type:"object",properties:{min:{type:"number",minimum:1},max:{type:"number",minimum:1},desired:{type:"number",minimum:1}}}}},fargate:{type:"object",description:"ECS Fargate configuration",properties:{cpu:{type:"number",description:"CPU units (256, 512, 1024, 2048, 4096)",enum:[256,512,1024,2048,4096]},memory:{type:"number",description:"Memory in MB"},desiredCount:{type:"number",description:"Desired number of tasks",minimum:1}}}}},database:{type:"object",properties:{postgres:{type:"object",properties:{instanceClass:{type:"string",description:"RDS instance class",pattern:"^db\\.[a-z0-9]+\\.[a-z0-9]+$"},engine:{type:"string",const:"postgres"},version:{type:"string",description:"PostgreSQL version"},multiAZ:{type:"boolean",description:"Enable Multi-AZ deployment",default:!1},backupRetentionDays:{type:"number",description:"Backup retention period in days",minimum:0,maximum:35,default:7}}},mysql:{type:"object",properties:{instanceClass:{type:"string",pattern:"^db\\.[a-z0-9]+\\.[a-z0-9]+$"},engine:{type:"string",const:"mysql"},version:{type:"string"},multiAZ:{type:"boolean",default:!1},backupRetentionDays:{type:"number",minimum:0,maximum:35,default:7}}},dynamodb:{type:"object",properties:{tables:{type:"array",items:{type:"object",required:["name","partitionKey"],properties:{name:{type:"string"},partitionKey:{type:"string"},sortKey:{type:"string"},billingMode:{type:"string",enum:["PAY_PER_REQUEST","PROVISIONED"],default:"PAY_PER_REQUEST"}}}}}}}},cache:{type:"object",properties:{redis:{type:"object",properties:{nodeType:{type:"string",description:"ElastiCache node type",pattern:"^cache\\.[a-z0-9]+\\.[a-z0-9]+$"},numCacheNodes:{type:"number",minimum:1,default:1},engineVersion:{type:"string",description:"Redis engine version"}}},memcached:{type:"object",properties:{nodeType:{type:"string",pattern:"^cache\\.[a-z0-9]+\\.[a-z0-9]+$"},numCacheNodes:{type:"number",minimum:1,default:1}}}}},cdn:{type:"object",properties:{enabled:{type:"boolean",default:!0},originShield:{type:"boolean",description:"Enable CloudFront Origin Shield",default:!1},originShieldRegion:{type:"string",description:"AWS region used by CloudFront Origin Shield"},compress:{type:"boolean",description:"Enable automatic compression",default:!0},http3:{type:"boolean",description:"Enable HTTP/3 support",default:!0},customDomain:{type:"object",properties:{domain:{type:"string"},certificateArn:{type:"string"}}},cachePolicy:{type:"object",properties:{minTTL:{type:"number",minimum:0},defaultTTL:{type:"number",minimum:0},maxTTL:{type:"number",minimum:0}}}}},sftp:{type:"object",required:["bucket","users"],properties:{bucket:{type:"string",description:"S3 bucket backing the SFTP server"},endpointType:{type:"string",enum:["PUBLIC","VPC"],default:"PUBLIC"},endpointDetails:{type:"object",required:["vpcId","subnetIds"],properties:{vpcId:{type:"string"},subnetIds:{type:"array",items:{type:"string"},minItems:1},securityGroupIds:{type:"array",items:{type:"string"}},addressAllocationIds:{type:"array",items:{type:"string"}}}},securityPolicyName:{type:"string"},logging:{type:"boolean",default:!0},users:{type:"object",additionalProperties:{type:"object",required:["sshPublicKeys"],properties:{sshPublicKeys:{type:"array",items:{type:"string"},minItems:1},homeDirectory:{type:"string"},roleArn:{type:"string"}}}}}},function:{type:"object",required:["name","runtime"],properties:{name:{type:"string"},runtime:{type:"string",enum:["nodejs18.x","nodejs20.x","python3.10","python3.11","python3.12"]},handler:{type:"string",default:"index.handler"},timeout:{type:"number",minimum:1,maximum:900,default:30},memory:{type:"number",minimum:128,maximum:10240,default:1024}}},monitoring:{type:"object",properties:{alarms:{type:"array",items:{type:"object",required:["metric","threshold"],properties:{metric:{type:"string"},threshold:{type:"number"},evaluationPeriods:{type:"number",minimum:1,default:2}}}},dashboard:{type:"object",properties:{name:{type:"string"},widgets:{type:"array"}}}}},security:{type:"object",properties:{waf:{type:"boolean",description:"Enable AWS WAF",default:!1},certificates:{type:"array",items:{type:"object",required:["domain"],properties:{domain:{type:"string"},subdomains:{type:"array",items:{type:"string"}}}}}}},queue:{type:"object",properties:{fifo:{type:"boolean",default:!1},deadLetterQueue:{type:"boolean",default:!0},visibilityTimeout:{type:"number",minimum:0,maximum:43200,default:30},messageRetentionPeriod:{type:"number",minimum:60,maximum:1209600,default:345600}}}}};function _b(n){let i=[];if(!n.project)i.push("Missing required field: project");else{if(!n.project.name)i.push("Missing required field: project.name");if(!n.project.slug)i.push("Missing required field: project.slug")}if(n.project?.slug&&!/^[a-z0-9-]+$/.test(n.project.slug))i.push("Invalid project.slug: must contain only lowercase letters, numbers, and hyphens");let s=["us-east-1","us-east-2","us-west-1","us-west-2","eu-west-1","eu-west-2","eu-west-3","eu-central-1","ap-southeast-1","ap-southeast-2","ap-northeast-1","ap-northeast-2","sa-east-1","ca-central-1"];if(n.project?.region&&!s.includes(n.project.region))i.push(`Invalid region: ${n.project.region}. Must be one of: ${s.join(", ")}`);if(n.mode&&!["server","serverless"].includes(n.mode))i.push("Invalid mode: must be one of server or serverless");return{valid:i.length===0,errors:i}}var wm={enabled:process.env.TS_CLOUD_LOCAL==="true"||!0,localstackEndpoint:process.env.LOCALSTACK_ENDPOINT||"http://localhost:4566",postgresUrl:process.env.POSTGRES_URL||"postgresql://tscloud:tscloud@localhost:5432/tscloud",redisUrl:process.env.REDIS_URL||"redis://localhost:6379",dynamodbEndpoint:process.env.DYNAMODB_ENDPOINT||"http://localhost:8000",s3Endpoint:process.env.S3_ENDPOINT||"http://localhost:9000",emailEndpoint:process.env.EMAIL_ENDPOINT||"smtp://localhost:1025",awsRegion:process.env.AWS_REGION||"us-east-1",awsAccessKeyId:process.env.AWS_ACCESS_KEY_ID||"test",awsSecretAccessKey:process.env.AWS_SECRET_ACCESS_KEY||"test"};function dl(){return wm}function Lb(){return wm.enabled}function $b(n){let i=dl();if(!i.enabled)return"";switch(n.toLowerCase()){case"dynamodb":return i.dynamodbEndpoint;case"s3":return i.s3Endpoint;case"localstack":case"cloudformation":case"lambda":case"apigateway":case"sns":case"sqs":case"cloudwatch":case"iam":case"sts":return i.localstackEndpoint;default:return i.localstackEndpoint}}function Mb(){let n=dl();return{accessKeyId:n.awsAccessKeyId,secretAccessKey:n.awsSecretAccessKey,region:n.awsRegion}}function Fb(){let n=dl();if(!n.enabled)return{};return{AWS_ACCESS_KEY_ID:n.awsAccessKeyId,AWS_SECRET_ACCESS_KEY:n.awsSecretAccessKey,AWS_REGION:n.awsRegion,AWS_ENDPOINT_URL:n.localstackEndpoint,LOCALSTACK_ENDPOINT:n.localstackEndpoint,TS_CLOUD_LOCAL:"true"}}class Rm{stacks=new Map;stackEvents=new Map;async createStack(n){let i=`arn:aws:cloudformation:${n.region||"us-east-1"}:123456789012:stack/${n.StackName}/${Date.now()}`;return this.stacks.set(n.StackName,{StackId:i,StackName:n.StackName,StackStatus:"CREATE_IN_PROGRESS",CreationTime:new Date().toISOString(),TemplateBody:n.TemplateBody,Parameters:n.Parameters||[]}),this.addEvent(n.StackName,{EventId:Date.now().toString(),StackName:n.StackName,LogicalResourceId:n.StackName,ResourceType:"AWS::CloudFormation::Stack",Timestamp:new Date().toISOString(),ResourceStatus:"CREATE_IN_PROGRESS"}),setTimeout(()=>{let s=this.stacks.get(n.StackName);if(s)s.StackStatus="CREATE_COMPLETE",this.addEvent(n.StackName,{EventId:(Date.now()+1).toString(),StackName:n.StackName,LogicalResourceId:n.StackName,ResourceType:"AWS::CloudFormation::Stack",Timestamp:new Date().toISOString(),ResourceStatus:"CREATE_COMPLETE"})},100),{StackId:i}}async updateStack(n){let i=this.stacks.get(n.StackName);if(!i)throw Error(`Stack ${n.StackName} does not exist`);return i.StackStatus="UPDATE_IN_PROGRESS",i.TemplateBody=n.TemplateBody||i.TemplateBody,this.addEvent(n.StackName,{EventId:Date.now().toString(),StackName:n.StackName,LogicalResourceId:n.StackName,ResourceType:"AWS::CloudFormation::Stack",Timestamp:new Date().toISOString(),ResourceStatus:"UPDATE_IN_PROGRESS"}),setTimeout(()=>{i.StackStatus="UPDATE_COMPLETE",this.addEvent(n.StackName,{EventId:(Date.now()+1).toString(),StackName:n.StackName,LogicalResourceId:n.StackName,ResourceType:"AWS::CloudFormation::Stack",Timestamp:new Date().toISOString(),ResourceStatus:"UPDATE_COMPLETE"})},100),{StackId:i.StackId}}async deleteStack(n){let i=this.stacks.get(n.StackName);if(!i)throw Error(`Stack ${n.StackName} does not exist`);i.StackStatus="DELETE_IN_PROGRESS",this.addEvent(n.StackName,{EventId:Date.now().toString(),StackName:n.StackName,LogicalResourceId:n.StackName,ResourceType:"AWS::CloudFormation::Stack",Timestamp:new Date().toISOString(),ResourceStatus:"DELETE_IN_PROGRESS"}),setTimeout(()=>{this.stacks.delete(n.StackName),this.addEvent(n.StackName,{EventId:(Date.now()+1).toString(),StackName:n.StackName,LogicalResourceId:n.StackName,ResourceType:"AWS::CloudFormation::Stack",Timestamp:new Date().toISOString(),ResourceStatus:"DELETE_COMPLETE"})},100)}async describeStacks(n){if(n.StackName){let i=this.stacks.get(n.StackName);if(!i)throw Error(`Stack ${n.StackName} does not exist`);return{Stacks:[i]}}return{Stacks:Array.from(this.stacks.values())}}async describeStackEvents(n){return{StackEvents:this.stackEvents.get(n.StackName)||[]}}addEvent(n,i){if(!this.stackEvents.has(n))this.stackEvents.set(n,[]);this.stackEvents.get(n).unshift(i)}reset(){this.stacks.clear(),this.stackEvents.clear()}}class Dm{buckets=new Map;async createBucket(n){return this.buckets.set(n.Bucket,new Map),{Location:`/${n.Bucket}`}}async deleteBucket(n){this.buckets.delete(n.Bucket)}async putObject(n){let i=this.buckets.get(n.Bucket);if(!i)i=new Map,this.buckets.set(n.Bucket,i);return i.set(n.Key,Buffer.from(n.Body||"")),{ETag:`"${Date.now()}"`}}async getObject(n){let i=this.buckets.get(n.Bucket);if(!i)throw Error(`Bucket ${n.Bucket} does not exist`);let s=i.get(n.Key);if(!s)throw Error(`Object ${n.Key} does not exist`);return{Body:s,ContentLength:s.length}}async deleteObject(n){let i=this.buckets.get(n.Bucket);if(i)i.delete(n.Key)}async listObjects(n){let i=this.buckets.get(n.Bucket);if(!i)throw Error(`Bucket ${n.Bucket} does not exist`);return{Contents:Array.from(i.keys()).map((o)=>({Key:o,Size:i.get(o).length,LastModified:new Date().toISOString()}))}}reset(){this.buckets.clear()}}class Pm{tables=new Map;data=new Map;async createTable(n){return this.tables.set(n.TableName,{TableName:n.TableName,KeySchema:n.KeySchema,AttributeDefinitions:n.AttributeDefinitions,TableStatus:"ACTIVE",CreationDateTime:new Date().toISOString()}),this.data.set(n.TableName,new Map),{TableDescription:this.tables.get(n.TableName)}}async deleteTable(n){this.tables.delete(n.TableName),this.data.delete(n.TableName)}async putItem(n){let i=this.data.get(n.TableName);if(!i)i=new Map,this.data.set(n.TableName,i);let s=JSON.stringify(n.Item);i.set(s,n.Item)}async getItem(n){let i=this.data.get(n.TableName);if(!i)return{};let s=JSON.stringify(n.Key),o=i.get(s);return o?{Item:o}:{}}async deleteItem(n){let i=this.data.get(n.TableName);if(i){let s=JSON.stringify(n.Key);i.delete(s)}}async scan(n){let i=this.data.get(n.TableName);if(!i)return{Items:[]};return{Items:Array.from(i.values())}}reset(){this.tables.clear(),this.data.clear()}}function Ub(n){return{cloudformation:new Rm,s3:new Dm,dynamodb:new Pm}}class ll{environments=new Map;async createPreviewEnvironment(n){let{branch:i,pr:s,commitSha:o,ttl:c=24,baseConfig:u,region:d="us-east-1"}=n,f=this.generatePreviewId(i,s,o),h=this.generatePreviewName(i,s),S=`preview-${h}`,A=new Date,T=new Date(A.getTime()+c*60*60*1000),v={id:f,name:h,branch:i,pr:s,commitSha:o,createdAt:A,expiresAt:T,status:"creating",stackName:S,region:d,resources:[]};this.environments.set(f,v);try{let R=this.createPreviewConfig(u,h);return v.status="active",v.url=`https://${h}.preview.example.com`,v}catch(R){throw v.status="failed",R}}async destroyPreviewEnvironment(n){let i=this.environments.get(n);if(!i)throw Error(`Preview environment ${n} not found`);i.status="destroying";try{i.status="destroyed",this.environments.delete(n)}catch(s){throw Error(`Failed to destroy preview environment: ${s}`)}}getPreviewEnvironment(n){return this.environments.get(n)}getPreviewEnvironmentByBranch(n){return Array.from(this.environments.values()).find((i)=>i.branch===n)}getPreviewEnvironmentByPR(n){return Array.from(this.environments.values()).find((i)=>i.pr===n)}listPreviewEnvironments(){return Array.from(this.environments.values())}listActivePreviewEnvironments(){return this.listPreviewEnvironments().filter((n)=>n.status==="active")}async cleanupExpiredEnvironments(n={}){let{maxAge:i,keepCount:s,dryRun:o=!1}=n,c=[],u=[],d=new Date,f=this.listPreviewEnvironments().sort((h,S)=>S.createdAt.getTime()-h.createdAt.getTime());for(let h=0;h<f.length;h++){let S=f[h];if(S.status!=="active")continue;let A=!1;if(S.expiresAt<d)A=!0;if(i){if((d.getTime()-S.createdAt.getTime())/3600000>i)A=!0}if(s&&h>=s)A=!0;if(A)if(o)c.push(S.id);else try{await this.destroyPreviewEnvironment(S.id),c.push(S.id)}catch(T){u.push(S.id)}}return{destroyed:c,failed:u}}async updatePreviewEnvironment(n,i){let s=this.environments.get(n);if(!s)throw Error(`Preview environment ${n} not found`);s.commitSha=i,s.status="creating";try{return s.status="active",s}catch(o){throw s.status="failed",o}}async getPreviewEnvironmentsCost(){let n={},i=0;for(let s of this.environments.values())n[s.id]=0,i+=0;return{total:i,byEnvironment:n}}generatePreviewId(n,i,s){let o=n.replace(/[^a-z0-9-]/gi,"-").toLowerCase(),c=s?.substring(0,7)||Date.now().toString();return i?`pr-${i}-${c}`:`${o}-${c}`}generatePreviewName(n,i){let s=n.replace(/[^a-z0-9-]/gi,"-").toLowerCase();return i?`pr-${i}`:s}createPreviewConfig(n,i){return{...n,project:{...n.project,name:`${n.project.name} Preview (${i})`,slug:`${n.project.slug}-preview-${i}`}}}}var Sy=new ll;function Iy(n={}){let{workflowName:i="Preview Environment",trigger:s="pull_request",branches:o=["main","develop"],awsRegion:c="us-east-1",awsRole:u,configFile:d="cloud.config.ts",ttl:f=24}=n;return`name: ${i}
|
|
2478
2478
|
|
|
2479
2479
|
on:
|
|
@@ -2726,8 +2726,8 @@ ${i.map((s)=>` • ${s}`).join(`
|
|
|
2726
2726
|
`))}catch(n){console.error(`Failed to save history: ${n}`)}}searchHistory(n){return this.history.commands.filter((i)=>i.includes(n))}clearHistory(){this.history.commands=[],this.historyIndex=0}}class Py{variables=new Map;workingDirectory=process.cwd();set(n,i){this.variables.set(n,i)}get(n){return this.variables.get(n)}has(n){return this.variables.has(n)}delete(n){this.variables.delete(n)}getAll(){return Object.fromEntries(this.variables)}clear(){this.variables.clear()}setWorkingDirectory(n){this.workingDirectory=n}getWorkingDirectory(){return this.workingDirectory}}class Ny{command={};name(n){return this.command.name=n,this}description(n){return this.command.description=n,this}aliases(...n){return this.command.aliases=n,this}handler(n){return this.command.handler=n,this}autocomplete(n){return this.command.autocomplete=n,this}build(){if(!this.command.name||!this.command.description||!this.command.handler)throw Error("Command must have name, description, and handler");return this.command}}class ky{entries=[];maxSize;persistFile;trackOutput;constructor(n={}){this.maxSize=n.maxSize||1000,this.persistFile=n.persistFile,this.trackOutput=n.trackOutput||!1}add(n){if(this.entries.push({...n,timestamp:new Date}),this.entries.length>this.maxSize)this.entries=this.entries.slice(-this.maxSize)}getAll(){return[...this.entries]}getRecent(n=10){return this.entries.slice(-n)}search(n){let i=n.toLowerCase();return this.entries.filter((s)=>s.command.toLowerCase().includes(i))}searchByDate(n,i){return this.entries.filter((s)=>s.timestamp>=n&&s.timestamp<=i)}getSuccessful(){return this.entries.filter((n)=>n.success)}getFailed(){return this.entries.filter((n)=>!n.success)}getMostUsed(n=10){let i=new Map;for(let s of this.entries){let o=s.command.split(" ")[0];i.set(o,(i.get(o)||0)+1)}return Array.from(i.entries()).map(([s,o])=>({command:s,count:o})).sort((s,o)=>o.count-s.count).slice(0,n)}getStats(){let n=this.entries.length,i=this.entries.filter((f)=>f.success).length,s=this.entries.filter((f)=>!f.success).length,o=this.entries.filter((f)=>f.duration!==void 0),c=o.length>0?o.reduce((f,h)=>f+(h.duration||0),0)/o.length:0,u=this.getMostUsed(1),d=u.length>0?u[0].command:"N/A";return{total:n,successful:i,failed:s,averageDuration:c,mostUsed:d}}clear(){this.entries=[]}getByIndex(n){if(n<0||n>=this.entries.length)return;return this.entries[n]}removeByIndex(n){if(n>=0&&n<this.entries.length)this.entries.splice(n,1)}async save(){if(!this.persistFile)return;try{let n=await import("node:fs/promises"),i=JSON.stringify(this.entries,null,2);await n.writeFile(this.persistFile,i,"utf-8")}catch(n){throw Error(`Failed to save history: ${n}`)}}async load(){if(!this.persistFile)return;try{let n=await import("node:fs/promises"),i=await n.readFile(this.persistFile,"utf-8"),s=JSON.parse(i);this.entries=s.map((o)=>({...o,timestamp:new Date(o.timestamp)}))}catch{this.entries=[]}}exportJSON(){return JSON.stringify(this.entries,null,2)}exportCSV(){return["Timestamp,Command,Success,Duration",...this.entries.map((s)=>[s.timestamp.toISOString(),`"${s.command.replace(/"/g,'""')}"`,s.success,s.duration||""].join(","))].join(`
|
|
2727
2727
|
`)}importJSON(n){let s=JSON.parse(n).map((o)=>({...o,timestamp:new Date(o.timestamp)}));if(this.entries.push(...s),this.entries.length>this.maxSize)this.entries=this.entries.slice(-this.maxSize)}groupByDate(){let n=new Map;for(let i of this.entries){let s=i.timestamp.toISOString().split("T")[0];if(!n.has(s))n.set(s,[]);n.get(s).push(i)}return n}groupByCommand(){let n=new Map;for(let i of this.entries){let s=i.command.split(" ")[0];if(!n.has(s))n.set(s,[]);n.get(s).push(i)}return n}replay(n){return this.getByIndex(n)?.command}getSuggestions(n,i=5){let s=n.toLowerCase(),o=this.entries.filter((c)=>c.command.toLowerCase().startsWith(s)).map((c)=>c.command);return[...new Set(o)].slice(0,i)}analyzePatterns(){let n=new Map,i=new Map;for(let o of this.entries){let c=o.timestamp.getHours(),u=o.timestamp.getDay();n.set(c,(n.get(c)||0)+1),i.set(u,(i.get(u)||0)+1)}let s=this.entries.length>0?this.getSuccessful().length/this.entries.length:0;return{timeOfDay:n,dayOfWeek:i,successRate:s}}}function nC(n,i={}){let{maxWidth:s=100}=i;if(n.length===0)return"No command history";let o=[];for(let c=0;c<n.length;c++){let u=n[c],d=(c+1).toString().padStart(4),f=u.timestamp.toLocaleString(),h=u.success?"✓":"✗",S=u.command;if(S.length>s-30)S=S.substring(0,s-33)+"...";let A=`${d} ${f} ${h} ${S}`;if(u.duration)A+=` (${u.duration}ms)`;o.push(A)}return o.join(`
|
|
2728
2728
|
`)}function iC(n){let i=[];return i.push("Command History Statistics"),i.push("─".repeat(30)),i.push(`Total commands: ${n.total}`),i.push(`Successful: ${n.successful}`),i.push(`Failed: ${n.failed}`),i.push(`Success rate: ${(n.successful/n.total*100).toFixed(1)}%`),i.push(`Average duration: ${n.averageDuration.toFixed(0)}ms`),i.push(`Most used: ${n.mostUsed}`),i.join(`
|
|
2729
|
-
`)}class km{deployments=new Map;async deploy(n,i){let s=this.generateDeploymentId(),o={id:s,regions:i.regions.map((c)=>({region:c.code,stackName:this.getStackName(n,c.code),status:"pending"})),status:"deploying",startTime:new Date};this.deployments.set(s,o);try{let c=i.regions.find((d)=>d.isPrimary)||i.regions[0];await this.deployToRegion(n,c,o);let u=i.regions.filter((d)=>d.code!==c.code);if(await Promise.all(u.map((d)=>this.deployToRegion(n,d,o))),i.globalResources)await this.deployGlobalResources(o,i);if(i.replication)await this.setupReplication(o,i);if(i.failover?.enabled)await this.setupFailover(o,i);return o.status="deployed",o.endTime=new Date,o}catch(c){throw o.status="failed",o.endTime=new Date,c}}async deployToRegion(n,i,s){let o=s.regions.find((c)=>c.region===i.code);if(!o)throw Error(`Region deployment not found: ${i.code}`);o.status="deploying",o.startTime=new Date;try{let c=this.createRegionConfig(n,i);await this.deployStack(o.stackName,c,i.code),o.status="deployed",o.endTime=new Date,o.outputs={stackId:`arn:aws:cloudformation:${i.code}:123456789012:stack/${o.stackName}/guid`,endpoint:`https://${o.stackName}.${i.code}.example.com`}}catch(c){throw o.status="failed",o.endTime=new Date,o.error=c instanceof Error?c.message:String(c),c}}async deployGlobalResources(n,i){let s={};if(i.globalResources?.route53)s.route53=await this.deployRoute53(n,i);if(i.globalResources?.cloudfront)s.cloudfront=await this.deployCloudFront(n,i);if(i.globalResources?.waf)s.waf=await this.deployWAF(n);n.globalResources=s}async deployRoute53(n,i){let s=[],o=[];for(let c of n.regions){if(c.status!=="deployed")continue;let u={id:`health-${c.region}`,endpoint:c.outputs?.endpoint,path:i.failover?.healthCheckPath||"/health",region:c.region};s.push(u);let d={name:"example.com",type:"A",region:c.region,setIdentifier:c.region,healthCheckId:u.id,resourceRecords:[c.outputs?.endpoint]};o.push(d)}return{healthChecks:s,recordSets:o,hostedZoneId:"Z1234567890ABC"}}async deployCloudFront(n,i){return{distributionId:"E1234567890ABC",domainName:"d1234567890abc.cloudfront.net",origins:n.regions.filter((o)=>o.status==="deployed").map((o,c)=>{let u=i.regions[c];return{id:`origin-${o.region}`,domainName:o.outputs?.endpoint,weight:u?.weight||100}}),status:"Deployed"}}async deployWAF(n){return{webAclId:"arn:aws:wafv2:us-east-1:123456789012:global/webacl/test/a1234567-b890-c123-d456-e789012345f6",webAclArn:"arn:aws:wafv2:us-east-1:123456789012:global/webacl/test/a1234567-b890-c123-d456-e789012345f6"}}async setupReplication(n,i){if(i.replication?.s3)await this.setupS3Replication(n);if(i.replication?.dynamodb)await this.setupDynamoDBReplication(n);if(i.replication?.secrets)await this.setupSecretsReplication(n)}async setupS3Replication(n){let i=n.regions.filter((s)=>s.status==="deployed");for(let s=0;s<i.length-1;s++){let o=i[s],c=i[s+1];console.log(`Setting up S3 replication: ${o.region} -> ${c.region}`)}}async setupDynamoDBReplication(n){let i=n.regions.filter((s)=>s.status==="deployed").map((s)=>s.region);console.log(`Setting up DynamoDB global table in regions: ${i.join(", ")}`)}async setupSecretsReplication(n){let i=n.regions.filter((s)=>s.status==="deployed").map((s)=>s.region);console.log(`Setting up Secrets Manager replication in regions: ${i.join(", ")}`)}async setupFailover(n,i){let s=n.regions.find((c,u)=>i.regions[u]?.isPrimary)||n.regions[0],o=n.regions.filter((c)=>c.region!==s.region);console.log(`Setting up failover: primary=${s.region}, secondary=${o.map((c)=>c.region).join(", ")}`)}async destroy(n){let i=this.deployments.get(n);if(!i)throw Error(`Deployment not found: ${n}`);i.status="rolling-back";try{if(i.globalResources)await this.destroyGlobalResources(i.globalResources);await Promise.all(i.regions.map((s)=>this.destroyRegionStack(s))),this.deployments.delete(n)}catch(s){throw i.status="failed",s}}async destroyGlobalResources(n){if(n.waf)console.log("Destroying WAF resources");if(n.cloudfront)console.log("Destroying CloudFront distribution");if(n.route53)console.log("Destroying Route53 resources")}async destroyRegionStack(n){if(n.status!=="deployed")return;n.status="rolling-back";try{console.log(`Destroying stack ${n.stackName} in ${n.region}`),n.status="pending"}catch(i){throw n.status="failed",n.error=i instanceof Error?i.message:String(i),i}}getDeployment(n){return this.deployments.get(n)}listDeployments(){return Array.from(this.deployments.values())}getStackName(n,i){return`${n.project.slug}-${i}`}createRegionConfig(n,i){return{...n,infrastructure:{...n.infrastructure}}}async deployStack(n,i,s){console.log(`Deploying stack ${n} to ${s}`)}generateDeploymentId(){return`deploy-${Date.now()}-${Math.random().toString(36).substring(7)}`}}var sC=new km;class Bm{references=[];exports=new Map;addExport(n){let i=`${n.region}:${n.exportName}`;if(!this.exports.has(n.region))this.exports.set(n.region,[]);this.exports.get(n.region).push(n)}getExport(n,i){let s=this.exports.get(n);if(!s)return;return s.find((c)=>c.exportName===i)?.value}createReference(n,i,s,o){let c=`/cross-region/${n}/${s}/${o}`;return this.references.push({sourceRegion:n,targetRegion:i,resourceType:s,resourceId:o,value:c}),c}async resolveReference(n,i){let s=this.references.find((o)=>o.targetRegion===n&&o.value===i);if(!s)throw Error(`Reference not found: ${i}`);return`arn:aws:resource:${s.sourceRegion}:123456789012:${s.resourceType}/${s.resourceId}`}getReferencesForRegion(n){return this.references.filter((i)=>i.sourceRegion===n||i.targetRegion===n)}clear(){this.references=[],this.exports.clear()}}class xm{resources=new Map;register(n){this.resources.set(n.id,n)}get(n){return this.resources.get(n)}getByType(n){return Array.from(this.resources.values()).filter((i)=>i.type===n)}getCloudFrontDistributions(){return this.getByType("cloudfront")}getRoute53HostedZones(){return this.getByType("route53")}getWAFWebACLs(){return this.getByType("waf")}remove(n){this.resources.delete(n)}clear(){this.resources.clear()}}class Om{pairs=[];addPair(n){this.pairs.push(n)}getPairedRegion(n){let i=this.pairs.find((s)=>s.primary===n||s.secondary===n);if(!i)return;return i.primary===n?i.secondary:i.primary}getAllPairs(){return[...this.pairs]}getReplicatedPairs(){return this.pairs.filter((n)=>n.replicationConfig)}getFailoverPairs(){return this.pairs.filter((n)=>n.failoverConfig?.automatic)}arePaired(n,i){return this.pairs.some((s)=>s.primary===n&&s.secondary===i||s.primary===i&&s.secondary===n)}clear(){this.pairs=[]}}class _m{dependencies=[];addDependency(n){this.dependencies.push(n)}getDependencies(n,i){return this.dependencies.filter((s)=>s.dependentStack===n&&s.dependentRegion===i)}getDependents(n,i){return this.dependencies.filter((s)=>s.dependsOnStack===n&&s.dependsOnRegion===i)}hasDependencies(n,i){return this.getDependencies(n,i).length>0}getDeploymentOrder(n){let i=new Set,s=[],o=(c)=>{let u=`${c.name}:${c.region}`;if(i.has(u))return;i.add(u);let d=this.getDependencies(c.name,c.region);for(let f of d)o({name:f.dependsOnStack,region:f.dependsOnRegion});s.push(c)};for(let c of n)o(c);return s}detectCircularDependencies(){let n=new Set,i=new Set,s=(o,c)=>{let u=`${o}:${c}`;if(i.has(u))return!0;if(n.has(u))return!1;n.add(u),i.add(u);let d=this.getDependencies(o,c);for(let f of d)if(s(f.dependsOnStack,f.dependsOnRegion))return!0;return i.delete(u),!1};for(let o of this.dependencies)if(s(o.dependentStack,o.dependentRegion))return!0;return!1}clear(){this.dependencies=[]}}var oC=new Bm,aC=new xm,cC=new Om,dC=new _m;var _e=[{code:"us-east-1",name:"US East (N. Virginia)",location:"Virginia, USA",launchYear:2006,availabilityZones:6,localZones:16,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"standard",multiplier:1},compliance:["PCI-DSS","HIPAA","SOC","ISO","FedRAMP"]},{code:"us-east-2",name:"US East (Ohio)",location:"Ohio, USA",launchYear:2016,availabilityZones:3,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"standard",multiplier:1},compliance:["PCI-DSS","HIPAA","SOC","ISO"]},{code:"us-west-1",name:"US West (N. California)",location:"California, USA",launchYear:2009,availabilityZones:3,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"premium",multiplier:1.1},compliance:["PCI-DSS","HIPAA","SOC","ISO"]},{code:"us-west-2",name:"US West (Oregon)",location:"Oregon, USA",launchYear:2011,availabilityZones:4,localZones:2,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"standard",multiplier:1},compliance:["PCI-DSS","HIPAA","SOC","ISO"]},{code:"eu-west-1",name:"Europe (Ireland)",location:"Dublin, Ireland",launchYear:2007,availabilityZones:3,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"standard",multiplier:1.05},compliance:["PCI-DSS","GDPR","SOC","ISO"]},{code:"eu-central-1",name:"Europe (Frankfurt)",location:"Frankfurt, Germany",launchYear:2014,availabilityZones:3,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"premium",multiplier:1.1},compliance:["PCI-DSS","GDPR","SOC","ISO"]},{code:"ap-southeast-1",name:"Asia Pacific (Singapore)",location:"Singapore",launchYear:2010,availabilityZones:3,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"premium",multiplier:1.12},compliance:["PCI-DSS","SOC","ISO","MTCS"]},{code:"ap-northeast-1",name:"Asia Pacific (Tokyo)",location:"Tokyo, Japan",launchYear:2011,availabilityZones:4,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"premium",multiplier:1.15},compliance:["PCI-DSS","SOC","ISO"]}];function zi(n){return _e.find((i)=>i.code===n)}function lC(){return _e}function uC(n){let i=n.toLowerCase();return _e.filter((s)=>s.location.toLowerCase().includes(i))}function gC(n){return _e.filter((i)=>i.compliance.includes(n))}function pC(n){return _e.filter((i)=>i.pricing.tier===n)}function mC(n){return _e.some((i)=>i.code===n)}function fC(n){if(n.continent==="North America")return zi("us-east-1");if(n.continent==="Europe")return zi("eu-west-1");if(n.continent==="Asia")return zi("ap-southeast-1");return zi("us-east-1")}function hC(n){let i=[..._e];if(n.compliance)i=i.filter((s)=>n.compliance.every((o)=>s.compliance.includes(o)));if(n.requiredServices)i=i.filter((s)=>n.requiredServices.every((o)=>s.services[o]));if(n.pricingSensitive)i.sort((s,o)=>s.pricing.multiplier-o.pricing.multiplier);return i.slice(0,5)}function AC(n){let i=zi(n);if(!i)throw Error(`Invalid region: ${n}`);let s=[];for(let o of _e){if(o.code===n)continue;let c=Di(i,o),u=Ni(i,o);s.push({primary:i,secondary:o,distance:c,sameContinent:u})}return s.sort((o,c)=>{if(o.sameContinent!==c.sameContinent)return o.sameContinent?1:-1;return o.distance-c.distance}),s.slice(0,3)}function Di(n,i){let s={"North America":0,"South America":1,Europe:2,Asia:3,Africa:4,Oceania:5},o=qe(n.location),c=qe(i.location);return Math.abs((s[o]||0)-(s[c]||0))}function Ni(n,i){return qe(n.location)===qe(i.location)}function qe(n){if(n.includes("USA")||n.includes("Canada"))return"North America";if(n.includes("Europe")||n.includes("Ireland")||n.includes("Germany"))return"Europe";if(n.includes("Asia")||n.includes("Singapore")||n.includes("Japan"))return"Asia";if(n.includes("Brazil"))return"South America";if(n.includes("Australia"))return"Oceania";return"Unknown"}function By(n){return`${n.name} (${n.code})`}function yC(n){return n.map((i)=>By(i)).join(`
|
|
2730
|
-
`)}function SC(){let n={total:_e.length,byContinent:{},byPricingTier:{}};for(let i of _e){let s=qe(i.location);n.byContinent[s]=(n.byContinent[s]||0)+1,n.byPricingTier[i.pricing.tier]=(n.byPricingTier[i.pricing.tier]||0)+1}return n}class Lm{accounts=new Map;crossAccountRoles=[];accountMappings=[];registerAccount(n){this.accounts.set(n.id,n)}getAccount(n){return this.accounts.get(n)}getAccountByAlias(n){return Array.from(this.accounts.values()).find((i)=>i.alias===n)}listAccounts(){return Array.from(this.accounts.values())}getAccountsByRole(n){return Array.from(this.accounts.values()).filter((i)=>i.role===n)}createCrossAccountRole(n,i,s,o,c){let u={roleArn:`arn:aws:iam::${i}:role/${s}`,roleName:s,sourceAccountId:n,targetAccountId:i,permissions:o,externalId:c?.externalId,sessionDuration:c?.sessionDuration||3600};return this.crossAccountRoles.push(u),u}getAssumeRolePolicyDocument(n,i){let s={Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:`arn:aws:iam::${n}:root`},Action:"sts:AssumeRole"}]};if(i)s.Statement[0].Condition={StringEquals:{"sts:ExternalId":i}};return s}generateCrossAccountPolicy(n){return{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:n,Resource:"*"}]}}mapEnvironmentToAccount(n,i,s){this.accountMappings.push({environment:n,accountId:i,region:s})}getAccountForEnvironment(n){return this.accountMappings.find((i)=>i.environment===n)}async assumeRole(n,i,s){return console.log(`Assuming role: ${n} with session: ${i}`),{accessKeyId:"AKIAIOSFODNN7EXAMPLE",secretAccessKey:"wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",sessionToken:"token",expiration:new Date(Date.now()+3600000)}}async getCredentialsForAccount(n){let i=this.accounts.get(n);if(!i)throw Error(`Account not found: ${n}`);if(i.assumeRoleArn){let s=await this.assumeRole(i.assumeRoleArn,`ts-cloud-${Date.now()}`);return{accessKeyId:s.accessKeyId,secretAccessKey:s.secretAccessKey,sessionToken:s.sessionToken}}throw Error("No credentials available for account")}listCrossAccountRoles(){return[...this.crossAccountRoles]}getCrossAccountRolesForAccount(n){return this.crossAccountRoles.filter((i)=>i.sourceAccountId===n||i.targetAccountId===n)}async validateAccountAccess(n){try{let i=await this.getCredentialsForAccount(n);return console.log(`Validating access to account: ${n}`),!0}catch{return!1}}async getConsolidatedBilling(){let n={};for(let s of this.accounts.values())n[s.id]=Math.random()*1000;return{totalCost:Object.values(n).reduce((s,o)=>s+o,0),byAccount:n}}clear(){this.accounts.clear(),this.crossAccountRoles=[],this.accountMappings=[]}}class $m{organizationId;organizationalUnits=new Map;getOrganizationId(){return this.organizationId}setOrganizationId(n){this.organizationId=n}createOrganizationalUnit(n,i){let s={id:`ou-${Date.now()}`,name:n,parentId:i,accounts:[]};return this.organizationalUnits.set(s.id,s),s}getOrganizationalUnit(n){return this.organizationalUnits.get(n)}listOrganizationalUnits(){return Array.from(this.organizationalUnits.values())}addAccountToOU(n,i){let s=this.organizationalUnits.get(n);if(!s)throw Error(`Organizational unit not found: ${n}`);if(!s.accounts.includes(i))s.accounts.push(i)}removeAccountFromOU(n,i){let s=this.organizationalUnits.get(n);if(!s)throw Error(`Organizational unit not found: ${n}`);s.accounts=s.accounts.filter((o)=>o!==i)}getAccountsInOU(n){let i=this.organizationalUnits.get(n);if(!i)return[];return[...i.accounts]}applyServiceControlPolicy(n,i){return{id:`scp-${Date.now()}`,name:"Custom SCP",targetId:n,policyDocument:i}}clear(){this.organizationId=void 0,this.organizationalUnits.clear()}}var IC=new Lm,bC=new $m;var xy={basic:{name:"Basic (3 Accounts)",description:"Simple structure for small teams",accounts:[{alias:"management",email:"aws+management@example.com",role:"management",ou:"root",description:"Management account for AWS Organizations"},{alias:"production",email:"aws+production@example.com",role:"production",ou:"workloads",description:"Production workloads"},{alias:"development",email:"aws+development@example.com",role:"development",ou:"workloads",description:"Development and testing"}],organizationalUnits:[{name:"root"},{name:"workloads",parent:"root"}]},standard:{name:"Standard (5 Accounts)",description:"Recommended for most organizations",accounts:[{alias:"management",email:"aws+management@example.com",role:"management",ou:"root",description:"Management account"},{alias:"security",email:"aws+security@example.com",role:"security",ou:"security",description:"Security tooling and audit logs"},{alias:"shared-services",email:"aws+shared@example.com",role:"shared-services",ou:"infrastructure",description:"Shared services (CI/CD, monitoring)"},{alias:"production",email:"aws+production@example.com",role:"production",ou:"workloads",description:"Production environment"},{alias:"staging",email:"aws+staging@example.com",role:"staging",ou:"workloads",description:"Staging environment"},{alias:"development",email:"aws+development@example.com",role:"development",ou:"workloads",description:"Development environment"}],organizationalUnits:[{name:"root"},{name:"security",parent:"root"},{name:"infrastructure",parent:"root"},{name:"workloads",parent:"root"}]},enterprise:{name:"Enterprise (7+ Accounts)",description:"For large organizations with strict compliance requirements",accounts:[{alias:"management",email:"aws+management@example.com",role:"management",ou:"root",description:"Management account"},{alias:"audit",email:"aws+audit@example.com",role:"security",ou:"security",description:"Audit and compliance"},{alias:"log-archive",email:"aws+logs@example.com",role:"security",ou:"security",description:"Centralized log storage"},{alias:"shared-services",email:"aws+shared@example.com",role:"shared-services",ou:"infrastructure",description:"Shared infrastructure"},{alias:"network",email:"aws+network@example.com",role:"shared-services",ou:"infrastructure",description:"Network infrastructure (Transit Gateway)"},{alias:"production",email:"aws+production@example.com",role:"production",ou:"production-ou",description:"Production workloads"},{alias:"staging",email:"aws+staging@example.com",role:"staging",ou:"non-production-ou",description:"Staging environment"},{alias:"development",email:"aws+development@example.com",role:"development",ou:"non-production-ou",description:"Development environment"}],organizationalUnits:[{name:"root"},{name:"security",parent:"root",policies:["deny-root-access"]},{name:"infrastructure",parent:"root"},{name:"production-ou",parent:"root",policies:["require-mfa"]},{name:"non-production-ou",parent:"root"}]}},CC={denyRootAccess:{name:"Deny Root User Access",description:"Prevent root user from performing any actions",policyDocument:{Version:"2012-10-17",Statement:[{Sid:"DenyRootUser",Effect:"Deny",Action:"*",Resource:"*",Condition:{StringLike:{"aws:PrincipalArn":"arn:aws:iam::*:root"}}}]}},requireMFA:{name:"Require MFA for All Actions",description:"Require MFA for console and API access",policyDocument:{Version:"2012-10-17",Statement:[{Sid:"RequireMFA",Effect:"Deny",Action:"*",Resource:"*",Condition:{BoolIfExists:{"aws:MultiFactorAuthPresent":"false"}}}]}},denyRegions:{name:"Deny Access to Non-Approved Regions",description:"Restrict operations to specific regions",policyDocument:{Version:"2012-10-17",Statement:[{Sid:"DenyNonApprovedRegions",Effect:"Deny",NotAction:["iam:*","organizations:*","route53:*","cloudfront:*","support:*","s3:*"],Resource:"*",Condition:{StringNotEquals:{"aws:RequestedRegion":["us-east-1","us-west-2"]}}}]}},preventLeaving:{name:"Prevent Leaving Organization",description:"Prevent accounts from leaving the organization",policyDocument:{Version:"2012-10-17",Statement:[{Sid:"PreventLeaving",Effect:"Deny",Action:"organizations:LeaveOrganization",Resource:"*"}]}},denyS3Unencrypted:{name:"Deny Unencrypted S3 Uploads",description:"Require encryption for all S3 uploads",policyDocument:{Version:"2012-10-17",Statement:[{Sid:"DenyUnencryptedS3Uploads",Effect:"Deny",Action:"s3:PutObject",Resource:"*",Condition:{StringNotEquals:{"s3:x-amz-server-side-encryption":["AES256","aws:kms"]}}}]}}},EC={deploymentRole:{name:"CrossAccountDeploymentRole",description:"Role for deploying infrastructure from CI/CD",permissions:["cloudformation:*","s3:*","ec2:*","ecs:*","lambda:*","iam:GetRole","iam:PassRole","logs:*","events:*"]},readOnlyRole:{name:"CrossAccountReadOnlyRole",description:"Read-only access for monitoring and auditing",permissions:["cloudformation:Describe*","cloudformation:List*","ec2:Describe*","ecs:Describe*","lambda:Get*","lambda:List*","s3:Get*","s3:List*","logs:Get*","logs:Describe*"]},securityAuditRole:{name:"CrossAccountSecurityAuditRole",description:"Security audit and compliance checks",permissions:["iam:Get*","iam:List*","iam:Generate*","access-analyzer:*","guardduty:Get*","guardduty:List*","securityhub:Get*","securityhub:List*","config:Describe*","config:Get*","config:List*"]},breakGlassRole:{name:"CrossAccountBreakGlassRole",description:"Emergency access role (use with caution)",permissions:["*"]}};function vC(n){return xy[n]}function TC(n,i){return{Type:"AWS::IAM::Role",Properties:{RoleName:n.roleName,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:`arn:aws:iam::${n.sourceAccountId}:root`},Action:"sts:AssumeRole",...n.externalId&&{Condition:{StringEquals:{"sts:ExternalId":n.externalId}}}}]},Policies:[{PolicyName:`${n.roleName}Policy`,PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:n.permissions,Resource:"*"}]}}],...i&&{ManagedPolicyArns:i},MaxSessionDuration:n.sessionDuration||3600,Tags:[{Key:"ManagedBy",Value:"TS-Cloud"},{Key:"SourceAccount",Value:n.sourceAccountId}]}}}function wC(n){let i=[],s=[],o=n.accounts.filter((h)=>h.role==="management");if(o.length===0)i.push("No management account defined");if(o.length>1)i.push("Multiple management accounts defined");let c=n.accounts.map((h)=>h.email),u=c.filter((h,S)=>c.indexOf(h)!==S);if(u.length>0)i.push(`Duplicate email addresses: ${u.join(", ")}`);let d=n.accounts.map((h)=>h.alias),f=d.filter((h,S)=>d.indexOf(h)!==S);if(f.length>0)i.push(`Duplicate aliases: ${f.join(", ")}`);if(!n.accounts.some((h)=>h.role==="security"))s.push("No dedicated security account - consider adding one for audit logs");if(n.accounts.length<3)s.push("Less than 3 accounts - consider separating environments");if(!n.accounts.some((h)=>h.role==="production"))s.push("No production account defined");return{valid:i.length===0,errors:i,warnings:s}}function RC(n){let i=[];if(i.push(`${n.name}`),i.push("─".repeat(n.name.length)),i.push(n.description),i.push(""),n.organizationalUnits){i.push("Organizational Units:");for(let s of n.organizationalUnits){let o=s.parent?" └─ ":" ";i.push(`${o}${s.name}`)}i.push("")}i.push("Accounts:");for(let s of n.accounts)i.push(` ${s.alias.padEnd(20)} ${s.role.padEnd(15)} ${s.email}`),i.push(` ${"".padEnd(20)} ${s.description}`),i.push("");return i.join(`
|
|
2729
|
+
`)}class km{deployments=new Map;async deploy(n,i){let s=this.generateDeploymentId(),o={id:s,regions:i.regions.map((c)=>({region:c.code,stackName:this.getStackName(n,c.code),status:"pending"})),status:"deploying",startTime:new Date};this.deployments.set(s,o);try{let c=i.regions.find((d)=>d.isPrimary)||i.regions[0];await this.deployToRegion(n,c,o);let u=i.regions.filter((d)=>d.code!==c.code);if(await Promise.all(u.map((d)=>this.deployToRegion(n,d,o))),i.globalResources)await this.deployGlobalResources(o,i);if(i.replication)await this.setupReplication(o,i);if(i.failover?.enabled)await this.setupFailover(o,i);return o.status="deployed",o.endTime=new Date,o}catch(c){throw o.status="failed",o.endTime=new Date,c}}async deployToRegion(n,i,s){let o=s.regions.find((c)=>c.region===i.code);if(!o)throw Error(`Region deployment not found: ${i.code}`);o.status="deploying",o.startTime=new Date;try{let c=this.createRegionConfig(n,i);await this.deployStack(o.stackName,c,i.code),o.status="deployed",o.endTime=new Date,o.outputs={stackId:`arn:aws:cloudformation:${i.code}:123456789012:stack/${o.stackName}/guid`,endpoint:`https://${o.stackName}.${i.code}.example.com`}}catch(c){throw o.status="failed",o.endTime=new Date,o.error=c instanceof Error?c.message:String(c),c}}async deployGlobalResources(n,i){let s={};if(i.globalResources?.route53)s.route53=await this.deployRoute53(n,i);if(i.globalResources?.cloudfront)s.cloudfront=await this.deployCloudFront(n,i);if(i.globalResources?.waf)s.waf=await this.deployWAF(n);n.globalResources=s}async deployRoute53(n,i){let s=[],o=[];for(let c of n.regions){if(c.status!=="deployed")continue;let u={id:`health-${c.region}`,endpoint:c.outputs?.endpoint,path:i.failover?.healthCheckPath||"/health",region:c.region};s.push(u);let d={name:"example.com",type:"A",region:c.region,setIdentifier:c.region,healthCheckId:u.id,resourceRecords:[c.outputs?.endpoint]};o.push(d)}return{healthChecks:s,recordSets:o,hostedZoneId:"Z1234567890ABC"}}async deployCloudFront(n,i){return{distributionId:"E1234567890ABC",domainName:"d1234567890abc.cloudfront.net",origins:n.regions.filter((o)=>o.status==="deployed").map((o,c)=>{let u=i.regions[c];return{id:`origin-${o.region}`,domainName:o.outputs?.endpoint,weight:u?.weight||100}}),status:"Deployed"}}async deployWAF(n){return{webAclId:"arn:aws:wafv2:us-east-1:123456789012:global/webacl/test/a1234567-b890-c123-d456-e789012345f6",webAclArn:"arn:aws:wafv2:us-east-1:123456789012:global/webacl/test/a1234567-b890-c123-d456-e789012345f6"}}async setupReplication(n,i){if(i.replication?.s3)await this.setupS3Replication(n);if(i.replication?.dynamodb)await this.setupDynamoDBReplication(n);if(i.replication?.secrets)await this.setupSecretsReplication(n)}async setupS3Replication(n){let i=n.regions.filter((s)=>s.status==="deployed");for(let s=0;s<i.length-1;s++){let o=i[s],c=i[s+1];console.log(`Setting up S3 replication: ${o.region} -> ${c.region}`)}}async setupDynamoDBReplication(n){let i=n.regions.filter((s)=>s.status==="deployed").map((s)=>s.region);console.log(`Setting up DynamoDB global table in regions: ${i.join(", ")}`)}async setupSecretsReplication(n){let i=n.regions.filter((s)=>s.status==="deployed").map((s)=>s.region);console.log(`Setting up Secrets Manager replication in regions: ${i.join(", ")}`)}async setupFailover(n,i){let s=n.regions.find((c,u)=>i.regions[u]?.isPrimary)||n.regions[0],o=n.regions.filter((c)=>c.region!==s.region);console.log(`Setting up failover: primary=${s.region}, secondary=${o.map((c)=>c.region).join(", ")}`)}async destroy(n){let i=this.deployments.get(n);if(!i)throw Error(`Deployment not found: ${n}`);i.status="rolling-back";try{if(i.globalResources)await this.destroyGlobalResources(i.globalResources);await Promise.all(i.regions.map((s)=>this.destroyRegionStack(s))),this.deployments.delete(n)}catch(s){throw i.status="failed",s}}async destroyGlobalResources(n){if(n.waf)console.log("Destroying WAF resources");if(n.cloudfront)console.log("Destroying CloudFront distribution");if(n.route53)console.log("Destroying Route53 resources")}async destroyRegionStack(n){if(n.status!=="deployed")return;n.status="rolling-back";try{console.log(`Destroying stack ${n.stackName} in ${n.region}`),n.status="pending"}catch(i){throw n.status="failed",n.error=i instanceof Error?i.message:String(i),i}}getDeployment(n){return this.deployments.get(n)}listDeployments(){return Array.from(this.deployments.values())}getStackName(n,i){return`${n.project.slug}-${i}`}createRegionConfig(n,i){return{...n,infrastructure:{...n.infrastructure}}}async deployStack(n,i,s){console.log(`Deploying stack ${n} to ${s}`)}generateDeploymentId(){return`deploy-${Date.now()}-${Math.random().toString(36).substring(7)}`}}var sC=new km;class Bm{references=[];exports=new Map;addExport(n){let i=`${n.region}:${n.exportName}`;if(!this.exports.has(n.region))this.exports.set(n.region,[]);this.exports.get(n.region).push(n)}getExport(n,i){let s=this.exports.get(n);if(!s)return;return s.find((c)=>c.exportName===i)?.value}createReference(n,i,s,o){let c=`/cross-region/${n}/${s}/${o}`;return this.references.push({sourceRegion:n,targetRegion:i,resourceType:s,resourceId:o,value:c}),c}async resolveReference(n,i){let s=this.references.find((o)=>o.targetRegion===n&&o.value===i);if(!s)throw Error(`Reference not found: ${i}`);return`arn:aws:resource:${s.sourceRegion}:123456789012:${s.resourceType}/${s.resourceId}`}getReferencesForRegion(n){return this.references.filter((i)=>i.sourceRegion===n||i.targetRegion===n)}clear(){this.references=[],this.exports.clear()}}class xm{resources=new Map;register(n){this.resources.set(n.id,n)}get(n){return this.resources.get(n)}getByType(n){return Array.from(this.resources.values()).filter((i)=>i.type===n)}getCloudFrontDistributions(){return this.getByType("cloudfront")}getRoute53HostedZones(){return this.getByType("route53")}getWAFWebACLs(){return this.getByType("waf")}remove(n){this.resources.delete(n)}clear(){this.resources.clear()}}class Om{pairs=[];addPair(n){this.pairs.push(n)}getPairedRegion(n){let i=this.pairs.find((s)=>s.primary===n||s.secondary===n);if(!i)return;return i.primary===n?i.secondary:i.primary}getAllPairs(){return[...this.pairs]}getReplicatedPairs(){return this.pairs.filter((n)=>n.replicationConfig)}getFailoverPairs(){return this.pairs.filter((n)=>n.failoverConfig?.automatic)}arePaired(n,i){return this.pairs.some((s)=>s.primary===n&&s.secondary===i||s.primary===i&&s.secondary===n)}clear(){this.pairs=[]}}class _m{dependencies=[];addDependency(n){this.dependencies.push(n)}getDependencies(n,i){return this.dependencies.filter((s)=>s.dependentStack===n&&s.dependentRegion===i)}getDependents(n,i){return this.dependencies.filter((s)=>s.dependsOnStack===n&&s.dependsOnRegion===i)}hasDependencies(n,i){return this.getDependencies(n,i).length>0}getDeploymentOrder(n){let i=new Set,s=[],o=(c)=>{let u=`${c.name}:${c.region}`;if(i.has(u))return;i.add(u);let d=this.getDependencies(c.name,c.region);for(let f of d)o({name:f.dependsOnStack,region:f.dependsOnRegion});s.push(c)};for(let c of n)o(c);return s}detectCircularDependencies(){let n=new Set,i=new Set,s=(o,c)=>{let u=`${o}:${c}`;if(i.has(u))return!0;if(n.has(u))return!1;n.add(u),i.add(u);let d=this.getDependencies(o,c);for(let f of d)if(s(f.dependsOnStack,f.dependsOnRegion))return!0;return i.delete(u),!1};for(let o of this.dependencies)if(s(o.dependentStack,o.dependentRegion))return!0;return!1}clear(){this.dependencies=[]}}var oC=new Bm,aC=new xm,cC=new Om,dC=new _m;var _e=[{code:"us-east-1",name:"US East (N. Virginia)",location:"Virginia, USA",launchYear:2006,availabilityZones:6,localZones:16,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"standard",multiplier:1},compliance:["PCI-DSS","HIPAA","SOC","ISO","FedRAMP"]},{code:"us-east-2",name:"US East (Ohio)",location:"Ohio, USA",launchYear:2016,availabilityZones:3,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"standard",multiplier:1},compliance:["PCI-DSS","HIPAA","SOC","ISO"]},{code:"us-west-1",name:"US West (N. California)",location:"California, USA",launchYear:2009,availabilityZones:3,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"premium",multiplier:1.1},compliance:["PCI-DSS","HIPAA","SOC","ISO"]},{code:"us-west-2",name:"US West (Oregon)",location:"Oregon, USA",launchYear:2011,availabilityZones:4,localZones:2,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"standard",multiplier:1},compliance:["PCI-DSS","HIPAA","SOC","ISO"]},{code:"eu-west-1",name:"Europe (Ireland)",location:"Dublin, Ireland",launchYear:2007,availabilityZones:3,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"standard",multiplier:1.05},compliance:["PCI-DSS","GDPR","SOC","ISO"]},{code:"eu-central-1",name:"Europe (Frankfurt)",location:"Frankfurt, Germany",launchYear:2014,availabilityZones:3,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"premium",multiplier:1.1},compliance:["PCI-DSS","GDPR","SOC","ISO"]},{code:"ap-southeast-1",name:"Asia Pacific (Singapore)",location:"Singapore",launchYear:2010,availabilityZones:3,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"premium",multiplier:1.12},compliance:["PCI-DSS","SOC","ISO","MTCS"]},{code:"ap-northeast-1",name:"Asia Pacific (Tokyo)",location:"Tokyo, Japan",launchYear:2011,availabilityZones:4,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"premium",multiplier:1.15},compliance:["PCI-DSS","SOC","ISO"]}];function zi(n){return _e.find((i)=>i.code===n)}function lC(){return _e}function uC(n){let i=n.toLowerCase();return _e.filter((s)=>s.location.toLowerCase().includes(i))}function gC(n){return _e.filter((i)=>i.compliance.includes(n))}function pC(n){return _e.filter((i)=>i.pricing.tier===n)}function mC(n){return _e.some((i)=>i.code===n)}function fC(n){if(n.continent==="North America")return zi("us-east-1");if(n.continent==="Europe")return zi("eu-west-1");if(n.continent==="Asia")return zi("ap-southeast-1");return zi("us-east-1")}function hC(n){let i=[..._e];if(n.compliance)i=i.filter((s)=>n.compliance.every((o)=>s.compliance.includes(o)));if(n.requiredServices)i=i.filter((s)=>n.requiredServices.every((o)=>s.services[o]));if(n.pricingSensitive)i.sort((s,o)=>s.pricing.multiplier-o.pricing.multiplier);return i.slice(0,5)}function AC(n){let i=zi(n);if(!i)throw Error(`Invalid region: ${n}`);let s=[];for(let o of _e){if(o.code===n)continue;let c=Di(i,o),u=Ni(i,o);s.push({primary:i,secondary:o,distance:c,sameContinent:u})}return s.sort((o,c)=>{if(o.sameContinent!==c.sameContinent)return o.sameContinent?1:-1;return o.distance-c.distance}),s.slice(0,3)}function Di(n,i){let s={"North America":0,"South America":1,Europe:2,Asia:3,Africa:4,Oceania:5},o=Je(n.location),c=Je(i.location);return Math.abs((s[o]||0)-(s[c]||0))}function Ni(n,i){return Je(n.location)===Je(i.location)}function Je(n){if(n.includes("USA")||n.includes("Canada"))return"North America";if(n.includes("Europe")||n.includes("Ireland")||n.includes("Germany"))return"Europe";if(n.includes("Asia")||n.includes("Singapore")||n.includes("Japan"))return"Asia";if(n.includes("Brazil"))return"South America";if(n.includes("Australia"))return"Oceania";return"Unknown"}function By(n){return`${n.name} (${n.code})`}function yC(n){return n.map((i)=>By(i)).join(`
|
|
2730
|
+
`)}function SC(){let n={total:_e.length,byContinent:{},byPricingTier:{}};for(let i of _e){let s=Je(i.location);n.byContinent[s]=(n.byContinent[s]||0)+1,n.byPricingTier[i.pricing.tier]=(n.byPricingTier[i.pricing.tier]||0)+1}return n}class Lm{accounts=new Map;crossAccountRoles=[];accountMappings=[];registerAccount(n){this.accounts.set(n.id,n)}getAccount(n){return this.accounts.get(n)}getAccountByAlias(n){return Array.from(this.accounts.values()).find((i)=>i.alias===n)}listAccounts(){return Array.from(this.accounts.values())}getAccountsByRole(n){return Array.from(this.accounts.values()).filter((i)=>i.role===n)}createCrossAccountRole(n,i,s,o,c){let u={roleArn:`arn:aws:iam::${i}:role/${s}`,roleName:s,sourceAccountId:n,targetAccountId:i,permissions:o,externalId:c?.externalId,sessionDuration:c?.sessionDuration||3600};return this.crossAccountRoles.push(u),u}getAssumeRolePolicyDocument(n,i){let s={Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:`arn:aws:iam::${n}:root`},Action:"sts:AssumeRole"}]};if(i)s.Statement[0].Condition={StringEquals:{"sts:ExternalId":i}};return s}generateCrossAccountPolicy(n){return{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:n,Resource:"*"}]}}mapEnvironmentToAccount(n,i,s){this.accountMappings.push({environment:n,accountId:i,region:s})}getAccountForEnvironment(n){return this.accountMappings.find((i)=>i.environment===n)}async assumeRole(n,i,s){return console.log(`Assuming role: ${n} with session: ${i}`),{accessKeyId:"AKIAIOSFODNN7EXAMPLE",secretAccessKey:"wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",sessionToken:"token",expiration:new Date(Date.now()+3600000)}}async getCredentialsForAccount(n){let i=this.accounts.get(n);if(!i)throw Error(`Account not found: ${n}`);if(i.assumeRoleArn){let s=await this.assumeRole(i.assumeRoleArn,`ts-cloud-${Date.now()}`);return{accessKeyId:s.accessKeyId,secretAccessKey:s.secretAccessKey,sessionToken:s.sessionToken}}throw Error("No credentials available for account")}listCrossAccountRoles(){return[...this.crossAccountRoles]}getCrossAccountRolesForAccount(n){return this.crossAccountRoles.filter((i)=>i.sourceAccountId===n||i.targetAccountId===n)}async validateAccountAccess(n){try{let i=await this.getCredentialsForAccount(n);return console.log(`Validating access to account: ${n}`),!0}catch{return!1}}async getConsolidatedBilling(){let n={};for(let s of this.accounts.values())n[s.id]=Math.random()*1000;return{totalCost:Object.values(n).reduce((s,o)=>s+o,0),byAccount:n}}clear(){this.accounts.clear(),this.crossAccountRoles=[],this.accountMappings=[]}}class $m{organizationId;organizationalUnits=new Map;getOrganizationId(){return this.organizationId}setOrganizationId(n){this.organizationId=n}createOrganizationalUnit(n,i){let s={id:`ou-${Date.now()}`,name:n,parentId:i,accounts:[]};return this.organizationalUnits.set(s.id,s),s}getOrganizationalUnit(n){return this.organizationalUnits.get(n)}listOrganizationalUnits(){return Array.from(this.organizationalUnits.values())}addAccountToOU(n,i){let s=this.organizationalUnits.get(n);if(!s)throw Error(`Organizational unit not found: ${n}`);if(!s.accounts.includes(i))s.accounts.push(i)}removeAccountFromOU(n,i){let s=this.organizationalUnits.get(n);if(!s)throw Error(`Organizational unit not found: ${n}`);s.accounts=s.accounts.filter((o)=>o!==i)}getAccountsInOU(n){let i=this.organizationalUnits.get(n);if(!i)return[];return[...i.accounts]}applyServiceControlPolicy(n,i){return{id:`scp-${Date.now()}`,name:"Custom SCP",targetId:n,policyDocument:i}}clear(){this.organizationId=void 0,this.organizationalUnits.clear()}}var IC=new Lm,bC=new $m;var xy={basic:{name:"Basic (3 Accounts)",description:"Simple structure for small teams",accounts:[{alias:"management",email:"aws+management@example.com",role:"management",ou:"root",description:"Management account for AWS Organizations"},{alias:"production",email:"aws+production@example.com",role:"production",ou:"workloads",description:"Production workloads"},{alias:"development",email:"aws+development@example.com",role:"development",ou:"workloads",description:"Development and testing"}],organizationalUnits:[{name:"root"},{name:"workloads",parent:"root"}]},standard:{name:"Standard (5 Accounts)",description:"Recommended for most organizations",accounts:[{alias:"management",email:"aws+management@example.com",role:"management",ou:"root",description:"Management account"},{alias:"security",email:"aws+security@example.com",role:"security",ou:"security",description:"Security tooling and audit logs"},{alias:"shared-services",email:"aws+shared@example.com",role:"shared-services",ou:"infrastructure",description:"Shared services (CI/CD, monitoring)"},{alias:"production",email:"aws+production@example.com",role:"production",ou:"workloads",description:"Production environment"},{alias:"staging",email:"aws+staging@example.com",role:"staging",ou:"workloads",description:"Staging environment"},{alias:"development",email:"aws+development@example.com",role:"development",ou:"workloads",description:"Development environment"}],organizationalUnits:[{name:"root"},{name:"security",parent:"root"},{name:"infrastructure",parent:"root"},{name:"workloads",parent:"root"}]},enterprise:{name:"Enterprise (7+ Accounts)",description:"For large organizations with strict compliance requirements",accounts:[{alias:"management",email:"aws+management@example.com",role:"management",ou:"root",description:"Management account"},{alias:"audit",email:"aws+audit@example.com",role:"security",ou:"security",description:"Audit and compliance"},{alias:"log-archive",email:"aws+logs@example.com",role:"security",ou:"security",description:"Centralized log storage"},{alias:"shared-services",email:"aws+shared@example.com",role:"shared-services",ou:"infrastructure",description:"Shared infrastructure"},{alias:"network",email:"aws+network@example.com",role:"shared-services",ou:"infrastructure",description:"Network infrastructure (Transit Gateway)"},{alias:"production",email:"aws+production@example.com",role:"production",ou:"production-ou",description:"Production workloads"},{alias:"staging",email:"aws+staging@example.com",role:"staging",ou:"non-production-ou",description:"Staging environment"},{alias:"development",email:"aws+development@example.com",role:"development",ou:"non-production-ou",description:"Development environment"}],organizationalUnits:[{name:"root"},{name:"security",parent:"root",policies:["deny-root-access"]},{name:"infrastructure",parent:"root"},{name:"production-ou",parent:"root",policies:["require-mfa"]},{name:"non-production-ou",parent:"root"}]}},CC={denyRootAccess:{name:"Deny Root User Access",description:"Prevent root user from performing any actions",policyDocument:{Version:"2012-10-17",Statement:[{Sid:"DenyRootUser",Effect:"Deny",Action:"*",Resource:"*",Condition:{StringLike:{"aws:PrincipalArn":"arn:aws:iam::*:root"}}}]}},requireMFA:{name:"Require MFA for All Actions",description:"Require MFA for console and API access",policyDocument:{Version:"2012-10-17",Statement:[{Sid:"RequireMFA",Effect:"Deny",Action:"*",Resource:"*",Condition:{BoolIfExists:{"aws:MultiFactorAuthPresent":"false"}}}]}},denyRegions:{name:"Deny Access to Non-Approved Regions",description:"Restrict operations to specific regions",policyDocument:{Version:"2012-10-17",Statement:[{Sid:"DenyNonApprovedRegions",Effect:"Deny",NotAction:["iam:*","organizations:*","route53:*","cloudfront:*","support:*","s3:*"],Resource:"*",Condition:{StringNotEquals:{"aws:RequestedRegion":["us-east-1","us-west-2"]}}}]}},preventLeaving:{name:"Prevent Leaving Organization",description:"Prevent accounts from leaving the organization",policyDocument:{Version:"2012-10-17",Statement:[{Sid:"PreventLeaving",Effect:"Deny",Action:"organizations:LeaveOrganization",Resource:"*"}]}},denyS3Unencrypted:{name:"Deny Unencrypted S3 Uploads",description:"Require encryption for all S3 uploads",policyDocument:{Version:"2012-10-17",Statement:[{Sid:"DenyUnencryptedS3Uploads",Effect:"Deny",Action:"s3:PutObject",Resource:"*",Condition:{StringNotEquals:{"s3:x-amz-server-side-encryption":["AES256","aws:kms"]}}}]}}},EC={deploymentRole:{name:"CrossAccountDeploymentRole",description:"Role for deploying infrastructure from CI/CD",permissions:["cloudformation:*","s3:*","ec2:*","ecs:*","lambda:*","iam:GetRole","iam:PassRole","logs:*","events:*"]},readOnlyRole:{name:"CrossAccountReadOnlyRole",description:"Read-only access for monitoring and auditing",permissions:["cloudformation:Describe*","cloudformation:List*","ec2:Describe*","ecs:Describe*","lambda:Get*","lambda:List*","s3:Get*","s3:List*","logs:Get*","logs:Describe*"]},securityAuditRole:{name:"CrossAccountSecurityAuditRole",description:"Security audit and compliance checks",permissions:["iam:Get*","iam:List*","iam:Generate*","access-analyzer:*","guardduty:Get*","guardduty:List*","securityhub:Get*","securityhub:List*","config:Describe*","config:Get*","config:List*"]},breakGlassRole:{name:"CrossAccountBreakGlassRole",description:"Emergency access role (use with caution)",permissions:["*"]}};function vC(n){return xy[n]}function TC(n,i){return{Type:"AWS::IAM::Role",Properties:{RoleName:n.roleName,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:`arn:aws:iam::${n.sourceAccountId}:root`},Action:"sts:AssumeRole",...n.externalId&&{Condition:{StringEquals:{"sts:ExternalId":n.externalId}}}}]},Policies:[{PolicyName:`${n.roleName}Policy`,PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:n.permissions,Resource:"*"}]}}],...i&&{ManagedPolicyArns:i},MaxSessionDuration:n.sessionDuration||3600,Tags:[{Key:"ManagedBy",Value:"TS-Cloud"},{Key:"SourceAccount",Value:n.sourceAccountId}]}}}function wC(n){let i=[],s=[],o=n.accounts.filter((h)=>h.role==="management");if(o.length===0)i.push("No management account defined");if(o.length>1)i.push("Multiple management accounts defined");let c=n.accounts.map((h)=>h.email),u=c.filter((h,S)=>c.indexOf(h)!==S);if(u.length>0)i.push(`Duplicate email addresses: ${u.join(", ")}`);let d=n.accounts.map((h)=>h.alias),f=d.filter((h,S)=>d.indexOf(h)!==S);if(f.length>0)i.push(`Duplicate aliases: ${f.join(", ")}`);if(!n.accounts.some((h)=>h.role==="security"))s.push("No dedicated security account - consider adding one for audit logs");if(n.accounts.length<3)s.push("Less than 3 accounts - consider separating environments");if(!n.accounts.some((h)=>h.role==="production"))s.push("No production account defined");return{valid:i.length===0,errors:i,warnings:s}}function RC(n){let i=[];if(i.push(`${n.name}`),i.push("─".repeat(n.name.length)),i.push(n.description),i.push(""),n.organizationalUnits){i.push("Organizational Units:");for(let s of n.organizationalUnits){let o=s.parent?" └─ ":" ";i.push(`${o}${s.name}`)}i.push("")}i.push("Accounts:");for(let s of n.accounts)i.push(` ${s.alias.padEnd(20)} ${s.role.padEnd(15)} ${s.email}`),i.push(` ${"".padEnd(20)} ${s.description}`),i.push("");return i.join(`
|
|
2731
2731
|
`)}function DC(n={}){let{workflowName:i="Deploy",trigger:s="push",branches:o=["main"],environments:c=["production"],awsRegion:u="us-east-1",awsRole:d,bunVersion:f="latest",deployCommand:h="bun run cloud deploy",testCommand:S="bun test",buildCommand:A="bun run build"}=n,T=!!d;return`name: ${i}
|
|
2732
2732
|
|
|
2733
2733
|
on:
|
|
@@ -4127,7 +4127,7 @@ else {
|
|
|
4127
4127
|
|
|
4128
4128
|
return raw;
|
|
4129
4129
|
}
|
|
4130
|
-
`;static createSchedulerLambda(n){return{[`${n.slug}EmailSchedulerLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${n.slug}-email-scheduler`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n.roleArn,Timeout:300,MemorySize:256,Code:{ZipFile:Wt.SchedulerLambdaCode},Environment:{Variables:{EMAIL_BUCKET:n.emailBucket}}}}}}static createSchedulerRule(n){return{[`${n.slug}EmailSchedulerRule`]:{Type:"AWS::Events::Rule",Properties:{Name:`${n.slug}-email-scheduler`,Description:"Trigger email scheduler every minute",ScheduleExpression:n.scheduleExpression||"rate(1 minute)",State:"ENABLED",Targets:[{Id:"EmailSchedulerTarget",Arn:n.lambdaArn}]}},[`${n.slug}EmailSchedulerPermission`]:{Type:"AWS::Lambda::Permission",Properties:{FunctionName:n.lambdaArn,Action:"lambda:InvokeFunction",Principal:"events.amazonaws.com",SourceArn:{"Fn::GetAtt":[`${n.slug}EmailSchedulerRule`,"Arn"]}}}}}static async scheduleEmail(n){let{s3Client:i,bucket:s,email:o,scheduledFor:c,timezone:u}=n,d=`sched-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,f={id:d,email:o,scheduledFor:typeof c==="string"?c:c.toISOString(),timezone:u,status:"pending",createdAt:new Date().toISOString()};return await i.send({Bucket:s,Key:`scheduled/${d}.json`,Body:JSON.stringify(f,null,2),ContentType:"application/json"}),f}static async cancelScheduledEmail(n){let{s3Client:i,bucket:s,id:o}=n;try{let c=await i.send({Bucket:s,Key:`scheduled/${o}.json`}),u=JSON.parse(c.Body);if(u.status!=="pending")return!1;return u.status="cancelled",await i.send({Bucket:s,Key:`scheduled/${o}.json`,Body:JSON.stringify(u,null,2),ContentType:"application/json"}),!0}catch{return!1}}static async listScheduledEmails(n){let{s3Client:i,bucket:s,status:o}=n,c=await i.send({Bucket:s,Prefix:"scheduled/"}),u=[];for(let d of c.Contents||[]){if(!d.Key.endsWith(".json"))continue;try{let f=await i.send({Bucket:s,Key:d.Key}),h=JSON.parse(f.Body);if(!o||h.status===o)u.push(h)}catch{}}return u.sort((d,f)=>new Date(d.scheduledFor).getTime()-new Date(f.scheduledFor).getTime()),u}}class
|
|
4130
|
+
`;static createSchedulerLambda(n){return{[`${n.slug}EmailSchedulerLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${n.slug}-email-scheduler`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n.roleArn,Timeout:300,MemorySize:256,Code:{ZipFile:Wt.SchedulerLambdaCode},Environment:{Variables:{EMAIL_BUCKET:n.emailBucket}}}}}}static createSchedulerRule(n){return{[`${n.slug}EmailSchedulerRule`]:{Type:"AWS::Events::Rule",Properties:{Name:`${n.slug}-email-scheduler`,Description:"Trigger email scheduler every minute",ScheduleExpression:n.scheduleExpression||"rate(1 minute)",State:"ENABLED",Targets:[{Id:"EmailSchedulerTarget",Arn:n.lambdaArn}]}},[`${n.slug}EmailSchedulerPermission`]:{Type:"AWS::Lambda::Permission",Properties:{FunctionName:n.lambdaArn,Action:"lambda:InvokeFunction",Principal:"events.amazonaws.com",SourceArn:{"Fn::GetAtt":[`${n.slug}EmailSchedulerRule`,"Arn"]}}}}}static async scheduleEmail(n){let{s3Client:i,bucket:s,email:o,scheduledFor:c,timezone:u}=n,d=`sched-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,f={id:d,email:o,scheduledFor:typeof c==="string"?c:c.toISOString(),timezone:u,status:"pending",createdAt:new Date().toISOString()};return await i.send({Bucket:s,Key:`scheduled/${d}.json`,Body:JSON.stringify(f,null,2),ContentType:"application/json"}),f}static async cancelScheduledEmail(n){let{s3Client:i,bucket:s,id:o}=n;try{let c=await i.send({Bucket:s,Key:`scheduled/${o}.json`}),u=JSON.parse(c.Body);if(u.status!=="pending")return!1;return u.status="cancelled",await i.send({Bucket:s,Key:`scheduled/${o}.json`,Body:JSON.stringify(u,null,2),ContentType:"application/json"}),!0}catch{return!1}}static async listScheduledEmails(n){let{s3Client:i,bucket:s,status:o}=n,c=await i.send({Bucket:s,Prefix:"scheduled/"}),u=[];for(let d of c.Contents||[]){if(!d.Key.endsWith(".json"))continue;try{let f=await i.send({Bucket:s,Key:d.Key}),h=JSON.parse(f.Body);if(!o||h.status===o)u.push(h)}catch{}}return u.sort((d,f)=>new Date(d.scheduledFor).getTime()-new Date(f.scheduledFor).getTime()),u}}class it{static TrackingPixelLambdaCode=`
|
|
4131
4131
|
const { DynamoDBClient, UpdateItemCommand } = require('@aws-sdk/client-dynamodb');
|
|
4132
4132
|
|
|
4133
4133
|
const dynamodb = new DynamoDBClient({});
|
|
@@ -4330,7 +4330,7 @@ catch (error) {
|
|
|
4330
4330
|
|
|
4331
4331
|
return { statusCode: 200 };
|
|
4332
4332
|
};
|
|
4333
|
-
`;static createAnalyticsTable(n){return{[`${n.slug}EmailAnalyticsTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${n.slug}-email-analytics`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"messageId",AttributeType:"S"}],KeySchema:[{AttributeName:"messageId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createTrackingPixelLambda(n){return{[`${n.slug}TrackingPixelLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${n.slug}-tracking-pixel`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n.roleArn,Timeout:10,MemorySize:128,Code:{ZipFile:
|
|
4333
|
+
`;static createAnalyticsTable(n){return{[`${n.slug}EmailAnalyticsTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${n.slug}-email-analytics`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"messageId",AttributeType:"S"}],KeySchema:[{AttributeName:"messageId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createTrackingPixelLambda(n){return{[`${n.slug}TrackingPixelLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${n.slug}-tracking-pixel`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n.roleArn,Timeout:10,MemorySize:128,Code:{ZipFile:it.TrackingPixelLambdaCode},Environment:{Variables:{ANALYTICS_TABLE:n.analyticsTable}}}}}}static createClickTrackingLambda(n){return{[`${n.slug}ClickTrackingLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${n.slug}-click-tracking`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n.roleArn,Timeout:10,MemorySize:128,Code:{ZipFile:it.ClickTrackingLambdaCode},Environment:{Variables:{ANALYTICS_TABLE:n.analyticsTable}}}}}}static createSesEventProcessorLambda(n){return{[`${n.slug}SesEventProcessorLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${n.slug}-ses-event-processor`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:it.SesEventProcessorCode},Environment:{Variables:{ANALYTICS_TABLE:n.analyticsTable}}}}}}static injectTracking(n){let{html:i,messageId:s,trackingDomain:o}=n,c=`<img src="https://${o}/track/open/${s}" width="1" height="1" style="display:none" alt="" />`,u=i.replace("</body>",`${c}</body>`);return u=u.replace(/href="(https?:\/\/[^"]+)"/g,(d,f)=>{let h=encodeURIComponent(f);return`href="https://${o}/track/click/${s}?url=${h}"`}),u}static calculateMetrics(n){let i=n.filter((h)=>h.sent).length,s=n.filter((h)=>h.delivered).length,o=n.filter((h)=>h.opened).length,c=n.filter((h)=>h.clicked).length,u=n.filter((h)=>h.bounced).length,d=n.filter((h)=>h.complained).length,f=n.filter((h)=>h.unsubscribed).length;return{period:new Date().toISOString(),sent:i,delivered:s,opened:o,clicked:c,bounced:u,complained:d,unsubscribed:f,deliveryRate:i>0?s/i*100:0,openRate:s>0?o/s*100:0,clickRate:o>0?c/o*100:0,bounceRate:i>0?u/i*100:0,complaintRate:s>0?d/s*100:0}}}class ke{static TemplateRendererCode=`
|
|
4334
4334
|
const { S3Client, GetObjectCommand } = require('@aws-sdk/client-s3');
|
|
4335
4335
|
|
|
4336
4336
|
const s3 = new S3Client({});
|
|
@@ -4585,7 +4585,7 @@ The {{appName}} Team`,variables:["appName","userName","resetUrl","expiresIn"],ca
|
|
|
4585
4585
|
|
|
4586
4586
|
<p>Best regards,<br>The {{appName}} Team</p>
|
|
4587
4587
|
</body>
|
|
4588
|
-
</html>`,variables:["invoiceNumber","customerName","period","items","total","paymentUrl","appName"],category:"billing"}};static createTemplateBucket(n){return{[`${n.slug}EmailTemplateBucket`]:{Type:"AWS::S3::Bucket",Properties:{BucketName:`${n.slug}-email-templates`,VersioningConfiguration:{Status:"Enabled"}}}}}static createTemplateRendererLambda(n){return{[`${n.slug}TemplateRendererLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${n.slug}-template-renderer`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:
|
|
4588
|
+
</html>`,variables:["invoiceNumber","customerName","period","items","total","paymentUrl","appName"],category:"billing"}};static createTemplateBucket(n){return{[`${n.slug}EmailTemplateBucket`]:{Type:"AWS::S3::Bucket",Properties:{BucketName:`${n.slug}-email-templates`,VersioningConfiguration:{Status:"Enabled"}}}}}static createTemplateRendererLambda(n){return{[`${n.slug}TemplateRendererLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${n.slug}-template-renderer`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:ke.TemplateRendererCode},Environment:{Variables:{TEMPLATE_BUCKET:n.templateBucket}}}}}}static render(n,i){if(!n||!i)return n;let s=n;return s=s.replace(/\{\{\s*([\w.]+)\s*\}\}/g,(o,c)=>{let u=ke.getNestedValue(i,c);return u!==void 0?String(u):o}),s=s.replace(/\{\{#if\s+([\w.]+)\}\}([\s\S]*?)\{\{\/if\}\}/g,(o,c,u)=>ke.getNestedValue(i,c)?u:""),s=s.replace(/\{\{#unless\s+([\w.]+)\}\}([\s\S]*?)\{\{\/unless\}\}/g,(o,c,u)=>!ke.getNestedValue(i,c)?u:""),s=s.replace(/\{\{#each\s+([\w.]+)\}\}([\s\S]*?)\{\{\/each\}\}/g,(o,c,u)=>{let d=ke.getNestedValue(i,c);if(!Array.isArray(d))return"";return d.map((f,h)=>{let S=u;if(S=S.replace(/\{\{this\}\}/g,String(f)),S=S.replace(/\{\{@index\}\}/g,String(h)),typeof f==="object")Object.entries(f).forEach(([A,T])=>{S=S.replace(new RegExp(`\\{\\{\\s*${A}\\s*\\}\\}`,"g"),String(T))});return S}).join("")}),s}static getNestedValue(n,i){return i.split(".").reduce((s,o)=>s?.[o],n)}static extractVariables(n){let i=new Set,s=n.matchAll(/\{\{\s*([\w.]+)\s*\}\}/g);for(let c of s)if(!c[1].startsWith("#")&&!c[1].startsWith("/")&&!c[1].startsWith("@"))i.add(c[1].split(".")[0]);let o=n.matchAll(/\{\{#(?:if|unless|each)\s+([\w.]+)\}\}/g);for(let c of o)i.add(c[1].split(".")[0]);return Array.from(i)}}class Vt{static SharedMailboxLambdaCode=`
|
|
4589
4589
|
const { S3Client, GetObjectCommand } = require('@aws-sdk/client-s3');
|
|
4590
4590
|
const { DynamoDBClient, GetItemCommand, PutItemCommand, QueryCommand, UpdateItemCommand } = require('@aws-sdk/client-dynamodb');
|
|
4591
4591
|
|
|
@@ -5637,7 +5637,7 @@ else if (jobStatus === 'FAILED') {
|
|
|
5637
5637
|
|
|
5638
5638
|
return { statusCode: 200 };
|
|
5639
5639
|
};
|
|
5640
|
-
`;static createRecordingsTable(n){return{[`${n.slug}CallRecordingsTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${n.slug}-call-recordings`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"recordingId",AttributeType:"S"},{AttributeName:"transcriptionJobName",AttributeType:"S"}],KeySchema:[{AttributeName:"recordingId",KeyType:"HASH"}],GlobalSecondaryIndexes:[{IndexName:"job-index",KeySchema:[{AttributeName:"transcriptionJobName",KeyType:"HASH"}],Projection:{ProjectionType:"ALL"}}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createRecordingProcessorLambda(n){return{[`${n.slug}RecordingProcessorLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${n.slug}-recording-processor`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n.roleArn,Timeout:60,MemorySize:256,Code:{ZipFile:Ht.RecordingProcessorCode},Environment:{Variables:{RECORDING_BUCKET:n.recordingBucket,RECORDINGS_TABLE:n.recordingsTable}}}}}}}class
|
|
5640
|
+
`;static createRecordingsTable(n){return{[`${n.slug}CallRecordingsTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${n.slug}-call-recordings`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"recordingId",AttributeType:"S"},{AttributeName:"transcriptionJobName",AttributeType:"S"}],KeySchema:[{AttributeName:"recordingId",KeyType:"HASH"}],GlobalSecondaryIndexes:[{IndexName:"job-index",KeySchema:[{AttributeName:"transcriptionJobName",KeyType:"HASH"}],Projection:{ProjectionType:"ALL"}}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createRecordingProcessorLambda(n){return{[`${n.slug}RecordingProcessorLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${n.slug}-recording-processor`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n.roleArn,Timeout:60,MemorySize:256,Code:{ZipFile:Ht.RecordingProcessorCode},Environment:{Variables:{RECORDING_BUCKET:n.recordingBucket,RECORDINGS_TABLE:n.recordingsTable}}}}}}}class Be{nodes=[];connections=[];startNodeId="";static create(n){return new Be}start(){let n={id:this.generateId(),type:"start",position:{x:0,y:0},config:{}};return this.nodes.push(n),this.startNodeId=n.id,this}playPrompt(n,i){let s={id:this.generateId(),type:"play-prompt",position:{x:0,y:0},config:{text:n,textType:i?.ssml?"ssml":"text",voice:i?.voice||"Joanna"}};return this.nodes.push(s),this.connectToLast(s.id),this}getInput(n,i){let s={id:this.generateId(),type:"get-input",position:{x:0,y:0},config:{prompt:n,maxDigits:i?.maxDigits||1,timeout:i?.timeout||5,errorPrompt:i?.errorPrompt||"Sorry, I didn't get that."}};return this.nodes.push(s),this.connectToLast(s.id),this}menu(n,i){let s={id:this.generateId(),type:"menu",position:{x:0,y:0},config:{prompt:n,options:i}};return this.nodes.push(s),this.connectToLast(s.id),this}transferToQueue(n,i){let s={id:this.generateId(),type:"transfer-queue",position:{x:0,y:0},config:{queueArn:n,priority:i?.priority||5}};return this.nodes.push(s),this.connectToLast(s.id),this}transferToPhone(n){let i={id:this.generateId(),type:"transfer-phone",position:{x:0,y:0},config:{phoneNumber:n}};return this.nodes.push(i),this.connectToLast(i.id),this}invokeLambda(n,i){let s={id:this.generateId(),type:"invoke-lambda",position:{x:0,y:0},config:{functionArn:n,timeout:i?.timeout||8}};return this.nodes.push(s),this.connectToLast(s.id),this}setAttribute(n,i){let s={id:this.generateId(),type:"set-attribute",position:{x:0,y:0},config:{key:n,value:i}};return this.nodes.push(s),this.connectToLast(s.id),this}checkHours(n){let i={id:this.generateId(),type:"check-hours",position:{x:0,y:0},config:{hoursOfOperationArn:n}};return this.nodes.push(i),this.connectToLast(i.id),this}recordVoicemail(n){let i={id:this.generateId(),type:"record-voicemail",position:{x:0,y:0},config:{maxDuration:n?.maxDuration||120,greeting:n?.greeting||"Please leave a message after the beep.",beep:n?.beep!==!1}};return this.nodes.push(i),this.connectToLast(i.id),this}wait(n){let i={id:this.generateId(),type:"wait",position:{x:0,y:0},config:{seconds:n}};return this.nodes.push(i),this.connectToLast(i.id),this}disconnect(){let n={id:this.generateId(),type:"disconnect",position:{x:0,y:0},config:{}};return this.nodes.push(n),this.connectToLast(n.id),this}build(){return{id:this.generateId(),name:"IVR Flow",nodes:this.nodes,connections:this.connections,startNodeId:this.startNodeId,version:1,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}}toContactFlow(){let n=[],i=new Map(this.nodes.map((o)=>[o.id,o]));for(let o of this.nodes){let c=this.nodeToAction(o,i);if(c)n.push(c)}let s={Version:"2019-10-30",StartAction:this.startNodeId,Actions:n};return JSON.stringify(s,null,2)}nodeToAction(n,i){let s=this.getNextNodeId(n.id),o={NextAction:s||"disconnect",Errors:[{NextAction:"disconnect"}]};switch(n.type){case"start":return null;case"play-prompt":return{Identifier:n.id,Type:"MessageParticipant",Parameters:{Text:n.config.text,TextType:n.config.textType},Transitions:o};case"get-input":return{Identifier:n.id,Type:"GetParticipantInput",Parameters:{Text:n.config.prompt,InputTimeLimitSeconds:n.config.timeout,MaxDigits:n.config.maxDigits},Transitions:{...o,Conditions:[]}};case"transfer-queue":return{Identifier:n.id,Type:"TransferToQueue",Parameters:{QueueId:n.config.queueArn},Transitions:o};case"transfer-phone":return{Identifier:n.id,Type:"TransferToPhoneNumber",Parameters:{PhoneNumber:n.config.phoneNumber},Transitions:o};case"invoke-lambda":return{Identifier:n.id,Type:"InvokeLambdaFunction",Parameters:{LambdaFunctionARN:n.config.functionArn,InvocationTimeLimitSeconds:n.config.timeout},Transitions:o};case"set-attribute":return{Identifier:n.id,Type:"UpdateContactAttributes",Parameters:{Attributes:{[n.config.key]:n.config.value}},Transitions:o};case"check-hours":return{Identifier:n.id,Type:"CheckHoursOfOperation",Parameters:{HoursOfOperationId:n.config.hoursOfOperationArn},Transitions:{NextAction:s,Conditions:[{NextAction:s,Condition:{Operator:"Equals",Operands:["True"]}}],Errors:[{NextAction:"disconnect"}]}};case"wait":return{Identifier:n.id,Type:"Wait",Parameters:{Seconds:n.config.seconds},Transitions:o};case"disconnect":return{Identifier:n.id,Type:"DisconnectParticipant",Parameters:{},Transitions:{}};default:return null}}connectToLast(n){if(this.nodes.length>1){let i=this.nodes[this.nodes.length-2];this.connections.push({id:this.generateId(),sourceNodeId:i.id,targetNodeId:n,sourcePort:"default"})}}getNextNodeId(n){return this.connections.find((s)=>s.sourceNodeId===n)?.targetNodeId||null}generateId(){return`node-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}static Templates={basicSupport:()=>Be.create("Basic Support").start().playPrompt("Welcome to customer support.").menu("Press 1 for sales, 2 for support, or 3 to leave a message.",{"1":"sales","2":"support","3":"voicemail"}),afterHours:(n)=>Be.create("After Hours").start().playPrompt(n).recordVoicemail({greeting:"Please leave your name, number, and a brief message.",maxDuration:120}).playPrompt("Thank you for your message. Goodbye.").disconnect(),callbackRequest:(n)=>Be.create("Callback Request").start().playPrompt("All agents are currently busy.").getInput("Press 1 to request a callback, or 2 to wait.",{maxDigits:1}).invokeLambda(n).playPrompt("We will call you back shortly. Goodbye.").disconnect()}}class jt{static MetricsAggregatorCode=`
|
|
5641
5641
|
const { DynamoDBClient, PutItemCommand, ScanCommand } = require('@aws-sdk/client-dynamodb');
|
|
5642
5642
|
|
|
5643
5643
|
const dynamodb = new DynamoDBClient({});
|
|
@@ -5836,7 +5836,7 @@ catch (error) {
|
|
|
5836
5836
|
};
|
|
5837
5837
|
}
|
|
5838
5838
|
};
|
|
5839
|
-
`;static createMetricsTable(n){return{[`${n.slug}CallMetricsTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${n.slug}-call-metrics`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"period",AttributeType:"S"}],KeySchema:[{AttributeName:"period",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createMetricsAggregatorLambda(n){return{[`${n.slug}CallMetricsAggregatorLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${n.slug}-call-metrics-aggregator`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n.roleArn,Timeout:60,MemorySize:256,Code:{ZipFile:jt.MetricsAggregatorCode},Environment:{Variables:{CALL_LOG_TABLE:n.callLogTable,METRICS_TABLE:n.metricsTable}}}}}}static createMetricsSchedule(n){return{[`${n.slug}CallMetricsSchedule`]:{Type:"AWS::Events::Rule",Properties:{Name:`${n.slug}-call-metrics-schedule`,Description:"Aggregate call metrics hourly",ScheduleExpression:"rate(1 hour)",State:"ENABLED",Targets:[{Id:"MetricsAggregatorTarget",Arn:n.lambdaArn}]}}}}}class
|
|
5839
|
+
`;static createMetricsTable(n){return{[`${n.slug}CallMetricsTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${n.slug}-call-metrics`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"period",AttributeType:"S"}],KeySchema:[{AttributeName:"period",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createMetricsAggregatorLambda(n){return{[`${n.slug}CallMetricsAggregatorLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${n.slug}-call-metrics-aggregator`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n.roleArn,Timeout:60,MemorySize:256,Code:{ZipFile:jt.MetricsAggregatorCode},Environment:{Variables:{CALL_LOG_TABLE:n.callLogTable,METRICS_TABLE:n.metricsTable}}}}}}static createMetricsSchedule(n){return{[`${n.slug}CallMetricsSchedule`]:{Type:"AWS::Events::Rule",Properties:{Name:`${n.slug}-call-metrics-schedule`,Description:"Aggregate call metrics hourly",ScheduleExpression:"rate(1 hour)",State:"ENABLED",Targets:[{Id:"MetricsAggregatorTarget",Arn:n.lambdaArn}]}}}}}class mt{static CallbackRequestCode=`
|
|
5840
5840
|
const { DynamoDBClient, PutItemCommand, UpdateItemCommand } = require('@aws-sdk/client-dynamodb');
|
|
5841
5841
|
const { ConnectClient, StartOutboundVoiceContactCommand } = require('@aws-sdk/client-connect');
|
|
5842
5842
|
const { SNSClient, PublishCommand } = require('@aws-sdk/client-sns');
|
|
@@ -6126,7 +6126,7 @@ catch (error) {
|
|
|
6126
6126
|
return { statusCode: 500, error: error.message };
|
|
6127
6127
|
}
|
|
6128
6128
|
};
|
|
6129
|
-
`;static createCallbacksTable(n){return{[`${n.slug}CallbacksTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${n.slug}-callbacks`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createCallbackRequestLambda(n){return{[`${n.slug}CallbackRequestLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${n.slug}-callback-request`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:
|
|
6129
|
+
`;static createCallbacksTable(n){return{[`${n.slug}CallbacksTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${n.slug}-callbacks`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createCallbackRequestLambda(n){return{[`${n.slug}CallbackRequestLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${n.slug}-callback-request`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:mt.CallbackRequestCode},Environment:{Variables:{CALLBACKS_TABLE:n.callbacksTable,NOTIFICATION_TOPIC_ARN:n.notificationTopicArn||""}}}}}}static createCallbackProcessorLambda(n){return{[`${n.slug}CallbackProcessorLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${n.slug}-callback-processor`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n.roleArn,Timeout:300,MemorySize:256,Code:{ZipFile:mt.CallbackProcessorCode},Environment:{Variables:{CALLBACKS_TABLE:n.callbacksTable,CONNECT_INSTANCE_ID:n.connectInstanceId,CONTACT_FLOW_ID:n.contactFlowId,SOURCE_PHONE_NUMBER:n.sourcePhoneNumber,QUEUE_ID:n.queueId||""}}}}}}}class Kt{static CampaignManagerCode=`
|
|
6130
6130
|
const { DynamoDBClient, PutItemCommand, GetItemCommand, UpdateItemCommand, ScanCommand } = require('@aws-sdk/client-dynamodb');
|
|
6131
6131
|
|
|
6132
6132
|
const dynamodb = new DynamoDBClient({});
|
|
@@ -7032,7 +7032,7 @@ function generateShortId() {
|
|
|
7032
7032
|
}
|
|
7033
7033
|
return id;
|
|
7034
7034
|
}
|
|
7035
|
-
`;static createLinksTable(n){return{[`${n.slug}ShortLinksTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${n.slug}-short-links`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createLinkShortenerLambda(n){return{[`${n.slug}LinkShortenerLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${n.slug}-link-shortener`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n.roleArn,Timeout:10,MemorySize:128,Code:{ZipFile:Jt.LinkShortenerCode},Environment:{Variables:{LINKS_TABLE:n.linksTable,SHORT_DOMAIN:n.shortDomain||""}}}}}}static shortenUrlsInMessage(n,i,s){let o=/(https?:\/\/[^\s]+)/g,c=[],u=0;return{message:n.replace(o,(f)=>{let h=`${s}-${u++}`,S=`https://${i}/l/${h}`;return c.push({original:f,short:S,id:h}),S}),links:c}}}class
|
|
7035
|
+
`;static createLinksTable(n){return{[`${n.slug}ShortLinksTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${n.slug}-short-links`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createLinkShortenerLambda(n){return{[`${n.slug}LinkShortenerLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${n.slug}-link-shortener`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n.roleArn,Timeout:10,MemorySize:128,Code:{ZipFile:Jt.LinkShortenerCode},Environment:{Variables:{LINKS_TABLE:n.linksTable,SHORT_DOMAIN:n.shortDomain||""}}}}}}static shortenUrlsInMessage(n,i,s){let o=/(https?:\/\/[^\s]+)/g,c=[],u=0;return{message:n.replace(o,(f)=>{let h=`${s}-${u++}`,S=`https://${i}/l/${h}`;return c.push({original:f,short:S,id:h}),S}),links:c}}}class Ee{static AbTestManagerCode=`
|
|
7036
7036
|
const { DynamoDBClient, PutItemCommand, GetItemCommand, UpdateItemCommand, ScanCommand } = require('@aws-sdk/client-dynamodb');
|
|
7037
7037
|
|
|
7038
7038
|
const dynamodb = new DynamoDBClient({});
|
|
@@ -7226,7 +7226,7 @@ function unmarshallTest(item) {
|
|
|
7226
7226
|
|
|
7227
7227
|
return test;
|
|
7228
7228
|
}
|
|
7229
|
-
`;static createAbTestsTable(n){return{[`${n.slug}AbTestsTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${n.slug}-ab-tests`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}]}}}}static createAbTestManagerLambda(n){return{[`${n.slug}AbTestManagerLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${n.slug}-ab-test-manager`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:Re.AbTestManagerCode},Environment:{Variables:{AB_TESTS_TABLE:n.abTestsTable}}}}}}static selectVariant(n,i){let o=Re.hashString(i+n.id)%100,c=0;for(let u=0;u<n.variants.length;u++)if(c+=n.trafficSplit[u],o<c)return n.variants[u];return n.variants[n.variants.length-1]}static determineWinner(n){if(n.variants.length===0)return null;let i=n.winningCriteria,s=n.variants[0],o=Re.getMetricValue(s,i);for(let c of n.variants.slice(1)){let u=Re.getMetricValue(c,i);if(u>o)o=u,s=c}return s}static calculateSignificance(n,i,s){let o=n.stats.sent,c=i.stats.sent;if(o<30||c<30)return 0;let u=Re.getMetricValue(n,s)/100,d=Re.getMetricValue(i,s)/100,f=(u*o+d*c)/(o+c),h=Math.sqrt(f*(1-f)*(1/o+1/c));if(h===0)return 0;let S=Math.abs(u-d)/h;if(S>=2.576)return 99;if(S>=1.96)return 95;if(S>=1.645)return 90;if(S>=1.28)return 80;return Math.round(S*30)}static getMetricValue(n,i){switch(i){case"delivery_rate":return n.stats.deliveryRate;case"click_rate":return n.stats.clickRate;case"reply_rate":return n.stats.replyRate;case"conversion_rate":return n.stats.conversionRate;default:return n.stats.deliveryRate}}static hashString(n){let i=0;for(let s=0;s<n.length;s++){let o=n.charCodeAt(s);i=(i<<5)-i+o,i=i&i}return Math.abs(i)}}class uf{queues=new Map;messageGroups=new Map;deduplicationConfigs=new Map;messages=new Map;queueCounter=0;groupCounter=0;deduplicationCounter=0;messageCounter=0;sequenceCounter=0;createFIFOQueue(n){let i=`fifo-queue-${Date.now()}-${this.queueCounter++}`,s=n.name.endsWith(".fifo")?n.name:`${n.name}.fifo`,{name:o,...c}=n,u={id:i,name:s,queueUrl:`https://sqs.us-east-1.amazonaws.com/123456789012/${s}`,...c};return this.queues.set(i,u),this.createDeduplicationConfig({queueId:i,contentBasedDeduplication:n.contentBasedDeduplication,deduplicationInterval:300}),u}createHighThroughputFIFO(n){return this.createFIFOQueue({name:n.name,contentBasedDeduplication:n.contentBasedDeduplication??!0,deduplicationScope:"messageGroup",fifoThroughputLimit:"perMessageGroupId",messageRetentionPeriod:345600,visibilityTimeout:30,receiveMessageWaitTime:0})}createStandardFIFO(n){return this.createFIFOQueue({name:n.name,contentBasedDeduplication:n.contentBasedDeduplication??!1,deduplicationScope:"queue",fifoThroughputLimit:"perQueue",messageRetentionPeriod:345600,visibilityTimeout:30,receiveMessageWaitTime:0})}createDeduplicationConfig(n){let s={id:`dedup-${Date.now()}-${this.deduplicationCounter++}`,deduplicationHashes:new Map,...n};return this.deduplicationConfigs.set(n.queueId,s),s}sendMessage(n){let i=this.queues.get(n.queueId);if(!i)throw Error(`Queue not found: ${n.queueId}`);let s=this.deduplicationConfigs.get(n.queueId);if(s){let d=n.messageDeduplicationId||(i.contentBasedDeduplication?this.generateHash(n.messageBody):void 0);if(d&&this.isDuplicate(s,d))return null;if(d)s.deduplicationHashes.set(d,new Date)}let o=`msg-${Date.now()}-${this.messageCounter++}`,c=this.generateSequenceNumber(),u={id:o,messageId:o,messageGroupId:n.messageGroupId,messageDeduplicationId:n.messageDeduplicationId,body:n.messageBody,attributes:n.messageAttributes||{},sentTimestamp:new Date,sequenceNumber:c};return this.messages.set(o,u),this.updateMessageGroup(n.queueId,n.messageGroupId),u}isDuplicate(n,i){let s=n.deduplicationHashes.get(i);if(!s)return!1;if((Date.now()-s.getTime())/1000>n.deduplicationInterval)return n.deduplicationHashes.delete(i),!1;return!0}generateHash(n){let i=0;for(let s=0;s<n.length;s++){let o=n.charCodeAt(s);i=(i<<5)-i+o,i=i&i}return Math.abs(i).toString(36)}generateSequenceNumber(){return`${Date.now()}${this.sequenceCounter++}`.padStart(20,"0")}updateMessageGroup(n,i){let s=`${n}-${i}`,o=this.messageGroups.get(s);if(!o)o={id:`group-${Date.now()}-${this.groupCounter++}`,messageGroupId:i,queueId:n,messagesInFlight:0},this.messageGroups.set(s,o);o.messagesInFlight++,o.lastMessageTimestamp=new Date}getMessageGroups(n){return Array.from(this.messageGroups.values()).filter((i)=>i.queueId===n)}getQueue(n){return this.queues.get(n)}listQueues(){return Array.from(this.queues.values())}getMessages(n,i){let s=Array.from(this.messages.values());if(i)s=s.filter((o)=>o.messageGroupId===i);return s.sort((o,c)=>o.sequenceNumber.localeCompare(c.sequenceNumber))}generateFIFOQueueCF(n){return{Type:"AWS::SQS::Queue",Properties:{QueueName:n.name,FifoQueue:!0,ContentBasedDeduplication:n.contentBasedDeduplication,DeduplicationScope:n.deduplicationScope,FifoThroughputLimit:n.fifoThroughputLimit,MessageRetentionPeriod:n.messageRetentionPeriod,VisibilityTimeout:n.visibilityTimeout,ReceiveMessageWaitTimeSeconds:n.receiveMessageWaitTime,...n.deadLetterTargetArn&&{RedrivePolicy:{deadLetterTargetArn:n.deadLetterTargetArn,maxReceiveCount:n.maxReceiveCount||3}}}}}clear(){this.queues.clear(),this.messageGroups.clear(),this.deduplicationConfigs.clear(),this.messages.clear(),this.queueCounter=0,this.groupCounter=0,this.deduplicationCounter=0,this.messageCounter=0,this.sequenceCounter=0}}var uE=new uf;class gf{monitors=new Map;metrics=new Map;alerts=new Map;reprocessJobs=new Map;monitorCounter=0;metricsCounter=0;alertCounter=0;jobCounter=0;createDLQMonitor(n){let i=`dlq-monitor-${Date.now()}-${this.monitorCounter++}`,s={id:i,...n};return this.monitors.set(i,s),s}createAutomatedMonitor(n){return this.createDLQMonitor({name:n.name,queueUrl:n.queueUrl,sourceQueues:n.sourceQueues,maxReceiveCount:3,alarmThreshold:10,autoReprocess:!0,reprocessStrategy:"scheduled",notificationTopicArn:n.notificationTopicArn})}collectMetrics(n){let s={id:`metrics-${Date.now()}-${this.metricsCounter++}`,queueUrl:n,timestamp:new Date,approximateNumberOfMessages:Math.floor(Math.random()*100),approximateAgeOfOldestMessage:Math.floor(Math.random()*86400),messagesReceived:Math.floor(Math.random()*50),messagesDeleted:Math.floor(Math.random()*30),messagesReprocessed:Math.floor(Math.random()*20)},o=this.metrics.get(n)||[];return o.push(s),this.metrics.set(n,o),this.checkForAlerts(n,s),s}checkForAlerts(n,i){let s=Array.from(this.monitors.values()).find((c)=>c.queueUrl===n);if(!s)return;if(i.approximateNumberOfMessages>=s.alarmThreshold)this.createAlert({monitorId:s.id,alertType:"threshold_exceeded",severity:"high",message:`DLQ ${s.name} has ${i.approximateNumberOfMessages} messages (threshold: ${s.alarmThreshold})`});let o=3600;if(i.approximateAgeOfOldestMessage>o)this.createAlert({monitorId:s.id,alertType:"old_message",severity:"medium",message:`DLQ ${s.name} has messages older than ${o} seconds`})}createAlert(n){let i=`alert-${Date.now()}-${this.alertCounter++}`,s={id:i,timestamp:new Date,acknowledged:!1,...n};return this.alerts.set(i,s),s}acknowledgeAlert(n){let i=this.alerts.get(n);if(!i)throw Error(`Alert not found: ${n}`);return i.acknowledged=!0,i}createReprocessJob(n){let i=`reprocess-${Date.now()}-${this.jobCounter++}`,s={id:i,queueUrl:n.queueUrl,messageId:n.messageId,attempts:0,status:"pending"};return this.reprocessJobs.set(i,s),s}async executeReprocessJob(n){let i=this.reprocessJobs.get(n);if(!i)throw Error(`Reprocess job not found: ${n}`);i.status="processing",i.startedAt=new Date,i.attempts++,await new Promise((o)=>setTimeout(o,100));let s=Math.random()>0.3;if(i.status=s?"success":"failed",i.completedAt=new Date,!s)i.error="Reprocessing failed - original error still present";return i}async batchReprocess(n){let i=[];for(let s=0;s<n.maxMessages;s++){let o=this.createReprocessJob({queueUrl:n.queueUrl,messageId:`msg-${s}`});await this.executeReprocessJob(o.id),i.push(o)}return i}getDLQStatistics(n,i=24){let s=new Date(Date.now()-i*60*60*1000),o=(this.metrics.get(n)||[]).filter((A)=>A.timestamp>=s);if(o.length===0)return{totalMessages:0,avgAge:0,messagesReceived:0,messagesDeleted:0,messagesReprocessed:0,successRate:0};let c=o[o.length-1],u=o.reduce((A,T)=>A+T.messagesReceived,0),d=o.reduce((A,T)=>A+T.messagesDeleted,0),f=o.reduce((A,T)=>A+T.messagesReprocessed,0),h=o.reduce((A,T)=>A+T.approximateAgeOfOldestMessage,0)/o.length,S=f>0?d/f*100:0;return{totalMessages:c.approximateNumberOfMessages,avgAge:h,messagesReceived:u,messagesDeleted:d,messagesReprocessed:f,successRate:S}}getMonitor(n){return this.monitors.get(n)}listMonitors(){return Array.from(this.monitors.values())}getAlerts(n,i){let s=Array.from(this.alerts.values());if(n)s=s.filter((o)=>o.monitorId===n);if(i!==void 0)s=s.filter((o)=>o.acknowledged===i);return s.sort((o,c)=>c.timestamp.getTime()-o.timestamp.getTime())}getReprocessJobs(n){let i=Array.from(this.reprocessJobs.values());if(n)i=i.filter((s)=>s.queueUrl===n);return i}generateDLQAlarmCF(n){return{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${n.name}-messages-alarm`,AlarmDescription:`Alert when DLQ ${n.name} exceeds threshold`,MetricName:"ApproximateNumberOfMessagesVisible",Namespace:"AWS/SQS",Statistic:"Average",Period:300,EvaluationPeriods:1,Threshold:n.alarmThreshold,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:n.queueUrl.split("/").pop()}],...n.notificationTopicArn&&{AlarmActions:[n.notificationTopicArn]}}}}clear(){this.monitors.clear(),this.metrics.clear(),this.alerts.clear(),this.reprocessJobs.clear(),this.monitorCounter=0,this.metricsCounter=0,this.alertCounter=0,this.jobCounter=0}}var gE=new gf;class pf{configs=new Map;jobs=new Map;metrics=new Map;configCounter=0;jobCounter=0;metricsCounter=0;createBatchConfig(n){let i=`batch-config-${Date.now()}-${this.configCounter++}`,s={id:i,...n};return this.configs.set(i,s),s}createHighThroughputConfig(n){return this.createBatchConfig({queueUrl:n.queueUrl,batchSize:10,maxWaitTime:100,parallelProcessors:10,retryAttempts:3,visibilityTimeout:30})}createLowLatencyConfig(n){return this.createBatchConfig({queueUrl:n.queueUrl,batchSize:1,maxWaitTime:0,parallelProcessors:5,retryAttempts:2,visibilityTimeout:10})}createBatchJob(n){let i=`batch-job-${Date.now()}-${this.jobCounter++}`;if(!this.configs.get(n.configId))throw Error(`Batch config not found: ${n.configId}`);let o=[];for(let u=0;u<n.messageCount;u++)o.push({id:`msg-${i}-${u}`,messageId:`${i}-${u}`,body:`Message ${u}`,receiptHandle:`receipt-${i}-${u}`,attributes:{},status:"pending"});let c={id:i,configId:n.configId,messages:o,status:"pending",processedCount:0,failedCount:0};return this.jobs.set(i,c),c}async processBatchJob(n){let i=this.jobs.get(n);if(!i)throw Error(`Batch job not found: ${n}`);let s=this.configs.get(i.configId);if(!s)throw Error(`Batch config not found: ${i.configId}`);i.status="processing",i.startedAt=new Date;let o=this.chunkArray(i.messages,s.batchSize);for(let c of o)await this.processBatch(c,s);return i.processedCount=i.messages.filter((c)=>c.status==="success").length,i.failedCount=i.messages.filter((c)=>c.status==="failed").length,i.status=i.failedCount===0?"completed":"failed",i.completedAt=new Date,this.collectProcessorMetrics(s.id,i),i}async processBatch(n,i){let s=n.map((o)=>this.processMessage(o,i));await Promise.all(s)}async processMessage(n,i){n.status="processing";let s=Date.now();await new Promise((u)=>setTimeout(u,Math.random()*100));let o=Date.now()-s;if(n.processingTime=o,Math.random()>0.1)n.status="success";else n.status="failed",n.error="Processing error"}chunkArray(n,i){let s=[];for(let o=0;o<n.length;o+=i)s.push(n.slice(o,o+i));return s}collectProcessorMetrics(n,i){let s=`metrics-${Date.now()}-${this.metricsCounter++}`,c=i.messages.filter((T)=>T.status==="success").map((T)=>T.processingTime||0).filter((T)=>T>0),u=c.length>0?c.reduce((T,v)=>T+v,0)/c.length:0,d=i.completedAt&&i.startedAt?(i.completedAt.getTime()-i.startedAt.getTime())/1000:1,f=i.processedCount/d,h=i.messages.length>0?i.failedCount/i.messages.length*100:0,S={id:s,configId:n,timestamp:new Date,messagesProcessed:i.processedCount,averageProcessingTime:u,throughput:f,errorRate:h},A=this.metrics.get(n)||[];A.push(S),this.metrics.set(n,A)}getBatchStatistics(n){let i=this.metrics.get(n)||[];if(i.length===0)return{totalJobsProcessed:0,totalMessagesProcessed:0,averageThroughput:0,averageErrorRate:0,averageProcessingTime:0};let s=i.reduce((d,f)=>d+f.messagesProcessed,0),o=i.reduce((d,f)=>d+f.throughput,0)/i.length,c=i.reduce((d,f)=>d+f.errorRate,0)/i.length,u=i.reduce((d,f)=>d+f.averageProcessingTime,0)/i.length;return{totalJobsProcessed:i.length,totalMessagesProcessed:s,averageThroughput:o,averageErrorRate:c,averageProcessingTime:u}}optimizeBatchConfig(n){let i=this.configs.get(n);if(!i)throw Error(`Batch config not found: ${n}`);let s=this.getBatchStatistics(n);if(s.averageErrorRate<5&&i.batchSize<10)i.batchSize=Math.min(10,i.batchSize+1);if(s.averageErrorRate>20&&i.batchSize>1)i.batchSize=Math.max(1,i.batchSize-1);if(s.averageThroughput<5&&i.parallelProcessors<20)i.parallelProcessors++;return i}getConfig(n){return this.configs.get(n)}listConfigs(){return Array.from(this.configs.values())}getJob(n){return this.jobs.get(n)}listJobs(n){let i=Array.from(this.jobs.values());if(n)i=i.filter((s)=>s.configId===n);return i}generateBatchProcessorCF(n){return{Type:"AWS::Lambda::EventSourceMapping",Properties:{EventSourceArn:`arn:aws:sqs:us-east-1:123456789012:${n.queueUrl.split("/").pop()}`,FunctionName:"batch-processor-function",BatchSize:n.batchSize,MaximumBatchingWindowInSeconds:n.maxWaitTime/1000,FunctionResponseTypes:["ReportBatchItemFailures"]}}}clear(){this.configs.clear(),this.jobs.clear(),this.metrics.clear(),this.configCounter=0,this.jobCounter=0,this.metricsCounter=0}}var pE=new pf;class mf{queues=new Map;retentionPolicies=new Map;delayQueues=new Map;purgeOperations=new Map;metrics=new Map;queueCounter=0;retentionCounter=0;delayCounter=0;purgeCounter=0;metricsCounter=0;createQueue(n){let i=`queue-${Date.now()}-${this.queueCounter++}`,s={id:i,purgeInProgress:!1,...n};return this.queues.set(i,s),s}createStandardQueue(n){return this.createQueue({queueUrl:`https://sqs.us-east-1.amazonaws.com/123456789012/${n.queueName}`,queueName:n.queueName,messageRetentionPeriod:(n.messageRetentionDays||4)*24*60*60,delaySeconds:0,maximumMessageSize:262144,receiveMessageWaitTime:0})}createLongPollingQueue(n){return this.createQueue({queueUrl:`https://sqs.us-east-1.amazonaws.com/123456789012/${n.queueName}`,queueName:n.queueName,messageRetentionPeriod:345600,delaySeconds:0,maximumMessageSize:262144,receiveMessageWaitTime:n.waitTimeSeconds||20})}createRetentionPolicy(n){let i=`retention-${Date.now()}-${this.retentionCounter++}`,s={id:i,...n};this.retentionPolicies.set(i,s);let o=this.queues.get(n.queueId);if(o)o.messageRetentionPeriod=n.retentionPeriod;return s}createShortRetentionPolicy(n){return this.createRetentionPolicy({queueId:n.queueId,retentionPeriod:n.retentionHours*60*60,autoCleanup:!0,archiveExpiredMessages:!1})}createArchivalRetentionPolicy(n){return this.createRetentionPolicy({queueId:n.queueId,retentionPeriod:n.retentionDays*24*60*60,autoCleanup:!0,cleanupSchedule:"cron(0 0 * * ? *)",archiveExpiredMessages:!0,archiveS3Bucket:n.s3Bucket})}createDelayQueue(n){let i=`delay-${Date.now()}-${this.delayCounter++}`,s={id:i,...n};this.delayQueues.set(i,s);let o=Array.from(this.queues.values()).find((c)=>c.queueUrl===n.queueUrl);if(o)o.delaySeconds=n.defaultDelay;return s}createScheduledDelayQueue(n){return this.createDelayQueue({queueUrl:n.queueUrl,defaultDelay:n.delayMinutes*60,perMessageDelay:!1,maxDelay:900})}async purgeQueue(n){let i=this.queues.get(n);if(!i)throw Error(`Queue not found: ${n}`);if(i.purgeInProgress)throw Error("Purge already in progress for this queue");let s=`purge-${Date.now()}-${this.purgeCounter++}`,o={id:s,queueUrl:i.queueUrl,status:"in_progress",startedAt:new Date};return this.purgeOperations.set(s,o),i.purgeInProgress=!0,setTimeout(()=>{o.status="completed",o.completedAt=new Date,o.messagesPurged=Math.floor(Math.random()*1000),i.purgeInProgress=!1},100),o}collectQueueMetrics(n){let s={id:`metrics-${Date.now()}-${this.metricsCounter++}`,queueUrl:n,timestamp:new Date,approximateNumberOfMessages:Math.floor(Math.random()*1000),approximateNumberOfMessagesNotVisible:Math.floor(Math.random()*100),approximateNumberOfMessagesDelayed:Math.floor(Math.random()*50),oldestMessageAge:Math.floor(Math.random()*86400)},o=this.metrics.get(n)||[];return o.push(s),this.metrics.set(n,o),s}getQueueHealth(n){let i=this.metrics.get(n)||[];if(i.length===0)return{status:"healthy",issues:[],recommendations:[]};let s=i[i.length-1],o=[],c=[],u="healthy";if(s.approximateNumberOfMessages>1e4)u="critical",o.push("Large message backlog detected"),c.push("Increase consumer capacity");else if(s.approximateNumberOfMessages>1000)u="warning",o.push("Growing message backlog"),c.push("Monitor consumer performance");if(s.oldestMessageAge&&s.oldestMessageAge>3600){if(u!=="critical")u="warning";o.push("Old messages in queue"),c.push("Review message processing")}if(s.approximateNumberOfMessagesDelayed>100){if(u!=="critical")u="warning";o.push("High number of delayed messages")}return{status:u,issues:o,recommendations:c}}getQueue(n){return this.queues.get(n)}listQueues(){return Array.from(this.queues.values())}getRetentionPolicy(n){return this.retentionPolicies.get(n)}listRetentionPolicies(){return Array.from(this.retentionPolicies.values())}getPurgeOperations(n){let i=Array.from(this.purgeOperations.values());if(n)i=i.filter((s)=>s.queueUrl===n);return i}generateQueueCF(n){return{Type:"AWS::SQS::Queue",Properties:{QueueName:n.queueName,MessageRetentionPeriod:n.messageRetentionPeriod,DelaySeconds:n.delaySeconds,MaximumMessageSize:n.maximumMessageSize,ReceiveMessageWaitTimeSeconds:n.receiveMessageWaitTime}}}generateCleanupRuleCF(n){return{Type:"AWS::Events::Rule",Properties:{Name:`${n.id}-cleanup`,Description:"Automated queue cleanup",ScheduleExpression:n.cleanupSchedule||"cron(0 0 * * ? *)",State:"ENABLED",Targets:[{Arn:"arn:aws:lambda:us-east-1:123456789012:function:queue-cleanup",Id:n.id,Input:JSON.stringify({queueId:n.queueId,archiveBucket:n.archiveS3Bucket})}]}}}clear(){this.queues.clear(),this.retentionPolicies.clear(),this.delayQueues.clear(),this.purgeOperations.clear(),this.metrics.clear(),this.queueCounter=0,this.retentionCounter=0,this.delayCounter=0,this.purgeCounter=0,this.metricsCounter=0}}var mE=new mf;import{deflateRawSync as Mi}from"node:zlib";var Li=(()=>{let n=[];for(let i=0;i<256;i++){let s=i;for(let o=0;o<8;o++)s=s&1?3988292384^s>>>1:s>>>1;n[i]=s>>>0}return n})();function Oi(n){let i=4294967295;for(let s=0;s<n.length;s++)i=Li[(i^n[s])&255]^i>>>8;return(i^4294967295)>>>0}function $i(n){if(typeof n==="string")return Buffer.from(n,"utf-8");if(Buffer.isBuffer(n))return n;return Buffer.from(n)}function Bi(n){let i=Math.max(1980,n.getFullYear()),s=(n.getHours()<<11|n.getMinutes()<<5|n.getSeconds()>>1)&65535,o=(i-1980<<9|n.getMonth()+1<<5|n.getDate())&65535;return{time:s,date:o}}function rt(n){let i=[],s=[],o=0;for(let d of n){let f=$i(d.data),h=Mi(f),S=Oi(f),A=Buffer.from(d.name.replace(/\\/g,"/"),"utf-8"),{time:T,date:v}=Bi(d.date??new Date(0)),R=d.mode??420,P=Buffer.alloc(30+A.length);P.writeUInt32LE(67324752,0),P.writeUInt16LE(20,4),P.writeUInt16LE(0,6),P.writeUInt16LE(8,8),P.writeUInt16LE(T,10),P.writeUInt16LE(v,12),P.writeUInt32LE(S,14),P.writeUInt32LE(h.length,18),P.writeUInt32LE(f.length,22),P.writeUInt16LE(A.length,26),P.writeUInt16LE(0,28),A.copy(P,30);let E=Buffer.alloc(46+A.length);E.writeUInt32LE(33639248,0),E.writeUInt16LE(798,4),E.writeUInt16LE(20,6),E.writeUInt16LE(0,8),E.writeUInt16LE(8,10),E.writeUInt16LE(T,12),E.writeUInt16LE(v,14),E.writeUInt32LE(S,16),E.writeUInt32LE(h.length,20),E.writeUInt32LE(f.length,24),E.writeUInt16LE(A.length,28),E.writeUInt16LE(0,30),E.writeUInt16LE(0,32),E.writeUInt16LE(0,34),E.writeUInt16LE(0,36),E.writeUInt32LE((R&65535)<<16,38),E.writeUInt32LE(o,42),A.copy(E,46),i.push(P,h),s.push(E),o+=P.length+h.length}let c=Buffer.concat(s),u=Buffer.alloc(22);return u.writeUInt32LE(101010256,0),u.writeUInt16LE(0,4),u.writeUInt16LE(0,6),u.writeUInt16LE(n.length,8),u.writeUInt16LE(n.length,10),u.writeUInt32LE(c.length,12),u.writeUInt32LE(o,16),u.writeUInt16LE(0,20),Buffer.concat([...i,c,u])}function ff(n){let i=n.adapterImport??"./adapter",s=n.entryImport.replace(/\\/g,"/");return`// Generated by ts-cloud — serverless app bootstrap. Do not edit.
|
|
7229
|
+
`;static createAbTestsTable(n){return{[`${n.slug}AbTestsTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${n.slug}-ab-tests`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}]}}}}static createAbTestManagerLambda(n){return{[`${n.slug}AbTestManagerLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${n.slug}-ab-test-manager`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:Ee.AbTestManagerCode},Environment:{Variables:{AB_TESTS_TABLE:n.abTestsTable}}}}}}static selectVariant(n,i){let o=Ee.hashString(i+n.id)%100,c=0;for(let u=0;u<n.variants.length;u++)if(c+=n.trafficSplit[u],o<c)return n.variants[u];return n.variants[n.variants.length-1]}static determineWinner(n){if(n.variants.length===0)return null;let i=n.winningCriteria,s=n.variants[0],o=Ee.getMetricValue(s,i);for(let c of n.variants.slice(1)){let u=Ee.getMetricValue(c,i);if(u>o)o=u,s=c}return s}static calculateSignificance(n,i,s){let o=n.stats.sent,c=i.stats.sent;if(o<30||c<30)return 0;let u=Ee.getMetricValue(n,s)/100,d=Ee.getMetricValue(i,s)/100,f=(u*o+d*c)/(o+c),h=Math.sqrt(f*(1-f)*(1/o+1/c));if(h===0)return 0;let S=Math.abs(u-d)/h;if(S>=2.576)return 99;if(S>=1.96)return 95;if(S>=1.645)return 90;if(S>=1.28)return 80;return Math.round(S*30)}static getMetricValue(n,i){switch(i){case"delivery_rate":return n.stats.deliveryRate;case"click_rate":return n.stats.clickRate;case"reply_rate":return n.stats.replyRate;case"conversion_rate":return n.stats.conversionRate;default:return n.stats.deliveryRate}}static hashString(n){let i=0;for(let s=0;s<n.length;s++){let o=n.charCodeAt(s);i=(i<<5)-i+o,i=i&i}return Math.abs(i)}}class uf{queues=new Map;messageGroups=new Map;deduplicationConfigs=new Map;messages=new Map;queueCounter=0;groupCounter=0;deduplicationCounter=0;messageCounter=0;sequenceCounter=0;createFIFOQueue(n){let i=`fifo-queue-${Date.now()}-${this.queueCounter++}`,s=n.name.endsWith(".fifo")?n.name:`${n.name}.fifo`,{name:o,...c}=n,u={id:i,name:s,queueUrl:`https://sqs.us-east-1.amazonaws.com/123456789012/${s}`,...c};return this.queues.set(i,u),this.createDeduplicationConfig({queueId:i,contentBasedDeduplication:n.contentBasedDeduplication,deduplicationInterval:300}),u}createHighThroughputFIFO(n){return this.createFIFOQueue({name:n.name,contentBasedDeduplication:n.contentBasedDeduplication??!0,deduplicationScope:"messageGroup",fifoThroughputLimit:"perMessageGroupId",messageRetentionPeriod:345600,visibilityTimeout:30,receiveMessageWaitTime:0})}createStandardFIFO(n){return this.createFIFOQueue({name:n.name,contentBasedDeduplication:n.contentBasedDeduplication??!1,deduplicationScope:"queue",fifoThroughputLimit:"perQueue",messageRetentionPeriod:345600,visibilityTimeout:30,receiveMessageWaitTime:0})}createDeduplicationConfig(n){let s={id:`dedup-${Date.now()}-${this.deduplicationCounter++}`,deduplicationHashes:new Map,...n};return this.deduplicationConfigs.set(n.queueId,s),s}sendMessage(n){let i=this.queues.get(n.queueId);if(!i)throw Error(`Queue not found: ${n.queueId}`);let s=this.deduplicationConfigs.get(n.queueId);if(s){let d=n.messageDeduplicationId||(i.contentBasedDeduplication?this.generateHash(n.messageBody):void 0);if(d&&this.isDuplicate(s,d))return null;if(d)s.deduplicationHashes.set(d,new Date)}let o=`msg-${Date.now()}-${this.messageCounter++}`,c=this.generateSequenceNumber(),u={id:o,messageId:o,messageGroupId:n.messageGroupId,messageDeduplicationId:n.messageDeduplicationId,body:n.messageBody,attributes:n.messageAttributes||{},sentTimestamp:new Date,sequenceNumber:c};return this.messages.set(o,u),this.updateMessageGroup(n.queueId,n.messageGroupId),u}isDuplicate(n,i){let s=n.deduplicationHashes.get(i);if(!s)return!1;if((Date.now()-s.getTime())/1000>n.deduplicationInterval)return n.deduplicationHashes.delete(i),!1;return!0}generateHash(n){let i=0;for(let s=0;s<n.length;s++){let o=n.charCodeAt(s);i=(i<<5)-i+o,i=i&i}return Math.abs(i).toString(36)}generateSequenceNumber(){return`${Date.now()}${this.sequenceCounter++}`.padStart(20,"0")}updateMessageGroup(n,i){let s=`${n}-${i}`,o=this.messageGroups.get(s);if(!o)o={id:`group-${Date.now()}-${this.groupCounter++}`,messageGroupId:i,queueId:n,messagesInFlight:0},this.messageGroups.set(s,o);o.messagesInFlight++,o.lastMessageTimestamp=new Date}getMessageGroups(n){return Array.from(this.messageGroups.values()).filter((i)=>i.queueId===n)}getQueue(n){return this.queues.get(n)}listQueues(){return Array.from(this.queues.values())}getMessages(n,i){let s=Array.from(this.messages.values());if(i)s=s.filter((o)=>o.messageGroupId===i);return s.sort((o,c)=>o.sequenceNumber.localeCompare(c.sequenceNumber))}generateFIFOQueueCF(n){return{Type:"AWS::SQS::Queue",Properties:{QueueName:n.name,FifoQueue:!0,ContentBasedDeduplication:n.contentBasedDeduplication,DeduplicationScope:n.deduplicationScope,FifoThroughputLimit:n.fifoThroughputLimit,MessageRetentionPeriod:n.messageRetentionPeriod,VisibilityTimeout:n.visibilityTimeout,ReceiveMessageWaitTimeSeconds:n.receiveMessageWaitTime,...n.deadLetterTargetArn&&{RedrivePolicy:{deadLetterTargetArn:n.deadLetterTargetArn,maxReceiveCount:n.maxReceiveCount||3}}}}}clear(){this.queues.clear(),this.messageGroups.clear(),this.deduplicationConfigs.clear(),this.messages.clear(),this.queueCounter=0,this.groupCounter=0,this.deduplicationCounter=0,this.messageCounter=0,this.sequenceCounter=0}}var uE=new uf;class gf{monitors=new Map;metrics=new Map;alerts=new Map;reprocessJobs=new Map;monitorCounter=0;metricsCounter=0;alertCounter=0;jobCounter=0;createDLQMonitor(n){let i=`dlq-monitor-${Date.now()}-${this.monitorCounter++}`,s={id:i,...n};return this.monitors.set(i,s),s}createAutomatedMonitor(n){return this.createDLQMonitor({name:n.name,queueUrl:n.queueUrl,sourceQueues:n.sourceQueues,maxReceiveCount:3,alarmThreshold:10,autoReprocess:!0,reprocessStrategy:"scheduled",notificationTopicArn:n.notificationTopicArn})}collectMetrics(n){let s={id:`metrics-${Date.now()}-${this.metricsCounter++}`,queueUrl:n,timestamp:new Date,approximateNumberOfMessages:Math.floor(Math.random()*100),approximateAgeOfOldestMessage:Math.floor(Math.random()*86400),messagesReceived:Math.floor(Math.random()*50),messagesDeleted:Math.floor(Math.random()*30),messagesReprocessed:Math.floor(Math.random()*20)},o=this.metrics.get(n)||[];return o.push(s),this.metrics.set(n,o),this.checkForAlerts(n,s),s}checkForAlerts(n,i){let s=Array.from(this.monitors.values()).find((c)=>c.queueUrl===n);if(!s)return;if(i.approximateNumberOfMessages>=s.alarmThreshold)this.createAlert({monitorId:s.id,alertType:"threshold_exceeded",severity:"high",message:`DLQ ${s.name} has ${i.approximateNumberOfMessages} messages (threshold: ${s.alarmThreshold})`});let o=3600;if(i.approximateAgeOfOldestMessage>o)this.createAlert({monitorId:s.id,alertType:"old_message",severity:"medium",message:`DLQ ${s.name} has messages older than ${o} seconds`})}createAlert(n){let i=`alert-${Date.now()}-${this.alertCounter++}`,s={id:i,timestamp:new Date,acknowledged:!1,...n};return this.alerts.set(i,s),s}acknowledgeAlert(n){let i=this.alerts.get(n);if(!i)throw Error(`Alert not found: ${n}`);return i.acknowledged=!0,i}createReprocessJob(n){let i=`reprocess-${Date.now()}-${this.jobCounter++}`,s={id:i,queueUrl:n.queueUrl,messageId:n.messageId,attempts:0,status:"pending"};return this.reprocessJobs.set(i,s),s}async executeReprocessJob(n){let i=this.reprocessJobs.get(n);if(!i)throw Error(`Reprocess job not found: ${n}`);i.status="processing",i.startedAt=new Date,i.attempts++,await new Promise((o)=>setTimeout(o,100));let s=Math.random()>0.3;if(i.status=s?"success":"failed",i.completedAt=new Date,!s)i.error="Reprocessing failed - original error still present";return i}async batchReprocess(n){let i=[];for(let s=0;s<n.maxMessages;s++){let o=this.createReprocessJob({queueUrl:n.queueUrl,messageId:`msg-${s}`});await this.executeReprocessJob(o.id),i.push(o)}return i}getDLQStatistics(n,i=24){let s=new Date(Date.now()-i*60*60*1000),o=(this.metrics.get(n)||[]).filter((A)=>A.timestamp>=s);if(o.length===0)return{totalMessages:0,avgAge:0,messagesReceived:0,messagesDeleted:0,messagesReprocessed:0,successRate:0};let c=o[o.length-1],u=o.reduce((A,T)=>A+T.messagesReceived,0),d=o.reduce((A,T)=>A+T.messagesDeleted,0),f=o.reduce((A,T)=>A+T.messagesReprocessed,0),h=o.reduce((A,T)=>A+T.approximateAgeOfOldestMessage,0)/o.length,S=f>0?d/f*100:0;return{totalMessages:c.approximateNumberOfMessages,avgAge:h,messagesReceived:u,messagesDeleted:d,messagesReprocessed:f,successRate:S}}getMonitor(n){return this.monitors.get(n)}listMonitors(){return Array.from(this.monitors.values())}getAlerts(n,i){let s=Array.from(this.alerts.values());if(n)s=s.filter((o)=>o.monitorId===n);if(i!==void 0)s=s.filter((o)=>o.acknowledged===i);return s.sort((o,c)=>c.timestamp.getTime()-o.timestamp.getTime())}getReprocessJobs(n){let i=Array.from(this.reprocessJobs.values());if(n)i=i.filter((s)=>s.queueUrl===n);return i}generateDLQAlarmCF(n){return{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${n.name}-messages-alarm`,AlarmDescription:`Alert when DLQ ${n.name} exceeds threshold`,MetricName:"ApproximateNumberOfMessagesVisible",Namespace:"AWS/SQS",Statistic:"Average",Period:300,EvaluationPeriods:1,Threshold:n.alarmThreshold,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:n.queueUrl.split("/").pop()}],...n.notificationTopicArn&&{AlarmActions:[n.notificationTopicArn]}}}}clear(){this.monitors.clear(),this.metrics.clear(),this.alerts.clear(),this.reprocessJobs.clear(),this.monitorCounter=0,this.metricsCounter=0,this.alertCounter=0,this.jobCounter=0}}var gE=new gf;class pf{configs=new Map;jobs=new Map;metrics=new Map;configCounter=0;jobCounter=0;metricsCounter=0;createBatchConfig(n){let i=`batch-config-${Date.now()}-${this.configCounter++}`,s={id:i,...n};return this.configs.set(i,s),s}createHighThroughputConfig(n){return this.createBatchConfig({queueUrl:n.queueUrl,batchSize:10,maxWaitTime:100,parallelProcessors:10,retryAttempts:3,visibilityTimeout:30})}createLowLatencyConfig(n){return this.createBatchConfig({queueUrl:n.queueUrl,batchSize:1,maxWaitTime:0,parallelProcessors:5,retryAttempts:2,visibilityTimeout:10})}createBatchJob(n){let i=`batch-job-${Date.now()}-${this.jobCounter++}`;if(!this.configs.get(n.configId))throw Error(`Batch config not found: ${n.configId}`);let o=[];for(let u=0;u<n.messageCount;u++)o.push({id:`msg-${i}-${u}`,messageId:`${i}-${u}`,body:`Message ${u}`,receiptHandle:`receipt-${i}-${u}`,attributes:{},status:"pending"});let c={id:i,configId:n.configId,messages:o,status:"pending",processedCount:0,failedCount:0};return this.jobs.set(i,c),c}async processBatchJob(n){let i=this.jobs.get(n);if(!i)throw Error(`Batch job not found: ${n}`);let s=this.configs.get(i.configId);if(!s)throw Error(`Batch config not found: ${i.configId}`);i.status="processing",i.startedAt=new Date;let o=this.chunkArray(i.messages,s.batchSize);for(let c of o)await this.processBatch(c,s);return i.processedCount=i.messages.filter((c)=>c.status==="success").length,i.failedCount=i.messages.filter((c)=>c.status==="failed").length,i.status=i.failedCount===0?"completed":"failed",i.completedAt=new Date,this.collectProcessorMetrics(s.id,i),i}async processBatch(n,i){let s=n.map((o)=>this.processMessage(o,i));await Promise.all(s)}async processMessage(n,i){n.status="processing";let s=Date.now();await new Promise((u)=>setTimeout(u,Math.random()*100));let o=Date.now()-s;if(n.processingTime=o,Math.random()>0.1)n.status="success";else n.status="failed",n.error="Processing error"}chunkArray(n,i){let s=[];for(let o=0;o<n.length;o+=i)s.push(n.slice(o,o+i));return s}collectProcessorMetrics(n,i){let s=`metrics-${Date.now()}-${this.metricsCounter++}`,c=i.messages.filter((T)=>T.status==="success").map((T)=>T.processingTime||0).filter((T)=>T>0),u=c.length>0?c.reduce((T,v)=>T+v,0)/c.length:0,d=i.completedAt&&i.startedAt?(i.completedAt.getTime()-i.startedAt.getTime())/1000:1,f=i.processedCount/d,h=i.messages.length>0?i.failedCount/i.messages.length*100:0,S={id:s,configId:n,timestamp:new Date,messagesProcessed:i.processedCount,averageProcessingTime:u,throughput:f,errorRate:h},A=this.metrics.get(n)||[];A.push(S),this.metrics.set(n,A)}getBatchStatistics(n){let i=this.metrics.get(n)||[];if(i.length===0)return{totalJobsProcessed:0,totalMessagesProcessed:0,averageThroughput:0,averageErrorRate:0,averageProcessingTime:0};let s=i.reduce((d,f)=>d+f.messagesProcessed,0),o=i.reduce((d,f)=>d+f.throughput,0)/i.length,c=i.reduce((d,f)=>d+f.errorRate,0)/i.length,u=i.reduce((d,f)=>d+f.averageProcessingTime,0)/i.length;return{totalJobsProcessed:i.length,totalMessagesProcessed:s,averageThroughput:o,averageErrorRate:c,averageProcessingTime:u}}optimizeBatchConfig(n){let i=this.configs.get(n);if(!i)throw Error(`Batch config not found: ${n}`);let s=this.getBatchStatistics(n);if(s.averageErrorRate<5&&i.batchSize<10)i.batchSize=Math.min(10,i.batchSize+1);if(s.averageErrorRate>20&&i.batchSize>1)i.batchSize=Math.max(1,i.batchSize-1);if(s.averageThroughput<5&&i.parallelProcessors<20)i.parallelProcessors++;return i}getConfig(n){return this.configs.get(n)}listConfigs(){return Array.from(this.configs.values())}getJob(n){return this.jobs.get(n)}listJobs(n){let i=Array.from(this.jobs.values());if(n)i=i.filter((s)=>s.configId===n);return i}generateBatchProcessorCF(n){return{Type:"AWS::Lambda::EventSourceMapping",Properties:{EventSourceArn:`arn:aws:sqs:us-east-1:123456789012:${n.queueUrl.split("/").pop()}`,FunctionName:"batch-processor-function",BatchSize:n.batchSize,MaximumBatchingWindowInSeconds:n.maxWaitTime/1000,FunctionResponseTypes:["ReportBatchItemFailures"]}}}clear(){this.configs.clear(),this.jobs.clear(),this.metrics.clear(),this.configCounter=0,this.jobCounter=0,this.metricsCounter=0}}var pE=new pf;class mf{queues=new Map;retentionPolicies=new Map;delayQueues=new Map;purgeOperations=new Map;metrics=new Map;queueCounter=0;retentionCounter=0;delayCounter=0;purgeCounter=0;metricsCounter=0;createQueue(n){let i=`queue-${Date.now()}-${this.queueCounter++}`,s={id:i,purgeInProgress:!1,...n};return this.queues.set(i,s),s}createStandardQueue(n){return this.createQueue({queueUrl:`https://sqs.us-east-1.amazonaws.com/123456789012/${n.queueName}`,queueName:n.queueName,messageRetentionPeriod:(n.messageRetentionDays||4)*24*60*60,delaySeconds:0,maximumMessageSize:262144,receiveMessageWaitTime:0})}createLongPollingQueue(n){return this.createQueue({queueUrl:`https://sqs.us-east-1.amazonaws.com/123456789012/${n.queueName}`,queueName:n.queueName,messageRetentionPeriod:345600,delaySeconds:0,maximumMessageSize:262144,receiveMessageWaitTime:n.waitTimeSeconds||20})}createRetentionPolicy(n){let i=`retention-${Date.now()}-${this.retentionCounter++}`,s={id:i,...n};this.retentionPolicies.set(i,s);let o=this.queues.get(n.queueId);if(o)o.messageRetentionPeriod=n.retentionPeriod;return s}createShortRetentionPolicy(n){return this.createRetentionPolicy({queueId:n.queueId,retentionPeriod:n.retentionHours*60*60,autoCleanup:!0,archiveExpiredMessages:!1})}createArchivalRetentionPolicy(n){return this.createRetentionPolicy({queueId:n.queueId,retentionPeriod:n.retentionDays*24*60*60,autoCleanup:!0,cleanupSchedule:"cron(0 0 * * ? *)",archiveExpiredMessages:!0,archiveS3Bucket:n.s3Bucket})}createDelayQueue(n){let i=`delay-${Date.now()}-${this.delayCounter++}`,s={id:i,...n};this.delayQueues.set(i,s);let o=Array.from(this.queues.values()).find((c)=>c.queueUrl===n.queueUrl);if(o)o.delaySeconds=n.defaultDelay;return s}createScheduledDelayQueue(n){return this.createDelayQueue({queueUrl:n.queueUrl,defaultDelay:n.delayMinutes*60,perMessageDelay:!1,maxDelay:900})}async purgeQueue(n){let i=this.queues.get(n);if(!i)throw Error(`Queue not found: ${n}`);if(i.purgeInProgress)throw Error("Purge already in progress for this queue");let s=`purge-${Date.now()}-${this.purgeCounter++}`,o={id:s,queueUrl:i.queueUrl,status:"in_progress",startedAt:new Date};return this.purgeOperations.set(s,o),i.purgeInProgress=!0,setTimeout(()=>{o.status="completed",o.completedAt=new Date,o.messagesPurged=Math.floor(Math.random()*1000),i.purgeInProgress=!1},100),o}collectQueueMetrics(n){let s={id:`metrics-${Date.now()}-${this.metricsCounter++}`,queueUrl:n,timestamp:new Date,approximateNumberOfMessages:Math.floor(Math.random()*1000),approximateNumberOfMessagesNotVisible:Math.floor(Math.random()*100),approximateNumberOfMessagesDelayed:Math.floor(Math.random()*50),oldestMessageAge:Math.floor(Math.random()*86400)},o=this.metrics.get(n)||[];return o.push(s),this.metrics.set(n,o),s}getQueueHealth(n){let i=this.metrics.get(n)||[];if(i.length===0)return{status:"healthy",issues:[],recommendations:[]};let s=i[i.length-1],o=[],c=[],u="healthy";if(s.approximateNumberOfMessages>1e4)u="critical",o.push("Large message backlog detected"),c.push("Increase consumer capacity");else if(s.approximateNumberOfMessages>1000)u="warning",o.push("Growing message backlog"),c.push("Monitor consumer performance");if(s.oldestMessageAge&&s.oldestMessageAge>3600){if(u!=="critical")u="warning";o.push("Old messages in queue"),c.push("Review message processing")}if(s.approximateNumberOfMessagesDelayed>100){if(u!=="critical")u="warning";o.push("High number of delayed messages")}return{status:u,issues:o,recommendations:c}}getQueue(n){return this.queues.get(n)}listQueues(){return Array.from(this.queues.values())}getRetentionPolicy(n){return this.retentionPolicies.get(n)}listRetentionPolicies(){return Array.from(this.retentionPolicies.values())}getPurgeOperations(n){let i=Array.from(this.purgeOperations.values());if(n)i=i.filter((s)=>s.queueUrl===n);return i}generateQueueCF(n){return{Type:"AWS::SQS::Queue",Properties:{QueueName:n.queueName,MessageRetentionPeriod:n.messageRetentionPeriod,DelaySeconds:n.delaySeconds,MaximumMessageSize:n.maximumMessageSize,ReceiveMessageWaitTimeSeconds:n.receiveMessageWaitTime}}}generateCleanupRuleCF(n){return{Type:"AWS::Events::Rule",Properties:{Name:`${n.id}-cleanup`,Description:"Automated queue cleanup",ScheduleExpression:n.cleanupSchedule||"cron(0 0 * * ? *)",State:"ENABLED",Targets:[{Arn:"arn:aws:lambda:us-east-1:123456789012:function:queue-cleanup",Id:n.id,Input:JSON.stringify({queueId:n.queueId,archiveBucket:n.archiveS3Bucket})}]}}}clear(){this.queues.clear(),this.retentionPolicies.clear(),this.delayQueues.clear(),this.purgeOperations.clear(),this.metrics.clear(),this.queueCounter=0,this.retentionCounter=0,this.delayCounter=0,this.purgeCounter=0,this.metricsCounter=0}}var mE=new mf;import{deflateRawSync as Mi}from"node:zlib";var Li=(()=>{let n=[];for(let i=0;i<256;i++){let s=i;for(let o=0;o<8;o++)s=s&1?3988292384^s>>>1:s>>>1;n[i]=s>>>0}return n})();function Oi(n){let i=4294967295;for(let s=0;s<n.length;s++)i=Li[(i^n[s])&255]^i>>>8;return(i^4294967295)>>>0}function $i(n){if(typeof n==="string")return Buffer.from(n,"utf-8");if(Buffer.isBuffer(n))return n;return Buffer.from(n)}function Bi(n){let i=Math.max(1980,n.getFullYear()),s=(n.getHours()<<11|n.getMinutes()<<5|n.getSeconds()>>1)&65535,o=(i-1980<<9|n.getMonth()+1<<5|n.getDate())&65535;return{time:s,date:o}}function rt(n){let i=[],s=[],o=0;for(let d of n){let f=$i(d.data),h=Mi(f),S=Oi(f),A=Buffer.from(d.name.replace(/\\/g,"/"),"utf-8"),{time:T,date:v}=Bi(d.date??new Date(0)),R=d.mode??420,P=Buffer.alloc(30+A.length);P.writeUInt32LE(67324752,0),P.writeUInt16LE(20,4),P.writeUInt16LE(0,6),P.writeUInt16LE(8,8),P.writeUInt16LE(T,10),P.writeUInt16LE(v,12),P.writeUInt32LE(S,14),P.writeUInt32LE(h.length,18),P.writeUInt32LE(f.length,22),P.writeUInt16LE(A.length,26),P.writeUInt16LE(0,28),A.copy(P,30);let E=Buffer.alloc(46+A.length);E.writeUInt32LE(33639248,0),E.writeUInt16LE(798,4),E.writeUInt16LE(20,6),E.writeUInt16LE(0,8),E.writeUInt16LE(8,10),E.writeUInt16LE(T,12),E.writeUInt16LE(v,14),E.writeUInt32LE(S,16),E.writeUInt32LE(h.length,20),E.writeUInt32LE(f.length,24),E.writeUInt16LE(A.length,28),E.writeUInt16LE(0,30),E.writeUInt16LE(0,32),E.writeUInt16LE(0,34),E.writeUInt16LE(0,36),E.writeUInt32LE((R&65535)<<16,38),E.writeUInt32LE(o,42),A.copy(E,46),i.push(P,h),s.push(E),o+=P.length+h.length}let c=Buffer.concat(s),u=Buffer.alloc(22);return u.writeUInt32LE(101010256,0),u.writeUInt16LE(0,4),u.writeUInt16LE(0,6),u.writeUInt16LE(n.length,8),u.writeUInt16LE(n.length,10),u.writeUInt32LE(c.length,12),u.writeUInt32LE(o,16),u.writeUInt16LE(0,20),Buffer.concat([...i,c,u])}function ff(n){let i=n.adapterImport??"./adapter",s=n.entryImport.replace(/\\/g,"/");return`// Generated by ts-cloud — serverless app bootstrap. Do not edit.
|
|
7230
7230
|
import * as __userModule from ${JSON.stringify(s)}
|
|
7231
7231
|
import { resolveApp, createHandlers } from ${JSON.stringify(i)}
|
|
7232
7232
|
|
|
@@ -7236,9 +7236,9 @@ const __handlers = createHandlers(__app)
|
|
|
7236
7236
|
export const http = __handlers.http
|
|
7237
7237
|
export const queue = __handlers.queue
|
|
7238
7238
|
export const cli = __handlers.cli
|
|
7239
|
-
`}import{execSync as Fi}from"node:child_process";import{createHash as _i}from"node:crypto";import{cpSync as Ui,mkdtempSync as Qi,rmSync as Yi,writeFileSync as Zi}from"node:fs";import{tmpdir as Xi}from"node:os";import{dirname as
|
|
7239
|
+
`}import{execSync as Fi}from"node:child_process";import{createHash as _i}from"node:crypto";import{cpSync as Ui,mkdtempSync as Qi,rmSync as Yi,writeFileSync as Zi}from"node:fs";import{tmpdir as Xi}from"node:os";import{dirname as ea,isAbsolute as ta,join as Fe,resolve as na}from"node:path";import{fileURLToPath as ra}from"node:url";var ia=["adapter.ts","recursion.ts","auto-recursion.ts"];function aa(){return Fe(ea(ra(import.meta.url)),"runtime")}function Xy(n,i,s){for(let o of n??[])s?.(`build: ${o}`),Fi(o,{stdio:"inherit",cwd:i})}function Fo(n){return _i("sha256").update(n).digest("hex")}function wl(n,i,s){return`deployments/${n}/${i}/${s}.zip`}async function ln(n){let i=na(n.projectRoot??process.cwd()),{app:s}=n;if(!n.skipBuild)Xy(s.build,i,n.onStep);let o=s.entry;if(!o)throw Error("serverless app: `entry` is required to package a Node/Bun application");let c=ta(o)?o:Fe(i,o),u=Qi(Fe(Xi(),"tscloud-pkg-"));try{for(let v of ia)Ui(Fe(aa(),v),Fe(u,v));let d=Fe(u,"bootstrap.ts");Zi(d,ff({entryImport:c,adapterImport:"./adapter"})),n.onStep?.("bundling application");let f=await Bun.build({entrypoints:[d],target:s.kind==="bun"?"bun":"node",format:"esm",minify:!1,sourcemap:"none"});if(!f.success){let v=f.logs.map((R)=>String(R)).join(`
|
|
7240
7240
|
`);throw Error(`serverless app bundle failed:
|
|
7241
|
-
${v}`)}let h=f.outputs[0],S=Buffer.from(await h.arrayBuffer()),A="index",T=rt([{name:`${A}.mjs`,data:S}]);return{zip:T,bundle:S,sha256:Fo(T),handlerFile:A,handlers:{http:s.handlers?.http??`${A}.http`,queue:s.handlers?.queue??`${A}.queue`,cli:s.handlers?.cli??`${A}.cli`},bundleBytes:S.length}}finally{Yi(u,{recursive:!0,force:!0})}}var Yy=["18","20","22"];function as(n){if(!n)return"22";let i=String(n).match(/(\d+)/);return i?i[1]:"22"}function Wi(n){let i=n.kind??"node";if(i==="php")return{lambdaRuntime:"provided.al2023",kind:"php",version:n.phpVersion??"8.3",usesLayer:!0,layerKind:"php",layerEnvVar:"TSCLOUD_PHP_LAYER_ARN"};if(i==="bun")return{lambdaRuntime:"provided.al2023",kind:"bun",version:n.runtimeVersion??"latest",usesLayer:!0,layerKind:"bun",layerEnvVar:"TSCLOUD_BUN_LAYER_ARN"};let s=as(n.runtimeVersion);if(n.runtime!=="provided.al2023"&&Yy.includes(s))return{lambdaRuntime:n.runtime&&n.runtime.startsWith("nodejs")?n.runtime:`nodejs${s}.x`,kind:"node",version:s,usesLayer:!1};return{lambdaRuntime:"provided.al2023",kind:"node",version:s,usesLayer:!0,layerKind:"node",layerEnvVar:"TSCLOUD_NODE_LAYER_ARN"}}function gr(n,i,s){if(n.queues===!1)return[];if(n.queues===void 0||n.queues===!0)return[{name:`${i}-${s}-default`}];return n.queues.map((o)=>{if(typeof o==="string")return{name:`${i}-${s}-${o}`};let[c,u]=Object.entries(o)[0];return{name:`${i}-${s}-${c}`,concurrency:u}})}function Rl(n,i,s){return gr(n,i,s).map((o)=>o.name)}function Dl(n){let{app:i,environment:s,handlers:o}=n,c=n.config.project.slug,u=Wi(i).lambdaRuntime,d=i.architecture??"x86_64",f=n.config.project.region,h={http:`${c}-${s}-http`,queue:`${c}-${s}-queue`,cli:`${c}-${s}-cli`};if(i.gatewayVersion===1)throw Error("serverless app: `gatewayVersion: 1` (REST API) is not supported — ts-cloud uses API Gateway HTTP API (v2). Remove `gatewayVersion` or set it to 2.");let S=gr(i,c,s),A=S.map((G)=>G.name),T=A.length>0,v=i.logRetention??14,R=i.packaging==="image";if(R&&i.lambdaInsights)throw Error("serverless app: `lambdaInsights` layer attachment is only supported for zip packaging. Container images must install the Lambda Insights extension in the image.");let P=(i.scheduler??"on")!=="off",E=(i.cache?.driver??"dynamodb")==="dynamodb",I=Boolean(i.assets),M=Gi(c,s),L=i.tmpStorage??512,x={},O={},B=[{PolicyName:"tscloud-serverless-app",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["logs:CreateLogGroup","logs:CreateLogStream","logs:PutLogEvents"],Resource:e.sub("arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/*")},{Effect:"Allow",Action:["lambda:InvokeFunction"],Resource:e.sub(`arn:aws:lambda:\${AWS::Region}:\${AWS::AccountId}:function:${c}-${s}-*`)},{Effect:"Allow",Action:["secretsmanager:GetSecretValue","ssm:GetParameter","ssm:GetParameters","ssm:GetParametersByPath"],Resource:[e.sub(`arn:aws:secretsmanager:\${AWS::Region}:\${AWS::AccountId}:secret:${c}/${s}/*`),e.sub(`arn:aws:ssm:\${AWS::Region}:\${AWS::AccountId}:parameter/${c}/${s}/*`)]},{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:ListBucket"],Resource:[e.sub(`arn:aws:s3:::${M}`),e.sub(`arn:aws:s3:::${M}/*`),...i.storage?.bucket?[e.sub(`arn:aws:s3:::${i.storage.bucket}`),e.sub(`arn:aws:s3:::${i.storage.bucket}/*`)]:[]]}]}}];if(T)B[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["sqs:SendMessage","sqs:ReceiveMessage","sqs:DeleteMessage","sqs:GetQueueAttributes","sqs:GetQueueUrl"],Resource:e.sub(`arn:aws:sqs:\${AWS::Region}:\${AWS::AccountId}:${c}-${s}-*`)});if(E)B[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["dynamodb:GetItem","dynamodb:PutItem","dynamodb:UpdateItem","dynamodb:DeleteItem","dynamodb:Query","dynamodb:Scan","dynamodb:BatchGetItem","dynamodb:BatchWriteItem"],Resource:e.sub(`arn:aws:dynamodb:\${AWS::Region}:\${AWS::AccountId}:table/${c}-${s}-cache*`)});let F=["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"];if(i.vpc?.subnets?.length)F.push("arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole");if(i.lambdaInsights)F.push("arn:aws:iam::aws:policy/CloudWatchLambdaInsightsExecutionRolePolicy");x.AppRole={Type:"AWS::IAM::Role",Properties:{RoleName:`${c}-${s}-app-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:F,Policies:B}};let U=(G)=>({TSCLOUD_LAMBDA_MODE:G,TSCLOUD_ENV:s,...i.octane?{TSCLOUD_OCTANE:"1"}:{},...i.scheduler==="sub-minute"?{TSCLOUD_SCHEDULER:"sub-minute"}:{},...E?{TSCLOUD_CACHE_TABLE:`${c}-${s}-cache`}:{},...T?{TSCLOUD_QUEUE:A[0]}:{},...i.env??{}}),j=Boolean(i.efs),H=typeof i.efs==="object"?i.efs:{},z=H.mountPath??"/mnt/local",se=j&&!H.accessPointArn,ue=H.accessPointArn??(se?e.getAtt("EfsAccessPoint","Arn"):void 0),me=i.vpc?.subnets??[],Ee=me.length>0,ae=i.cache?.driver==="elasticache"||i.database?.connection==="aurora-serverless"||Boolean(i.rdsProxy)||j;if(ae&&!Ee)throw Error("serverless app: elasticache / aurora-serverless / rdsProxy / efs require app.vpc.subnets (private subnets) to be set.");let gt=Ee?{VpcConfig:{SubnetIds:me,SecurityGroupIds:[...i.vpc?.securityGroups??[],...ae?[e.getAtt("DataSecurityGroup","GroupId")]:[]]}}:{},yt=se?me.map((G,ne)=>`EfsMountTarget${ne}`):[],ft=j?{FileSystemConfigs:[{Arn:ue,LocalMountPath:z}]}:{};if(j)B[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["elasticfilesystem:ClientMount","elasticfilesystem:ClientWrite","elasticfilesystem:ClientRootAccess","elasticfilesystem:DescribeMountTargets"],Resource:"*"});function ye(G,ne,ie,re,ge,ht,Fe,Ie=L){x[`${G}LogGroup`]={Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:`/aws/lambda/${ne}`,RetentionInDays:v}};let Ge=[...n.runtimeLayers??[],...i.lambdaInsights?[i.lambdaInsights.layerArn]:[]],en=R?{PackageType:"Image",Code:{ImageUri:e.ref("ImageUri")},...i.kind==="php"?{}:{ImageConfig:{Command:[ie]}}}:{Runtime:u,Handler:ie,Code:{S3Bucket:e.ref("ArtifactBucket"),S3Key:e.ref("ArtifactKey")},...Ge.length?{Layers:[...new Set(Ge)]}:{}};x[G]={Type:"AWS::Lambda::Function",DependsOn:[`${G}LogGroup`,...yt],Properties:{FunctionName:ne,Architectures:[d],MemorySize:ge,Timeout:ht,Role:e.getAtt("AppRole","Arn"),Environment:{Variables:U(re)},EphemeralStorage:{Size:Ie},...en,...Fe!==void 0?{ReservedConcurrentExecutions:Fe}:{},...gt,...ft}}}if(ye("HttpFunction",h.http,o.http,"http",i.memory??1024,i.timeout??28,i.concurrency,L),ye("CliFunction",h.cli,o.cli,"cli",i.cliMemory??1024,i.cliTimeout??900,void 0,i.cliTmpStorage??L),T)ye("QueueFunction",h.queue,o.queue,"queue",i.queueMemory??1024,i.queueTimeout??120,void 0,i.queueTmpStorage??L);let pe=(i.provisionedConcurrency??0)>0?i.provisionedConcurrency:0,fe=["HttpFunction","CliFunction",...T?["QueueFunction"]:[]];if(pe)for(let G of fe)x[`${G}Version`]={Type:"AWS::Lambda::Version",DeletionPolicy:"Retain",Properties:{FunctionName:e.ref(G)}},x[`${G}Alias`]={Type:"AWS::Lambda::Alias",Properties:{FunctionName:e.ref(G),Name:"live",FunctionVersion:e.getAtt(`${G}Version`,"Version"),ProvisionedConcurrencyConfig:{ProvisionedConcurrentExecutions:pe}}};let we=(G)=>pe?e.ref(`${G}Alias`):e.getAtt(G,"Arn"),he=(G)=>pe?e.ref(`${G}Alias`):e.ref(G);x.HttpApi={Type:"AWS::ApiGatewayV2::Api",Properties:{Name:`${c}-${s}`,ProtocolType:"HTTP"}},x.HttpIntegration={Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:e.ref("HttpApi"),IntegrationType:"AWS_PROXY",IntegrationUri:we("HttpFunction"),PayloadFormatVersion:"2.0"}},x.HttpRoute={Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:e.ref("HttpApi"),RouteKey:"$default",Target:e.join("/",["integrations",e.ref("HttpIntegration")])}},x.HttpStage={Type:"AWS::ApiGatewayV2::Stage",Properties:{ApiId:e.ref("HttpApi"),StageName:"$default",AutoDeploy:!0}},x.HttpPermission={Type:"AWS::Lambda::Permission",Properties:{FunctionName:he("HttpFunction"),Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:e.sub("arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${HttpApi}/*/*")}},O.HttpApiEndpoint={Description:"HTTP API endpoint",Value:e.getAtt("HttpApi","ApiEndpoint")},O.HttpApiId={Description:"HTTP API id",Value:e.ref("HttpApi")};let ve=(Array.isArray(i.domain)?i.domain:i.domain?[i.domain]:[]).filter(Boolean);if(ve.length){if(!i.certificateArn&&!i.hostedZoneId)throw Error("serverless app: a custom `domain` needs either `certificateArn` (pre-issued, regional) or `hostedZoneId` (to auto-issue + validate an ACM cert).");let G=i.certificateArn;if(!G)x.HttpCertificate={Type:"AWS::CertificateManager::Certificate",Properties:{DomainName:ve[0],...ve.length>1?{SubjectAlternativeNames:ve.slice(1)}:{},ValidationMethod:"DNS",DomainValidationOptions:ve.map((ne)=>({DomainName:ne,HostedZoneId:i.hostedZoneId}))}},G=e.ref("HttpCertificate");ve.forEach((ne,ie)=>{let re=`HttpDomain${ie}`;if(x[re]={Type:"AWS::ApiGatewayV2::DomainName",Properties:{DomainName:ne,DomainNameConfigurations:[{CertificateArn:G,EndpointType:"REGIONAL"}]}},x[`HttpApiMapping${ie}`]={Type:"AWS::ApiGatewayV2::ApiMapping",DependsOn:["HttpStage"],Properties:{ApiId:e.ref("HttpApi"),DomainName:e.ref(re),Stage:"$default"}},i.hostedZoneId)x[`HttpDomainRecord${ie}`]={Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:i.hostedZoneId,Name:ne,Type:"A",AliasTarget:{DNSName:e.getAtt(re,"RegionalDomainName"),HostedZoneId:e.getAtt(re,"RegionalHostedZoneId")}}};O[`CustomDomain${ie}`]={Description:`Custom domain ${ne}`,Value:ne},O[`CustomDomainTarget${ie}`]={Description:`Point ${ne} (CNAME/alias) at this APIGW regional domain`,Value:e.getAtt(re,"RegionalDomainName")}})}if(T)x.AppQueueDlq={Type:"AWS::SQS::Queue",Properties:{QueueName:`${c}-${s}-dlq`,MessageRetentionPeriod:1209600}},S.forEach((G,ne)=>{let ie=`AppQueue${ne}`,re=i.queueTimeout??120;x[ie]={Type:"AWS::SQS::Queue",Properties:{QueueName:G.name,VisibilityTimeout:Math.min(43200,re*6),RedrivePolicy:{deadLetterTargetArn:e.getAtt("AppQueueDlq","Arn"),maxReceiveCount:i.queueTries??3}}};let ge=G.concurrency??i.queueConcurrency;x[`${ie}Mapping`]={Type:"AWS::Lambda::EventSourceMapping",Properties:{EventSourceArn:e.getAtt(ie,"Arn"),FunctionName:he("QueueFunction"),BatchSize:1,FunctionResponseTypes:["ReportBatchItemFailures"],...ge?{ScalingConfig:{MaximumConcurrency:Math.max(2,ge)}}:{}}},O[`QueueUrl${ne}`]={Description:`Queue URL: ${G.name}`,Value:e.ref(ie)}});if(P)x.SchedulerRule={Type:"AWS::Events::Rule",Properties:{Name:`${c}-${s}-scheduler`,ScheduleExpression:"rate(1 minute)",State:"ENABLED",Targets:[{Id:"cli",Arn:we("CliFunction"),Input:JSON.stringify({command:"schedule:run"})}]}},x.SchedulerPermission={Type:"AWS::Lambda::Permission",Properties:{FunctionName:he("CliFunction"),Action:"lambda:InvokeFunction",Principal:"events.amazonaws.com",SourceArn:e.getAtt("SchedulerRule","Arn")}};if(i.warm&&i.warm>0){let ne={http:"HttpFunction",queue:"QueueFunction",cli:"CliFunction"},ie=(i.warmFunctions??["http"]).filter((re)=>re!=="queue"||T);for(let re of ie){let ge=re.charAt(0).toUpperCase()+re.slice(1),ht=Math.ceil(i.warm/5),Fe=0;for(let Ie=0;Ie<ht;Ie++){let Ge=Math.min(5,i.warm-Fe);x[`Warmer${ge}Rule${Ie}`]={Type:"AWS::Events::Rule",Properties:{Name:`${c}-${s}-warmer-${re}-${Ie}`,ScheduleExpression:"rate(5 minutes)",State:"ENABLED",Targets:Array.from({length:Ge},(en,mr)=>({Id:`warm-${re}-${Ie}-${mr}`,Arn:e.getAtt(ne[re],"Arn"),Input:JSON.stringify({warmer:!0})}))}},Fe+=Ge}x[`Warmer${ge}Permission`]={Type:"AWS::Lambda::Permission",Properties:{FunctionName:e.ref(ne[re]),Action:"lambda:InvokeFunction",Principal:"events.amazonaws.com",SourceArn:e.sub(`arn:aws:events:\${AWS::Region}:\${AWS::AccountId}:rule/${c}-${s}-warmer-${re}-*`)}}}}if(E)x.CacheTable={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${c}-${s}-cache`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"key",AttributeType:"S"}],KeySchema:[{AttributeName:"key",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"expires_at",Enabled:!0}}},O.CacheTableName={Description:"DynamoDB cache table",Value:e.ref("CacheTable")};if(I){if(x.AssetsBucket={Type:"AWS::S3::Bucket",Properties:{BucketName:M,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0}}},x.AssetsOAC={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`${c}-${s}-assets-oac`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},x.AssetsDistribution={Type:"AWS::CloudFront::Distribution",Properties:{DistributionConfig:{Enabled:!0,DefaultCacheBehavior:{TargetOriginId:"assets",ViewerProtocolPolicy:"redirect-to-https",Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6"},Origins:[{Id:"assets",DomainName:e.getAtt("AssetsBucket","RegionalDomainName"),OriginAccessControlId:e.ref("AssetsOAC"),S3OriginConfig:{OriginAccessIdentity:""}}],...i.assetDomain?{Aliases:[i.assetDomain],ViewerCertificate:{AcmCertificateArn:i.assetCertificateArn??e.ref("AssetsCertificate"),SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}}:{}}}},i.assetDomain){if(!i.assetCertificateArn){if(!i.hostedZoneId)throw Error("serverless app: `assetDomain` requires either `assetCertificateArn` (a us-east-1 ACM cert) or `hostedZoneId` (to auto-issue + validate one). CloudFront only accepts certs from us-east-1.");if(f!=="us-east-1")throw Error(`serverless app: auto-issuing an asset-domain cert needs a us-east-1 app (CloudFront certs must be us-east-1); this app is in ${f}. Supply a pre-issued us-east-1 \`assetCertificateArn\` instead.`);x.AssetsCertificate={Type:"AWS::CertificateManager::Certificate",Properties:{DomainName:i.assetDomain,ValidationMethod:"DNS",DomainValidationOptions:[{DomainName:i.assetDomain,HostedZoneId:i.hostedZoneId}]}}}if(i.hostedZoneId)x.AssetsDomainRecord={Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:i.hostedZoneId,Name:i.assetDomain,Type:"A",AliasTarget:{DNSName:e.getAtt("AssetsDistribution","DomainName"),HostedZoneId:"Z2FDTNDATAQYW2"}}};O.AssetDomain={Description:"Custom asset CDN host",Value:i.assetDomain}}x.AssetsBucketPolicy={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:e.ref("AssetsBucket"),PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:e.sub(`arn:aws:s3:::${M}/*`),Condition:{StringEquals:{"AWS:SourceArn":e.sub("arn:aws:cloudfront::${AWS::AccountId}:distribution/${AssetsDistribution}")}}}]}}},O.AssetsBucketName={Description:"Assets bucket",Value:e.ref("AssetsBucket")},O.AssetsCdnDomain={Description:"Assets CloudFront domain",Value:e.getAtt("AssetsDistribution","DomainName")}}if(i.firewall?.enabled){let G=[],ne=0;if(i.firewall.rateLimit)G.push({Name:"rate-limit",Priority:ne++,Action:{Block:{}},Statement:{RateBasedStatement:{Limit:i.firewall.rateLimit,AggregateKeyType:"IP"}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${c}-${s}-rate`}});let ie={sqlInjection:"AWSManagedRulesSQLiRuleSet",xss:"AWSManagedRulesCommonRuleSet",common:"AWSManagedRulesCommonRuleSet",botControl:"AWSManagedRulesBotControlRuleSet",ipReputation:"AWSManagedRulesAmazonIpReputationList"};for(let re of i.firewall.rules??[]){let ge=ie[re];if(!ge)continue;G.push({Name:`managed-${re}`,Priority:ne++,OverrideAction:{None:{}},Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:ge}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${c}-${s}-${re}`}})}x.WebAcl={Type:"AWS::WAFv2::WebACL",Properties:{Name:`${c}-${s}-waf`,Scope:"REGIONAL",DefaultAction:{Allow:{}},Rules:G,VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${c}-${s}-waf`}}},O.WafAclArn={Description:"WAF web ACL ARN. Attach to a CloudFront distribution fronting the API to enforce (HTTP API v2 stages do not support direct WAF association).",Value:e.getAtt("WebAcl","Arn")}}if(Ee&&ae){if(!i.vpc?.id)throw Error("serverless app: data services (elasticache / aurora-serverless / rdsProxy / efs) need app.vpc.id (the VPC id) so the managed security group is created in the right VPC.");x.DataSecurityGroup={Type:"AWS::EC2::SecurityGroup",Properties:{VpcId:i.vpc.id,GroupDescription:`${c}-${s} serverless data access`,SecurityGroupIngress:[{IpProtocol:"-1",CidrIp:"10.0.0.0/8"}]}}}if(se)x.EfsFileSystem={Type:"AWS::EFS::FileSystem",Properties:{Encrypted:!0,FileSystemTags:[{Key:"Name",Value:`${c}-${s}-efs`}]}},me.forEach((G,ne)=>{x[`EfsMountTarget${ne}`]={Type:"AWS::EFS::MountTarget",Properties:{FileSystemId:e.ref("EfsFileSystem"),SubnetId:G,SecurityGroups:[e.getAtt("DataSecurityGroup","GroupId")]}}}),x.EfsAccessPoint={Type:"AWS::EFS::AccessPoint",Properties:{FileSystemId:e.ref("EfsFileSystem"),PosixUser:{Uid:1001,Gid:1001},RootDirectory:{Path:"/lambda",CreationInfo:{OwnerUid:1001,OwnerGid:1001,Permissions:"0755"}}}},O.EfsFileSystemId={Description:"EFS file system id",Value:e.ref("EfsFileSystem")};if(i.cache?.driver==="elasticache")x.CacheSubnetGroup={Type:"AWS::ElastiCache::SubnetGroup",Properties:{Description:`${c}-${s} cache subnets`,SubnetIds:me}},x.CacheCluster={Type:"AWS::ElastiCache::ReplicationGroup",Properties:{ReplicationGroupId:`${c}-${s}-cache`,ReplicationGroupDescription:`${c}-${s} redis`,Engine:"redis",CacheNodeType:"cache.t4g.micro",NumCacheClusters:1,AutomaticFailoverEnabled:!1,CacheSubnetGroupName:e.ref("CacheSubnetGroup"),SecurityGroupIds:[e.getAtt("DataSecurityGroup","GroupId")],TransitEncryptionEnabled:!1}},O.CacheEndpoint={Description:"Redis primary endpoint",Value:e.getAtt("CacheCluster","PrimaryEndPoint.Address")};if(i.database?.connection==="aurora-serverless")x.DbSubnetGroup={Type:"AWS::RDS::DBSubnetGroup",Properties:{DBSubnetGroupDescription:`${c}-${s} db subnets`,SubnetIds:me}},x.DbSecret={Type:"AWS::SecretsManager::Secret",Properties:{Name:`${c}/${s}/db`,GenerateSecretString:{SecretStringTemplate:JSON.stringify({username:"app"}),GenerateStringKey:"password",PasswordLength:32,ExcludePunctuation:!0}}},x.DbCluster={Type:"AWS::RDS::DBCluster",Properties:{Engine:"aurora-mysql",EngineMode:"provisioned",DBClusterIdentifier:`${c}-${s}-db`,DatabaseName:"app",MasterUsername:e.sub("{{resolve:secretsmanager:${DbSecret}:SecretString:username}}"),MasterUserPassword:e.sub("{{resolve:secretsmanager:${DbSecret}:SecretString:password}}"),ServerlessV2ScalingConfiguration:{MinCapacity:i.database?.minCapacity??0.5,MaxCapacity:i.database?.maxCapacity??4},DBSubnetGroupName:e.ref("DbSubnetGroup"),VpcSecurityGroupIds:[e.getAtt("DataSecurityGroup","GroupId")]}},x.DbInstance={Type:"AWS::RDS::DBInstance",Properties:{Engine:"aurora-mysql",DBInstanceClass:"db.serverless",DBClusterIdentifier:e.ref("DbCluster")}},O.DbEndpoint={Description:"Aurora cluster endpoint",Value:e.getAtt("DbCluster","Endpoint.Address")};if(i.rdsProxy&&i.database?.connection==="aurora-serverless")x.DbProxyRole={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"rds.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"read-db-secret",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["secretsmanager:GetSecretValue"],Resource:e.ref("DbSecret")}]}}]}},x.DbProxy={Type:"AWS::RDS::DBProxy",Properties:{DBProxyName:typeof i.rdsProxy==="object"&&i.rdsProxy.name?i.rdsProxy.name:`${c}-${s}-proxy`,EngineFamily:"MYSQL",RoleArn:e.getAtt("DbProxyRole","Arn"),Auth:[{AuthScheme:"SECRETS",SecretArn:e.ref("DbSecret"),IAMAuth:"DISABLED"}],VpcSubnetIds:me,VpcSecurityGroupIds:[e.getAtt("DataSecurityGroup","GroupId")],RequireTLS:!1}},x.DbProxyTargetGroup={Type:"AWS::RDS::DBProxyTargetGroup",DependsOn:["DbInstance"],Properties:{DBProxyName:e.ref("DbProxy"),TargetGroupName:"default",DBClusterIdentifiers:[e.ref("DbCluster")]}},O.DbProxyEndpoint={Description:"RDS Proxy endpoint",Value:e.getAtt("DbProxy","Endpoint")};if(O.HttpFunctionName={Description:"HTTP function name",Value:e.ref("HttpFunction")},O.CliFunctionName={Description:"CLI function name",Value:e.ref("CliFunction")},T)O.QueueFunctionName={Description:"Queue function name",Value:e.ref("QueueFunction")};let ke={AWSTemplateFormatVersion:"2010-09-09",Description:`Serverless application for ${n.config.project.name} (${c}-${s})`,Parameters:R?{ImageUri:{Type:"String",Description:"ECR image URI of the deployment artifact"}}:{ArtifactBucket:{Type:"String",Description:"S3 bucket holding the deployment artifact"},ArtifactKey:{Type:"String",Description:"S3 key of the deployment artifact (zip)"}},Resources:x,Outputs:O},Be={};for(let G of Object.values(x))Be[G.Type]=(Be[G.Type]??0)+1;return{template:ke,functionNames:h,queueNames:A,resourceSummary:Be}}var Zy=["cli","fpm","curl","mbstring","xml","pdo","mysqlnd","gd","bcmath","intl","opcache","sodium","process","pecl-redis6","pecl-apcu","pgsql"];function eS(n){let i=`php${n.replace(".","")}`;return Zy.map((s)=>`${i}-php-${s}`)}function Pl(n,i){let s=`php${n.replace(".","")}`,o=eS(n).join(" \\\n "),c=`/opt/remi/${s}/root`,u=`/etc/opt/remi/${s}`;return`${i?`FROM almalinux:9 AS ${i}`:"FROM almalinux:9"}
|
|
7241
|
+
${v}`)}let h=f.outputs[0],S=Buffer.from(await h.arrayBuffer()),A="index",T=rt([{name:`${A}.mjs`,data:S}]);return{zip:T,bundle:S,sha256:Fo(T),handlerFile:A,handlers:{http:s.handlers?.http??`${A}.http`,queue:s.handlers?.queue??`${A}.queue`,cli:s.handlers?.cli??`${A}.cli`},bundleBytes:S.length}}finally{Yi(u,{recursive:!0,force:!0})}}var Yy=["18","20","22"];function sa(n){if(!n)return"22";let i=String(n).match(/(\d+)/);return i?i[1]:"22"}function Wi(n){let i=n.kind??"node";if(i==="php")return{lambdaRuntime:"provided.al2023",kind:"php",version:n.phpVersion??"8.3",usesLayer:!0,layerKind:"php",layerEnvVar:"TSCLOUD_PHP_LAYER_ARN"};if(i==="bun")return{lambdaRuntime:"provided.al2023",kind:"bun",version:n.runtimeVersion??"latest",usesLayer:!0,layerKind:"bun",layerEnvVar:"TSCLOUD_BUN_LAYER_ARN"};let s=sa(n.runtimeVersion);if(n.runtime!=="provided.al2023"&&Yy.includes(s))return{lambdaRuntime:n.runtime&&n.runtime.startsWith("nodejs")?n.runtime:`nodejs${s}.x`,kind:"node",version:s,usesLayer:!1};return{lambdaRuntime:"provided.al2023",kind:"node",version:s,usesLayer:!0,layerKind:"node",layerEnvVar:"TSCLOUD_NODE_LAYER_ARN"}}function gr(n,i,s){if(n.queues===!1)return[];if(n.queues===void 0||n.queues===!0)return[{name:`${i}-${s}-default`}];return n.queues.map((o)=>{if(typeof o==="string")return{name:`${i}-${s}-${o}`};let[c,u]=Object.entries(o)[0];return{name:`${i}-${s}-${c}`,concurrency:u}})}function Rl(n,i,s){return gr(n,i,s).map((o)=>o.name)}function Dl(n){let{app:i,environment:s,handlers:o}=n,c=n.config.project.slug,u=Wi(i).lambdaRuntime,d=i.architecture??"x86_64",f=n.config.project.region,h={http:`${c}-${s}-http`,queue:`${c}-${s}-queue`,cli:`${c}-${s}-cli`};if(i.gatewayVersion===1)throw Error("serverless app: `gatewayVersion: 1` (REST API) is not supported — ts-cloud uses API Gateway HTTP API (v2). Remove `gatewayVersion` or set it to 2.");let S=gr(i,c,s),A=S.map((G)=>G.name),T=A.length>0,v=i.logRetention??14,R=i.packaging==="image";if(R&&i.lambdaInsights)throw Error("serverless app: `lambdaInsights` layer attachment is only supported for zip packaging. Container images must install the Lambda Insights extension in the image.");let P=(i.scheduler??"on")!=="off",E=(i.cache?.driver??"dynamodb")==="dynamodb",I=Boolean(i.assets),M=Gi(c,s),L=i.tmpStorage??512,x={},O={},B=[{PolicyName:"tscloud-serverless-app",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["logs:CreateLogGroup","logs:CreateLogStream","logs:PutLogEvents"],Resource:e.sub("arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/*")},{Effect:"Allow",Action:["lambda:InvokeFunction"],Resource:e.sub(`arn:aws:lambda:\${AWS::Region}:\${AWS::AccountId}:function:${c}-${s}-*`)},{Effect:"Allow",Action:["secretsmanager:GetSecretValue","ssm:GetParameter","ssm:GetParameters","ssm:GetParametersByPath"],Resource:[e.sub(`arn:aws:secretsmanager:\${AWS::Region}:\${AWS::AccountId}:secret:${c}/${s}/*`),e.sub(`arn:aws:ssm:\${AWS::Region}:\${AWS::AccountId}:parameter/${c}/${s}/*`)]},{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:ListBucket"],Resource:[e.sub(`arn:aws:s3:::${M}`),e.sub(`arn:aws:s3:::${M}/*`),...i.storage?.bucket?[e.sub(`arn:aws:s3:::${i.storage.bucket}`),e.sub(`arn:aws:s3:::${i.storage.bucket}/*`)]:[]]}]}}];if(T)B[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["sqs:SendMessage","sqs:ReceiveMessage","sqs:DeleteMessage","sqs:GetQueueAttributes","sqs:GetQueueUrl"],Resource:e.sub(`arn:aws:sqs:\${AWS::Region}:\${AWS::AccountId}:${c}-${s}-*`)});if(E)B[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["dynamodb:GetItem","dynamodb:PutItem","dynamodb:UpdateItem","dynamodb:DeleteItem","dynamodb:Query","dynamodb:Scan","dynamodb:BatchGetItem","dynamodb:BatchWriteItem"],Resource:e.sub(`arn:aws:dynamodb:\${AWS::Region}:\${AWS::AccountId}:table/${c}-${s}-cache*`)});let F=["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"];if(i.vpc?.subnets?.length)F.push("arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole");if(i.lambdaInsights)F.push("arn:aws:iam::aws:policy/CloudWatchLambdaInsightsExecutionRolePolicy");x.AppRole={Type:"AWS::IAM::Role",Properties:{RoleName:`${c}-${s}-app-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:F,Policies:B}};let U=(G)=>({TSCLOUD_LAMBDA_MODE:G,TSCLOUD_ENV:s,...i.octane?{TSCLOUD_OCTANE:"1"}:{},...i.scheduler==="sub-minute"?{TSCLOUD_SCHEDULER:"sub-minute"}:{},...E?{TSCLOUD_CACHE_TABLE:`${c}-${s}-cache`}:{},...T?{TSCLOUD_QUEUE:A[0]}:{},...i.env??{}}),j=Boolean(i.efs),H=typeof i.efs==="object"?i.efs:{},z=H.mountPath??"/mnt/local",ae=j&&!H.accessPointArn,Te=H.accessPointArn??(ae?e.getAtt("EfsAccessPoint","Arn"):void 0),oe=i.vpc?.subnets??[],pe=oe.length>0,se=i.cache?.driver==="elasticache"||i.database?.connection==="aurora-serverless"||Boolean(i.rdsProxy)||j;if(se&&!pe)throw Error("serverless app: elasticache / aurora-serverless / rdsProxy / efs require app.vpc.subnets (private subnets) to be set.");let me=pe?{VpcConfig:{SubnetIds:oe,SecurityGroupIds:[...i.vpc?.securityGroups??[],...se?[e.getAtt("DataSecurityGroup","GroupId")]:[]]}}:{},Ie=ae?oe.map((G,ne)=>`EfsMountTarget${ne}`):[],Le=j?{FileSystemConfigs:[{Arn:Te,LocalMountPath:z}]}:{};if(j)B[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["elasticfilesystem:ClientMount","elasticfilesystem:ClientWrite","elasticfilesystem:ClientRootAccess","elasticfilesystem:DescribeMountTargets"],Resource:"*"});function fe(G,ne,ie,re,ye,ht,Ve,Ne=L){x[`${G}LogGroup`]={Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:`/aws/lambda/${ne}`,RetentionInDays:v}};let Ue=[...n.runtimeLayers??[],...i.lambdaInsights?[i.lambdaInsights.layerArn]:[]],en=R?{PackageType:"Image",Code:{ImageUri:e.ref("ImageUri")},...i.kind==="php"?{}:{ImageConfig:{Command:[ie]}}}:{Runtime:u,Handler:ie,Code:{S3Bucket:e.ref("ArtifactBucket"),S3Key:e.ref("ArtifactKey")},...Ue.length?{Layers:[...new Set(Ue)]}:{}};x[G]={Type:"AWS::Lambda::Function",DependsOn:[`${G}LogGroup`,...Ie],Properties:{FunctionName:ne,Architectures:[d],MemorySize:ye,Timeout:ht,Role:e.getAtt("AppRole","Arn"),Environment:{Variables:U(re)},EphemeralStorage:{Size:Ne},...en,...Ve!==void 0?{ReservedConcurrentExecutions:Ve}:{},...me,...Le}}}if(fe("HttpFunction",h.http,o.http,"http",i.memory??1024,i.timeout??28,i.concurrency,L),fe("CliFunction",h.cli,o.cli,"cli",i.cliMemory??1024,i.cliTimeout??900,void 0,i.cliTmpStorage??L),T)fe("QueueFunction",h.queue,o.queue,"queue",i.queueMemory??1024,i.queueTimeout??120,void 0,i.queueTmpStorage??L);let ge=(i.provisionedConcurrency??0)>0?i.provisionedConcurrency:0,he=["HttpFunction","CliFunction",...T?["QueueFunction"]:[]];if(ge)for(let G of he)x[`${G}Version`]={Type:"AWS::Lambda::Version",DeletionPolicy:"Retain",Properties:{FunctionName:e.ref(G)}},x[`${G}Alias`]={Type:"AWS::Lambda::Alias",Properties:{FunctionName:e.ref(G),Name:"live",FunctionVersion:e.getAtt(`${G}Version`,"Version"),ProvisionedConcurrencyConfig:{ProvisionedConcurrentExecutions:ge}}};let De=(G)=>ge?e.ref(`${G}Alias`):e.getAtt(G,"Arn"),Se=(G)=>ge?e.ref(`${G}Alias`):e.ref(G);x.HttpApi={Type:"AWS::ApiGatewayV2::Api",Properties:{Name:`${c}-${s}`,ProtocolType:"HTTP"}},x.HttpIntegration={Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:e.ref("HttpApi"),IntegrationType:"AWS_PROXY",IntegrationUri:De("HttpFunction"),PayloadFormatVersion:"2.0"}},x.HttpRoute={Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:e.ref("HttpApi"),RouteKey:"$default",Target:e.join("/",["integrations",e.ref("HttpIntegration")])}},x.HttpStage={Type:"AWS::ApiGatewayV2::Stage",Properties:{ApiId:e.ref("HttpApi"),StageName:"$default",AutoDeploy:!0}},x.HttpPermission={Type:"AWS::Lambda::Permission",Properties:{FunctionName:Se("HttpFunction"),Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:e.sub("arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${HttpApi}/*/*")}},O.HttpApiEndpoint={Description:"HTTP API endpoint",Value:e.getAtt("HttpApi","ApiEndpoint")},O.HttpApiId={Description:"HTTP API id",Value:e.ref("HttpApi")};let Re=(Array.isArray(i.domain)?i.domain:i.domain?[i.domain]:[]).filter(Boolean);if(Re.length){if(!i.certificateArn&&!i.hostedZoneId)throw Error("serverless app: a custom `domain` needs either `certificateArn` (pre-issued, regional) or `hostedZoneId` (to auto-issue + validate an ACM cert).");let G=i.certificateArn;if(!G)x.HttpCertificate={Type:"AWS::CertificateManager::Certificate",Properties:{DomainName:Re[0],...Re.length>1?{SubjectAlternativeNames:Re.slice(1)}:{},ValidationMethod:"DNS",DomainValidationOptions:Re.map((ne)=>({DomainName:ne,HostedZoneId:i.hostedZoneId}))}},G=e.ref("HttpCertificate");Re.forEach((ne,ie)=>{let re=`HttpDomain${ie}`;if(x[re]={Type:"AWS::ApiGatewayV2::DomainName",Properties:{DomainName:ne,DomainNameConfigurations:[{CertificateArn:G,EndpointType:"REGIONAL"}]}},x[`HttpApiMapping${ie}`]={Type:"AWS::ApiGatewayV2::ApiMapping",DependsOn:["HttpStage"],Properties:{ApiId:e.ref("HttpApi"),DomainName:e.ref(re),Stage:"$default"}},i.hostedZoneId)x[`HttpDomainRecord${ie}`]={Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:i.hostedZoneId,Name:ne,Type:"A",AliasTarget:{DNSName:e.getAtt(re,"RegionalDomainName"),HostedZoneId:e.getAtt(re,"RegionalHostedZoneId")}}};O[`CustomDomain${ie}`]={Description:`Custom domain ${ne}`,Value:ne},O[`CustomDomainTarget${ie}`]={Description:`Point ${ne} (CNAME/alias) at this APIGW regional domain`,Value:e.getAtt(re,"RegionalDomainName")}})}if(T)x.AppQueueDlq={Type:"AWS::SQS::Queue",Properties:{QueueName:`${c}-${s}-dlq`,MessageRetentionPeriod:1209600}},S.forEach((G,ne)=>{let ie=`AppQueue${ne}`,re=i.queueTimeout??120;x[ie]={Type:"AWS::SQS::Queue",Properties:{QueueName:G.name,VisibilityTimeout:Math.min(43200,re*6),RedrivePolicy:{deadLetterTargetArn:e.getAtt("AppQueueDlq","Arn"),maxReceiveCount:i.queueTries??3}}};let ye=G.concurrency??i.queueConcurrency;x[`${ie}Mapping`]={Type:"AWS::Lambda::EventSourceMapping",Properties:{EventSourceArn:e.getAtt(ie,"Arn"),FunctionName:Se("QueueFunction"),BatchSize:1,FunctionResponseTypes:["ReportBatchItemFailures"],...ye?{ScalingConfig:{MaximumConcurrency:Math.max(2,ye)}}:{}}},O[`QueueUrl${ne}`]={Description:`Queue URL: ${G.name}`,Value:e.ref(ie)}});if(P)x.SchedulerRule={Type:"AWS::Events::Rule",Properties:{Name:`${c}-${s}-scheduler`,ScheduleExpression:"rate(1 minute)",State:"ENABLED",Targets:[{Id:"cli",Arn:De("CliFunction"),Input:JSON.stringify({command:"schedule:run"})}]}},x.SchedulerPermission={Type:"AWS::Lambda::Permission",Properties:{FunctionName:Se("CliFunction"),Action:"lambda:InvokeFunction",Principal:"events.amazonaws.com",SourceArn:e.getAtt("SchedulerRule","Arn")}};if(i.warm&&i.warm>0){let ne={http:"HttpFunction",queue:"QueueFunction",cli:"CliFunction"},ie=(i.warmFunctions??["http"]).filter((re)=>re!=="queue"||T);for(let re of ie){let ye=re.charAt(0).toUpperCase()+re.slice(1),ht=Math.ceil(i.warm/5),Ve=0;for(let Ne=0;Ne<ht;Ne++){let Ue=Math.min(5,i.warm-Ve);x[`Warmer${ye}Rule${Ne}`]={Type:"AWS::Events::Rule",Properties:{Name:`${c}-${s}-warmer-${re}-${Ne}`,ScheduleExpression:"rate(5 minutes)",State:"ENABLED",Targets:Array.from({length:Ue},(en,mr)=>({Id:`warm-${re}-${Ne}-${mr}`,Arn:e.getAtt(ne[re],"Arn"),Input:JSON.stringify({warmer:!0})}))}},Ve+=Ue}x[`Warmer${ye}Permission`]={Type:"AWS::Lambda::Permission",Properties:{FunctionName:e.ref(ne[re]),Action:"lambda:InvokeFunction",Principal:"events.amazonaws.com",SourceArn:e.sub(`arn:aws:events:\${AWS::Region}:\${AWS::AccountId}:rule/${c}-${s}-warmer-${re}-*`)}}}}if(E)x.CacheTable={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${c}-${s}-cache`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"key",AttributeType:"S"}],KeySchema:[{AttributeName:"key",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"expires_at",Enabled:!0}}},O.CacheTableName={Description:"DynamoDB cache table",Value:e.ref("CacheTable")};if(I){if(x.AssetsBucket={Type:"AWS::S3::Bucket",Properties:{BucketName:M,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0}}},x.AssetsOAC={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`${c}-${s}-assets-oac`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},x.AssetsDistribution={Type:"AWS::CloudFront::Distribution",Properties:{DistributionConfig:{Enabled:!0,DefaultCacheBehavior:{TargetOriginId:"assets",ViewerProtocolPolicy:"redirect-to-https",Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6"},Origins:[{Id:"assets",DomainName:e.getAtt("AssetsBucket","RegionalDomainName"),OriginAccessControlId:e.ref("AssetsOAC"),S3OriginConfig:{OriginAccessIdentity:""}}],...i.assetDomain?{Aliases:[i.assetDomain],ViewerCertificate:{AcmCertificateArn:i.assetCertificateArn??e.ref("AssetsCertificate"),SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}}:{}}}},i.assetDomain){if(!i.assetCertificateArn){if(!i.hostedZoneId)throw Error("serverless app: `assetDomain` requires either `assetCertificateArn` (a us-east-1 ACM cert) or `hostedZoneId` (to auto-issue + validate one). CloudFront only accepts certs from us-east-1.");if(f!=="us-east-1")throw Error(`serverless app: auto-issuing an asset-domain cert needs a us-east-1 app (CloudFront certs must be us-east-1); this app is in ${f}. Supply a pre-issued us-east-1 \`assetCertificateArn\` instead.`);x.AssetsCertificate={Type:"AWS::CertificateManager::Certificate",Properties:{DomainName:i.assetDomain,ValidationMethod:"DNS",DomainValidationOptions:[{DomainName:i.assetDomain,HostedZoneId:i.hostedZoneId}]}}}if(i.hostedZoneId)x.AssetsDomainRecord={Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:i.hostedZoneId,Name:i.assetDomain,Type:"A",AliasTarget:{DNSName:e.getAtt("AssetsDistribution","DomainName"),HostedZoneId:"Z2FDTNDATAQYW2"}}};O.AssetDomain={Description:"Custom asset CDN host",Value:i.assetDomain}}x.AssetsBucketPolicy={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:e.ref("AssetsBucket"),PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:e.sub(`arn:aws:s3:::${M}/*`),Condition:{StringEquals:{"AWS:SourceArn":e.sub("arn:aws:cloudfront::${AWS::AccountId}:distribution/${AssetsDistribution}")}}}]}}},O.AssetsBucketName={Description:"Assets bucket",Value:e.ref("AssetsBucket")},O.AssetsCdnDomain={Description:"Assets CloudFront domain",Value:e.getAtt("AssetsDistribution","DomainName")}}if(i.firewall?.enabled){let G=[],ne=0;if(i.firewall.rateLimit)G.push({Name:"rate-limit",Priority:ne++,Action:{Block:{}},Statement:{RateBasedStatement:{Limit:i.firewall.rateLimit,AggregateKeyType:"IP"}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${c}-${s}-rate`}});let ie={sqlInjection:"AWSManagedRulesSQLiRuleSet",xss:"AWSManagedRulesCommonRuleSet",common:"AWSManagedRulesCommonRuleSet",botControl:"AWSManagedRulesBotControlRuleSet",ipReputation:"AWSManagedRulesAmazonIpReputationList"};for(let re of i.firewall.rules??[]){let ye=ie[re];if(!ye)continue;G.push({Name:`managed-${re}`,Priority:ne++,OverrideAction:{None:{}},Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:ye}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${c}-${s}-${re}`}})}x.WebAcl={Type:"AWS::WAFv2::WebACL",Properties:{Name:`${c}-${s}-waf`,Scope:"REGIONAL",DefaultAction:{Allow:{}},Rules:G,VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${c}-${s}-waf`}}},O.WafAclArn={Description:"WAF web ACL ARN. Attach to a CloudFront distribution fronting the API to enforce (HTTP API v2 stages do not support direct WAF association).",Value:e.getAtt("WebAcl","Arn")}}if(pe&&se){if(!i.vpc?.id)throw Error("serverless app: data services (elasticache / aurora-serverless / rdsProxy / efs) need app.vpc.id (the VPC id) so the managed security group is created in the right VPC.");x.DataSecurityGroup={Type:"AWS::EC2::SecurityGroup",Properties:{VpcId:i.vpc.id,GroupDescription:`${c}-${s} serverless data access`,SecurityGroupIngress:[{IpProtocol:"-1",CidrIp:"10.0.0.0/8"}]}}}if(ae)x.EfsFileSystem={Type:"AWS::EFS::FileSystem",Properties:{Encrypted:!0,FileSystemTags:[{Key:"Name",Value:`${c}-${s}-efs`}]}},oe.forEach((G,ne)=>{x[`EfsMountTarget${ne}`]={Type:"AWS::EFS::MountTarget",Properties:{FileSystemId:e.ref("EfsFileSystem"),SubnetId:G,SecurityGroups:[e.getAtt("DataSecurityGroup","GroupId")]}}}),x.EfsAccessPoint={Type:"AWS::EFS::AccessPoint",Properties:{FileSystemId:e.ref("EfsFileSystem"),PosixUser:{Uid:1001,Gid:1001},RootDirectory:{Path:"/lambda",CreationInfo:{OwnerUid:1001,OwnerGid:1001,Permissions:"0755"}}}},O.EfsFileSystemId={Description:"EFS file system id",Value:e.ref("EfsFileSystem")};if(i.cache?.driver==="elasticache")x.CacheSubnetGroup={Type:"AWS::ElastiCache::SubnetGroup",Properties:{Description:`${c}-${s} cache subnets`,SubnetIds:oe}},x.CacheCluster={Type:"AWS::ElastiCache::ReplicationGroup",Properties:{ReplicationGroupId:`${c}-${s}-cache`,ReplicationGroupDescription:`${c}-${s} redis`,Engine:"redis",CacheNodeType:"cache.t4g.micro",NumCacheClusters:1,AutomaticFailoverEnabled:!1,CacheSubnetGroupName:e.ref("CacheSubnetGroup"),SecurityGroupIds:[e.getAtt("DataSecurityGroup","GroupId")],TransitEncryptionEnabled:!1}},O.CacheEndpoint={Description:"Redis primary endpoint",Value:e.getAtt("CacheCluster","PrimaryEndPoint.Address")};if(i.database?.connection==="aurora-serverless")x.DbSubnetGroup={Type:"AWS::RDS::DBSubnetGroup",Properties:{DBSubnetGroupDescription:`${c}-${s} db subnets`,SubnetIds:oe}},x.DbSecret={Type:"AWS::SecretsManager::Secret",Properties:{Name:`${c}/${s}/db`,GenerateSecretString:{SecretStringTemplate:JSON.stringify({username:"app"}),GenerateStringKey:"password",PasswordLength:32,ExcludePunctuation:!0}}},x.DbCluster={Type:"AWS::RDS::DBCluster",Properties:{Engine:"aurora-mysql",EngineMode:"provisioned",DBClusterIdentifier:`${c}-${s}-db`,DatabaseName:"app",MasterUsername:e.sub("{{resolve:secretsmanager:${DbSecret}:SecretString:username}}"),MasterUserPassword:e.sub("{{resolve:secretsmanager:${DbSecret}:SecretString:password}}"),ServerlessV2ScalingConfiguration:{MinCapacity:i.database?.minCapacity??0.5,MaxCapacity:i.database?.maxCapacity??4},DBSubnetGroupName:e.ref("DbSubnetGroup"),VpcSecurityGroupIds:[e.getAtt("DataSecurityGroup","GroupId")]}},x.DbInstance={Type:"AWS::RDS::DBInstance",Properties:{Engine:"aurora-mysql",DBInstanceClass:"db.serverless",DBClusterIdentifier:e.ref("DbCluster")}},O.DbEndpoint={Description:"Aurora cluster endpoint",Value:e.getAtt("DbCluster","Endpoint.Address")};if(i.rdsProxy&&i.database?.connection==="aurora-serverless")x.DbProxyRole={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"rds.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"read-db-secret",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["secretsmanager:GetSecretValue"],Resource:e.ref("DbSecret")}]}}]}},x.DbProxy={Type:"AWS::RDS::DBProxy",Properties:{DBProxyName:typeof i.rdsProxy==="object"&&i.rdsProxy.name?i.rdsProxy.name:`${c}-${s}-proxy`,EngineFamily:"MYSQL",RoleArn:e.getAtt("DbProxyRole","Arn"),Auth:[{AuthScheme:"SECRETS",SecretArn:e.ref("DbSecret"),IAMAuth:"DISABLED"}],VpcSubnetIds:oe,VpcSecurityGroupIds:[e.getAtt("DataSecurityGroup","GroupId")],RequireTLS:!1}},x.DbProxyTargetGroup={Type:"AWS::RDS::DBProxyTargetGroup",DependsOn:["DbInstance"],Properties:{DBProxyName:e.ref("DbProxy"),TargetGroupName:"default",DBClusterIdentifiers:[e.ref("DbCluster")]}},O.DbProxyEndpoint={Description:"RDS Proxy endpoint",Value:e.getAtt("DbProxy","Endpoint")};if(O.HttpFunctionName={Description:"HTTP function name",Value:e.ref("HttpFunction")},O.CliFunctionName={Description:"CLI function name",Value:e.ref("CliFunction")},T)O.QueueFunctionName={Description:"Queue function name",Value:e.ref("QueueFunction")};let $e={AWSTemplateFormatVersion:"2010-09-09",Description:`Serverless application for ${n.config.project.name} (${c}-${s})`,Parameters:R?{ImageUri:{Type:"String",Description:"ECR image URI of the deployment artifact"}}:{ArtifactBucket:{Type:"String",Description:"S3 bucket holding the deployment artifact"},ArtifactKey:{Type:"String",Description:"S3 key of the deployment artifact (zip)"}},Resources:x,Outputs:O},We={};for(let G of Object.values(x))We[G.Type]=(We[G.Type]??0)+1;return{template:$e,functionNames:h,queueNames:A,resourceSummary:We}}var Zy=["cli","fpm","curl","mbstring","xml","pdo","mysqlnd","gd","bcmath","intl","opcache","sodium","process","pecl-redis6","pecl-apcu","pgsql"];function eS(n){let i=`php${n.replace(".","")}`;return Zy.map((s)=>`${i}-php-${s}`)}function Pl(n,i){let s=`php${n.replace(".","")}`,o=eS(n).join(" \\\n "),c=`/opt/remi/${s}/root`,u=`/etc/opt/remi/${s}`;return`${i?`FROM almalinux:9 AS ${i}`:"FROM almalinux:9"}
|
|
7242
7242
|
|
|
7243
7243
|
# Build PHP on AlmaLinux 9 (where Remi's version-isolated SCL packages install
|
|
7244
7244
|
# cleanly — Remi's release RPM rejects Amazon Linux 2023). AlmaLinux 9 shares
|
|
@@ -7299,7 +7299,7 @@ COPY app/ \${LAMBDA_TASK_ROOT}/
|
|
|
7299
7299
|
|
|
7300
7300
|
# Per-function CMD (e.g. index.http) is supplied via ImageConfig.Command.
|
|
7301
7301
|
CMD [ "index.http" ]
|
|
7302
|
-
`}import{execFileSync as ut}from"node:child_process";import{mkdtempSync as jn,readFileSync as dt,rmSync as Kn}from"node:fs";import{tmpdir as qn}from"node:os";import{dirname as os,join as Pe}from"node:path";import{fileURLToPath as cs}from"node:url";function zn(){return os(cs(import.meta.url))}function Af(){return dt(Pe(zn(),"runtime.mjs"),"utf-8")}function Qn(n){return dt(Pe(zn(),`${n}-bootstrap`),"utf-8")}function fE(n){let i=n.architecture??"x86_64",s=i==="arm64"?"arm64":"x64",o=n.version.replace(/^v/,""),c=n.onStep??(()=>{}),u=jn(Pe(qn(),"tscloud-node-layer-"));try{let d=o.includes(".")?o:ls(o),f=`node-v${d}-linux-${s}`,h=`https://nodejs.org/dist/v${d}/${f}.tar.xz`;c(`downloading Node ${d} (${i})`);let S=Pe(u,"node.tar.xz");Jn(h,S),c("extracting node binary"),ut("tar",["-xf",S,"-C",u,`${f}/bin/node`],{stdio:"inherit"});let A=dt(Pe(u,f,"bin","node"));c("packaging layer");let T=[{name:"bootstrap",data:Qn("node"),mode:493},{name:"runtime.mjs",data:Af(),mode:420},{name:"bin/node",data:A,mode:493}];return{zip:rt(T),architecture:i,version:d,fileCount:T.length}}finally{Kn(u,{recursive:!0,force:!0})}}function hE(n){let i=n.architecture??"x86_64",s=i==="arm64"?"bun-linux-aarch64":"bun-linux-x64",o=n.version==="latest"?"":n.version.replace(/^v/,""),c=n.onStep??(()=>{}),u=jn(Pe(qn(),"tscloud-bun-layer-"));try{let d=o?`https://github.com/oven-sh/bun/releases/download/bun-v${o}/${s}.zip`:`https://github.com/oven-sh/bun/releases/latest/download/${s}.zip`;c(`downloading Bun ${o||"latest"} (${i})`);let f=Pe(u,"bun.zip");Jn(d,f),c("extracting bun binary"),ut("unzip",["-o","-q",f,"-d",u],{stdio:"inherit"});let h=dt(Pe(u,s,"bun"));c("packaging layer");let S=[{name:"bootstrap",data:Qn("bun"),mode:493},{name:"runtime.mjs",data:Af(),mode:420},{name:"bin/bun",data:h,mode:493}];return{zip:rt(S),architecture:i,version:o||"latest",fileCount:S.length}}finally{Kn(u,{recursive:!0,force:!0})}}function Jn(n,i){ut("curl",["-fsSL","-o",i,n],{stdio:["ignore","ignore","inherit"]})}function ls(n){let i=ut("curl",["-fsSL","https://nodejs.org/dist/index.json"],{encoding:"utf-8"}),o=JSON.parse(i).find((c)=>c.version.startsWith(`v${n}.`));if(!o)throw Error(`No Node release found for major version ${n}`);return o.version.replace(/^v/,"")}import{AsyncLocalStorage as ds}from"node:async_hooks";import{createHash as us}from"node:crypto";var Uo="x-ts-cloud-invoke-depth",Qo="x-ts-cloud-invoke-chain",Ho="x-ts-cloud-trace-id";function kl(n){return us("sha256").update(n).digest("hex").slice(0,8)}var un={maxDepth:10,maxRepeats:3,maxInvocationsPerTrace:100,traceWindowMs:60000,breakerThreshold:5,breakerCooldownMs:60000};function Yt(n,i){if(typeof n.get==="function")return n.get(i)??void 0;let s=n;return s[i]??s[i.toLowerCase()]??s[i.toUpperCase()]}function Bl(n,i=64){if(!n)return[];return n.split(".").map((s)=>s.trim()).filter((s)=>/^[0-9a-f]{8}$/.test(s)).slice(-i)}function xl(n,i=un){let s=kl(n.functionId),o=Bl(Yt(n.headers,Qo)),c=n.traceId??Yt(n.headers,Ho)??crypto.randomUUID(),u=[...o,s],d=o.filter((T)=>T===s).length,f=o[o.length-1]===s,h=Number.parseInt(Yt(n.headers,Uo)??"",10),S=Math.max(u.length,Number.isFinite(h)?h+1:0),A="ok";if(S>i.maxDepth)A="depth_exceeded";else if(d>=i.maxRepeats)A="cycle_detected";else if(f&&i.maxRepeats<=1)A="self_invocation";return{reason:A,depth:S,chain:u,traceId:c,selfInvocation:f,repeats:d,propagate:{[Uo]:String(S),[Qo]:u.join("."),[Ho]:c}}}var Yn={ok:"",depth_exceeded:"Invocation chain is deeper than the configured limit; the call was refused to stop a runaway loop.",cycle_detected:"This function already appears in the invocation chain; the call was refused as a recursion loop.",self_invocation:"This function invoked itself directly; the call was refused.",trace_budget_exceeded:"This request has already made more invocations than its budget allows.",breaker_open:"Recursion protection is open for this function after repeated loop detections."};class Ji{limits;clock;traces=new Map;breakers=new Map;constructor(n=un,i=()=>Date.now()){this.limits=n;this.clock=i}check(n){let i=this.clock();this.expireTraces(i);let s=xl(n,this.limits),o=this.breakers.get(n.functionId);if(o?.openUntil!=null&&o.openUntil>i)return this.deny(n.functionId,s,"breaker_open",i,!1);if(s.reason!=="ok")return this.deny(n.functionId,s,s.reason,i,!0);let c=this.traces.get(s.traceId)??{count:0,firstAt:i};if(c.count>=this.limits.maxInvocationsPerTrace)return this.traces.set(s.traceId,c),this.deny(n.functionId,s,"trace_budget_exceeded",i,!0);if(this.traces.set(s.traceId,{count:c.count+1,firstAt:c.firstAt}),o)this.breakers.set(n.functionId,{consecutiveBlocks:0});return{...s,allowed:!0,reason:"ok",propagate:s.propagate}}deny(n,i,s,o,c){if(c){let u=this.breakers.get(n)??{consecutiveBlocks:0},d=u.consecutiveBlocks+1;this.breakers.set(n,{consecutiveBlocks:d,openUntil:d>=this.limits.breakerThreshold?o+this.limits.breakerCooldownMs:u.openUntil})}return{...i,allowed:!1,reason:s,message:Yn[s]}}breakerOpen(n){let i=this.breakers.get(n);return i?.openUntil!=null&&i.openUntil>this.clock()}reset(n){if(n){this.breakers.delete(n);return}this.breakers.clear(),this.traces.clear()}expireTraces(n){if(this.traces.size===0)return;for(let[i,s]of this.traces)if(n-s.firstAt>this.limits.traceWindowMs)this.traces.delete(i)}get trackedTraces(){return this.traces.size}}function Go(n){return{...n.propagate}}function Vo(n){return{status:508,headers:{"content-type":"application/json","x-ts-cloud-recursion-blocked":n.reason},body:{error:"recursion_blocked",reason:n.reason,message:n.message??Yn[n.reason],depth:n.depth,traceId:n.traceId}}}var yf=new ds;function Zn(n){let i=globalThis.process?.env?.[n];if(i==null||i==="")return;return i!=="0"&&i.toLowerCase()!=="false"}function ms(){let n=globalThis.process?.env??{};return n.TS_CLOUD_FUNCTION_ID||n.AWS_LAMBDA_FUNCTION_NAME||n.FUNCTION_NAME||"function"}function tS(n){let i=n===!1?{enabled:!1}:n??{},s=Zn("TS_CLOUD_RECURSION_PROTECTION"),o=Zn("TS_CLOUD_RECURSION_DETECTION_ONLY");return{enabled:s??i.enabled??!0,detectionOnly:o??i.detectionOnly??!1,limits:{...un,...i.limits},functionId:i.functionId??ms()}}var Ne,Ae;function rS(){let n=globalThis.fetch;if(!n||Ne===n)return()=>{};Ae=n;let i=async(s,o)=>{let c=yf.getStore();if(!c)return Ae(s,o);let u=new Headers(o?.headers??(s instanceof Request?s.headers:void 0));for(let[d,f]of Object.entries(Go(c)))u.set(d,f);if(s instanceof Request)return Ae(new Request(s,{headers:u}),o);return Ae(s,{...o,headers:u})};return Object.assign(i,n),globalThis.fetch=i,Ne=i,()=>{if(globalThis.fetch===Ne&&Ae)globalThis.fetch=Ae;Ne=void 0}}var mt,Zt;function nS(n){if(!mt||JSON.stringify(Zt)!==JSON.stringify(n))mt=new Ji(n),Zt=n;return mt}function AE(){if(mt=void 0,Zt=void 0,Ne&&Ae&&globalThis.fetch===Ne)globalThis.fetch=Ae;Ne=void 0,Ae=void 0}function Sf(n,i){let s=tS(i);if(!s.enabled)return;let o=nS(s.limits),c={functionId:s.functionId,headers:n},u=o.check(c);return{verdict:u,blocked:!u.allowed&&!s.detectionOnly,observed:!u.allowed&&s.detectionOnly}}function If(n,i){return rS(),yf.run(n,i)}function yE(n){let i=n,s=i?.default??i;if(typeof s==="function")return{fetch:s};return{fetch:s?.fetch??i?.fetch,queue:s?.queue??i?.queue,cli:s?.cli??i?.cli}}var ps=/^(?:text\/|application\/(?:json|xml|javascript|graphql|x-www-form-urlencoded|.*\+json|.*\+xml)|image\/svg)/i;function gs(n){if(!n)return!0;return ps.test(n)}function ys(n){if(n?.maintenance)return n.maintenance;let i=globalThis.process?.env??{};return{enabled:i.MAINTENANCE_MODE==="1"||i.MAINTENANCE_MODE==="true",bypassSecret:i.MAINTENANCE_BYPASS_SECRET}}function iS(n){let i=n.requestContext?.domainName??"localhost",s=n.rawQueryString?`?${n.rawQueryString}`:"",o=`https://${i}${n.rawPath||"/"}${s}`,c=new Headers;for(let[f,h]of Object.entries(n.headers??{}))if(h!==void 0)c.set(f,h);if(n.cookies?.length)c.set("cookie",n.cookies.join("; "));let u=n.requestContext.http.method,d;if(n.body!==void 0&&u!=="GET"&&u!=="HEAD")d=n.isBase64Encoded?new Uint8Array(Buffer.from(n.body,"base64")):new TextEncoder().encode(n.body);return new Request(o,{method:u,headers:c,body:d})}async function bf(n){let i={},s=[],o=typeof n.headers.getSetCookie==="function"?n.headers.getSetCookie():[];for(let d of o)s.push(d);n.headers.forEach((d,f)=>{if(f.toLowerCase()==="set-cookie")return;i[f]=d});let c=Buffer.from(await n.arrayBuffer()),u=gs(n.headers.get("content-type"));return{statusCode:n.status,headers:i,...s.length?{cookies:s}:{},body:u?c.toString("utf-8"):c.toString("base64"),isBase64Encoded:!u}}function sS(n,i){return async(s)=>{if(s.warmer)return{statusCode:200,headers:{"content-type":"text/plain"},body:"warm",isBase64Encoded:!1};if(!n)return{statusCode:501,headers:{"content-type":"text/plain"},body:"No HTTP handler configured",isBase64Encoded:!1};let o=ys(i);if(o.enabled){let d=s.headers?.["x-maintenance-bypass"]??s.cookies?.find((f)=>f.startsWith("tscloud_bypass="))?.split("=")[1];if(!o.bypassSecret||d!==o.bypassSecret)return{statusCode:503,headers:{"content-type":"text/plain","retry-after":"120"},body:"Service temporarily unavailable (maintenance mode)",isBase64Encoded:!1}}let c=Sf(s.headers??{},i?.recursionProtection);if(c?.blocked){let d=Vo(c.verdict);return{statusCode:d.status,headers:{...d.headers,"retry-after":"60"},body:JSON.stringify(d.body),isBase64Encoded:!1}}let u=iS(s);if(!c){let d=await n(u);return bf(d)}if(c.observed)console.warn(`[ts-cloud] recursion detected (${c.verdict.reason}) at depth ${c.verdict.depth}; detection-only mode let it run`);return If(c.verdict,async()=>bf(await n(u)))}}function fs(n){try{return JSON.parse(n)}catch{return n}}function oS(n){return async(i)=>{let s=[];if(i.warmer)return{batchItemFailures:s};if(!n)return{batchItemFailures:s};for(let o of i.Records??[])try{await n(fs(o.body),o)}catch{s.push({itemIdentifier:o.messageId})}return{batchItemFailures:s}}}function aS(n){return async(i)=>{if(i.warmer)return{statusCode:0,output:"warm"};if(!n)return{statusCode:501,output:"No CLI handler configured"};return n(i)}}function SE(n,i){return{http:sS(n.fetch,i),queue:oS(n.queue),cli:aS(n.cli)}}function Cf(n={}){let i=n.socketPath??"/tmp/.tscloud-fpm.sock",s=n.maxChildren??1;return`; ts-cloud php-fpm configuration (generated) — AWS Lambda custom runtime.
|
|
7302
|
+
`}import{execFileSync as pt}from"node:child_process";import{mkdtempSync as jn,readFileSync as gt,rmSync as Kn}from"node:fs";import{tmpdir as qn}from"node:os";import{dirname as oa,join as we}from"node:path";import{fileURLToPath as ca}from"node:url";function zn(){return oa(ca(import.meta.url))}function Af(){return gt(we(zn(),"runtime.mjs"),"utf-8")}function Qn(n){return gt(we(zn(),`${n}-bootstrap`),"utf-8")}function fE(n){let i=n.architecture??"x86_64",s=i==="arm64"?"arm64":"x64",o=n.version.replace(/^v/,""),c=n.onStep??(()=>{}),u=jn(we(qn(),"tscloud-node-layer-"));try{let d=o.includes(".")?o:la(o),f=`node-v${d}-linux-${s}`,h=`https://nodejs.org/dist/v${d}/${f}.tar.xz`;c(`downloading Node ${d} (${i})`);let S=we(u,"node.tar.xz");Jn(h,S),c("extracting node binary"),pt("tar",["-xf",S,"-C",u,`${f}/bin/node`],{stdio:"inherit"});let A=gt(we(u,f,"bin","node"));c("packaging layer");let T=[{name:"bootstrap",data:Qn("node"),mode:493},{name:"runtime.mjs",data:Af(),mode:420},{name:"bin/node",data:A,mode:493}];return{zip:rt(T),architecture:i,version:d,fileCount:T.length}}finally{Kn(u,{recursive:!0,force:!0})}}function hE(n){let i=n.architecture??"x86_64",s=i==="arm64"?"bun-linux-aarch64":"bun-linux-x64",o=n.version==="latest"?"":n.version.replace(/^v/,""),c=n.onStep??(()=>{}),u=jn(we(qn(),"tscloud-bun-layer-"));try{let d=o?`https://github.com/oven-sh/bun/releases/download/bun-v${o}/${s}.zip`:`https://github.com/oven-sh/bun/releases/latest/download/${s}.zip`;c(`downloading Bun ${o||"latest"} (${i})`);let f=we(u,"bun.zip");Jn(d,f),c("extracting bun binary"),pt("unzip",["-o","-q",f,"-d",u],{stdio:"inherit"});let h=gt(we(u,s,"bun"));c("packaging layer");let S=[{name:"bootstrap",data:Qn("bun"),mode:493},{name:"runtime.mjs",data:Af(),mode:420},{name:"bin/bun",data:h,mode:493}];return{zip:rt(S),architecture:i,version:o||"latest",fileCount:S.length}}finally{Kn(u,{recursive:!0,force:!0})}}function Jn(n,i){pt("curl",["-fsSL","-o",i,n],{stdio:["ignore","ignore","inherit"]})}function la(n){let i=pt("curl",["-fsSL","https://nodejs.org/dist/index.json"],{encoding:"utf-8"}),o=JSON.parse(i).find((c)=>c.version.startsWith(`v${n}.`));if(!o)throw Error(`No Node release found for major version ${n}`);return o.version.replace(/^v/,"")}import{AsyncLocalStorage as da}from"node:async_hooks";import{createHash as ua}from"node:crypto";var Uo="x-ts-cloud-invoke-depth",Qo="x-ts-cloud-invoke-chain",Ho="x-ts-cloud-trace-id";function kl(n){return ua("sha256").update(n).digest("hex").slice(0,8)}var un={maxDepth:10,maxRepeats:3,maxInvocationsPerTrace:100,traceWindowMs:60000,breakerThreshold:5,breakerCooldownMs:60000};function Yt(n,i){if(typeof n.get==="function")return n.get(i)??void 0;let s=n;return s[i]??s[i.toLowerCase()]??s[i.toUpperCase()]}function Bl(n,i=64){if(!n)return[];return n.split(".").map((s)=>s.trim()).filter((s)=>/^[0-9a-f]{8}$/.test(s)).slice(-i)}function xl(n,i=un){let s=kl(n.functionId),o=Bl(Yt(n.headers,Qo)),c=n.traceId??Yt(n.headers,Ho)??crypto.randomUUID(),u=[...o,s],d=o.filter((T)=>T===s).length,f=o[o.length-1]===s,h=Number.parseInt(Yt(n.headers,Uo)??"",10),S=Math.max(u.length,Number.isFinite(h)?h+1:0),A="ok";if(S>i.maxDepth)A="depth_exceeded";else if(d>=i.maxRepeats)A="cycle_detected";else if(f&&i.maxRepeats<=1)A="self_invocation";return{reason:A,depth:S,chain:u,traceId:c,selfInvocation:f,repeats:d,propagate:{[Uo]:String(S),[Qo]:u.join("."),[Ho]:c}}}var Yn={ok:"",depth_exceeded:"Invocation chain is deeper than the configured limit; the call was refused to stop a runaway loop.",cycle_detected:"This function already appears in the invocation chain; the call was refused as a recursion loop.",self_invocation:"This function invoked itself directly; the call was refused.",trace_budget_exceeded:"This request has already made more invocations than its budget allows.",breaker_open:"Recursion protection is open for this function after repeated loop detections."};class Ji{limits;clock;traces=new Map;breakers=new Map;constructor(n=un,i=()=>Date.now()){this.limits=n;this.clock=i}check(n){let i=this.clock();this.expireTraces(i);let s=xl(n,this.limits),o=this.breakers.get(n.functionId);if(o?.openUntil!=null&&o.openUntil>i)return this.deny(n.functionId,s,"breaker_open",i,!1);if(s.reason!=="ok")return this.deny(n.functionId,s,s.reason,i,!0);let c=this.traces.get(s.traceId)??{count:0,firstAt:i};if(c.count>=this.limits.maxInvocationsPerTrace)return this.traces.set(s.traceId,c),this.deny(n.functionId,s,"trace_budget_exceeded",i,!0);if(this.traces.set(s.traceId,{count:c.count+1,firstAt:c.firstAt}),o)this.breakers.set(n.functionId,{consecutiveBlocks:0});return{...s,allowed:!0,reason:"ok",propagate:s.propagate}}deny(n,i,s,o,c){if(c){let u=this.breakers.get(n)??{consecutiveBlocks:0},d=u.consecutiveBlocks+1;this.breakers.set(n,{consecutiveBlocks:d,openUntil:d>=this.limits.breakerThreshold?o+this.limits.breakerCooldownMs:u.openUntil})}return{...i,allowed:!1,reason:s,message:Yn[s]}}breakerOpen(n){let i=this.breakers.get(n);return i?.openUntil!=null&&i.openUntil>this.clock()}reset(n){if(n){this.breakers.delete(n);return}this.breakers.clear(),this.traces.clear()}expireTraces(n){if(this.traces.size===0)return;for(let[i,s]of this.traces)if(n-s.firstAt>this.limits.traceWindowMs)this.traces.delete(i)}get trackedTraces(){return this.traces.size}}function Go(n){return{...n.propagate}}function Vo(n){return{status:508,headers:{"content-type":"application/json","x-ts-cloud-recursion-blocked":n.reason},body:{error:"recursion_blocked",reason:n.reason,message:n.message??Yn[n.reason],depth:n.depth,traceId:n.traceId}}}var yf=new da;function Zn(n){let i=globalThis.process?.env?.[n];if(i==null||i==="")return;return i!=="0"&&i.toLowerCase()!=="false"}function ma(){let n=globalThis.process?.env??{};return n.TS_CLOUD_FUNCTION_ID||n.AWS_LAMBDA_FUNCTION_NAME||n.FUNCTION_NAME||"function"}function tS(n){let i=n===!1?{enabled:!1}:n??{},s=Zn("TS_CLOUD_RECURSION_PROTECTION"),o=Zn("TS_CLOUD_RECURSION_DETECTION_ONLY");return{enabled:s??i.enabled??!0,detectionOnly:o??i.detectionOnly??!1,limits:{...un,...i.limits},functionId:i.functionId??ma()}}var Me,ve;function rS(){let n=globalThis.fetch;if(!n||Me===n)return()=>{};ve=n;let i=async(s,o)=>{let c=yf.getStore();if(!c)return ve(s,o);let u=new Headers(o?.headers??(s instanceof Request?s.headers:void 0));for(let[d,f]of Object.entries(Go(c)))u.set(d,f);if(s instanceof Request)return ve(new Request(s,{headers:u}),o);return ve(s,{...o,headers:u})};return Object.assign(i,n),globalThis.fetch=i,Me=i,()=>{if(globalThis.fetch===Me&&ve)globalThis.fetch=ve;Me=void 0}}var yt,Zt;function nS(n){if(!yt||JSON.stringify(Zt)!==JSON.stringify(n))yt=new Ji(n),Zt=n;return yt}function AE(){if(yt=void 0,Zt=void 0,Me&&ve&&globalThis.fetch===Me)globalThis.fetch=ve;Me=void 0,ve=void 0}function Sf(n,i){let s=tS(i);if(!s.enabled)return;let o=nS(s.limits),c={functionId:s.functionId,headers:n},u=o.check(c);return{verdict:u,blocked:!u.allowed&&!s.detectionOnly,observed:!u.allowed&&s.detectionOnly}}function If(n,i){return rS(),yf.run(n,i)}function yE(n){let i=n,s=i?.default??i;if(typeof s==="function")return{fetch:s};return{fetch:s?.fetch??i?.fetch,queue:s?.queue??i?.queue,cli:s?.cli??i?.cli}}var pa=/^(?:text\/|application\/(?:json|xml|javascript|graphql|x-www-form-urlencoded|.*\+json|.*\+xml)|image\/svg)/i;function ga(n){if(!n)return!0;return pa.test(n)}function ya(n){if(n?.maintenance)return n.maintenance;let i=globalThis.process?.env??{};return{enabled:i.MAINTENANCE_MODE==="1"||i.MAINTENANCE_MODE==="true",bypassSecret:i.MAINTENANCE_BYPASS_SECRET}}function iS(n){let i=n.requestContext?.domainName??"localhost",s=n.rawQueryString?`?${n.rawQueryString}`:"",o=`https://${i}${n.rawPath||"/"}${s}`,c=new Headers;for(let[f,h]of Object.entries(n.headers??{}))if(h!==void 0)c.set(f,h);if(n.cookies?.length)c.set("cookie",n.cookies.join("; "));let u=n.requestContext.http.method,d;if(n.body!==void 0&&u!=="GET"&&u!=="HEAD")d=n.isBase64Encoded?new Uint8Array(Buffer.from(n.body,"base64")):new TextEncoder().encode(n.body);return new Request(o,{method:u,headers:c,body:d})}async function bf(n){let i={},s=[],o=typeof n.headers.getSetCookie==="function"?n.headers.getSetCookie():[];for(let d of o)s.push(d);n.headers.forEach((d,f)=>{if(f.toLowerCase()==="set-cookie")return;i[f]=d});let c=Buffer.from(await n.arrayBuffer()),u=ga(n.headers.get("content-type"));return{statusCode:n.status,headers:i,...s.length?{cookies:s}:{},body:u?c.toString("utf-8"):c.toString("base64"),isBase64Encoded:!u}}function sS(n,i){return async(s)=>{if(s.warmer)return{statusCode:200,headers:{"content-type":"text/plain"},body:"warm",isBase64Encoded:!1};if(!n)return{statusCode:501,headers:{"content-type":"text/plain"},body:"No HTTP handler configured",isBase64Encoded:!1};let o=ya(i);if(o.enabled){let d=s.headers?.["x-maintenance-bypass"]??s.cookies?.find((f)=>f.startsWith("tscloud_bypass="))?.split("=")[1];if(!o.bypassSecret||d!==o.bypassSecret)return{statusCode:503,headers:{"content-type":"text/plain","retry-after":"120"},body:"Service temporarily unavailable (maintenance mode)",isBase64Encoded:!1}}let c=Sf(s.headers??{},i?.recursionProtection);if(c?.blocked){let d=Vo(c.verdict);return{statusCode:d.status,headers:{...d.headers,"retry-after":"60"},body:JSON.stringify(d.body),isBase64Encoded:!1}}let u=iS(s);if(!c){let d=await n(u);return bf(d)}if(c.observed)console.warn(`[ts-cloud] recursion detected (${c.verdict.reason}) at depth ${c.verdict.depth}; detection-only mode let it run`);return If(c.verdict,async()=>bf(await n(u)))}}function fa(n){try{return JSON.parse(n)}catch{return n}}function oS(n){return async(i)=>{let s=[];if(i.warmer)return{batchItemFailures:s};if(!n)return{batchItemFailures:s};for(let o of i.Records??[])try{await n(fa(o.body),o)}catch{s.push({itemIdentifier:o.messageId})}return{batchItemFailures:s}}}function aS(n){return async(i)=>{if(i.warmer)return{statusCode:0,output:"warm"};if(!n)return{statusCode:501,output:"No CLI handler configured"};return n(i)}}function SE(n,i){return{http:sS(n.fetch,i),queue:oS(n.queue),cli:aS(n.cli)}}function Cf(n={}){let i=n.socketPath??"/tmp/.tscloud-fpm.sock",s=n.maxChildren??1;return`; ts-cloud php-fpm configuration (generated) — AWS Lambda custom runtime.
|
|
7303
7303
|
[global]
|
|
7304
7304
|
daemonize = no
|
|
7305
7305
|
error_log = ${n.errorLog??"/tmp/storage/logs/php-fpm.log"}
|
|
@@ -7316,4 +7316,4 @@ decorate_workers_output = no
|
|
|
7316
7316
|
php_admin_value[error_log] = /dev/stderr
|
|
7317
7317
|
php_admin_flag[log_errors] = on
|
|
7318
7318
|
clear_env = no
|
|
7319
|
-
`}import{readFileSync as hs}from"node:fs";import{dirname as bs,join as Xn}from"node:path";import{fileURLToPath as Ss}from"node:url";function As(){return Xn(bs(Ss(import.meta.url)),"runtime-assets")}function gn(){let n=As(),i=(s)=>hs(Xn(n,s),"utf-8");return[{path:"bootstrap",contents:i("bootstrap"),mode:493},{path:"tscloud/runtime.php",contents:i("runtime.php"),mode:420},{path:"tscloud/octane-runtime.php",contents:i("octane-runtime.php"),mode:420},{path:"tscloud/cli-runtime.php",contents:i("cli-runtime.php"),mode:420},{path:"tscloud/fastcgi-client.php",contents:i("fastcgi-client.php"),mode:420},{path:"tscloud/php-fpm.conf",contents:Cf(),mode:420}]}function Ol(n={}){let i=n.cacheDriver??"dynamodb";return{APP_ENV:"production",LOG_CHANNEL:"stderr",CACHE_STORE:i,CACHE_DRIVER:i,SESSION_DRIVER:i,QUEUE_CONNECTION:"sqs",FILESYSTEM_DISK:"s3",VIEW_COMPILED_PATH:"/tmp/storage/framework/views",APP_SERVICES_CACHE:"/tmp/bootstrap/cache/services.php",APP_PACKAGES_CACHE:"/tmp/bootstrap/cache/packages.php",APP_CONFIG_CACHE:"/tmp/bootstrap/cache/config.php",APP_ROUTES_CACHE:"/tmp/bootstrap/cache/routes.php",APP_EVENTS_CACHE:"/tmp/bootstrap/cache/events.php"}}var Ef=["composer install --no-dev --optimize-autoloader --no-interaction","php artisan config:cache","php artisan route:cache","php artisan event:cache","php artisan view:cache"];import{execFileSync as pt}from"node:child_process";import{existsSync as Cs,mkdirSync as vs,mkdtempSync as Ts,readdirSync as Rs,readFileSync as Ps,rmSync as Es,statSync as er,writeFileSync as ws}from"node:fs";import{tmpdir as Is}from"node:os";import{join as $e,relative as Ds}from"node:path";function*tr(n){for(let i of Rs(n)){let s=$e(n,i);if(er(s).isDirectory())yield*tr(s);else yield s}}function IE(n={}){let i=n.architecture??"x86_64",s=n.platform??(i==="arm64"?"linux/arm64":"linux/amd64"),o=n.onStep??(()=>{}),c=Ts($e(Is(),"tscloud-php-layer-")),u="tscloud-php-layer:build";try{ws($e(c,"Dockerfile"),hf(n)),o("Building PHP runtime image (docker)"),pt("docker",["build","--platform",s,"-t","tscloud-php-layer:build",c],{stdio:"inherit"}),o("Extracting /opt/php from image");let d=pt("docker",["create","--platform",s,"tscloud-php-layer:build"],{encoding:"utf-8"}).trim(),f=$e(c,"opt");vs(f,{recursive:!0});try{pt("docker",["cp",`${d}:/opt/php`,$e(f,"php")],{stdio:"inherit"})}finally{pt("docker",["rm",d],{stdio:"ignore"})}if(!Cs($e(f,"php","bin","php")))throw Error("layer build produced no /opt/php/bin/php");let h=[];for(let v of tr(f)){let R=Ds(f,v).replace(/\\/g,"/"),P=er(v).mode&73?493:420;h.push({name:R,data:Ps(v),mode:P})}o("Injecting runtime assets");let S=new Set(gn().map((v)=>v.path)),A=h.filter((v)=>!S.has(v.name));for(let v of gn())A.push({name:v.path,data:v.contents,mode:v.mode});return o("Packaging layer ZIP"),{zip:rt(A),architecture:i,fileCount:A.length}}finally{Es(c,{recursive:!0,force:!0})}}import{execSync as Ns}from"node:child_process";import{createHash as xs}from"node:crypto";import{readdirSync as ks,readFileSync as Ms,statSync as nr}from"node:fs";import{join as Ls,relative as rr,resolve as Xt}from"node:path";var cS=[".git",".github","node_modules","tests","storage/logs","storage/framework/cache","storage/framework/sessions","storage/framework/views",".env",".env.local",".vapor",".ts-cloud","dist-lambda"];function Os(n,i){return i.some((s)=>n===s||n.startsWith(`${s}/`))}function*ir(n,i,s){for(let o of ks(n)){let c=Ls(n,o),u=rr(i,c).replace(/\\/g,"/");if(Os(u,s))continue;if(nr(c).isDirectory())yield*ir(c,i,s);else yield c}}function qo(n){if(n.skipBuild)return;let i=Xt(n.projectRoot??process.cwd()),s=n.app.build??Ef;for(let o of s)n.onStep?.(`build: ${o}`),Ns(o,{stdio:"inherit",cwd:i})}function jo(n,i=[]){let s=Xt(n),o=[...cS,sn(),...i],c=[];for(let u of ir(s,s,o)){let d=rr(s,u).replace(/\\/g,"/"),f=(nr(u).mode&73)!==0;c.push({name:d,data:Ms(u),mode:f?493:420})}return c}function _l(n){let i=Xt(n.projectRoot??process.cwd());qo(n),n.onStep?.("packaging application tree");let s=jo(i,n.exclude);if(!s.length)throw Error(`No files to package under ${i}`);let o=rt(s),c=n.app.handlers?.http??"public/index.php";return{zip:o,sha256:xs("sha256").update(o).digest("hex"),handlers:{http:c,queue:n.app.handlers?.queue??c,cli:n.app.handlers?.cli??c},fileCount:s.length}}class vf{optimizations=new Map;imageConfigs=new Map;ssgConfigs=new Map;prerenderConfigs=new Map;counter=0;createAssetOptimization(n){let i=`asset-opt-${Date.now()}-${this.counter++}`,s={id:i,...n};return this.optimizations.set(i,s),s}createImageOptimization(n){let i=`image-opt-${Date.now()}-${this.counter++}`,s={id:i,...n};return this.imageConfigs.set(i,s),s}createSSGConfig(n){let i=`ssg-${Date.now()}-${this.counter++}`,s={id:i,...n};return this.ssgConfigs.set(i,s),s}createPrerenderConfig(n){let i=`prerender-${Date.now()}-${this.counter++}`,s={id:i,...n};return this.prerenderConfigs.set(i,s),s}listOptimizations(){return Array.from(this.optimizations.values())}listImageConfigs(){return Array.from(this.imageConfigs.values())}clear(){this.optimizations.clear(),this.imageConfigs.clear(),this.ssgConfigs.clear(),this.prerenderConfigs.clear()}}var bE=new vf;class Ll{policies=new Map;versioningConfigs=new Map;replicationRules=new Map;tieringConfigs=new Map;objectLocks=new Map;transferAcceleration=new Map;accessPoints=new Map;glacierConfigs=new Map;inventories=new Map;batchOps=new Map;eventNotifications=new Map;counter=0;createLifecyclePolicy(n,i){let s=`lifecycle-${Date.now()}-${this.counter++}`,o={id:s,transitions:n,expiration:i};return this.policies.set(s,o),o}enableVersioning(n=!1){let i=`versioning-${Date.now()}-${this.counter++}`,s={id:i,enabled:!0,mfaDelete:n};return this.versioningConfigs.set(i,s),s}createReplicationRule(n,i,s){let o=`replication-${Date.now()}-${this.counter++}`,c={id:o,sourceRegion:n,destRegion:i,destBucket:s};return this.replicationRules.set(o,c),c}createIntelligentTiering(n,i){let s=`tiering-${Date.now()}-${this.counter++}`,o={id:s,archiveDays:n,deepArchiveDays:i};return this.tieringConfigs.set(s,o),o}enableObjectLock(n){let i=`object-lock-${Date.now()}-${this.counter++}`,s={id:i,bucketName:n.bucketName,mode:n.mode||"COMPLIANCE",retentionDays:n.retentionDays,retentionYears:n.retentionYears,legalHoldEnabled:n.legalHoldEnabled||!1};return this.objectLocks.set(i,s),s}enableTransferAcceleration(n){let i=`transfer-accel-${Date.now()}-${this.counter++}`,s={id:i,bucketName:n,enabled:!0,endpoint:`${n}.s3-accelerate.amazonaws.com`};return this.transferAcceleration.set(i,s),s}createAccessPoint(n){let i=`access-point-${Date.now()}-${this.counter++}`,s={id:i,name:n.name,bucketName:n.bucketName,vpcId:n.vpcId,publicAccessBlock:n.publicAccessBlock!==!1,policy:n.policy};return this.accessPoints.set(i,s),s}createGlacierArchive(n){let i=`glacier-${Date.now()}-${this.counter++}`,s={id:i,bucketName:n.bucketName,archiveType:n.archiveType,transitionDays:n.transitionDays,restoreConfig:n.restoreTier?{tier:n.restoreTier,days:n.restoreDays||7}:void 0};return this.glacierConfigs.set(i,s),s}createInventory(n){let i=`inventory-${Date.now()}-${this.counter++}`,s={id:i,sourceBucket:n.sourceBucket,destinationBucket:n.destinationBucket,schedule:n.schedule||"Daily",format:n.format||"CSV",includedFields:n.includedFields||["Size","LastModifiedDate","StorageClass","ETag"],prefix:n.prefix};return this.inventories.set(i,s),s}createBatchOperation(n){let i=`batch-op-${Date.now()}-${this.counter++}`,s={id:i,operation:n.operation,manifestBucket:n.manifestBucket,manifestKey:n.manifestKey,priority:n.priority||10,status:"pending"};return this.batchOps.set(i,s),s}executeBatchOperation(n){let i=this.batchOps.get(n);if(!i)throw Error(`Batch operation not found: ${n}`);return i.status="in_progress",i.totalObjects=1000,i.processedObjects=0,i}getBatchOperationStatus(n){return this.batchOps.get(n)}createLambdaNotification(n){let i=`event-${Date.now()}-${this.counter++}`,s={id:i,bucketName:n.bucketName,events:n.events,destination:{type:"Lambda",arn:n.lambdaArn},filter:n.prefix||n.suffix?{prefix:n.prefix,suffix:n.suffix}:void 0};return this.eventNotifications.set(i,s),s}createSQSNotification(n){let i=`event-${Date.now()}-${this.counter++}`,s={id:i,bucketName:n.bucketName,events:n.events,destination:{type:"SQS",arn:n.queueArn},filter:n.prefix||n.suffix?{prefix:n.prefix,suffix:n.suffix}:void 0};return this.eventNotifications.set(i,s),s}createSNSNotification(n){let i=`event-${Date.now()}-${this.counter++}`,s={id:i,bucketName:n.bucketName,events:n.events,destination:{type:"SNS",arn:n.topicArn},filter:n.prefix||n.suffix?{prefix:n.prefix,suffix:n.suffix}:void 0};return this.eventNotifications.set(i,s),s}generateObjectLockCF(n){let i={ObjectLockEnabled:"Enabled",ObjectLockConfiguration:{ObjectLockEnabled:"Enabled",Rule:{DefaultRetention:{Mode:n.mode}}}};if(n.retentionDays)i.ObjectLockConfiguration.Rule.DefaultRetention.Days=n.retentionDays;if(n.retentionYears)i.ObjectLockConfiguration.Rule.DefaultRetention.Years=n.retentionYears;return i}generateTransferAccelerationCF(n){return{AccelerateConfiguration:{AccelerationStatus:n.enabled?"Enabled":"Suspended"}}}generateAccessPointCF(n){return{Type:"AWS::S3::AccessPoint",Properties:{Name:n.name,Bucket:n.bucketName,...n.vpcId&&{VpcConfiguration:{VpcId:n.vpcId}},PublicAccessBlockConfiguration:n.publicAccessBlock?{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0}:void 0,...n.policy&&{Policy:n.policy}}}}generateInventoryCF(n){return{Type:"AWS::S3::Bucket",Properties:{InventoryConfigurations:[{Id:n.id,Destination:{BucketArn:`arn:aws:s3:::${n.destinationBucket}`,Format:n.format},Enabled:!0,IncludedObjectVersions:"Current",OptionalFields:n.includedFields,ScheduleFrequency:n.schedule,...n.prefix&&{Prefix:n.prefix}}]}}}generateEventNotificationCF(n){let i=n.destination.type==="Lambda"?"LambdaConfigurations":n.destination.type==="SQS"?"QueueConfigurations":"TopicConfigurations",s=n.destination.type==="Lambda"?"Function":n.destination.type==="SQS"?"Queue":"Topic",o={Event:n.events[0],[s]:n.destination.arn};if(n.filter)o.Filter={S3Key:{Rules:[...n.filter.prefix?[{Name:"prefix",Value:n.filter.prefix}]:[],...n.filter.suffix?[{Name:"suffix",Value:n.filter.suffix}]:[]]}};return{NotificationConfiguration:{[i]:[o]}}}clear(){this.policies.clear(),this.versioningConfigs.clear(),this.replicationRules.clear(),this.tieringConfigs.clear(),this.objectLocks.clear(),this.transferAcceleration.clear(),this.accessPoints.clear(),this.glacierConfigs.clear(),this.inventories.clear(),this.batchOps.clear(),this.eventNotifications.clear()}}var dS=new Ll;class Tf{checks=new Map;synthetics=new Map;uptimeTrackers=new Map;counter=0;createHealthCheck(n,i=30,s=10){let o=`health-${Date.now()}-${this.counter++}`,c={id:o,url:n,interval:i,timeout:s,status:"healthy"};return this.checks.set(o,c),c}createSyntheticMonitor(n,i,s,o){let c=`synthetic-${Date.now()}-${this.counter++}`,u={id:c,name:n,script:i,frequency:s,locations:o};return this.synthetics.set(c,u),u}trackUptime(n,i,s){let o=`uptime-${Date.now()}-${this.counter++}`,c=i/(i+s)*100,u={id:o,resource:n,uptime:i,downtime:s,availability:c};return this.uptimeTrackers.set(o,u),u}clear(){this.checks.clear(),this.synthetics.clear(),this.uptimeTrackers.clear()}}var CE=new Tf;class wf{wafRules=new Map;shieldProtections=new Map;securityGroups=new Map;nacls=new Map;counter=0;createWAFRule(n,i,s,o){let c=`waf-${Date.now()}-${this.counter++}`,u={id:c,name:n,priority:i,action:s,conditions:o};return this.wafRules.set(c,u),u}enableShield(n,i="standard"){let s=`shield-${Date.now()}-${this.counter++}`,o={id:s,resourceArn:n,protectionType:i};return this.shieldProtections.set(s,o),o}createSecurityGroup(n,i,s){let o=`sg-${Date.now()}-${this.counter++}`,c={id:o,name:n,vpcId:i,rules:s};return this.securityGroups.set(o,c),c}createNACL(n,i){let s=`nacl-${Date.now()}-${this.counter++}`,o={id:s,vpcId:n,rules:i};return this.nacls.set(s,o),o}clear(){this.wafRules.clear(),this.shieldProtections.clear(),this.securityGroups.clear(),this.nacls.clear()}}var EE=new wf;class Rf{strategies=new Map;allocations=new Map;groups=new Map;counter=0;createTaggingStrategy(n,i){let s=`tagging-${Date.now()}-${this.counter++}`,o={id:s,tags:n,resources:i};return this.strategies.set(s,o),o}createCostAllocation(n,i){let s=`cost-${Date.now()}-${this.counter++}`,o={id:s,tagKey:n,allocations:i};return this.allocations.set(s,o),o}createResourceGroup(n,i,s){let o=`group-${Date.now()}-${this.counter++}`,c={id:o,name:n,query:{resourceTypeFilters:i,tagFilters:s}};return this.groups.set(o,c),c}clear(){this.strategies.clear(),this.allocations.clear(),this.groups.clear()}}var vE=new Rf;export{EI,vI,qd,nm,jd,zd,sn,Q,l,Kd,im,K,Wd,g,HA,b,Xe,Hi,on,w,be,Jd,GA,r,t,TI,wI,p,RI,DI,PI,NI,kI,sr,Xd,Gi,VA,BI,xI,xe,Ye,Yd,sm,om,OI,am,cm,dm,Bo,Zd,ce,an,Tt,xo,wt,Ce,qA,el,Oo,lm,um,gm,pm,tl,_I,W,C,jA,zA,mm,a,y,Ze,m,fm,et,J,Rt,LI,hm,X,rl,Oe,or,_o,de,nl,le,KA,Lo,Y,Z,_,Vi,D,ar,Dt,ee,e,cn,$I,Am,il,MI,FI,UI,QI,sl,HI,GI,VI,qI,jI,zI,KI,WI,JI,XI,YI,ZI,WA,JA,XA,YA,ZA,ey,ty,cr,ym,Sm,dr,qi,eb,Im,tb,rb,dn,nb,ib,sb,ob,ab,cb,ry,ny,iy,sy,oy,ji,db,$o,ay,bm,V,cy,tt,Mo,Pt,dy,Cm,ly,uy,gy,Em,q,lb,ub,gb,pb,py,mb,te,fb,hb,Ab,ol,al,my,vm,Tm,yb,Sb,Ib,bb,Cb,fy,cl,Eb,vb,Tb,wb,Rb,hy,Ay,Db,Pb,Nb,kb,Bb,xb,Ob,yy,_b,wm,dl,Lb,$b,Mb,Fb,Rm,Dm,Pm,Ub,ll,Sy,Iy,by,Cy,ul,Ey,Qb,Hb,Gb,Vb,qb,jb,zb,vy,Ty,wy,Ry,Nm,Kb,Wb,Jb,Xb,Yb,Zb,eC,tC,rC,Dy,Py,Ny,ky,nC,iC,km,sC,Bm,xm,Om,_m,oC,aC,cC,dC,_e,zi,lC,uC,gC,pC,mC,fC,hC,AC,By,yC,SC,Lm,$m,IC,bC,xy,CC,EC,vC,TC,wC,RC,DC,PC,NC,kC,BC,xC,OC,_C,LC,$C,MC,FC,UC,QC,HC,gl,Oy,pl,_y,ml,Ly,fl,$y,hl,My,lr,Fy,Al,Uy,Ki,Qy,yl,Hy,Sl,Gy,Mm,GC,Fm,VC,Il,Vy,ur,qy,Um,qC,bl,jy,Qm,jC,Hm,zC,Gm,KC,Cl,zy,Vm,WC,qm,JC,jm,XC,zm,YC,El,Ky,vl,Wy,Km,ZC,Wm,eE,Jm,tE,Xm,rE,Ym,nE,Zm,iE,Tl,Jy,ef,sE,tf,oE,rf,aE,nf,cE,sf,dE,of,lE,af,cf,df,lf,uf,uE,gf,gE,pf,pE,mf,mE,rt,ff,Xy,Fo,wl,ln,Yy,Wi,gr,Rl,Dl,Zy,eS,Pl,hf,Nl,Af,fE,hE,Uo,Qo,Ho,kl,un,Bl,xl,Ji,Go,Vo,yf,tS,rS,nS,AE,Sf,If,yE,iS,bf,sS,oS,aS,SE,Cf,gn,Ol,Ef,IE,cS,qo,jo,_l,vf,bE,Ll,dS,Tf,CE,wf,EE,Rf,vE};
|
|
7319
|
+
`}import{readFileSync as ha}from"node:fs";import{dirname as ba,join as Xn}from"node:path";import{fileURLToPath as Sa}from"node:url";function Aa(){return Xn(ba(Sa(import.meta.url)),"runtime-assets")}function gn(){let n=Aa(),i=(s)=>ha(Xn(n,s),"utf-8");return[{path:"bootstrap",contents:i("bootstrap"),mode:493},{path:"tscloud/runtime.php",contents:i("runtime.php"),mode:420},{path:"tscloud/octane-runtime.php",contents:i("octane-runtime.php"),mode:420},{path:"tscloud/cli-runtime.php",contents:i("cli-runtime.php"),mode:420},{path:"tscloud/fastcgi-client.php",contents:i("fastcgi-client.php"),mode:420},{path:"tscloud/php-fpm.conf",contents:Cf(),mode:420}]}function Ol(n={}){let i=n.cacheDriver??"dynamodb";return{APP_ENV:"production",LOG_CHANNEL:"stderr",CACHE_STORE:i,CACHE_DRIVER:i,SESSION_DRIVER:i,QUEUE_CONNECTION:"sqs",FILESYSTEM_DISK:"s3",VIEW_COMPILED_PATH:"/tmp/storage/framework/views",APP_SERVICES_CACHE:"/tmp/bootstrap/cache/services.php",APP_PACKAGES_CACHE:"/tmp/bootstrap/cache/packages.php",APP_CONFIG_CACHE:"/tmp/bootstrap/cache/config.php",APP_ROUTES_CACHE:"/tmp/bootstrap/cache/routes.php",APP_EVENTS_CACHE:"/tmp/bootstrap/cache/events.php"}}var Ef=["composer install --no-dev --optimize-autoloader --no-interaction","php artisan config:cache","php artisan route:cache","php artisan event:cache","php artisan view:cache"];import{execFileSync as ft}from"node:child_process";import{existsSync as Ca,mkdirSync as va,mkdtempSync as Ta,readdirSync as Ra,readFileSync as Pa,rmSync as Ea,statSync as er,writeFileSync as wa}from"node:fs";import{tmpdir as Ia}from"node:os";import{join as Ge,relative as Da}from"node:path";function*tr(n){for(let i of Ra(n)){let s=Ge(n,i);if(er(s).isDirectory())yield*tr(s);else yield s}}function IE(n={}){let i=n.architecture??"x86_64",s=n.platform??(i==="arm64"?"linux/arm64":"linux/amd64"),o=n.onStep??(()=>{}),c=Ta(Ge(Ia(),"tscloud-php-layer-")),u="tscloud-php-layer:build";try{wa(Ge(c,"Dockerfile"),hf(n)),o("Building PHP runtime image (docker)"),ft("docker",["build","--platform",s,"-t","tscloud-php-layer:build",c],{stdio:"inherit"}),o("Extracting /opt/php from image");let d=ft("docker",["create","--platform",s,"tscloud-php-layer:build"],{encoding:"utf-8"}).trim(),f=Ge(c,"opt");va(f,{recursive:!0});try{ft("docker",["cp",`${d}:/opt/php`,Ge(f,"php")],{stdio:"inherit"})}finally{ft("docker",["rm",d],{stdio:"ignore"})}if(!Ca(Ge(f,"php","bin","php")))throw Error("layer build produced no /opt/php/bin/php");let h=[];for(let v of tr(f)){let R=Da(f,v).replace(/\\/g,"/"),P=er(v).mode&73?493:420;h.push({name:R,data:Pa(v),mode:P})}o("Injecting runtime assets");let S=new Set(gn().map((v)=>v.path)),A=h.filter((v)=>!S.has(v.name));for(let v of gn())A.push({name:v.path,data:v.contents,mode:v.mode});return o("Packaging layer ZIP"),{zip:rt(A),architecture:i,fileCount:A.length}}finally{Ea(c,{recursive:!0,force:!0})}}import{execSync as Na}from"node:child_process";import{createHash as xa}from"node:crypto";import{readdirSync as ka,readFileSync as Ma,statSync as nr}from"node:fs";import{join as La,relative as rr,resolve as Xt}from"node:path";var cS=[".git",".github","node_modules","tests","storage/logs","storage/framework/cache","storage/framework/sessions","storage/framework/views",".env",".env.local",".vapor",".ts-cloud","dist-lambda"];function Oa(n,i){return i.some((s)=>n===s||n.startsWith(`${s}/`))}function*ir(n,i,s){for(let o of ka(n)){let c=La(n,o),u=rr(i,c).replace(/\\/g,"/");if(Oa(u,s))continue;if(nr(c).isDirectory())yield*ir(c,i,s);else yield c}}function qo(n){if(n.skipBuild)return;let i=Xt(n.projectRoot??process.cwd()),s=n.app.build??Ef;for(let o of s)n.onStep?.(`build: ${o}`),Na(o,{stdio:"inherit",cwd:i})}function jo(n,i=[]){let s=Xt(n),o=[...cS,sn(),...i],c=[];for(let u of ir(s,s,o)){let d=rr(s,u).replace(/\\/g,"/"),f=(nr(u).mode&73)!==0;c.push({name:d,data:Ma(u),mode:f?493:420})}return c}function _l(n){let i=Xt(n.projectRoot??process.cwd());qo(n),n.onStep?.("packaging application tree");let s=jo(i,n.exclude);if(!s.length)throw Error(`No files to package under ${i}`);let o=rt(s),c=n.app.handlers?.http??"public/index.php";return{zip:o,sha256:xa("sha256").update(o).digest("hex"),handlers:{http:c,queue:n.app.handlers?.queue??c,cli:n.app.handlers?.cli??c},fileCount:s.length}}class vf{optimizations=new Map;imageConfigs=new Map;ssgConfigs=new Map;prerenderConfigs=new Map;counter=0;createAssetOptimization(n){let i=`asset-opt-${Date.now()}-${this.counter++}`,s={id:i,...n};return this.optimizations.set(i,s),s}createImageOptimization(n){let i=`image-opt-${Date.now()}-${this.counter++}`,s={id:i,...n};return this.imageConfigs.set(i,s),s}createSSGConfig(n){let i=`ssg-${Date.now()}-${this.counter++}`,s={id:i,...n};return this.ssgConfigs.set(i,s),s}createPrerenderConfig(n){let i=`prerender-${Date.now()}-${this.counter++}`,s={id:i,...n};return this.prerenderConfigs.set(i,s),s}listOptimizations(){return Array.from(this.optimizations.values())}listImageConfigs(){return Array.from(this.imageConfigs.values())}clear(){this.optimizations.clear(),this.imageConfigs.clear(),this.ssgConfigs.clear(),this.prerenderConfigs.clear()}}var bE=new vf;class Ll{policies=new Map;versioningConfigs=new Map;replicationRules=new Map;tieringConfigs=new Map;objectLocks=new Map;transferAcceleration=new Map;accessPoints=new Map;glacierConfigs=new Map;inventories=new Map;batchOps=new Map;eventNotifications=new Map;counter=0;createLifecyclePolicy(n,i){let s=`lifecycle-${Date.now()}-${this.counter++}`,o={id:s,transitions:n,expiration:i};return this.policies.set(s,o),o}enableVersioning(n=!1){let i=`versioning-${Date.now()}-${this.counter++}`,s={id:i,enabled:!0,mfaDelete:n};return this.versioningConfigs.set(i,s),s}createReplicationRule(n,i,s){let o=`replication-${Date.now()}-${this.counter++}`,c={id:o,sourceRegion:n,destRegion:i,destBucket:s};return this.replicationRules.set(o,c),c}createIntelligentTiering(n,i){let s=`tiering-${Date.now()}-${this.counter++}`,o={id:s,archiveDays:n,deepArchiveDays:i};return this.tieringConfigs.set(s,o),o}enableObjectLock(n){let i=`object-lock-${Date.now()}-${this.counter++}`,s={id:i,bucketName:n.bucketName,mode:n.mode||"COMPLIANCE",retentionDays:n.retentionDays,retentionYears:n.retentionYears,legalHoldEnabled:n.legalHoldEnabled||!1};return this.objectLocks.set(i,s),s}enableTransferAcceleration(n){let i=`transfer-accel-${Date.now()}-${this.counter++}`,s={id:i,bucketName:n,enabled:!0,endpoint:`${n}.s3-accelerate.amazonaws.com`};return this.transferAcceleration.set(i,s),s}createAccessPoint(n){let i=`access-point-${Date.now()}-${this.counter++}`,s={id:i,name:n.name,bucketName:n.bucketName,vpcId:n.vpcId,publicAccessBlock:n.publicAccessBlock!==!1,policy:n.policy};return this.accessPoints.set(i,s),s}createGlacierArchive(n){let i=`glacier-${Date.now()}-${this.counter++}`,s={id:i,bucketName:n.bucketName,archiveType:n.archiveType,transitionDays:n.transitionDays,restoreConfig:n.restoreTier?{tier:n.restoreTier,days:n.restoreDays||7}:void 0};return this.glacierConfigs.set(i,s),s}createInventory(n){let i=`inventory-${Date.now()}-${this.counter++}`,s={id:i,sourceBucket:n.sourceBucket,destinationBucket:n.destinationBucket,schedule:n.schedule||"Daily",format:n.format||"CSV",includedFields:n.includedFields||["Size","LastModifiedDate","StorageClass","ETag"],prefix:n.prefix};return this.inventories.set(i,s),s}createBatchOperation(n){let i=`batch-op-${Date.now()}-${this.counter++}`,s={id:i,operation:n.operation,manifestBucket:n.manifestBucket,manifestKey:n.manifestKey,priority:n.priority||10,status:"pending"};return this.batchOps.set(i,s),s}executeBatchOperation(n){let i=this.batchOps.get(n);if(!i)throw Error(`Batch operation not found: ${n}`);return i.status="in_progress",i.totalObjects=1000,i.processedObjects=0,i}getBatchOperationStatus(n){return this.batchOps.get(n)}createLambdaNotification(n){let i=`event-${Date.now()}-${this.counter++}`,s={id:i,bucketName:n.bucketName,events:n.events,destination:{type:"Lambda",arn:n.lambdaArn},filter:n.prefix||n.suffix?{prefix:n.prefix,suffix:n.suffix}:void 0};return this.eventNotifications.set(i,s),s}createSQSNotification(n){let i=`event-${Date.now()}-${this.counter++}`,s={id:i,bucketName:n.bucketName,events:n.events,destination:{type:"SQS",arn:n.queueArn},filter:n.prefix||n.suffix?{prefix:n.prefix,suffix:n.suffix}:void 0};return this.eventNotifications.set(i,s),s}createSNSNotification(n){let i=`event-${Date.now()}-${this.counter++}`,s={id:i,bucketName:n.bucketName,events:n.events,destination:{type:"SNS",arn:n.topicArn},filter:n.prefix||n.suffix?{prefix:n.prefix,suffix:n.suffix}:void 0};return this.eventNotifications.set(i,s),s}generateObjectLockCF(n){let i={ObjectLockEnabled:"Enabled",ObjectLockConfiguration:{ObjectLockEnabled:"Enabled",Rule:{DefaultRetention:{Mode:n.mode}}}};if(n.retentionDays)i.ObjectLockConfiguration.Rule.DefaultRetention.Days=n.retentionDays;if(n.retentionYears)i.ObjectLockConfiguration.Rule.DefaultRetention.Years=n.retentionYears;return i}generateTransferAccelerationCF(n){return{AccelerateConfiguration:{AccelerationStatus:n.enabled?"Enabled":"Suspended"}}}generateAccessPointCF(n){return{Type:"AWS::S3::AccessPoint",Properties:{Name:n.name,Bucket:n.bucketName,...n.vpcId&&{VpcConfiguration:{VpcId:n.vpcId}},PublicAccessBlockConfiguration:n.publicAccessBlock?{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0}:void 0,...n.policy&&{Policy:n.policy}}}}generateInventoryCF(n){return{Type:"AWS::S3::Bucket",Properties:{InventoryConfigurations:[{Id:n.id,Destination:{BucketArn:`arn:aws:s3:::${n.destinationBucket}`,Format:n.format},Enabled:!0,IncludedObjectVersions:"Current",OptionalFields:n.includedFields,ScheduleFrequency:n.schedule,...n.prefix&&{Prefix:n.prefix}}]}}}generateEventNotificationCF(n){let i=n.destination.type==="Lambda"?"LambdaConfigurations":n.destination.type==="SQS"?"QueueConfigurations":"TopicConfigurations",s=n.destination.type==="Lambda"?"Function":n.destination.type==="SQS"?"Queue":"Topic",o={Event:n.events[0],[s]:n.destination.arn};if(n.filter)o.Filter={S3Key:{Rules:[...n.filter.prefix?[{Name:"prefix",Value:n.filter.prefix}]:[],...n.filter.suffix?[{Name:"suffix",Value:n.filter.suffix}]:[]]}};return{NotificationConfiguration:{[i]:[o]}}}clear(){this.policies.clear(),this.versioningConfigs.clear(),this.replicationRules.clear(),this.tieringConfigs.clear(),this.objectLocks.clear(),this.transferAcceleration.clear(),this.accessPoints.clear(),this.glacierConfigs.clear(),this.inventories.clear(),this.batchOps.clear(),this.eventNotifications.clear()}}var dS=new Ll;class Tf{checks=new Map;synthetics=new Map;uptimeTrackers=new Map;counter=0;createHealthCheck(n,i=30,s=10){let o=`health-${Date.now()}-${this.counter++}`,c={id:o,url:n,interval:i,timeout:s,status:"healthy"};return this.checks.set(o,c),c}createSyntheticMonitor(n,i,s,o){let c=`synthetic-${Date.now()}-${this.counter++}`,u={id:c,name:n,script:i,frequency:s,locations:o};return this.synthetics.set(c,u),u}trackUptime(n,i,s){let o=`uptime-${Date.now()}-${this.counter++}`,c=i/(i+s)*100,u={id:o,resource:n,uptime:i,downtime:s,availability:c};return this.uptimeTrackers.set(o,u),u}clear(){this.checks.clear(),this.synthetics.clear(),this.uptimeTrackers.clear()}}var CE=new Tf;class wf{wafRules=new Map;shieldProtections=new Map;securityGroups=new Map;nacls=new Map;counter=0;createWAFRule(n,i,s,o){let c=`waf-${Date.now()}-${this.counter++}`,u={id:c,name:n,priority:i,action:s,conditions:o};return this.wafRules.set(c,u),u}enableShield(n,i="standard"){let s=`shield-${Date.now()}-${this.counter++}`,o={id:s,resourceArn:n,protectionType:i};return this.shieldProtections.set(s,o),o}createSecurityGroup(n,i,s){let o=`sg-${Date.now()}-${this.counter++}`,c={id:o,name:n,vpcId:i,rules:s};return this.securityGroups.set(o,c),c}createNACL(n,i){let s=`nacl-${Date.now()}-${this.counter++}`,o={id:s,vpcId:n,rules:i};return this.nacls.set(s,o),o}clear(){this.wafRules.clear(),this.shieldProtections.clear(),this.securityGroups.clear(),this.nacls.clear()}}var EE=new wf;class Rf{strategies=new Map;allocations=new Map;groups=new Map;counter=0;createTaggingStrategy(n,i){let s=`tagging-${Date.now()}-${this.counter++}`,o={id:s,tags:n,resources:i};return this.strategies.set(s,o),o}createCostAllocation(n,i){let s=`cost-${Date.now()}-${this.counter++}`,o={id:s,tagKey:n,allocations:i};return this.allocations.set(s,o),o}createResourceGroup(n,i,s){let o=`group-${Date.now()}-${this.counter++}`,c={id:o,name:n,query:{resourceTypeFilters:i,tagFilters:s}};return this.groups.set(o,c),c}clear(){this.strategies.clear(),this.allocations.clear(),this.groups.clear()}}var vE=new Rf;export{EI,vI,qd,nm,jd,zd,sn,Q,l,Kd,im,K,Wd,g,HA,b,Xe,Hi,on,w,be,Jd,GA,r,t,TI,wI,p,RI,DI,PI,NI,kI,sr,Xd,Gi,VA,BI,xI,xe,Ye,Yd,sm,om,OI,am,cm,dm,Bo,Zd,ce,an,Tt,xo,wt,Ce,qA,el,Oo,lm,um,gm,pm,tl,_I,W,C,jA,zA,mm,a,y,Ze,m,fm,et,J,Rt,LI,hm,X,rl,Oe,or,_o,de,nl,le,KA,Lo,Y,Z,_,Vi,D,ar,Dt,ee,e,cn,$I,Am,il,MI,FI,UI,QI,sl,HI,GI,VI,qI,jI,zI,KI,WI,JI,XI,YI,ZI,WA,JA,XA,YA,ZA,ey,ty,cr,ym,Sm,dr,qi,eb,Im,tb,rb,dn,nb,ib,sb,ob,ab,cb,ry,ny,iy,sy,oy,ji,db,$o,ay,bm,V,cy,tt,Mo,Pt,dy,Cm,ly,uy,gy,Em,q,lb,ub,gb,pb,py,mb,te,fb,hb,Ab,ol,al,my,vm,Tm,yb,Sb,Ib,bb,Cb,fy,cl,Eb,vb,Tb,wb,Rb,hy,Ay,Db,Pb,Nb,kb,Bb,xb,Ob,yy,_b,wm,dl,Lb,$b,Mb,Fb,Rm,Dm,Pm,Ub,ll,Sy,Iy,by,Cy,ul,Ey,Qb,Hb,Gb,Vb,qb,jb,zb,vy,Ty,wy,Ry,Nm,Kb,Wb,Jb,Xb,Yb,Zb,eC,tC,rC,Dy,Py,Ny,ky,nC,iC,km,sC,Bm,xm,Om,_m,oC,aC,cC,dC,_e,zi,lC,uC,gC,pC,mC,fC,hC,AC,By,yC,SC,Lm,$m,IC,bC,xy,CC,EC,vC,TC,wC,RC,DC,PC,NC,kC,BC,xC,OC,_C,LC,$C,MC,FC,UC,QC,HC,gl,Oy,pl,_y,ml,Ly,fl,$y,hl,My,lr,Fy,Al,Uy,Ki,Qy,yl,Hy,Sl,Gy,Mm,GC,Fm,VC,Il,Vy,ur,qy,Um,qC,bl,jy,Qm,jC,Hm,zC,Gm,KC,Cl,zy,Vm,WC,qm,JC,jm,XC,zm,YC,El,Ky,vl,Wy,Km,ZC,Wm,eE,Jm,tE,Xm,rE,Ym,nE,Zm,iE,Tl,Jy,ef,sE,tf,oE,rf,aE,nf,cE,sf,dE,of,lE,af,cf,df,lf,uf,uE,gf,gE,pf,pE,mf,mE,rt,ff,Xy,Fo,wl,ln,Yy,Wi,gr,Rl,Dl,Zy,eS,Pl,hf,Nl,Af,fE,hE,Uo,Qo,Ho,kl,un,Bl,xl,Ji,Go,Vo,yf,tS,rS,nS,AE,Sf,If,yE,iS,bf,sS,oS,aS,SE,Cf,gn,Ol,Ef,IE,cS,qo,jo,_l,vf,bE,Ll,dS,Tf,CE,wf,EE,Rf,vE};
|