@stacksjs/ts-cloud 0.16.74 → 0.16.75
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/aws/index.js +1 -1
- package/dist/bin/chunk-00j7xxxg.js +1 -0
- package/dist/bin/{chunk-10z6s9nj.js → chunk-06hwds44.js} +2 -2
- package/dist/bin/{chunk-xhe84hg1.js → chunk-0e7y7q0t.js} +1 -1
- package/dist/bin/{chunk-cs2a075v.js → chunk-0r8k7qth.js} +2 -2
- package/dist/bin/{chunk-jh4ajbt1.js → chunk-0v5q5sh0.js} +3 -3
- package/dist/bin/{chunk-fwcd0ef4.js → chunk-0zydd9s4.js} +3 -3
- package/dist/bin/chunk-1xfn93bc.js +1 -0
- package/dist/bin/{chunk-11xdxrp3.js → chunk-26vbw2m6.js} +70 -70
- package/dist/bin/{chunk-7v68hpgc.js → chunk-2h1q758c.js} +2 -2
- package/dist/bin/{chunk-bgjvxdds.js → chunk-33shhgye.js} +2 -2
- package/dist/bin/chunk-413nb697.js +1 -0
- package/dist/bin/{chunk-c99xvba1.js → chunk-4m2k5mvd.js} +4 -4
- package/dist/bin/{chunk-rg6r03q3.js → chunk-4vtyjj7c.js} +1 -1
- package/dist/bin/{chunk-9cj1fm00.js → chunk-540wkkhs.js} +3 -3
- package/dist/bin/{chunk-6wvgwn9q.js → chunk-6xx24qev.js} +1 -1
- package/dist/bin/chunk-72kpcqps.js +1 -0
- package/dist/bin/chunk-8esaawk6.js +1 -0
- package/dist/bin/chunk-8zc4kx6k.js +1 -0
- package/dist/bin/{chunk-whryzwb7.js → chunk-9ktyfegk.js} +1 -1
- package/dist/bin/chunk-9t6wztvn.js +1 -0
- package/dist/bin/{chunk-613m8vf9.js → chunk-b77qsk6r.js} +1 -1
- package/dist/bin/{chunk-ae9epvrr.js → chunk-by7dtwtj.js} +1 -1
- package/dist/bin/{chunk-6gspchrt.js → chunk-c1znyyca.js} +1 -1
- package/dist/bin/{chunk-9xs1fh7q.js → chunk-d73xkm0k.js} +1 -1
- package/dist/bin/{chunk-yjmydj1w.js → chunk-dmj5xv74.js} +1 -1
- package/dist/bin/chunk-dnswjyen.js +1 -0
- package/dist/bin/{chunk-bj94s3a7.js → chunk-e12679p1.js} +1 -1
- package/dist/bin/{chunk-zcq82zv1.js → chunk-eyzdhtp4.js} +3 -3
- package/dist/bin/{chunk-69j7md80.js → chunk-fhqjr3ba.js} +4 -4
- package/dist/bin/{chunk-eevqxagd.js → chunk-gndp57b6.js} +44 -44
- package/dist/bin/{chunk-648xb030.js → chunk-gq4htm3f.js} +2 -2
- package/dist/bin/{chunk-zph18vv6.js → chunk-gqstb8zn.js} +3 -3
- package/dist/bin/{chunk-7xd2tnjb.js → chunk-hhbmtgkq.js} +2 -2
- package/dist/bin/{chunk-8fspkmer.js → chunk-jcehsvnm.js} +10 -10
- package/dist/bin/chunk-k1bdndgj.js +1 -0
- package/dist/bin/{chunk-r5cpsqqk.js → chunk-k3cyh23p.js} +3 -3
- package/dist/bin/chunk-kkrp8100.js +1 -0
- package/dist/bin/{chunk-tvd5w8xq.js → chunk-kq526rgc.js} +1 -1
- package/dist/bin/{chunk-1g3gvxy2.js → chunk-ma0d990n.js} +2 -2
- package/dist/bin/{chunk-1n1s649d.js → chunk-nbffypj8.js} +1 -1
- package/dist/bin/chunk-nwcpck34.js +1 -0
- package/dist/bin/chunk-nzky7rgv.js +1 -0
- package/dist/bin/{chunk-qw5ch629.js → chunk-p35e4j11.js} +1 -1
- package/dist/bin/chunk-p96975b7.js +1 -0
- package/dist/bin/{chunk-sfv47z62.js → chunk-ps0pzqm0.js} +7 -7
- package/dist/bin/chunk-rgwwr6x2.js +1 -0
- package/dist/bin/{chunk-ekr2rzf6.js → chunk-s076q9sj.js} +2 -2
- package/dist/bin/chunk-sky689gw.js +1 -0
- package/dist/bin/{chunk-a8fqqd62.js → chunk-tf5tf414.js} +1 -1
- package/dist/bin/{chunk-47yznk07.js → chunk-th05q1gs.js} +1 -1
- package/dist/bin/chunk-tx56y5qk.js +1 -0
- package/dist/bin/{chunk-28a6yey5.js → chunk-v0fkhtgq.js} +1 -1
- package/dist/bin/chunk-v7dk21w9.js +1 -0
- package/dist/bin/{chunk-w244mfsx.js → chunk-vgcscxh1.js} +2 -2
- package/dist/bin/{chunk-gghy8mb4.js → chunk-wayhpmn7.js} +38 -38
- package/dist/bin/chunk-ww4r3r7x.js +1 -0
- package/dist/bin/{chunk-swbb39hj.js → chunk-y5gx3dq2.js} +1 -1
- package/dist/bin/chunk-y5hsmt17.js +1 -0
- package/dist/bin/{chunk-t6njpv8j.js → chunk-zfy6f6ph.js} +1 -1
- package/dist/bin/cli.js +82 -82
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/{chunk-fd6gsz34.js → chunk-0cgrk9g3.js} +2 -2
- package/dist/{chunk-zthcwfbg.js → chunk-4ccv5c4m.js} +1 -1
- package/dist/{chunk-207hnnpp.js → chunk-84z2a1xn.js} +3 -3
- package/dist/chunk-86qwnp25.js +1 -0
- package/dist/{chunk-1ktv8jxf.js → chunk-8k44kaz0.js} +2 -2
- package/dist/{chunk-tdhm38cg.js → chunk-9pwvnh3f.js} +2 -2
- package/dist/{chunk-mqr6s8wa.js → chunk-b6wsc7jp.js} +22 -22
- package/dist/{chunk-49rt1jbe.js → chunk-c8kf2268.js} +3 -3
- package/dist/chunk-crpbs450.js +1 -0
- package/dist/{chunk-dq9g7cg9.js → chunk-dvma06m5.js} +3 -3
- package/dist/{chunk-qcs3qkdf.js → chunk-etv0rcjd.js} +3 -3
- package/dist/chunk-f4fggc5f.js +1 -0
- package/dist/{chunk-ebb7j388.js → chunk-fdf181e6.js} +1 -1
- package/dist/chunk-fmhqz3eg.js +1 -0
- package/dist/{chunk-yqzc3a9m.js → chunk-fnc88v79.js} +89 -89
- package/dist/{chunk-c2hvf1h5.js → chunk-hg93a2g9.js} +1 -1
- package/dist/{chunk-k05g8vy5.js → chunk-jx1zz1pw.js} +1 -1
- package/dist/{chunk-z90dv6jx.js → chunk-m9szynnf.js} +3 -3
- package/dist/{chunk-s7gv665w.js → chunk-ne8btf6v.js} +86 -86
- package/dist/{chunk-ssywr12y.js → chunk-nftqsker.js} +1 -1
- package/dist/{chunk-2r334egt.js → chunk-nxj8pwa7.js} +2 -2
- package/dist/chunk-pev4cpbd.js +1 -0
- package/dist/{chunk-277enqjc.js → chunk-t7qgvz8z.js} +27 -27
- package/dist/{chunk-7qhcfnqf.js → chunk-tmp2ym80.js} +1 -1
- package/dist/{chunk-65fwpzeg.js → chunk-tp37gyhc.js} +5 -5
- package/dist/{chunk-8ynkxbj6.js → chunk-v6s9k1mp.js} +3 -3
- package/dist/{chunk-cfyn21gd.js → chunk-vq8bejep.js} +2 -2
- package/dist/{chunk-49raybtd.js → chunk-w8sctn7m.js} +7 -7
- package/dist/{chunk-ggqxjcbe.js → chunk-z56sccfh.js} +1 -1
- package/dist/{chunk-f4qv0c6w.js → chunk-z5c5amm1.js} +5 -5
- package/dist/deploy/index.js +1 -1
- package/dist/dns/index.js +1 -1
- package/dist/drivers/index.js +1 -1
- package/dist/drivers/shared/db-provision.d.ts +3 -3
- package/dist/index.js +10 -10
- 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 +6 -6
- package/dist/ui/data/volumes.html +6 -6
- package/dist/ui/index.html +5 -5
- package/dist/ui/infrastructure/topology.html +6 -6
- package/dist/ui/integrations.html +2 -2
- package/dist/ui/operations/alerts.html +6 -6
- package/dist/ui/operations/configuration.html +6 -6
- package/dist/ui/operations/jobs.html +6 -6
- package/dist/ui/operations/maintenance.html +5 -5
- package/dist/ui/operations/observability.html +6 -6
- package/dist/ui/operations/previews.html +6 -6
- package/dist/ui/operations/queue.html +6 -6
- package/dist/ui/operations/regions.html +5 -5
- package/dist/ui/operations/releases.html +6 -6
- package/dist/ui/operations/spend.html +6 -6
- package/dist/ui/operations/workloads.html +6 -6
- package/dist/ui/security.html +2 -2
- package/dist/ui/server/actions.html +6 -6
- package/dist/ui/server/activity.html +1 -1
- package/dist/ui/server/capacity.html +6 -6
- package/dist/ui/server/database.html +5 -5
- package/dist/ui/server/deployments.html +6 -6
- package/dist/ui/server/diagnostics.html +2 -2
- package/dist/ui/server/firewall.html +5 -5
- package/dist/ui/server/fleet.html +6 -6
- package/dist/ui/server/logs.html +6 -6
- package/dist/ui/server/metrics.html +6 -6
- package/dist/ui/server/security.html +1 -1
- package/dist/ui/server/services.html +1 -1
- package/dist/ui/server/sites.html +5 -5
- package/dist/ui/server/ssh-keys.html +5 -5
- package/dist/ui/server/team.html +5 -5
- package/dist/ui/server/terminal.html +2 -2
- package/dist/ui/serverless/alarms.html +5 -5
- package/dist/ui/serverless/assets.html +2 -2
- package/dist/ui/serverless/cost.html +2 -2
- package/dist/ui/serverless/data.html +5 -5
- package/dist/ui/serverless/deployments.html +1 -1
- package/dist/ui/serverless/firewall.html +1 -1
- package/dist/ui/serverless/functions.html +5 -5
- package/dist/ui/serverless/logs.html +6 -6
- package/dist/ui/serverless/metrics.html +2 -2
- package/dist/ui/serverless/queues.html +6 -6
- package/dist/ui/serverless/secrets.html +6 -6
- package/dist/ui/serverless/traces.html +6 -6
- package/dist/ui/serverless.html +5 -5
- package/package.json +3 -3
- package/dist/bin/chunk-0pptjpck.js +0 -1
- package/dist/bin/chunk-0sswdcvq.js +0 -1
- package/dist/bin/chunk-1pj60edk.js +0 -1
- package/dist/bin/chunk-1qcztara.js +0 -1
- package/dist/bin/chunk-6bnxvtvy.js +0 -1
- package/dist/bin/chunk-7x4vs33k.js +0 -1
- package/dist/bin/chunk-8bs3m2x7.js +0 -1
- package/dist/bin/chunk-8cxdvpzy.js +0 -1
- package/dist/bin/chunk-9twr514q.js +0 -1
- package/dist/bin/chunk-9zbfadg4.js +0 -1
- package/dist/bin/chunk-bgm9p3x6.js +0 -1
- package/dist/bin/chunk-cmraxfxd.js +0 -1
- package/dist/bin/chunk-cvet8kjp.js +0 -1
- package/dist/bin/chunk-d5n4d3pj.js +0 -1
- package/dist/bin/chunk-e6kfkaxc.js +0 -1
- package/dist/bin/chunk-f80asgbh.js +0 -1
- package/dist/bin/chunk-wkwcskhg.js +0 -1
- package/dist/bin/chunk-yqqx644v.js +0 -1
- package/dist/bin/chunk-ywpkvdfg.js +0 -1
- package/dist/chunk-c5pq3x7x.js +0 -1
- package/dist/chunk-fvad4wm8.js +0 -1
- package/dist/chunk-gc8r2gvd.js +0 -1
- package/dist/chunk-k0scshn2.js +0 -1
- package/dist/chunk-sacbxd79.js +0 -1
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import{Y,cs,_t,Nn}from"./chunk-bgjvxdds.js";import{rr,Gr}from"./chunk-7v68hpgc.js";var pl={};rr(pl,{default:()=>Dr,handler:()=>yt});var ml={};rr(ml,{default:()=>Nr,handler:()=>ft});var nd={};rr(nd,{EmailAnalyticsModule:()=>Je,EmailRules:()=>Ft,EmailScheduling:()=>$t,EmailSearch:()=>Lt,EmailTemplates:()=>Ce,EmailThreading:()=>Ot,SharedMailboxes:()=>Bt});var id={};rr(id,{default:()=>ms,handler:()=>ds});var od={};rr(od,{CallAnalytics:()=>Wt,CallRecording:()=>Gt,Callbacks:()=>it,IVRBuilder:()=>we});var sd={};rr(sd,{AbTesting:()=>me,LinkTracking:()=>Kt,MmsSupport:()=>Ht,SmsAnalytics:()=>Ut,SmsCampaigns:()=>Vt,SmsChatbot:()=>jt});var Tm={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}},Em={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 pt,join as Ye,relative as ur}from"node:path";var da=".ts-cloud",il="TS_CLOUD_STATE_DIR",gt=null;function ua(e){gt=e?.trim()||null}function pa(){return Boolean(process.env[il]?.trim()||gt)}function En(){return process.env[il]?.trim()||gt||da}function ze(...e){return Ye(En(),...e)}function I(e,...n){let r=En();return pt(r)?Ye(r,...n):Ye(e,r,...n)}function ma(e,n=process.cwd()){let r=(s,a)=>{let c=ur(s,a);return c===""||!c.startsWith("..")&&!pt(c)},i=pt(e)?e:Ye(n,e);return r(I(n),i)}function ol(e){let n=e.infrastructure?.compute!=null,r=Object.values(e.environments??{}).some((i)=>i?.app!=null);return{server:n,serverless:r}}function H(e){if(e.mode==="server"||e.mode==="serverless")return e.mode;let{serverless:n}=ol(e);return n?"serverless":"server"}function Fr(e){let{server:n,serverless:r}=ol(e);if(n&&r)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(e.mode==="server"&&r&&!n)return"Config sets `mode: 'server'` but declares a serverless app (`environments.<env>.app`). Remove the app or change the mode.";if(e.mode==="serverless"&&n&&!r)return"Config sets `mode: 'serverless'` but declares a server (`infrastructure.compute`). Remove the compute block or change the mode.";return null}function A(e){return e.infrastructure?.appDatabase??e.infrastructure?.compute?.database}function dr(e){return typeof e==="object"&&e!==null?e:{}}function ou(e){return e===!0||typeof e==="object"&&e!==null}function mr(e,n){let r=n?e.environments?.[n]:void 0;if(r?.domain)return r.domain;let i=Object.values(e.sites??{}),s=e.sites?.main?.domain??i.find((a)=>a.domain)?.domain;if(s)return s;return`${e.project?.slug??"app"}.local`}function pr(e){let n=e.indexOf(".");return n>0?e.slice(n+1):void 0}function ne(e,n={}){let r=e.infrastructure?.compute?.managedServices?.mail,i=dr(r),s=n.environmentType??(n.environment?e.environments?.[n.environment]?.type:void 0),a=i.mode??(s==="production"?"server":"catcher"),c=a==="server",u=mr(e,n.environment),d=i.hostname??(c?`mail.${u}`:"localhost"),m=i.ports??{},p=c?{smtp:m.smtp??25,submission:m.submission??587,submissions:m.submissions??465,imap:m.imap??143,imaps:m.imaps??993,webmail:m.webmail??8080,managesieve:m.managesieve}:{smtp:m.smtp??1025,submission:m.submission,submissions:m.submissions,imap:m.imap,imaps:m.imaps,webmail:m.webmail??8025,managesieve:m.managesieve},g=i.tls??{},y=g.enabled??c,f=!!(g.certPath&&g.keyPath),h=(i.accounts??[]).map((Q)=>({address:Q.address,password:Q.password,passwordPolicy:Q.passwordPolicy??"initial"})),S=typeof i.dkim==="object"&&i.dkim!==null?i.dkim:{},C=i.dkim===!1?!1:i.dkim===!0||c,P=typeof i.webmail==="object"&&i.webmail!==null?i.webmail:{},E=i.webmail===!1?!1:P.enabled??!0,v=d.includes(".")&&!d.endsWith(".local")&&!/^\d+\.\d+\.\d+\.\d+$/.test(d),w=P.domain===!1?void 0:P.domain??(c&&v?d:void 0),D=P.tls??(w?!1:y),x=[...new Set(P.aliases??[])].filter((Q)=>Q!==w),L=i.spam??{},B=i.delivery??(c?"direct":"none"),O=i.expose??c,F=pr(d),V=[...new Set([d,...F?[F]:[],...i.domains??[]])],ce=P.attachments?.maxFileBytes??20971520,q=P.attachments?.maxTotalBytes??20971520,J=P.attachments?.maxCount??20,K=P.undoSendSeconds??10;for(let[Q,ge,Te]of[["maxFileBytes",ce,104857600],["maxTotalBytes",q,104857600],["maxCount",J,100],["undoSendSeconds",K,30]])if(!Number.isInteger(ge)||ge<0||ge>Te)throw Error(`Mail webmail ${Q} must be an integer from 0 to ${Te}`);return{enabled:ou(r),mode:a,version:i.version,hostname:d,domains:V,ports:p,tls:{enabled:y,acme:y&&!f&&(g.acme??!0),certPath:g.certPath,keyPath:g.keyPath,requireForAuth:g.requireForAuth??(y&&c),acmeEmail:g.acmeEmail??h[0]?.address},dkim:{enabled:C,selector:S.selector??"default",rotate:S.rotate??!1,rotateIntervalDays:S.rotateIntervalDays??90},webmail:{enabled:E,port:P.port??p.webmail,domain:w,aliases:x,tls:D,secureCookies:P.secureCookies??(!!w||D),attachmentMaxFileBytes:ce,attachmentMaxTotalBytes:q,attachmentMaxCount:J,undoSendSeconds:K},delivery:B,sesRegion:i.sesRegion??"us-east-1",accounts:h,storagePath:i.storagePath??"/var/lib/mail",maxMessageSize:i.maxMessageSize??26214400,spam:{enabled:L.enabled??c,enforce:L.enforce??!1,junkScore:L.junkScore??5,rejectScore:L.rejectScore??12,dnsbl:L.dnsbl??c,dnsblReject:L.dnsblReject??!1,greylist:L.greylist??!1},webhookUrl:i.webhookUrl,expose:O,bindAddress:O?"0.0.0.0":"127.0.0.1"}}function jr(e){if(!e.enabled||!e.expose)return[];let n=[e.ports.smtp,e.ports.submission,e.ports.submissions,e.ports.imap,e.ports.imaps,e.ports.managesieve].filter((r)=>typeof r==="number");if(e.webmail.enabled&&!e.webmail.domain)n.push(e.webmail.port);return[...new Set(n)].sort((r,i)=>r-i)}function ga(e){if(!e.enabled)return{};let n=e.ports.submission??e.ports.smtp,r={MAIL_MAILER:"smtp",MAIL_HOST:"127.0.0.1",MAIL_PORT:String(n)};if(e.mode==="server"){r.MAIL_ENCRYPTION=e.tls.enabled?"tls":"null";let i=e.accounts[0];if(i)r.MAIL_USERNAME=i.address,r.MAIL_PASSWORD=i.password}else r.MAIL_ENCRYPTION="null",r.MAIL_USERNAME="null",r.MAIL_PASSWORD="null";return r}function Jo(e){if(!e.enabled||!e.webmail.enabled||!e.webmail.domain)return{};let n=[e.webmail.domain,...e.webmail.aliases];if(!Number.isInteger(e.webmail.port)||e.webmail.port<1||e.webmail.port>65535)throw Error("Mail webmail port must be between 1 and 65535");return Object.fromEntries(n.map((r,i)=>{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(r))throw Error(`Invalid mail webmail hostname: ${r}`);return[`__mail_webmail_${i}`,{domain:r,proxyTo:`localhost:${e.webmail.port}`}]}))}function le(e,n={}){let r=e.infrastructure?.compute?.proxy,i=ne(e,n);if(!i.enabled||!i.webmail.enabled||!i.webmail.domain)return r;return{engine:"rpx",onDemandTls:!0,onDemandTlsEmail:i.tls.acmeEmail??`webmaster@${i.webmail.domain}`,...r}}function U(e){if(e.cloud?.provider)return e.cloud.provider;if(e.ssh?.hosts?.length)return"ssh";if(e.hetzner?.apiToken)return"hetzner";return"aws"}class Xo{template;constructor(e){this.template={AWSTemplateFormatVersion:"2010-09-09",Description:e,Resources:{}}}addResource(e,n){return this.template.Resources[e]=n,this}addResources(e){return Object.assign(this.template.Resources,e),this}addParameter(e,n){if(!this.template.Parameters)this.template.Parameters={};return this.template.Parameters[e]=n,this}addOutput(e,n){if(!this.template.Outputs)this.template.Outputs={};return this.template.Outputs[e]=n,this}addMetadata(e,n){if(!this.template.Metadata)this.template.Metadata={};return this.template.Metadata[e]=n,this}hasResource(e){return e in this.template.Resources}getResources(){return this.template.Resources}build(){return this.template}toJSON(e=!0){return JSON.stringify(this.template,null,e?2:0)}toYAML(){return this.convertToYAML(this.template)}convertToYAML(e,n=0){let r=" ".repeat(n),i="";for(let[s,a]of Object.entries(e)){if(a===null||a===void 0)continue;if(typeof a==="object"&&!Array.isArray(a))i+=`${r}${s}:
|
|
1
|
+
import{Y,cs,Ot,xn}from"./chunk-33shhgye.js";import{nr,Gr}from"./chunk-2h1q758c.js";var pl={};nr(pl,{default:()=>Dr,handler:()=>yt});var ml={};nr(ml,{default:()=>Nr,handler:()=>ft});var nd={};nr(nd,{EmailAnalyticsModule:()=>Je,EmailRules:()=>Ft,EmailScheduling:()=>$t,EmailSearch:()=>Mt,EmailTemplates:()=>Ce,EmailThreading:()=>Lt,SharedMailboxes:()=>Bt});var id={};nr(id,{default:()=>ms,handler:()=>ds});var od={};nr(od,{CallAnalytics:()=>Wt,CallRecording:()=>Gt,Callbacks:()=>it,IVRBuilder:()=>we});var sd={};nr(sd,{AbTesting:()=>me,LinkTracking:()=>Kt,MmsSupport:()=>Ht,SmsAnalytics:()=>Ut,SmsCampaigns:()=>Vt,SmsChatbot:()=>jt});var Tm={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}},Em={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 pt,join as Ye,relative as ur}from"node:path";var da=".ts-cloud",il="TS_CLOUD_STATE_DIR",gt=null;function ua(e){gt=e?.trim()||null}function pa(){return Boolean(process.env[il]?.trim()||gt)}function wn(){return process.env[il]?.trim()||gt||da}function ze(...e){return Ye(wn(),...e)}function I(e,...n){let r=wn();return pt(r)?Ye(r,...n):Ye(e,r,...n)}function ma(e,n=process.cwd()){let r=(s,a)=>{let c=ur(s,a);return c===""||!c.startsWith("..")&&!pt(c)},i=pt(e)?e:Ye(n,e);return r(I(n),i)}function ol(e){let n=e.infrastructure?.compute!=null,r=Object.values(e.environments??{}).some((i)=>i?.app!=null);return{server:n,serverless:r}}function H(e){if(e.mode==="server"||e.mode==="serverless")return e.mode;let{serverless:n}=ol(e);return n?"serverless":"server"}function Fr(e){let{server:n,serverless:r}=ol(e);if(n&&r)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(e.mode==="server"&&r&&!n)return"Config sets `mode: 'server'` but declares a serverless app (`environments.<env>.app`). Remove the app or change the mode.";if(e.mode==="serverless"&&n&&!r)return"Config sets `mode: 'serverless'` but declares a server (`infrastructure.compute`). Remove the compute block or change the mode.";return null}function A(e){return e.infrastructure?.appDatabase??e.infrastructure?.compute?.database}function dr(e){return typeof e==="object"&&e!==null?e:{}}function ou(e){return e===!0||typeof e==="object"&&e!==null}function mr(e,n){let r=n?e.environments?.[n]:void 0;if(r?.domain)return r.domain;let i=Object.values(e.sites??{}),s=e.sites?.main?.domain??i.find((a)=>a.domain)?.domain;if(s)return s;return`${e.project?.slug??"app"}.local`}function pr(e){let n=e.indexOf(".");return n>0?e.slice(n+1):void 0}function ne(e,n={}){let r=e.infrastructure?.compute?.managedServices?.mail,i=dr(r),s=n.environmentType??(n.environment?e.environments?.[n.environment]?.type:void 0),a=i.mode??(s==="production"?"server":"catcher"),c=a==="server",u=mr(e,n.environment),d=i.hostname??(c?`mail.${u}`:"localhost"),m=i.ports??{},p=c?{smtp:m.smtp??25,submission:m.submission??587,submissions:m.submissions??465,imap:m.imap??143,imaps:m.imaps??993,webmail:m.webmail??8080,managesieve:m.managesieve}:{smtp:m.smtp??1025,submission:m.submission,submissions:m.submissions,imap:m.imap,imaps:m.imaps,webmail:m.webmail??8025,managesieve:m.managesieve},g=i.tls??{},y=g.enabled??c,f=!!(g.certPath&&g.keyPath),h=(i.accounts??[]).map((Q)=>({address:Q.address,password:Q.password,passwordPolicy:Q.passwordPolicy??"initial"})),S=typeof i.dkim==="object"&&i.dkim!==null?i.dkim:{},C=i.dkim===!1?!1:i.dkim===!0||c,P=typeof i.webmail==="object"&&i.webmail!==null?i.webmail:{},E=i.webmail===!1?!1:P.enabled??!0,v=d.includes(".")&&!d.endsWith(".local")&&!/^\d+\.\d+\.\d+\.\d+$/.test(d),w=P.domain===!1?void 0:P.domain??(c&&v?d:void 0),D=P.tls??(w?!1:y),x=[...new Set(P.aliases??[])].filter((Q)=>Q!==w),L=i.spam??{},B=i.delivery??(c?"direct":"none"),O=i.expose??c,F=pr(d),V=[...new Set([d,...F?[F]:[],...i.domains??[]])],ce=P.attachments?.maxFileBytes??20971520,q=P.attachments?.maxTotalBytes??20971520,J=P.attachments?.maxCount??20,K=P.undoSendSeconds??10;for(let[Q,ge,Te]of[["maxFileBytes",ce,104857600],["maxTotalBytes",q,104857600],["maxCount",J,100],["undoSendSeconds",K,30]])if(!Number.isInteger(ge)||ge<0||ge>Te)throw Error(`Mail webmail ${Q} must be an integer from 0 to ${Te}`);return{enabled:ou(r),mode:a,version:i.version,hostname:d,domains:V,ports:p,tls:{enabled:y,acme:y&&!f&&(g.acme??!0),certPath:g.certPath,keyPath:g.keyPath,requireForAuth:g.requireForAuth??(y&&c),acmeEmail:g.acmeEmail??h[0]?.address},dkim:{enabled:C,selector:S.selector??"default",rotate:S.rotate??!1,rotateIntervalDays:S.rotateIntervalDays??90},webmail:{enabled:E,port:P.port??p.webmail,domain:w,aliases:x,tls:D,secureCookies:P.secureCookies??(!!w||D),attachmentMaxFileBytes:ce,attachmentMaxTotalBytes:q,attachmentMaxCount:J,undoSendSeconds:K},delivery:B,sesRegion:i.sesRegion??"us-east-1",accounts:h,storagePath:i.storagePath??"/var/lib/mail",maxMessageSize:i.maxMessageSize??26214400,spam:{enabled:L.enabled??c,enforce:L.enforce??!1,junkScore:L.junkScore??5,rejectScore:L.rejectScore??12,dnsbl:L.dnsbl??c,dnsblReject:L.dnsblReject??!1,greylist:L.greylist??!1},webhookUrl:i.webhookUrl,expose:O,bindAddress:O?"0.0.0.0":"127.0.0.1"}}function jr(e){if(!e.enabled||!e.expose)return[];let n=[e.ports.smtp,e.ports.submission,e.ports.submissions,e.ports.imap,e.ports.imaps,e.ports.managesieve].filter((r)=>typeof r==="number");if(e.webmail.enabled&&!e.webmail.domain)n.push(e.webmail.port);return[...new Set(n)].sort((r,i)=>r-i)}function ga(e){if(!e.enabled)return{};let n=e.ports.submission??e.ports.smtp,r={MAIL_MAILER:"smtp",MAIL_HOST:"127.0.0.1",MAIL_PORT:String(n)};if(e.mode==="server"){r.MAIL_ENCRYPTION=e.tls.enabled?"tls":"null";let i=e.accounts[0];if(i)r.MAIL_USERNAME=i.address,r.MAIL_PASSWORD=i.password}else r.MAIL_ENCRYPTION="null",r.MAIL_USERNAME="null",r.MAIL_PASSWORD="null";return r}function Jo(e){if(!e.enabled||!e.webmail.enabled||!e.webmail.domain)return{};let n=[e.webmail.domain,...e.webmail.aliases];if(!Number.isInteger(e.webmail.port)||e.webmail.port<1||e.webmail.port>65535)throw Error("Mail webmail port must be between 1 and 65535");return Object.fromEntries(n.map((r,i)=>{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(r))throw Error(`Invalid mail webmail hostname: ${r}`);return[`__mail_webmail_${i}`,{domain:r,proxyTo:`localhost:${e.webmail.port}`}]}))}function le(e,n={}){let r=e.infrastructure?.compute?.proxy,i=ne(e,n);if(!i.enabled||!i.webmail.enabled||!i.webmail.domain)return r;return{engine:"rpx",onDemandTls:!0,onDemandTlsEmail:i.tls.acmeEmail??`webmaster@${i.webmail.domain}`,...r}}function U(e){if(e.cloud?.provider)return e.cloud.provider;if(e.ssh?.hosts?.length)return"ssh";if(e.hetzner?.apiToken)return"hetzner";return"aws"}class Xo{template;constructor(e){this.template={AWSTemplateFormatVersion:"2010-09-09",Description:e,Resources:{}}}addResource(e,n){return this.template.Resources[e]=n,this}addResources(e){return Object.assign(this.template.Resources,e),this}addParameter(e,n){if(!this.template.Parameters)this.template.Parameters={};return this.template.Parameters[e]=n,this}addOutput(e,n){if(!this.template.Outputs)this.template.Outputs={};return this.template.Outputs[e]=n,this}addMetadata(e,n){if(!this.template.Metadata)this.template.Metadata={};return this.template.Metadata[e]=n,this}hasResource(e){return e in this.template.Resources}getResources(){return this.template.Resources}build(){return this.template}toJSON(e=!0){return JSON.stringify(this.template,null,e?2:0)}toYAML(){return this.convertToYAML(this.template)}convertToYAML(e,n=0){let r=" ".repeat(n),i="";for(let[s,a]of Object.entries(e)){if(a===null||a===void 0)continue;if(typeof a==="object"&&!Array.isArray(a))i+=`${r}${s}:
|
|
2
2
|
${this.convertToYAML(a,n+1)}`;else if(Array.isArray(a)){i+=`${r}${s}:
|
|
3
3
|
`;for(let c of a)if(typeof c==="object")i+=`${r} -
|
|
4
4
|
${this.convertToYAML(c,n+2)}`;else i+=`${r} - ${c}
|
|
5
5
|
`}else i+=`${r}${s}: ${a}
|
|
6
|
-
`}return i}}function su(e){let n=[],r=[],i=[];if(gr(e,n),e.Resources)yr(e.Resources,n,r);else n.push({path:"Resources",message:"Template must contain at least one resource",severity:"error"});if(e.Parameters)fr(e.Parameters,n,r);if(e.Outputs)hr(e.Outputs,n);br(e,n);let s=Sr(e);if(s.length>0)for(let a of s)n.push({path:"Resources",message:`Circular dependency detected: ${a.join(" → ")}`,severity:"error"});return Cr(e,r,i),{valid:n.length===0,errors:n,warnings:r,info:i}}function gr(e,n){if(!e.AWSTemplateFormatVersion)n.push({path:"AWSTemplateFormatVersion",message:"Template should specify AWSTemplateFormatVersion",severity:"error"});else if(e.AWSTemplateFormatVersion!=="2010-09-09")n.push({path:"AWSTemplateFormatVersion",message:'AWSTemplateFormatVersion must be "2010-09-09"',severity:"error"})}function yr(e,n,r){let i=Object.keys(e);if(i.length===0){n.push({path:"Resources",message:"Template must contain at least one resource",severity:"error"});return}if(i.length>500)r.push({path:"Resources",message:`Template contains ${i.length} resources (limit is 500)`,severity:"warning"});for(let s of i){let a=e[s];if(!/^[a-zA-Z0-9]+$/.test(s))n.push({path:`Resources.${s}`,message:"Logical ID must contain only alphanumeric characters",severity:"error"});if(!a.Type)n.push({path:`Resources.${s}.Type`,message:"Resource Type is required",severity:"error"});else if(!a.Type.startsWith("AWS::")&&!a.Type.startsWith("Custom::"))n.push({path:`Resources.${s}.Type`,message:'Resource Type must start with "AWS::" or "Custom::"',severity:"error"});if(a.DeletionPolicy&&!["Delete","Retain","Snapshot"].includes(a.DeletionPolicy))n.push({path:`Resources.${s}.DeletionPolicy`,message:'DeletionPolicy must be "Delete", "Retain", or "Snapshot"',severity:"error"});if(!a.DeletionPolicy&&tn(a.Type))r.push({path:`Resources.${s}.DeletionPolicy`,message:`${a.Type} should specify DeletionPolicy to prevent accidental data loss`,severity:"warning"})}}function fr(e,n,r){let i=Object.keys(e);if(i.length>200)r.push({path:"Parameters",message:`Template contains ${i.length} parameters (limit is 200)`,severity:"warning"});for(let s of i){let a=e[s];if(!a.Type)n.push({path:`Parameters.${s}.Type`,message:"Parameter Type is required",severity:"error"});let c=["String","Number","List<Number>","CommaDelimitedList","AWS::EC2::AvailabilityZone::Name","AWS::EC2::Image::Id","AWS::EC2::Instance::Id","AWS::EC2::KeyPair::KeyName","AWS::EC2::SecurityGroup::GroupName","AWS::EC2::SecurityGroup::Id","AWS::EC2::Subnet::Id","AWS::EC2::Volume::Id","AWS::EC2::VPC::Id","AWS::Route53::HostedZone::Id","List<AWS::EC2::AvailabilityZone::Name>","List<AWS::EC2::Image::Id>","List<AWS::EC2::Instance::Id>","List<AWS::EC2::SecurityGroup::GroupName>","List<AWS::EC2::SecurityGroup::Id>","List<AWS::EC2::Subnet::Id>","List<AWS::EC2::Volume::Id>","List<AWS::EC2::VPC::Id>","List<AWS::Route53::HostedZone::Id>","AWS::SSM::Parameter::Name","AWS::SSM::Parameter::Value<String>","AWS::SSM::Parameter::Value<List<String>>","AWS::SSM::Parameter::Value<CommaDelimitedList>"];if(a.Type&&!c.includes(a.Type))n.push({path:`Parameters.${s}.Type`,message:`Invalid parameter type: ${a.Type}`,severity:"error"})}}function hr(e,n){let r=Object.keys(e);for(let i of r)if(!e[i].Value)n.push({path:`Outputs.${i}.Value`,message:"Output Value is required",severity:"error"})}function br(e,n){let r=e.Resources||{},i=e.Parameters||{},s=new Set(Object.keys(r)),a=new Set(Object.keys(i));function c(u,d){if(typeof u!=="object"||u===null)return;if(u.Ref){let m=u.Ref;if(!s.has(m)&&!a.has(m)&&m!=="AWS::Region"&&m!=="AWS::AccountId"&&m!=="AWS::StackName"&&m!=="AWS::StackId"&&m!=="AWS::URLSuffix"&&m!=="AWS::Partition"&&m!=="AWS::NoValue")n.push({path:d,message:`Reference to non-existent resource or parameter: ${m}`,severity:"error"})}if(u["Fn::GetAtt"]){let m=u["Fn::GetAtt"];if(Array.isArray(m)&&m.length>=1){let p=m[0];if(!s.has(p))n.push({path:d,message:`GetAtt references non-existent resource: ${p}`,severity:"error"})}}for(let m in u)c(u[m],`${d}.${m}`)}for(let u in r)c(r[u],`Resources.${u}`);if(e.Outputs)for(let u in e.Outputs)c(e.Outputs[u],`Outputs.${u}`)}function Sr(e){let n=e.Resources||{},r=new Map;for(let u in n){let d=new Set,m=n[u];if(m.DependsOn)if(Array.isArray(m.DependsOn))m.DependsOn.forEach((g)=>d.add(g));else d.add(m.DependsOn);Ar(m).forEach((g)=>d.add(g)),r.set(u,d)}let i=[],s=new Set,a=new Set;function c(u,d){s.add(u),a.add(u),d.push(u);let m=r.get(u)||new Set;for(let p of m)if(!s.has(p))c(p,[...d]);else if(a.has(p)){let g=d.indexOf(p),y=[...d.slice(g),p];i.push(y)}a.delete(u)}for(let u of r.keys())if(!s.has(u))c(u,[]);return i}function Ar(e){let n=new Set;function r(i){if(typeof i!=="object"||i===null)return;if(i.Ref&&typeof i.Ref==="string"){if(!i.Ref.startsWith("AWS::"))n.add(i.Ref)}if(i["Fn::GetAtt"]&&Array.isArray(i["Fn::GetAtt"]))n.add(i["Fn::GetAtt"][0]);for(let s in i)r(i[s])}return r(e),n}function tn(e){return["AWS::S3::Bucket","AWS::DynamoDB::Table","AWS::RDS::DBInstance","AWS::RDS::DBCluster","AWS::ElastiCache::CacheCluster","AWS::ElastiCache::ReplicationGroup","AWS::EFS::FileSystem","AWS::OpenSearchService::Domain"].includes(e)}function Cr(e,n,r){let i=e.Resources||{};if(!e.Description)r.push({path:"Description",message:"Consider adding a Description to the template",severity:"info"});for(let s in i){let a=i[s],c=a.Properties;if(c&&!c.Tags&&vr(a.Type))r.push({path:`Resources.${s}`,message:`Consider adding Tags to ${a.Type}`,severity:"info"});if(tn(a.Type)){if(a.Type==="AWS::S3::Bucket"&&!c?.BucketEncryption)n.push({path:`Resources.${s}`,message:"S3 bucket should enable encryption",severity:"warning"});if(a.Type==="AWS::RDS::DBInstance"&&!c?.StorageEncrypted)n.push({path:`Resources.${s}`,message:"RDS instance should enable storage encryption",severity:"warning"})}}}function vr(e){return!["AWS::CloudFormation::Stack","AWS::CloudFormation::WaitCondition","AWS::CloudFormation::WaitConditionHandle"].includes(e)}function au(e){let n=[],r=[],i=[],s=Buffer.byteLength(e,"utf8"),a=s/1024,c=51200,u=460800;if(s>460800)n.push({path:"Template",message:`Template size (${a.toFixed(2)} KB) exceeds maximum size of 450 KB`,severity:"error"});else if(s>51200)r.push({path:"Template",message:`Template size (${a.toFixed(2)} KB) exceeds 50 KB. Must use S3 for deployment.`,severity:"warning"});return{valid:n.length===0,errors:n,warnings:r,info:i}}function cu(e){let n=[],r=[],i=[],s=e.Resources||{},a=e.Parameters||{},c=e.Outputs||{};if(Object.keys(s).length>500)n.push({path:"Resources",message:`Template has ${Object.keys(s).length} resources (limit is 500)`,severity:"error"});if(Object.keys(a).length>200)n.push({path:"Parameters",message:`Template has ${Object.keys(a).length} parameters (limit is 200)`,severity:"error"});if(Object.keys(c).length>200)n.push({path:"Outputs",message:`Template has ${Object.keys(c).length} outputs (limit is 200)`,severity:"error"});return{valid:n.length===0,errors:n,warnings:r,info:i}}var R={Ref:(e)=>({Ref:e}),GetAtt:(e,n)=>({"Fn::GetAtt":[e,n]}),Sub:(e,n)=>{if(n)return{"Fn::Sub":[e,n]};return{"Fn::Sub":e}},Join:(e,n)=>({"Fn::Join":[e,n]}),Select:(e,n)=>({"Fn::Select":[e,n]}),Split:(e,n)=>({"Fn::Split":[e,n]}),GetAZs:(e="")=>({"Fn::GetAZs":e}),ImportValue:(e)=>({"Fn::ImportValue":e}),If:(e,n,r)=>({"Fn::If":[e,n,r]}),Equals:(e,n)=>({"Fn::Equals":[e,n]}),And:(...e)=>({"Fn::And":e}),Or:(...e)=>({"Fn::Or":e}),Not:(e)=>({"Fn::Not":[e]}),Base64:(e)=>({"Fn::Base64":e})},lu={AccountId:{Ref:"AWS::AccountId"},Region:{Ref:"AWS::Region"},StackId:{Ref:"AWS::StackId"},StackName:{Ref:"AWS::StackName"},NotificationARNs:{Ref:"AWS::NotificationARNs"},Partition:{Ref:"AWS::Partition"},URLSuffix:{Ref:"AWS::URLSuffix"},NoValue:{Ref:"AWS::NoValue"}};function l(e){let{slug:n,environment:r,resourceType:i,timestamp:s,suffix:a}=e,c=[n,r,i];if(s)c.push(s);if(a)c.push(a);return c.join("-")}function o(e){return e.split("-").map((n)=>n.charAt(0).toUpperCase()+n.slice(1)).join("")}function wm(){return Date.now().toString()}function Am(e){return e.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/^-+|-+$/g,"").replace(/-+/g,"-")}function T(e,n){return e.project.stackName??`${e.project.slug}-${n}`}function fa(e,n,r,i){return r.stackName??`${e.project.slug}-${i}-${n}-site`}function ha(e,n){return`${e.project.slug}-${n}`}function ya(e,n,r,i){if(i)return i;if(r==="main")return`${e}-${n}-site`;return`${e}-${n}-${r}`}function Rm(e,n,r,i){return i??`${e}-${n}-${r}`}function Im(e,n){return`${e}-${n}-deploy`}function $e(e,n){return`${e.project.slug}-${n}-app`}function ba(e,n){return`${e}-${n}-deployments`}function Bi(e,n){return`${e}-${n}-assets`}class du{nodes=new Map;addResource(e,n){let r=this.extractDependencies(n);this.nodes.set(e,{logicalId:e,resource:n,dependencies:r})}extractDependencies(e){let n=new Set;if(e.DependsOn)if(Array.isArray(e.DependsOn))e.DependsOn.forEach((r)=>n.add(r));else n.add(e.DependsOn);return this.findReferences(e.Properties||{},n),n}findReferences(e,n){if(!e||typeof e!=="object")return;if("Ref"in e&&typeof e.Ref==="string"){if(!e.Ref.startsWith("AWS::"))n.add(e.Ref)}if("Fn::GetAtt"in e&&Array.isArray(e["Fn::GetAtt"]))n.add(e["Fn::GetAtt"][0]);for(let r of Object.values(e))if(typeof r==="object")this.findReferences(r,n)}topologicalSort(){let e=[],n=new Set,r=new Set,i=(s)=>{if(n.has(s))return;if(r.has(s))throw Error(`Circular dependency detected: ${s}`);r.add(s);let a=this.nodes.get(s);if(a)for(let c of a.dependencies)i(c);r.delete(s),n.add(s),e.push(s)};for(let s of this.nodes.keys())i(s);return e}validate(){for(let[e,n]of this.nodes.entries())for(let r of n.dependencies)if(!this.nodes.has(r))throw Error(`Resource "${e}" depends on "${r}" which does not exist`)}getDependents(e){let n=[];for(let[r,i]of this.nodes.entries())if(i.dependencies.has(e))n.push(r);return n}}function Pm(e,n){let r=[],i=[],s=[],a=[],c=[],u=e.Resources||{},d=n.Resources||{},m=new Set([...Object.keys(u),...Object.keys(d)]);for(let g of m){let y=u[g],f=d[g];if(!y&&f)r.push({logicalId:g,action:"add",resourceType:f.Type});else if(y&&!f)i.push({logicalId:g,action:"remove",resourceType:y.Type});else if(y&&f)if(y.Type!==f.Type)a.push({logicalId:g,action:"replace",resourceType:f.Type,reason:`Type changed from ${y.Type} to ${f.Type}`});else{let h=nn(y.Properties||{},f.Properties||{});if(h.length>0)if(Tr(y.Type,h))a.push({logicalId:g,action:"replace",resourceType:f.Type,changes:h,reason:"Property changes require replacement"});else s.push({logicalId:g,action:"update",resourceType:f.Type,changes:h});else c.push(g)}}let p=Rr([...i,...a,...s]);return{added:r,removed:i,updated:s,replaced:a,unchanged:c,summary:{totalChanges:r.length+i.length+s.length+a.length,requiresReplacement:a.length>0,dangerousChanges:p}}}function nn(e,n,r=""){let i=[],s=new Set([...Object.keys(e),...Object.keys(n)]);for(let a of s){let c=r?`${r}.${a}`:a,u=e[a],d=n[a];if(u===void 0&&d!==void 0)i.push({path:c,oldValue:void 0,newValue:d});else if(u!==void 0&&d===void 0)i.push({path:c,oldValue:u,newValue:void 0});else if(typeof u!==typeof d)i.push({path:c,oldValue:u,newValue:d});else if(typeof u==="object"&&u!==null)if(Array.isArray(u)&&Array.isArray(d)){if(JSON.stringify(u)!==JSON.stringify(d))i.push({path:c,oldValue:u,newValue:d})}else if(!Array.isArray(u)&&!Array.isArray(d)){let m=nn(u,d,c);i.push(...m)}else i.push({path:c,oldValue:u,newValue:d});else if(u!==d)i.push({path:c,oldValue:u,newValue:d})}return i}function Tr(e,n){let i={"AWS::S3::Bucket":new Set(["BucketName"]),"AWS::DynamoDB::Table":new Set(["TableName","KeySchema"]),"AWS::RDS::DBInstance":new Set(["DBInstanceIdentifier","DBName","Engine"]),"AWS::Lambda::Function":new Set(["FunctionName"]),"AWS::EC2::Instance":new Set(["ImageId","InstanceType","KeyName"]),"AWS::ECS::TaskDefinition":new Set(["Family","ContainerDefinitions"]),"AWS::ElastiCache::CacheCluster":new Set(["CacheNodeType","Engine"]),"AWS::CloudFront::Distribution":new Set([]),"AWS::Route53::HostedZone":new Set(["Name"]),"AWS::IAM::Role":new Set(["RoleName","Path"]),"AWS::KMS::Key":new Set(["KeyPolicy"]),"AWS::Cognito::UserPool":new Set(["UserPoolName"]),"AWS::OpenSearchService::Domain":new Set(["DomainName"])}[e];if(!i)return!1;for(let s of n){let a=s.path.split(".")[0];if(i.has(a))return!0}return!1}function Rr(e){let n=[];for(let r of e){if(r.action==="remove"&&(r.resourceType==="AWS::RDS::DBInstance"||r.resourceType==="AWS::DynamoDB::Table"||r.resourceType==="AWS::ElastiCache::CacheCluster"))n.push(`Removing ${r.resourceType} ${r.logicalId} - data loss risk!`);if(r.action==="replace"&&(r.resourceType==="AWS::RDS::DBInstance"||r.resourceType==="AWS::DynamoDB::Table"))n.push(`Replacing ${r.resourceType} ${r.logicalId} - data loss risk!`);if((r.action==="remove"||r.action==="replace")&&r.resourceType==="AWS::S3::Bucket")n.push(`${r.action==="remove"?"Removing":"Replacing"} S3 bucket ${r.logicalId} - data loss risk!`);if(r.action==="replace"&&r.resourceType==="AWS::EC2::Instance")n.push(`Replacing EC2 instance ${r.logicalId} - downtime expected`);if(r.action==="update"&&r.resourceType==="AWS::EC2::SecurityGroup")n.push(`Updating security group ${r.logicalId} - may affect connectivity`);if((r.action==="update"||r.action==="replace")&&(r.resourceType==="AWS::IAM::Role"||r.resourceType==="AWS::IAM::Policy"))n.push(`Modifying IAM ${r.resourceType.split("::")[2]} ${r.logicalId} - may affect permissions`)}return n}function Dm(e){let n=[];if(n.push(`=== Stack Update Analysis ===
|
|
6
|
+
`}return i}}function su(e){let n=[],r=[],i=[];if(gr(e,n),e.Resources)yr(e.Resources,n,r);else n.push({path:"Resources",message:"Template must contain at least one resource",severity:"error"});if(e.Parameters)fr(e.Parameters,n,r);if(e.Outputs)hr(e.Outputs,n);br(e,n);let s=Sr(e);if(s.length>0)for(let a of s)n.push({path:"Resources",message:`Circular dependency detected: ${a.join(" → ")}`,severity:"error"});return Cr(e,r,i),{valid:n.length===0,errors:n,warnings:r,info:i}}function gr(e,n){if(!e.AWSTemplateFormatVersion)n.push({path:"AWSTemplateFormatVersion",message:"Template should specify AWSTemplateFormatVersion",severity:"error"});else if(e.AWSTemplateFormatVersion!=="2010-09-09")n.push({path:"AWSTemplateFormatVersion",message:'AWSTemplateFormatVersion must be "2010-09-09"',severity:"error"})}function yr(e,n,r){let i=Object.keys(e);if(i.length===0){n.push({path:"Resources",message:"Template must contain at least one resource",severity:"error"});return}if(i.length>500)r.push({path:"Resources",message:`Template contains ${i.length} resources (limit is 500)`,severity:"warning"});for(let s of i){let a=e[s];if(!/^[a-zA-Z0-9]+$/.test(s))n.push({path:`Resources.${s}`,message:"Logical ID must contain only alphanumeric characters",severity:"error"});if(!a.Type)n.push({path:`Resources.${s}.Type`,message:"Resource Type is required",severity:"error"});else if(!a.Type.startsWith("AWS::")&&!a.Type.startsWith("Custom::"))n.push({path:`Resources.${s}.Type`,message:'Resource Type must start with "AWS::" or "Custom::"',severity:"error"});if(a.DeletionPolicy&&!["Delete","Retain","Snapshot"].includes(a.DeletionPolicy))n.push({path:`Resources.${s}.DeletionPolicy`,message:'DeletionPolicy must be "Delete", "Retain", or "Snapshot"',severity:"error"});if(!a.DeletionPolicy&&en(a.Type))r.push({path:`Resources.${s}.DeletionPolicy`,message:`${a.Type} should specify DeletionPolicy to prevent accidental data loss`,severity:"warning"})}}function fr(e,n,r){let i=Object.keys(e);if(i.length>200)r.push({path:"Parameters",message:`Template contains ${i.length} parameters (limit is 200)`,severity:"warning"});for(let s of i){let a=e[s];if(!a.Type)n.push({path:`Parameters.${s}.Type`,message:"Parameter Type is required",severity:"error"});let c=["String","Number","List<Number>","CommaDelimitedList","AWS::EC2::AvailabilityZone::Name","AWS::EC2::Image::Id","AWS::EC2::Instance::Id","AWS::EC2::KeyPair::KeyName","AWS::EC2::SecurityGroup::GroupName","AWS::EC2::SecurityGroup::Id","AWS::EC2::Subnet::Id","AWS::EC2::Volume::Id","AWS::EC2::VPC::Id","AWS::Route53::HostedZone::Id","List<AWS::EC2::AvailabilityZone::Name>","List<AWS::EC2::Image::Id>","List<AWS::EC2::Instance::Id>","List<AWS::EC2::SecurityGroup::GroupName>","List<AWS::EC2::SecurityGroup::Id>","List<AWS::EC2::Subnet::Id>","List<AWS::EC2::Volume::Id>","List<AWS::EC2::VPC::Id>","List<AWS::Route53::HostedZone::Id>","AWS::SSM::Parameter::Name","AWS::SSM::Parameter::Value<String>","AWS::SSM::Parameter::Value<List<String>>","AWS::SSM::Parameter::Value<CommaDelimitedList>"];if(a.Type&&!c.includes(a.Type))n.push({path:`Parameters.${s}.Type`,message:`Invalid parameter type: ${a.Type}`,severity:"error"})}}function hr(e,n){let r=Object.keys(e);for(let i of r)if(!e[i].Value)n.push({path:`Outputs.${i}.Value`,message:"Output Value is required",severity:"error"})}function br(e,n){let r=e.Resources||{},i=e.Parameters||{},s=new Set(Object.keys(r)),a=new Set(Object.keys(i));function c(u,d){if(typeof u!=="object"||u===null)return;if(u.Ref){let m=u.Ref;if(!s.has(m)&&!a.has(m)&&m!=="AWS::Region"&&m!=="AWS::AccountId"&&m!=="AWS::StackName"&&m!=="AWS::StackId"&&m!=="AWS::URLSuffix"&&m!=="AWS::Partition"&&m!=="AWS::NoValue")n.push({path:d,message:`Reference to non-existent resource or parameter: ${m}`,severity:"error"})}if(u["Fn::GetAtt"]){let m=u["Fn::GetAtt"];if(Array.isArray(m)&&m.length>=1){let p=m[0];if(!s.has(p))n.push({path:d,message:`GetAtt references non-existent resource: ${p}`,severity:"error"})}}for(let m in u)c(u[m],`${d}.${m}`)}for(let u in r)c(r[u],`Resources.${u}`);if(e.Outputs)for(let u in e.Outputs)c(e.Outputs[u],`Outputs.${u}`)}function Sr(e){let n=e.Resources||{},r=new Map;for(let u in n){let d=new Set,m=n[u];if(m.DependsOn)if(Array.isArray(m.DependsOn))m.DependsOn.forEach((g)=>d.add(g));else d.add(m.DependsOn);Ar(m).forEach((g)=>d.add(g)),r.set(u,d)}let i=[],s=new Set,a=new Set;function c(u,d){s.add(u),a.add(u),d.push(u);let m=r.get(u)||new Set;for(let p of m)if(!s.has(p))c(p,[...d]);else if(a.has(p)){let g=d.indexOf(p),y=[...d.slice(g),p];i.push(y)}a.delete(u)}for(let u of r.keys())if(!s.has(u))c(u,[]);return i}function Ar(e){let n=new Set;function r(i){if(typeof i!=="object"||i===null)return;if(i.Ref&&typeof i.Ref==="string"){if(!i.Ref.startsWith("AWS::"))n.add(i.Ref)}if(i["Fn::GetAtt"]&&Array.isArray(i["Fn::GetAtt"]))n.add(i["Fn::GetAtt"][0]);for(let s in i)r(i[s])}return r(e),n}function en(e){return["AWS::S3::Bucket","AWS::DynamoDB::Table","AWS::RDS::DBInstance","AWS::RDS::DBCluster","AWS::ElastiCache::CacheCluster","AWS::ElastiCache::ReplicationGroup","AWS::EFS::FileSystem","AWS::OpenSearchService::Domain"].includes(e)}function Cr(e,n,r){let i=e.Resources||{};if(!e.Description)r.push({path:"Description",message:"Consider adding a Description to the template",severity:"info"});for(let s in i){let a=i[s],c=a.Properties;if(c&&!c.Tags&&vr(a.Type))r.push({path:`Resources.${s}`,message:`Consider adding Tags to ${a.Type}`,severity:"info"});if(en(a.Type)){if(a.Type==="AWS::S3::Bucket"&&!c?.BucketEncryption)n.push({path:`Resources.${s}`,message:"S3 bucket should enable encryption",severity:"warning"});if(a.Type==="AWS::RDS::DBInstance"&&!c?.StorageEncrypted)n.push({path:`Resources.${s}`,message:"RDS instance should enable storage encryption",severity:"warning"})}}}function vr(e){return!["AWS::CloudFormation::Stack","AWS::CloudFormation::WaitCondition","AWS::CloudFormation::WaitConditionHandle"].includes(e)}function au(e){let n=[],r=[],i=[],s=Buffer.byteLength(e,"utf8"),a=s/1024,c=51200,u=460800;if(s>460800)n.push({path:"Template",message:`Template size (${a.toFixed(2)} KB) exceeds maximum size of 450 KB`,severity:"error"});else if(s>51200)r.push({path:"Template",message:`Template size (${a.toFixed(2)} KB) exceeds 50 KB. Must use S3 for deployment.`,severity:"warning"});return{valid:n.length===0,errors:n,warnings:r,info:i}}function cu(e){let n=[],r=[],i=[],s=e.Resources||{},a=e.Parameters||{},c=e.Outputs||{};if(Object.keys(s).length>500)n.push({path:"Resources",message:`Template has ${Object.keys(s).length} resources (limit is 500)`,severity:"error"});if(Object.keys(a).length>200)n.push({path:"Parameters",message:`Template has ${Object.keys(a).length} parameters (limit is 200)`,severity:"error"});if(Object.keys(c).length>200)n.push({path:"Outputs",message:`Template has ${Object.keys(c).length} outputs (limit is 200)`,severity:"error"});return{valid:n.length===0,errors:n,warnings:r,info:i}}var R={Ref:(e)=>({Ref:e}),GetAtt:(e,n)=>({"Fn::GetAtt":[e,n]}),Sub:(e,n)=>{if(n)return{"Fn::Sub":[e,n]};return{"Fn::Sub":e}},Join:(e,n)=>({"Fn::Join":[e,n]}),Select:(e,n)=>({"Fn::Select":[e,n]}),Split:(e,n)=>({"Fn::Split":[e,n]}),GetAZs:(e="")=>({"Fn::GetAZs":e}),ImportValue:(e)=>({"Fn::ImportValue":e}),If:(e,n,r)=>({"Fn::If":[e,n,r]}),Equals:(e,n)=>({"Fn::Equals":[e,n]}),And:(...e)=>({"Fn::And":e}),Or:(...e)=>({"Fn::Or":e}),Not:(e)=>({"Fn::Not":[e]}),Base64:(e)=>({"Fn::Base64":e})},lu={AccountId:{Ref:"AWS::AccountId"},Region:{Ref:"AWS::Region"},StackId:{Ref:"AWS::StackId"},StackName:{Ref:"AWS::StackName"},NotificationARNs:{Ref:"AWS::NotificationARNs"},Partition:{Ref:"AWS::Partition"},URLSuffix:{Ref:"AWS::URLSuffix"},NoValue:{Ref:"AWS::NoValue"}};function l(e){let{slug:n,environment:r,resourceType:i,timestamp:s,suffix:a}=e,c=[n,r,i];if(s)c.push(s);if(a)c.push(a);return c.join("-")}function o(e){return e.split("-").map((n)=>n.charAt(0).toUpperCase()+n.slice(1)).join("")}function wm(){return Date.now().toString()}function Am(e){return e.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/^-+|-+$/g,"").replace(/-+/g,"-")}function T(e,n){return e.project.stackName??`${e.project.slug}-${n}`}function fa(e,n,r,i){return r.stackName??`${e.project.slug}-${i}-${n}-site`}function ha(e,n){return`${e.project.slug}-${n}`}function ya(e,n,r,i){if(i)return i;if(r==="main")return`${e}-${n}-site`;return`${e}-${n}-${r}`}function Rm(e,n,r,i){return i??`${e}-${n}-${r}`}function Im(e,n){return`${e}-${n}-deploy`}function $e(e,n){return`${e.project.slug}-${n}-app`}function ba(e,n){return`${e}-${n}-deployments`}function Bi(e,n){return`${e}-${n}-assets`}class du{nodes=new Map;addResource(e,n){let r=this.extractDependencies(n);this.nodes.set(e,{logicalId:e,resource:n,dependencies:r})}extractDependencies(e){let n=new Set;if(e.DependsOn)if(Array.isArray(e.DependsOn))e.DependsOn.forEach((r)=>n.add(r));else n.add(e.DependsOn);return this.findReferences(e.Properties||{},n),n}findReferences(e,n){if(!e||typeof e!=="object")return;if("Ref"in e&&typeof e.Ref==="string"){if(!e.Ref.startsWith("AWS::"))n.add(e.Ref)}if("Fn::GetAtt"in e&&Array.isArray(e["Fn::GetAtt"]))n.add(e["Fn::GetAtt"][0]);for(let r of Object.values(e))if(typeof r==="object")this.findReferences(r,n)}topologicalSort(){let e=[],n=new Set,r=new Set,i=(s)=>{if(n.has(s))return;if(r.has(s))throw Error(`Circular dependency detected: ${s}`);r.add(s);let a=this.nodes.get(s);if(a)for(let c of a.dependencies)i(c);r.delete(s),n.add(s),e.push(s)};for(let s of this.nodes.keys())i(s);return e}validate(){for(let[e,n]of this.nodes.entries())for(let r of n.dependencies)if(!this.nodes.has(r))throw Error(`Resource "${e}" depends on "${r}" which does not exist`)}getDependents(e){let n=[];for(let[r,i]of this.nodes.entries())if(i.dependencies.has(e))n.push(r);return n}}function Pm(e,n){let r=[],i=[],s=[],a=[],c=[],u=e.Resources||{},d=n.Resources||{},m=new Set([...Object.keys(u),...Object.keys(d)]);for(let g of m){let y=u[g],f=d[g];if(!y&&f)r.push({logicalId:g,action:"add",resourceType:f.Type});else if(y&&!f)i.push({logicalId:g,action:"remove",resourceType:y.Type});else if(y&&f)if(y.Type!==f.Type)a.push({logicalId:g,action:"replace",resourceType:f.Type,reason:`Type changed from ${y.Type} to ${f.Type}`});else{let h=tn(y.Properties||{},f.Properties||{});if(h.length>0)if(Tr(y.Type,h))a.push({logicalId:g,action:"replace",resourceType:f.Type,changes:h,reason:"Property changes require replacement"});else s.push({logicalId:g,action:"update",resourceType:f.Type,changes:h});else c.push(g)}}let p=Rr([...i,...a,...s]);return{added:r,removed:i,updated:s,replaced:a,unchanged:c,summary:{totalChanges:r.length+i.length+s.length+a.length,requiresReplacement:a.length>0,dangerousChanges:p}}}function tn(e,n,r=""){let i=[],s=new Set([...Object.keys(e),...Object.keys(n)]);for(let a of s){let c=r?`${r}.${a}`:a,u=e[a],d=n[a];if(u===void 0&&d!==void 0)i.push({path:c,oldValue:void 0,newValue:d});else if(u!==void 0&&d===void 0)i.push({path:c,oldValue:u,newValue:void 0});else if(typeof u!==typeof d)i.push({path:c,oldValue:u,newValue:d});else if(typeof u==="object"&&u!==null)if(Array.isArray(u)&&Array.isArray(d)){if(JSON.stringify(u)!==JSON.stringify(d))i.push({path:c,oldValue:u,newValue:d})}else if(!Array.isArray(u)&&!Array.isArray(d)){let m=tn(u,d,c);i.push(...m)}else i.push({path:c,oldValue:u,newValue:d});else if(u!==d)i.push({path:c,oldValue:u,newValue:d})}return i}function Tr(e,n){let i={"AWS::S3::Bucket":new Set(["BucketName"]),"AWS::DynamoDB::Table":new Set(["TableName","KeySchema"]),"AWS::RDS::DBInstance":new Set(["DBInstanceIdentifier","DBName","Engine"]),"AWS::Lambda::Function":new Set(["FunctionName"]),"AWS::EC2::Instance":new Set(["ImageId","InstanceType","KeyName"]),"AWS::ECS::TaskDefinition":new Set(["Family","ContainerDefinitions"]),"AWS::ElastiCache::CacheCluster":new Set(["CacheNodeType","Engine"]),"AWS::CloudFront::Distribution":new Set([]),"AWS::Route53::HostedZone":new Set(["Name"]),"AWS::IAM::Role":new Set(["RoleName","Path"]),"AWS::KMS::Key":new Set(["KeyPolicy"]),"AWS::Cognito::UserPool":new Set(["UserPoolName"]),"AWS::OpenSearchService::Domain":new Set(["DomainName"])}[e];if(!i)return!1;for(let s of n){let a=s.path.split(".")[0];if(i.has(a))return!0}return!1}function Rr(e){let n=[];for(let r of e){if(r.action==="remove"&&(r.resourceType==="AWS::RDS::DBInstance"||r.resourceType==="AWS::DynamoDB::Table"||r.resourceType==="AWS::ElastiCache::CacheCluster"))n.push(`Removing ${r.resourceType} ${r.logicalId} - data loss risk!`);if(r.action==="replace"&&(r.resourceType==="AWS::RDS::DBInstance"||r.resourceType==="AWS::DynamoDB::Table"))n.push(`Replacing ${r.resourceType} ${r.logicalId} - data loss risk!`);if((r.action==="remove"||r.action==="replace")&&r.resourceType==="AWS::S3::Bucket")n.push(`${r.action==="remove"?"Removing":"Replacing"} S3 bucket ${r.logicalId} - data loss risk!`);if(r.action==="replace"&&r.resourceType==="AWS::EC2::Instance")n.push(`Replacing EC2 instance ${r.logicalId} - downtime expected`);if(r.action==="update"&&r.resourceType==="AWS::EC2::SecurityGroup")n.push(`Updating security group ${r.logicalId} - may affect connectivity`);if((r.action==="update"||r.action==="replace")&&(r.resourceType==="AWS::IAM::Role"||r.resourceType==="AWS::IAM::Policy"))n.push(`Modifying IAM ${r.resourceType.split("::")[2]} ${r.logicalId} - may affect permissions`)}return n}function Dm(e){let n=[];if(n.push(`=== Stack Update Analysis ===
|
|
7
7
|
`),e.summary.totalChanges===0)return n.push(`No changes detected.
|
|
8
8
|
`),n.join(`
|
|
9
9
|
`);if(n.push(`Total changes: ${e.summary.totalChanges}`),n.push(`Requires replacement: ${e.summary.requiresReplacement?"Yes":"No"}
|
|
10
10
|
`),e.summary.dangerousChanges.length>0){n.push("⚠️ DANGEROUS CHANGES DETECTED:");for(let r of e.summary.dangerousChanges)n.push(` • ${r}`);n.push("")}if(e.added.length>0){n.push(`✅ Resources to Add (${e.added.length}):`);for(let r of e.added)n.push(` + ${r.logicalId} (${r.resourceType})`);n.push("")}if(e.removed.length>0){n.push(`❌ Resources to Remove (${e.removed.length}):`);for(let r of e.removed)n.push(` - ${r.logicalId} (${r.resourceType})`);n.push("")}if(e.replaced.length>0){n.push(`\uD83D\uDD04 Resources to Replace (${e.replaced.length}):`);for(let r of e.replaced){if(n.push(` ~ ${r.logicalId} (${r.resourceType})`),r.reason)n.push(` Reason: ${r.reason}`);if(r.changes){for(let i of r.changes.slice(0,3))n.push(` • ${i.path}: ${JSON.stringify(i.oldValue)} → ${JSON.stringify(i.newValue)}`);if(r.changes.length>3)n.push(` ... and ${r.changes.length-3} more changes`)}}n.push("")}if(e.updated.length>0){n.push(`\uD83D\uDCDD Resources to Update (${e.updated.length}):`);for(let r of e.updated)if(n.push(` ~ ${r.logicalId} (${r.resourceType})`),r.changes){for(let i of r.changes.slice(0,3))n.push(` • ${i.path}: ${JSON.stringify(i.oldValue)} → ${JSON.stringify(i.newValue)}`);if(r.changes.length>3)n.push(` ... and ${r.changes.length-3} more changes`)}n.push("")}if(e.unchanged.length>0)n.push(`⚪ Unchanged Resources (${e.unchanged.length})`);return n.join(`
|
|
11
|
-
`)}import{existsSync as _e,readdirSync as Pr}from"node:fs";import{join as de}from"node:path";class He{static createBucket(e){let{name:n,bucketName:r,slug:i,environment:s,public:a=!1,versioning:c=!1,website:u=!1,encryption:d=!0,intelligentTiering:m=!1,cors:p,lifecycleRules:g}=e,y=r??l({slug:i,environment:s,resourceType:"s3",suffix:n}),f=o(y),h={Type:"AWS::S3::Bucket",Properties:{BucketName:y}};if(d)h.Properties.BucketEncryption={ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]};if(c)h.Properties.VersioningConfiguration={Status:"Enabled"};if(u)h.Properties.WebsiteConfiguration={IndexDocument:"index.html",ErrorDocument:"error.html"};if(!a)h.Properties.PublicAccessBlockConfiguration={BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0};if(p&&p.length>0)h.Properties.CorsConfiguration={CorsRules:p.map((C)=>({AllowedOrigins:C.allowedOrigins,AllowedMethods:C.allowedMethods,AllowedHeaders:C.allowedHeaders,MaxAge:C.maxAge}))};if(g&&g.length>0)h.Properties.LifecycleConfiguration={Rules:g.map((C)=>({Id:C.id,Status:C.enabled?"Enabled":"Disabled",ExpirationInDays:C.expirationDays,Transitions:C.transitions?.map((P)=>({TransitionInDays:P.days,StorageClass:P.storageClass}))}))};if(m&&g){let C={id:"IntelligentTieringRule",enabled:!0,transitions:[{days:0,storageClass:"INTELLIGENT_TIERING"}]};if(!h.Properties.LifecycleConfiguration)h.Properties.LifecycleConfiguration={Rules:[]};h.Properties.LifecycleConfiguration.Rules.push({Id:C.id,Status:"Enabled",Transitions:C.transitions?.map((P)=>({TransitionInDays:P.days,StorageClass:P.storageClass}))})}let S;if(a)S={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:R.Ref(f),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadGetObject",Effect:"Allow",Principal:"*",Action:["s3:GetObject"],Resource:[R.Join("",[R.GetAtt(f,"Arn"),"/*"])]}]}}};return{bucket:h,bucketPolicy:S,logicalId:f}}static enableVersioning(e){if(!e.Properties)e.Properties={};return e.Properties.VersioningConfiguration={Status:"Enabled"},e}static enableWebsiteHosting(e,n="index.html",r="error.html"){if(!e.Properties)e.Properties={};return e.Properties.WebsiteConfiguration={IndexDocument:n,ErrorDocument:r},e}static setLifecycleRules(e,n){if(!e.Properties)e.Properties={};return e.Properties.LifecycleConfiguration={Rules:n.map((r)=>({Id:r.id,Status:r.enabled?"Enabled":"Disabled",ExpirationInDays:r.expirationDays,Transitions:r.transitions?.map((i)=>({TransitionInDays:i.days,StorageClass:i.storageClass}))}))},e}static enableIntelligentTiering(e){if(!e.Properties)e.Properties={};if(!e.Properties.LifecycleConfiguration)e.Properties.LifecycleConfiguration={Rules:[]};return e.Properties.LifecycleConfiguration.Rules.push({Id:"IntelligentTieringRule",Status:"Enabled",Transitions:[{TransitionInDays:0,StorageClass:"INTELLIGENT_TIERING"}]}),e}static addLambdaNotification(e,n){if(!e.Properties)e.Properties={};if(!e.Properties.NotificationConfiguration)e.Properties.NotificationConfiguration={};if(!e.Properties.NotificationConfiguration.LambdaConfigurations)e.Properties.NotificationConfiguration.LambdaConfigurations=[];let r={Event:n.events[0],Function:n.functionArn};if(n.filter)r.Filter={S3Key:{Rules:[...n.filter.prefix?[{Name:"prefix",Value:n.filter.prefix}]:[],...n.filter.suffix?[{Name:"suffix",Value:n.filter.suffix}]:[]]}};for(let i of n.events){let s={...r,Event:i};e.Properties.NotificationConfiguration.LambdaConfigurations.push(s)}return e}static Notifications={onObjectCreated:(e)=>({functionArn:e,events:["s3:ObjectCreated:*"]}),onObjectRemoved:(e)=>({functionArn:e,events:["s3:ObjectRemoved:*"]}),onImageUpload:(e,n)=>({functionArn:e,events:["s3:ObjectCreated:*"],filter:{prefix:n,suffix:".jpg"}}),onFileType:(e,n,r)=>({functionArn:e,events:["s3:ObjectCreated:*"],filter:{prefix:r,suffix:n}}),onFolderUpload:(e,n)=>({functionArn:e,events:["s3:ObjectCreated:*"],filter:{prefix:n.endsWith("/")?n:`${n}/`}})};static createBackupPlan(e){let{name:n,slug:r,environment:i,bucketLogicalIds:s,retentionDays:a,schedule:c="cron(0 5 * * ? *)",vaultName:u,enableContinuousBackup:d=!1,moveToColdStorageAfterDays:m}=e,p=u||l({slug:r,environment:i,resourceType:"backup-vault",suffix:n}),g=o(p),y={Type:"AWS::Backup::BackupVault",Properties:{BackupVaultName:p}},f=l({slug:r,environment:i,resourceType:"backup-role",suffix:n}),h=o(f),S={Type:"AWS::IAM::Role",Properties:{RoleName:f,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"]}},C=l({slug:r,environment:i,resourceType:"backup-plan",suffix:n}),P=o(C),E={DeleteAfterDays:a};if(m&&m<a)E.MoveToColdStorageAfterDays=m;let v={Type:"AWS::Backup::BackupPlan",Properties:{BackupPlan:{BackupPlanName:C,BackupPlanRule:[{RuleName:`${n}-daily-backup`,TargetBackupVault:R.Ref(g),ScheduleExpression:c,StartWindowMinutes:60,CompletionWindowMinutes:120,Lifecycle:E,EnableContinuousBackup:d}]}}},w=l({slug:r,environment:i,resourceType:"backup-selection",suffix:n}),D=o(w),x=s.map((B)=>R.GetAtt(B,"Arn")),L={Type:"AWS::Backup::BackupSelection",Properties:{BackupPlanId:R.Ref(P),BackupSelection:{SelectionName:w,IamRoleArn:R.GetAtt(h,"Arn"),Resources:x}}};return{vault:y,plan:v,selection:L,role:S,vaultLogicalId:g,planLogicalId:P,selectionLogicalId:D,roleLogicalId:h}}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(e){let{slug:n,environment:r,sourceDomain:i,targetDomain:s,protocol:a="https"}=e,c=l({slug:n,environment:r,resourceType:"s3",suffix:"www-redirect"}),u=o(c),d={Type:"AWS::S3::Bucket",Properties:{BucketName:i,WebsiteConfiguration:{RedirectAllRequestsTo:{HostName:s,Protocol:a}},PublicAccessBlockConfiguration:{BlockPublicAcls:!1,BlockPublicPolicy:!1,IgnorePublicAcls:!1,RestrictPublicBuckets:!1}}},m={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:R.Ref(u),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadForRedirect",Effect:"Allow",Principal:"*",Action:["s3:GetObject"],Resource:[R.Join("",[R.GetAtt(u,"Arn"),"/*"])]}]}}};return{bucket:d,bucketPolicy:m,logicalId:u}}static createDocsBucket(e){let{slug:n,environment:r,domain:i}=e,s=i||l({slug:n,environment:r,resourceType:"s3",suffix:"docs"}),a=o(s);return{bucket:{Type:"AWS::S3::Bucket",Properties:{BucketName:s,BucketEncryption:{ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]},PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},Tags:[{Key:"backup",Value:"weekly"}]}},logicalId:a}}static createEmailBucket(e){let{slug:n,environment:r}=e,i=l({slug:n,environment:r,resourceType:"s3",suffix:"email"}),s=o(i),a={Type:"AWS::S3::Bucket",Properties:{BucketName:i,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"}]}]}}},c={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:R.Ref(s),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowSESPuts",Effect:"Allow",Principal:{Service:"ses.amazonaws.com"},Action:"s3:PutObject",Resource:R.Join("",[R.GetAtt(s,"Arn"),"/*"]),Condition:{StringEquals:{"AWS:SourceAccount":R.Ref("AWS::AccountId")}}}]}}};return{bucket:a,bucketPolicy:c,logicalId:s}}static docsExist(e={}){let{projectRoot:n=process.cwd(),docsPaths:r=["docs","documentation","doc"]}=e;for(let i of r){let s=de(n,i);if(_e(s)){let a=["dist","build",".bunpress/dist","_site","out","public"];for(let c of a){let u=de(s,c);if(_e(u))try{if(Pr(u).length>0)return{exists:!0,path:s,hasDistFolder:!0,distPath:u}}catch{}}return{exists:!0,path:s,hasDistFolder:!1,distPath:null}}}return{exists:!1,path:null,hasDistFolder:!1,distPath:null}}static createDocsBucketIfExists(e){let n=He.docsExist({projectRoot:e.projectRoot,docsPaths:e.docsPaths});if(!n.exists)return{bucket:null,logicalId:null,docsInfo:n};let r=He.createDocsBucket({slug:e.slug,environment:e.environment,domain:e.domain});return{bucket:r.bucket,bucketPolicy:r.bucketPolicy,logicalId:r.logicalId,docsInfo:n}}static createPrivateBucket(e){let{slug:n,environment:r,enableVersioning:i=!0,retentionDays:s,encryptionKeyArn:a}=e,c=l({slug:n,environment:r,resourceType:"s3",suffix:"private"}),u=o(c);return{bucket:{Type:"AWS::S3::Bucket",Properties:{BucketName:c,BucketEncryption:{ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:a?{SSEAlgorithm:"aws:kms",KMSMasterKeyID:a}:{SSEAlgorithm:"AES256"}}]},PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},VersioningConfiguration:i?{Status:"Enabled"}:void 0,LifecycleConfiguration:s?{Rules:[{Id:"RetentionPolicy",Status:"Enabled",ExpirationInDays:s}]}:void 0,Tags:[{Key:"backup",Value:"daily"}]}},logicalId:u}}static checkSourcePaths(e={}){let{projectRoot:n=process.cwd(),paths:r={}}=e,i=r.web||"views/web/dist",s=r.docs||"docs/dist",a=r.private||"private";return{web:{exists:_e(de(n,i)),path:de(n,i)},docs:{exists:_e(de(n,s)),path:de(n,s)},private:{exists:_e(de(n,a)),path:de(n,a)}}}static createDeploymentBuckets(e){let{slug:n,environment:r,domain:i,projectRoot:s,paths:a}=e,c=He.checkSourcePaths({projectRoot:s,paths:a}),u={},d={web:!1,docs:!1,private:!1},m=He.createBucket({name:"web",slug:n,environment:r,public:!1,versioning:!1,encryption:!0});if(u[m.logicalId]=m.bucket,d.web=!0,c.docs.exists){let p=He.createDocsBucket({slug:n,environment:r,domain:i?`docs.${i}`:void 0});if(u[p.logicalId]=p.bucket,p.bucketPolicy)u[`${p.logicalId}Policy`]=p.bucketPolicy;d.docs=!0}if(c.private.exists){let p=He.createPrivateBucket({slug:n,environment:r,enableVersioning:!0});u[p.logicalId]=p.bucket,d.private=!0}return{resources:u,created:d,sourcePaths:c}}}class Pt{static createRepository(e){let{name:n,slug:r,environment:i,scanOnPush:s=!0,imageMutability:a="MUTABLE",encryption:c="AES256",kmsKey:u,lifecyclePolicy:d,tags:m}=e,p=l({slug:r,environment:i,resourceType:"ecr",suffix:n}),g=o(p),y={Type:"AWS::ECR::Repository",Properties:{RepositoryName:p,ImageTagMutability:a,ImageScanningConfiguration:{ScanOnPush:s},EncryptionConfiguration:{EncryptionType:c,...u&&c==="KMS"?{KmsKey:u}:{}}}};if(d)y.Properties.LifecyclePolicy={LifecyclePolicyText:JSON.stringify(Pt.generateLifecyclePolicy(d))};if(m)y.Properties.Tags=Object.entries(m).map(([f,h])=>({Key:f,Value:h}));return{repository:y,logicalId:g}}static generateLifecyclePolicy(e){let n=[];if(e.untaggedImageExpireDays!==void 0)n.push({rulePriority:1,description:"Delete untagged images",selection:{tagStatus:"untagged",countType:"sinceImagePushed",countNumber:e.untaggedImageExpireDays,countUnit:"days"},action:{type:"expire"}});if(e.maxImageCount!==void 0)n.push({rulePriority:n.length+1,description:"Keep only most recent images",selection:{tagStatus:"any",countType:"imageCountMoreThan",countNumber:e.maxImageCount},action:{type:"expire"}});if(e.maxImageAgeDays!==void 0)n.push({rulePriority:n.length+1,description:"Delete images older than specified days",selection:{tagStatus:"any",countType:"sinceImagePushed",countNumber:e.maxImageAgeDays,countUnit:"days"},action:{type:"expire"}});return{rules:n}}static LifecyclePolicies={production:{maxImageCount:10,untaggedImageExpireDays:7},development:{maxImageCount:5,untaggedImageExpireDays:3},minimal:{maxImageCount:3,untaggedImageExpireDays:1},archive:{maxImageCount:50,untaggedImageExpireDays:30}};static enableImmutableTags(e){if(!e.Properties)e.Properties={};return e.Properties.ImageTagMutability="IMMUTABLE",e}static enableScanOnPush(e){if(!e.Properties)e.Properties={};return e.Properties.ImageScanningConfiguration={ScanOnPush:!0},e}static setLifecyclePolicy(e,n){if(!e.Properties)e.Properties={};return e.Properties.LifecyclePolicy={LifecyclePolicyText:JSON.stringify(Pt.generateLifecyclePolicy(n))},e}static addCrossAccountAccess(e,n){if(!e.Properties)e.Properties={};return e.Properties.RepositoryPolicyText={Version:"2012-10-17",Statement:[{Sid:"CrossAccountPull",Effect:"Allow",Principal:{AWS:n.map((r)=>`arn:aws:iam::${r}:root`)},Action:["ecr:GetDownloadUrlForLayer","ecr:BatchGetImage","ecr:BatchCheckLayerAvailability"]}]},e}static addLambdaAccess(e){if(!e.Properties)e.Properties={};return e.Properties.RepositoryPolicyText={Version:"2012-10-17",Statement:[{Sid:"LambdaECRImageRetrievalPolicy",Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:["ecr:GetDownloadUrlForLayer","ecr:BatchGetImage"]}]},e}static generateBunDockerfile(e){let{baseImage:n="oven/bun:1-debian",serverPath:r,port:i=3000,additionalDirs:s=[],healthCheckEndpoint:a="/health",nodeCompatible:c=!1,envVars:u={},buildCommands:d=[],runCommand:m}=e,p=["app","config",...s],g=m||`bun run ${r}`,y=`# Multi-stage build for Bun application
|
|
11
|
+
`)}import{existsSync as _e,readdirSync as Pr}from"node:fs";import{join as de}from"node:path";class He{static createBucket(e){let{name:n,bucketName:r,slug:i,environment:s,public:a=!1,versioning:c=!1,website:u=!1,encryption:d=!0,intelligentTiering:m=!1,cors:p,lifecycleRules:g}=e,y=r??l({slug:i,environment:s,resourceType:"s3",suffix:n}),f=o(y),h={Type:"AWS::S3::Bucket",Properties:{BucketName:y}};if(d)h.Properties.BucketEncryption={ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]};if(c)h.Properties.VersioningConfiguration={Status:"Enabled"};if(u)h.Properties.WebsiteConfiguration={IndexDocument:"index.html",ErrorDocument:"error.html"};if(!a)h.Properties.PublicAccessBlockConfiguration={BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0};if(p&&p.length>0)h.Properties.CorsConfiguration={CorsRules:p.map((C)=>({AllowedOrigins:C.allowedOrigins,AllowedMethods:C.allowedMethods,AllowedHeaders:C.allowedHeaders,MaxAge:C.maxAge}))};if(g&&g.length>0)h.Properties.LifecycleConfiguration={Rules:g.map((C)=>({Id:C.id,Status:C.enabled?"Enabled":"Disabled",ExpirationInDays:C.expirationDays,Transitions:C.transitions?.map((P)=>({TransitionInDays:P.days,StorageClass:P.storageClass}))}))};if(m&&g){let C={id:"IntelligentTieringRule",enabled:!0,transitions:[{days:0,storageClass:"INTELLIGENT_TIERING"}]};if(!h.Properties.LifecycleConfiguration)h.Properties.LifecycleConfiguration={Rules:[]};h.Properties.LifecycleConfiguration.Rules.push({Id:C.id,Status:"Enabled",Transitions:C.transitions?.map((P)=>({TransitionInDays:P.days,StorageClass:P.storageClass}))})}let S;if(a)S={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:R.Ref(f),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadGetObject",Effect:"Allow",Principal:"*",Action:["s3:GetObject"],Resource:[R.Join("",[R.GetAtt(f,"Arn"),"/*"])]}]}}};return{bucket:h,bucketPolicy:S,logicalId:f}}static enableVersioning(e){if(!e.Properties)e.Properties={};return e.Properties.VersioningConfiguration={Status:"Enabled"},e}static enableWebsiteHosting(e,n="index.html",r="error.html"){if(!e.Properties)e.Properties={};return e.Properties.WebsiteConfiguration={IndexDocument:n,ErrorDocument:r},e}static setLifecycleRules(e,n){if(!e.Properties)e.Properties={};return e.Properties.LifecycleConfiguration={Rules:n.map((r)=>({Id:r.id,Status:r.enabled?"Enabled":"Disabled",ExpirationInDays:r.expirationDays,Transitions:r.transitions?.map((i)=>({TransitionInDays:i.days,StorageClass:i.storageClass}))}))},e}static enableIntelligentTiering(e){if(!e.Properties)e.Properties={};if(!e.Properties.LifecycleConfiguration)e.Properties.LifecycleConfiguration={Rules:[]};return e.Properties.LifecycleConfiguration.Rules.push({Id:"IntelligentTieringRule",Status:"Enabled",Transitions:[{TransitionInDays:0,StorageClass:"INTELLIGENT_TIERING"}]}),e}static addLambdaNotification(e,n){if(!e.Properties)e.Properties={};if(!e.Properties.NotificationConfiguration)e.Properties.NotificationConfiguration={};if(!e.Properties.NotificationConfiguration.LambdaConfigurations)e.Properties.NotificationConfiguration.LambdaConfigurations=[];let r={Event:n.events[0],Function:n.functionArn};if(n.filter)r.Filter={S3Key:{Rules:[...n.filter.prefix?[{Name:"prefix",Value:n.filter.prefix}]:[],...n.filter.suffix?[{Name:"suffix",Value:n.filter.suffix}]:[]]}};for(let i of n.events){let s={...r,Event:i};e.Properties.NotificationConfiguration.LambdaConfigurations.push(s)}return e}static Notifications={onObjectCreated:(e)=>({functionArn:e,events:["s3:ObjectCreated:*"]}),onObjectRemoved:(e)=>({functionArn:e,events:["s3:ObjectRemoved:*"]}),onImageUpload:(e,n)=>({functionArn:e,events:["s3:ObjectCreated:*"],filter:{prefix:n,suffix:".jpg"}}),onFileType:(e,n,r)=>({functionArn:e,events:["s3:ObjectCreated:*"],filter:{prefix:r,suffix:n}}),onFolderUpload:(e,n)=>({functionArn:e,events:["s3:ObjectCreated:*"],filter:{prefix:n.endsWith("/")?n:`${n}/`}})};static createBackupPlan(e){let{name:n,slug:r,environment:i,bucketLogicalIds:s,retentionDays:a,schedule:c="cron(0 5 * * ? *)",vaultName:u,enableContinuousBackup:d=!1,moveToColdStorageAfterDays:m}=e,p=u||l({slug:r,environment:i,resourceType:"backup-vault",suffix:n}),g=o(p),y={Type:"AWS::Backup::BackupVault",Properties:{BackupVaultName:p}},f=l({slug:r,environment:i,resourceType:"backup-role",suffix:n}),h=o(f),S={Type:"AWS::IAM::Role",Properties:{RoleName:f,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"]}},C=l({slug:r,environment:i,resourceType:"backup-plan",suffix:n}),P=o(C),E={DeleteAfterDays:a};if(m&&m<a)E.MoveToColdStorageAfterDays=m;let v={Type:"AWS::Backup::BackupPlan",Properties:{BackupPlan:{BackupPlanName:C,BackupPlanRule:[{RuleName:`${n}-daily-backup`,TargetBackupVault:R.Ref(g),ScheduleExpression:c,StartWindowMinutes:60,CompletionWindowMinutes:120,Lifecycle:E,EnableContinuousBackup:d}]}}},w=l({slug:r,environment:i,resourceType:"backup-selection",suffix:n}),D=o(w),x=s.map((B)=>R.GetAtt(B,"Arn")),L={Type:"AWS::Backup::BackupSelection",Properties:{BackupPlanId:R.Ref(P),BackupSelection:{SelectionName:w,IamRoleArn:R.GetAtt(h,"Arn"),Resources:x}}};return{vault:y,plan:v,selection:L,role:S,vaultLogicalId:g,planLogicalId:P,selectionLogicalId:D,roleLogicalId:h}}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(e){let{slug:n,environment:r,sourceDomain:i,targetDomain:s,protocol:a="https"}=e,c=l({slug:n,environment:r,resourceType:"s3",suffix:"www-redirect"}),u=o(c),d={Type:"AWS::S3::Bucket",Properties:{BucketName:i,WebsiteConfiguration:{RedirectAllRequestsTo:{HostName:s,Protocol:a}},PublicAccessBlockConfiguration:{BlockPublicAcls:!1,BlockPublicPolicy:!1,IgnorePublicAcls:!1,RestrictPublicBuckets:!1}}},m={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:R.Ref(u),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadForRedirect",Effect:"Allow",Principal:"*",Action:["s3:GetObject"],Resource:[R.Join("",[R.GetAtt(u,"Arn"),"/*"])]}]}}};return{bucket:d,bucketPolicy:m,logicalId:u}}static createDocsBucket(e){let{slug:n,environment:r,domain:i}=e,s=i||l({slug:n,environment:r,resourceType:"s3",suffix:"docs"}),a=o(s);return{bucket:{Type:"AWS::S3::Bucket",Properties:{BucketName:s,BucketEncryption:{ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]},PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},Tags:[{Key:"backup",Value:"weekly"}]}},logicalId:a}}static createEmailBucket(e){let{slug:n,environment:r}=e,i=l({slug:n,environment:r,resourceType:"s3",suffix:"email"}),s=o(i),a={Type:"AWS::S3::Bucket",Properties:{BucketName:i,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"}]}]}}},c={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:R.Ref(s),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowSESPuts",Effect:"Allow",Principal:{Service:"ses.amazonaws.com"},Action:"s3:PutObject",Resource:R.Join("",[R.GetAtt(s,"Arn"),"/*"]),Condition:{StringEquals:{"AWS:SourceAccount":R.Ref("AWS::AccountId")}}}]}}};return{bucket:a,bucketPolicy:c,logicalId:s}}static docsExist(e={}){let{projectRoot:n=process.cwd(),docsPaths:r=["docs","documentation","doc"]}=e;for(let i of r){let s=de(n,i);if(_e(s)){let a=["dist","build",".bunpress/dist","_site","out","public"];for(let c of a){let u=de(s,c);if(_e(u))try{if(Pr(u).length>0)return{exists:!0,path:s,hasDistFolder:!0,distPath:u}}catch{}}return{exists:!0,path:s,hasDistFolder:!1,distPath:null}}}return{exists:!1,path:null,hasDistFolder:!1,distPath:null}}static createDocsBucketIfExists(e){let n=He.docsExist({projectRoot:e.projectRoot,docsPaths:e.docsPaths});if(!n.exists)return{bucket:null,logicalId:null,docsInfo:n};let r=He.createDocsBucket({slug:e.slug,environment:e.environment,domain:e.domain});return{bucket:r.bucket,bucketPolicy:r.bucketPolicy,logicalId:r.logicalId,docsInfo:n}}static createPrivateBucket(e){let{slug:n,environment:r,enableVersioning:i=!0,retentionDays:s,encryptionKeyArn:a}=e,c=l({slug:n,environment:r,resourceType:"s3",suffix:"private"}),u=o(c);return{bucket:{Type:"AWS::S3::Bucket",Properties:{BucketName:c,BucketEncryption:{ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:a?{SSEAlgorithm:"aws:kms",KMSMasterKeyID:a}:{SSEAlgorithm:"AES256"}}]},PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},VersioningConfiguration:i?{Status:"Enabled"}:void 0,LifecycleConfiguration:s?{Rules:[{Id:"RetentionPolicy",Status:"Enabled",ExpirationInDays:s}]}:void 0,Tags:[{Key:"backup",Value:"daily"}]}},logicalId:u}}static checkSourcePaths(e={}){let{projectRoot:n=process.cwd(),paths:r={}}=e,i=r.web||"views/web/dist",s=r.docs||"docs/dist",a=r.private||"private";return{web:{exists:_e(de(n,i)),path:de(n,i)},docs:{exists:_e(de(n,s)),path:de(n,s)},private:{exists:_e(de(n,a)),path:de(n,a)}}}static createDeploymentBuckets(e){let{slug:n,environment:r,domain:i,projectRoot:s,paths:a}=e,c=He.checkSourcePaths({projectRoot:s,paths:a}),u={},d={web:!1,docs:!1,private:!1},m=He.createBucket({name:"web",slug:n,environment:r,public:!1,versioning:!1,encryption:!0});if(u[m.logicalId]=m.bucket,d.web=!0,c.docs.exists){let p=He.createDocsBucket({slug:n,environment:r,domain:i?`docs.${i}`:void 0});if(u[p.logicalId]=p.bucket,p.bucketPolicy)u[`${p.logicalId}Policy`]=p.bucketPolicy;d.docs=!0}if(c.private.exists){let p=He.createPrivateBucket({slug:n,environment:r,enableVersioning:!0});u[p.logicalId]=p.bucket,d.private=!0}return{resources:u,created:d,sourcePaths:c}}}class Dt{static createRepository(e){let{name:n,slug:r,environment:i,scanOnPush:s=!0,imageMutability:a="MUTABLE",encryption:c="AES256",kmsKey:u,lifecyclePolicy:d,tags:m}=e,p=l({slug:r,environment:i,resourceType:"ecr",suffix:n}),g=o(p),y={Type:"AWS::ECR::Repository",Properties:{RepositoryName:p,ImageTagMutability:a,ImageScanningConfiguration:{ScanOnPush:s},EncryptionConfiguration:{EncryptionType:c,...u&&c==="KMS"?{KmsKey:u}:{}}}};if(d)y.Properties.LifecyclePolicy={LifecyclePolicyText:JSON.stringify(Dt.generateLifecyclePolicy(d))};if(m)y.Properties.Tags=Object.entries(m).map(([f,h])=>({Key:f,Value:h}));return{repository:y,logicalId:g}}static generateLifecyclePolicy(e){let n=[];if(e.untaggedImageExpireDays!==void 0)n.push({rulePriority:1,description:"Delete untagged images",selection:{tagStatus:"untagged",countType:"sinceImagePushed",countNumber:e.untaggedImageExpireDays,countUnit:"days"},action:{type:"expire"}});if(e.maxImageCount!==void 0)n.push({rulePriority:n.length+1,description:"Keep only most recent images",selection:{tagStatus:"any",countType:"imageCountMoreThan",countNumber:e.maxImageCount},action:{type:"expire"}});if(e.maxImageAgeDays!==void 0)n.push({rulePriority:n.length+1,description:"Delete images older than specified days",selection:{tagStatus:"any",countType:"sinceImagePushed",countNumber:e.maxImageAgeDays,countUnit:"days"},action:{type:"expire"}});return{rules:n}}static LifecyclePolicies={production:{maxImageCount:10,untaggedImageExpireDays:7},development:{maxImageCount:5,untaggedImageExpireDays:3},minimal:{maxImageCount:3,untaggedImageExpireDays:1},archive:{maxImageCount:50,untaggedImageExpireDays:30}};static enableImmutableTags(e){if(!e.Properties)e.Properties={};return e.Properties.ImageTagMutability="IMMUTABLE",e}static enableScanOnPush(e){if(!e.Properties)e.Properties={};return e.Properties.ImageScanningConfiguration={ScanOnPush:!0},e}static setLifecyclePolicy(e,n){if(!e.Properties)e.Properties={};return e.Properties.LifecyclePolicy={LifecyclePolicyText:JSON.stringify(Dt.generateLifecyclePolicy(n))},e}static addCrossAccountAccess(e,n){if(!e.Properties)e.Properties={};return e.Properties.RepositoryPolicyText={Version:"2012-10-17",Statement:[{Sid:"CrossAccountPull",Effect:"Allow",Principal:{AWS:n.map((r)=>`arn:aws:iam::${r}:root`)},Action:["ecr:GetDownloadUrlForLayer","ecr:BatchGetImage","ecr:BatchCheckLayerAvailability"]}]},e}static addLambdaAccess(e){if(!e.Properties)e.Properties={};return e.Properties.RepositoryPolicyText={Version:"2012-10-17",Statement:[{Sid:"LambdaECRImageRetrievalPolicy",Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:["ecr:GetDownloadUrlForLayer","ecr:BatchGetImage"]}]},e}static generateBunDockerfile(e){let{baseImage:n="oven/bun:1-debian",serverPath:r,port:i=3000,additionalDirs:s=[],healthCheckEndpoint:a="/health",nodeCompatible:c=!1,envVars:u={},buildCommands:d=[],runCommand:m}=e,p=["app","config",...s],g=m||`bun run ${r}`,y=`# Multi-stage build for Bun application
|
|
12
12
|
# Generated by ts-cloud
|
|
13
13
|
|
|
14
14
|
# Builder stage
|
|
@@ -62,7 +62,7 @@ HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \\
|
|
|
62
62
|
|
|
63
63
|
# Start application
|
|
64
64
|
CMD ["bun", "run", "${r}"]
|
|
65
|
-
`,y}static generateDockerBuildCommands(e){let{repositoryUri:n,tag:r="latest",dockerfilePath:i="Dockerfile",context:s=".",additionalTags:a=[],buildArgs:c={},platform:u="linux/amd64",noCache:d=!1}=e,m=`${n}:${r}`,p=[r,...a],g=`docker build -f ${i} -t ${m}`;if(u)g+=` --platform ${u}`;if(d)g+=" --no-cache";for(let[h,S]of Object.entries(c))g+=` --build-arg ${h}=${S}`;g+=` ${s}`;let y=p.slice(1).map((h)=>`docker tag ${m} ${n}:${h}`),f=p.map((h)=>`docker push ${n}:${h}`);return{build:g,tag:y,push:f,all:[g,...y,...f]}}static generateEcrLoginCommand(e,n){return`aws ecr get-login-password --region ${e} | docker login --username AWS --password-stdin ${n}.dkr.ecr.${e}.amazonaws.com`}static buildRepositoryUri(e){return`${e.accountId}.dkr.ecr.${e.region}.amazonaws.com/${e.repositoryName}`}static generateImageTags(e){let n=["latest"];if(e.version){n.push(e.version);let r=e.version.split(".");if(r.length>=2)n.push(`${r[0]}.${r[1]}`);if(r.length>=1)n.push(r[0])}if(e.gitSha)n.push(e.gitSha.substring(0,7)),n.push(e.gitSha);if(e.gitBranch){let r=e.gitBranch.replace(/[^a-zA-Z0-9.-]/g,"-").replace(/^-+|-+$/g,"");n.push(r)}if(e.environment)n.push(e.environment);if(e.timestamp){let r=new Date().toISOString().replace(/[:.]/g,"-").substring(0,19);n.push(r)}return[...new Set(n)]}static DeploymentWorkflow={generateDeployScript:(e)=>{let n=
|
|
65
|
+
`,y}static generateDockerBuildCommands(e){let{repositoryUri:n,tag:r="latest",dockerfilePath:i="Dockerfile",context:s=".",additionalTags:a=[],buildArgs:c={},platform:u="linux/amd64",noCache:d=!1}=e,m=`${n}:${r}`,p=[r,...a],g=`docker build -f ${i} -t ${m}`;if(u)g+=` --platform ${u}`;if(d)g+=" --no-cache";for(let[h,S]of Object.entries(c))g+=` --build-arg ${h}=${S}`;g+=` ${s}`;let y=p.slice(1).map((h)=>`docker tag ${m} ${n}:${h}`),f=p.map((h)=>`docker push ${n}:${h}`);return{build:g,tag:y,push:f,all:[g,...y,...f]}}static generateEcrLoginCommand(e,n){return`aws ecr get-login-password --region ${e} | docker login --username AWS --password-stdin ${n}.dkr.ecr.${e}.amazonaws.com`}static buildRepositoryUri(e){return`${e.accountId}.dkr.ecr.${e.region}.amazonaws.com/${e.repositoryName}`}static generateImageTags(e){let n=["latest"];if(e.version){n.push(e.version);let r=e.version.split(".");if(r.length>=2)n.push(`${r[0]}.${r[1]}`);if(r.length>=1)n.push(r[0])}if(e.gitSha)n.push(e.gitSha.substring(0,7)),n.push(e.gitSha);if(e.gitBranch){let r=e.gitBranch.replace(/[^a-zA-Z0-9.-]/g,"-").replace(/^-+|-+$/g,"");n.push(r)}if(e.environment)n.push(e.environment);if(e.timestamp){let r=new Date().toISOString().replace(/[:.]/g,"-").substring(0,19);n.push(r)}return[...new Set(n)]}static DeploymentWorkflow={generateDeployScript:(e)=>{let n=Dt.buildRepositoryUri({accountId:e.accountId,region:e.region,repositoryName:e.repositoryName}),r=e.tags||["latest"],i=r[0];return`#!/bin/bash
|
|
66
66
|
set -e
|
|
67
67
|
|
|
68
68
|
# Configuration
|
|
@@ -73,7 +73,7 @@ IMAGE_URI="${n}"
|
|
|
73
73
|
DOCKERFILE="${e.dockerfilePath||"Dockerfile"}"
|
|
74
74
|
|
|
75
75
|
echo "=== ECR Login ==="
|
|
76
|
-
${
|
|
76
|
+
${Dt.generateEcrLoginCommand(e.region,e.accountId)}
|
|
77
77
|
|
|
78
78
|
echo "=== Building Image ==="
|
|
79
79
|
docker build -f $DOCKERFILE -t $IMAGE_URI:${i} --platform linux/amd64 .
|
|
@@ -91,7 +91,7 @@ echo "Image: $IMAGE_URI:${i}"
|
|
|
91
91
|
docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG
|
|
92
92
|
docker push $ECR_REGISTRY/$ECR_REPOSITORY:latest`},...e.ecsCluster&&e.ecsService?[{name:"Deploy to ECS",run:`aws ecs update-service --cluster ${e.ecsCluster} --service ${e.ecsService} --force-new-deployment`}]:[]]}}};return`# Generated by ts-cloud
|
|
93
93
|
${JSON.stringify(n,null,2).replace(/"/g,"").replace(/,\n/g,`
|
|
94
|
-
`)}`}};static DockerfileTemplates={bunServer:(e,n=3000)=>Pt.generateBunDockerfile({serverPath:e,port:n}),bunWithBuild:(e,n,r=3000)=>Pt.generateBunDockerfile({serverPath:e,port:r,buildCommands:[n]}),bunFullStack:(e,n=3000)=>Pt.generateBunDockerfile({serverPath:e,port:n,additionalDirs:["public","views","dist"],buildCommands:["bun run build"]}),bunApi:(e,n=3000)=>Pt.generateBunDockerfile({serverPath:e,port:n,healthCheckEndpoint:"/api/health"})}}var Sa=[400,403,404,416,429,500,502,503,504],sl=[500,502,503,504],al=["GET","HEAD","OPTIONS"],km="-failover-group",cl=["default","media-quality-based"],ll={min:1,max:3},dl={min:1,max:10};function Qo(e){if(e===void 0)return[...sl];if(e.length===0)throw Error(`CloudFront origin failover: statusCodes must list at least one code (allowed: ${Sa.join(", ")}). Omit it to use the default ${sl.join(", ")}.`);let n=e.filter((r)=>!Sa.includes(r));if(n.length>0)throw Error(`CloudFront origin failover: ${n.join(", ")} ${n.length===1?"is not a status code":"are not status codes"} CloudFront can fail over on. Allowed: ${Sa.join(", ")}.`);return[...new Set(e)].sort((r,i)=>r-i)}function va(e){let{primaryOriginId:n,secondaryOriginId:r}=e;if(!n||!r)throw Error("CloudFront origin failover: both a primary and a secondary origin id are required");if(n===r)throw Error(`CloudFront origin failover: the secondary origin must differ from the primary (both are "${n}")`);let i=Qo(e.statusCodes);return rn(e.selectionCriteria),{Id:e.groupId??`${n}-failover-group`,FailoverCriteria:{StatusCodes:{Quantity:i.length,Items:i}},Members:{Quantity:2,Items:[{OriginId:n},{OriginId:r}]},...e.selectionCriteria?{SelectionCriteria:e.selectionCriteria}:{}}}function rn(e,n="the origin group"){if(e===void 0)return;if(!cl.includes(e))throw Error(`CloudFront origin failover: ${n} has selection criteria ${JSON.stringify(e)}. Allowed: ${cl.join(", ")}.`)}function Ze(e,n,r){if(typeof e!=="number"||!Number.isInteger(e)||e<n.min||e>n.max)throw Error(`CloudFront origin: ${r} must be a whole number from ${n.min} to ${n.max}, got ${JSON.stringify(e)}.`)}function st(e,n="the origin"){let r={};if(e?.connectionAttempts!==void 0)Ze(e.connectionAttempts,ll,`${n} connectionAttempts`),r.ConnectionAttempts=e.connectionAttempts;if(e?.connectionTimeout!==void 0)Ze(e.connectionTimeout,dl,`${n} connectionTimeout (seconds)`),r.ConnectionTimeout=e.connectionTimeout;return r}function Yo(e){return{Quantity:1,Items:[va(e)]}}function wn(e,n="the cache behavior"){let i=(Array.isArray(e)?e:e?.Items??[]).filter((s)=>!al.includes(s.toUpperCase()));if(i.length>0)throw Error(`CloudFront origin failover: ${n} allows ${i.join(", ")}, but a cache behavior that targets an origin group may only allow ${al.join(", ")}. CloudFront never fails over a write, so point the write paths at a single origin in their own cache behavior.`)}function Fi(e){return/\.s3[.-](?:[a-z0-9-]+\.)?amazonaws\.com(?:\.cn)?$/i.test(e)&&!/s3-website/i.test(e)}function We(e){if(!e)return[];if(Array.isArray(e))return e;return e.Items??[]}function ae(e){return typeof e==="string"?e:void 0}var Er=/\.mediapackagev2\.[a-z0-9-]+\.amazonaws\.com$/i;function An(e,n="the distribution"){let r=We(e.Origins),i=new Set(r.map((p)=>ae(p.Id)).filter((p)=>!!p)),s=new Map(r.map((p)=>[ae(p.Id)??"",p.DomainName])),a=r.some((p)=>ae(p.Id)===void 0);for(let p of r){let g=ae(p.Id)??"(unnamed origin)";if(p.ConnectionAttempts!==void 0)Ze(p.ConnectionAttempts,ll,`${n} origin "${g}" ConnectionAttempts`);if(p.ConnectionTimeout!==void 0)Ze(p.ConnectionTimeout,dl,`${n} origin "${g}" ConnectionTimeout (seconds)`)}let c=e.OriginGroups,u=We(c);if(c&&!Array.isArray(c)&&c.Quantity!==void 0&&c.Quantity!==u.length)throw Error(`CloudFront origin failover: ${n} OriginGroups.Quantity is ${c.Quantity} but it lists ${u.length} group(s).`);let d=new Set;for(let p of u){let g=ae(p.Id);if(p.Id===void 0||p.Id==="")throw Error(`CloudFront origin failover: ${n} has an origin group without an Id.`);let y=`${n} origin group "${g??"(intrinsic id)"}"`;if(g){if(d.has(g))throw Error(`CloudFront origin failover: ${n} declares origin group "${g}" twice.`);if(i.has(g))throw Error(`CloudFront origin failover: ${y} has the same id as an origin. Cache behaviors target groups and origins by id, so the two must differ.`);d.add(g)}let f=p.Members,h=We(f);if(h.length!==2||f?.Quantity!==void 0&&f.Quantity!==h.length)throw Error(`CloudFront origin failover: ${y} must have exactly 2 members (a primary and a secondary), it has ${h.length}${f?.Quantity!==void 0&&f.Quantity!==h.length?` with Quantity ${f.Quantity}`:""}.`);let S=h.map((E)=>ae(E.OriginId));for(let E of S)if(E&&!i.has(E)&&!a)throw Error(`CloudFront origin failover: ${y} lists member "${E}", which is not an origin of this distribution. Origins: ${[...i].join(", ")||"(none)"}.`);if(S[0]&&S[0]===S[1])throw Error(`CloudFront origin failover: ${y} lists "${S[0]}" as both primary and secondary.`);let C=p.FailoverCriteria?.StatusCodes,P=We(C);if(Qo(P),C?.Quantity!==void 0&&C.Quantity!==P.length)throw Error(`CloudFront origin failover: ${y} FailoverCriteria.StatusCodes.Quantity is ${C.Quantity} but it lists ${P.length} code(s).`);if(rn(p.SelectionCriteria,y),p.SelectionCriteria==="media-quality-based")for(let E of S){let v=E?ae(s.get(E)):void 0;if(v&&!Er.test(v))throw Error(`CloudFront origin failover: ${y} uses media-quality-based selection, which only works between AWS Elemental MediaPackage v2 origins, but member "${E}" is ${v}. Use 'default'.`)}}let m=[];if(e.DefaultCacheBehavior)m.push({behavior:e.DefaultCacheBehavior,name:"the default cache behavior"});for(let p of We(e.CacheBehaviors))m.push({behavior:p,name:`the cache behavior for ${JSON.stringify(p.PathPattern)}`});for(let{behavior:p,name:g}of m){let y=ae(p.TargetOriginId);if(!y)continue;if(d.has(y))wn(p.AllowedMethods??["GET","HEAD"],`${g} of ${n} (origin group "${y}")`);else if(!i.has(y)&&!a&&u.every((f)=>ae(f.Id)!==void 0))throw Error(`CloudFront: ${g} of ${n} targets "${y}", which is neither an origin nor an origin group of this distribution.`)}}class Ge{static createDistribution(e){let{slug:n,environment:r,origin:i,customDomain:s,certificateArn:a,errorPages:c,cachePolicy:u,edgeFunctions:d,http3:m=!1,comment:p,failoverOrigin:g}=e,y=l({slug:n,environment:r,resourceType:"cdn"}),f=o(y),h={Id:"DefaultOrigin",DomainName:i.domainName,OriginPath:i.originPath||"",...st(i,"the CDN origin")},S;if(i.type==="s3"){let P=`${f}OAC`;S={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`${y}-oac`,Description:`Origin Access Control for ${y}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},h.OriginAccessControlId=R.Ref(P)}else if(i.type==="alb"||i.type==="custom")h.CustomOriginConfig={HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only"};let C={Type:"AWS::CloudFront::Distribution",Properties:{DistributionConfig:{Enabled:!0,Comment:p||`CDN for ${y}`,DefaultRootObject:"index.html",Origins:[h],DefaultCacheBehavior:{TargetOriginId:"DefaultOrigin",ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0},PriceClass:"PriceClass_100",HttpVersion:m?"http2and3":"http2"}}};if(s&&a)C.Properties.DistributionConfig.Aliases=[s],C.Properties.DistributionConfig.ViewerCertificate={AcmCertificateArn:a,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};if(c&&c.length>0)C.Properties.DistributionConfig.CustomErrorResponses=c.map((P)=>({ErrorCode:P.errorCode,ResponseCode:P.responseCode,ResponsePagePath:P.responsePagePath}));if(d&&d.length>0)C.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations=d.map((P)=>({EventType:P.event,LambdaFunctionARN:P.functionArn}));if(g)Ge.addOriginFailover(C,g);return{distribution:C,originAccessControl:S,logicalId:f}}static addOriginFailover(e,n){let r=e.Properties.DistributionConfig,i=r.DefaultCacheBehavior,s=i.TargetOriginId,a=n.id??"FailoverOrigin";if(r.OriginGroups&&r.OriginGroups.Quantity>0)throw Error("CloudFront origin failover: this distribution already has an origin group");if(wn(i.AllowedMethods??["GET","HEAD"],"the default cache behavior"),r.Origins.some((p)=>p.Id===a))throw Error(`CloudFront origin failover: an origin with id "${a}" already exists`);let c=va({primaryOriginId:s,secondaryOriginId:a,statusCodes:n.statusCodes,selectionCriteria:n.selectionCriteria}),u=n.type??(Fi(n.domainName)?"s3":"custom"),d={Id:a,DomainName:n.domainName,OriginPath:n.originPath||"",...st(n,"the failover origin")},m=st(n.primary,"the primary origin");if(Object.keys(m).length>0){let p=r.Origins.find((g)=>g.Id===s);if(p)Object.assign(p,m)}if(u==="s3"){let p=r.Origins.find((g)=>g.Id===s);if(d.S3OriginConfig={OriginAccessIdentity:""},p?.OriginAccessControlId)d.OriginAccessControlId=p.OriginAccessControlId}else d.CustomOriginConfig={HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only"};return r.Origins.push(d),r.OriginGroups={Quantity:1,Items:[c]},i.TargetOriginId=c.Id,An(r),e}static setCustomDomain(e,n,r){return e.Properties.DistributionConfig.Aliases=[n],e.Properties.DistributionConfig.ViewerCertificate={AcmCertificateArn:r,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"},e}static setErrorPages(e,n){return e.Properties.DistributionConfig.CustomErrorResponses=n.map((r)=>({ErrorCode:r.errorCode,ResponseCode:r.responseCode,ResponsePagePath:r.responsePagePath})),e}static enableHttp3(e){return e.Properties.DistributionConfig.HttpVersion="http2and3",e}static addEdgeFunction(e,n,r){if(!e.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations)e.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations=[];return e.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations.push({EventType:n,LambdaFunctionARN:r}),e}static setCachePolicy(e,n){return e.Properties.DistributionConfig.Comment=`${e.Properties.DistributionConfig.Comment||""} (TTL: ${n.default||86400}s)`,e}static createSpaDistribution(e){return Ge.createDistribution({...e,errorPages:[{errorCode:404,responseCode:200,responsePagePath:"/index.html"},{errorCode:403,responseCode:200,responsePagePath:"/index.html"}]})}static createDocsOriginRequestFunction(e){let{slug:n,environment:r}=e,i=l({slug:n,environment:r,resourceType:"edge-docs"}),s=o(i),a=o(`${i}-role`),c=o(`${i}-version`),u={Type:"AWS::IAM::Role",Properties:{RoleName:`${i}-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"]}},d=`
|
|
94
|
+
`)}`}};static DockerfileTemplates={bunServer:(e,n=3000)=>Dt.generateBunDockerfile({serverPath:e,port:n}),bunWithBuild:(e,n,r=3000)=>Dt.generateBunDockerfile({serverPath:e,port:r,buildCommands:[n]}),bunFullStack:(e,n=3000)=>Dt.generateBunDockerfile({serverPath:e,port:n,additionalDirs:["public","views","dist"],buildCommands:["bun run build"]}),bunApi:(e,n=3000)=>Dt.generateBunDockerfile({serverPath:e,port:n,healthCheckEndpoint:"/api/health"})}}var Sa=[400,403,404,416,429,500,502,503,504],sl=[500,502,503,504],al=["GET","HEAD","OPTIONS"],km="-failover-group",cl=["default","media-quality-based"],ll={min:1,max:3},dl={min:1,max:10};function Qo(e){if(e===void 0)return[...sl];if(e.length===0)throw Error(`CloudFront origin failover: statusCodes must list at least one code (allowed: ${Sa.join(", ")}). Omit it to use the default ${sl.join(", ")}.`);let n=e.filter((r)=>!Sa.includes(r));if(n.length>0)throw Error(`CloudFront origin failover: ${n.join(", ")} ${n.length===1?"is not a status code":"are not status codes"} CloudFront can fail over on. Allowed: ${Sa.join(", ")}.`);return[...new Set(e)].sort((r,i)=>r-i)}function va(e){let{primaryOriginId:n,secondaryOriginId:r}=e;if(!n||!r)throw Error("CloudFront origin failover: both a primary and a secondary origin id are required");if(n===r)throw Error(`CloudFront origin failover: the secondary origin must differ from the primary (both are "${n}")`);let i=Qo(e.statusCodes);return nn(e.selectionCriteria),{Id:e.groupId??`${n}-failover-group`,FailoverCriteria:{StatusCodes:{Quantity:i.length,Items:i}},Members:{Quantity:2,Items:[{OriginId:n},{OriginId:r}]},...e.selectionCriteria?{SelectionCriteria:e.selectionCriteria}:{}}}function nn(e,n="the origin group"){if(e===void 0)return;if(!cl.includes(e))throw Error(`CloudFront origin failover: ${n} has selection criteria ${JSON.stringify(e)}. Allowed: ${cl.join(", ")}.`)}function Ze(e,n,r){if(typeof e!=="number"||!Number.isInteger(e)||e<n.min||e>n.max)throw Error(`CloudFront origin: ${r} must be a whole number from ${n.min} to ${n.max}, got ${JSON.stringify(e)}.`)}function st(e,n="the origin"){let r={};if(e?.connectionAttempts!==void 0)Ze(e.connectionAttempts,ll,`${n} connectionAttempts`),r.ConnectionAttempts=e.connectionAttempts;if(e?.connectionTimeout!==void 0)Ze(e.connectionTimeout,dl,`${n} connectionTimeout (seconds)`),r.ConnectionTimeout=e.connectionTimeout;return r}function Yo(e){return{Quantity:1,Items:[va(e)]}}function An(e,n="the cache behavior"){let i=(Array.isArray(e)?e:e?.Items??[]).filter((s)=>!al.includes(s.toUpperCase()));if(i.length>0)throw Error(`CloudFront origin failover: ${n} allows ${i.join(", ")}, but a cache behavior that targets an origin group may only allow ${al.join(", ")}. CloudFront never fails over a write, so point the write paths at a single origin in their own cache behavior.`)}function Fi(e){return/\.s3[.-](?:[a-z0-9-]+\.)?amazonaws\.com(?:\.cn)?$/i.test(e)&&!/s3-website/i.test(e)}function We(e){if(!e)return[];if(Array.isArray(e))return e;return e.Items??[]}function ae(e){return typeof e==="string"?e:void 0}var Er=/\.mediapackagev2\.[a-z0-9-]+\.amazonaws\.com$/i;function Rn(e,n="the distribution"){let r=We(e.Origins),i=new Set(r.map((p)=>ae(p.Id)).filter((p)=>!!p)),s=new Map(r.map((p)=>[ae(p.Id)??"",p.DomainName])),a=r.some((p)=>ae(p.Id)===void 0);for(let p of r){let g=ae(p.Id)??"(unnamed origin)";if(p.ConnectionAttempts!==void 0)Ze(p.ConnectionAttempts,ll,`${n} origin "${g}" ConnectionAttempts`);if(p.ConnectionTimeout!==void 0)Ze(p.ConnectionTimeout,dl,`${n} origin "${g}" ConnectionTimeout (seconds)`)}let c=e.OriginGroups,u=We(c);if(c&&!Array.isArray(c)&&c.Quantity!==void 0&&c.Quantity!==u.length)throw Error(`CloudFront origin failover: ${n} OriginGroups.Quantity is ${c.Quantity} but it lists ${u.length} group(s).`);let d=new Set;for(let p of u){let g=ae(p.Id);if(p.Id===void 0||p.Id==="")throw Error(`CloudFront origin failover: ${n} has an origin group without an Id.`);let y=`${n} origin group "${g??"(intrinsic id)"}"`;if(g){if(d.has(g))throw Error(`CloudFront origin failover: ${n} declares origin group "${g}" twice.`);if(i.has(g))throw Error(`CloudFront origin failover: ${y} has the same id as an origin. Cache behaviors target groups and origins by id, so the two must differ.`);d.add(g)}let f=p.Members,h=We(f);if(h.length!==2||f?.Quantity!==void 0&&f.Quantity!==h.length)throw Error(`CloudFront origin failover: ${y} must have exactly 2 members (a primary and a secondary), it has ${h.length}${f?.Quantity!==void 0&&f.Quantity!==h.length?` with Quantity ${f.Quantity}`:""}.`);let S=h.map((E)=>ae(E.OriginId));for(let E of S)if(E&&!i.has(E)&&!a)throw Error(`CloudFront origin failover: ${y} lists member "${E}", which is not an origin of this distribution. Origins: ${[...i].join(", ")||"(none)"}.`);if(S[0]&&S[0]===S[1])throw Error(`CloudFront origin failover: ${y} lists "${S[0]}" as both primary and secondary.`);let C=p.FailoverCriteria?.StatusCodes,P=We(C);if(Qo(P),C?.Quantity!==void 0&&C.Quantity!==P.length)throw Error(`CloudFront origin failover: ${y} FailoverCriteria.StatusCodes.Quantity is ${C.Quantity} but it lists ${P.length} code(s).`);if(nn(p.SelectionCriteria,y),p.SelectionCriteria==="media-quality-based")for(let E of S){let v=E?ae(s.get(E)):void 0;if(v&&!Er.test(v))throw Error(`CloudFront origin failover: ${y} uses media-quality-based selection, which only works between AWS Elemental MediaPackage v2 origins, but member "${E}" is ${v}. Use 'default'.`)}}let m=[];if(e.DefaultCacheBehavior)m.push({behavior:e.DefaultCacheBehavior,name:"the default cache behavior"});for(let p of We(e.CacheBehaviors))m.push({behavior:p,name:`the cache behavior for ${JSON.stringify(p.PathPattern)}`});for(let{behavior:p,name:g}of m){let y=ae(p.TargetOriginId);if(!y)continue;if(d.has(y))An(p.AllowedMethods??["GET","HEAD"],`${g} of ${n} (origin group "${y}")`);else if(!i.has(y)&&!a&&u.every((f)=>ae(f.Id)!==void 0))throw Error(`CloudFront: ${g} of ${n} targets "${y}", which is neither an origin nor an origin group of this distribution.`)}}class Ge{static createDistribution(e){let{slug:n,environment:r,origin:i,customDomain:s,certificateArn:a,errorPages:c,cachePolicy:u,edgeFunctions:d,http3:m=!1,comment:p,failoverOrigin:g}=e,y=l({slug:n,environment:r,resourceType:"cdn"}),f=o(y),h={Id:"DefaultOrigin",DomainName:i.domainName,OriginPath:i.originPath||"",...st(i,"the CDN origin")},S;if(i.type==="s3"){let P=`${f}OAC`;S={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`${y}-oac`,Description:`Origin Access Control for ${y}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},h.OriginAccessControlId=R.Ref(P)}else if(i.type==="alb"||i.type==="custom")h.CustomOriginConfig={HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only"};let C={Type:"AWS::CloudFront::Distribution",Properties:{DistributionConfig:{Enabled:!0,Comment:p||`CDN for ${y}`,DefaultRootObject:"index.html",Origins:[h],DefaultCacheBehavior:{TargetOriginId:"DefaultOrigin",ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0},PriceClass:"PriceClass_100",HttpVersion:m?"http2and3":"http2"}}};if(s&&a)C.Properties.DistributionConfig.Aliases=[s],C.Properties.DistributionConfig.ViewerCertificate={AcmCertificateArn:a,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};if(c&&c.length>0)C.Properties.DistributionConfig.CustomErrorResponses=c.map((P)=>({ErrorCode:P.errorCode,ResponseCode:P.responseCode,ResponsePagePath:P.responsePagePath}));if(d&&d.length>0)C.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations=d.map((P)=>({EventType:P.event,LambdaFunctionARN:P.functionArn}));if(g)Ge.addOriginFailover(C,g);return{distribution:C,originAccessControl:S,logicalId:f}}static addOriginFailover(e,n){let r=e.Properties.DistributionConfig,i=r.DefaultCacheBehavior,s=i.TargetOriginId,a=n.id??"FailoverOrigin";if(r.OriginGroups&&r.OriginGroups.Quantity>0)throw Error("CloudFront origin failover: this distribution already has an origin group");if(An(i.AllowedMethods??["GET","HEAD"],"the default cache behavior"),r.Origins.some((p)=>p.Id===a))throw Error(`CloudFront origin failover: an origin with id "${a}" already exists`);let c=va({primaryOriginId:s,secondaryOriginId:a,statusCodes:n.statusCodes,selectionCriteria:n.selectionCriteria}),u=n.type??(Fi(n.domainName)?"s3":"custom"),d={Id:a,DomainName:n.domainName,OriginPath:n.originPath||"",...st(n,"the failover origin")},m=st(n.primary,"the primary origin");if(Object.keys(m).length>0){let p=r.Origins.find((g)=>g.Id===s);if(p)Object.assign(p,m)}if(u==="s3"){let p=r.Origins.find((g)=>g.Id===s);if(d.S3OriginConfig={OriginAccessIdentity:""},p?.OriginAccessControlId)d.OriginAccessControlId=p.OriginAccessControlId}else d.CustomOriginConfig={HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only"};return r.Origins.push(d),r.OriginGroups={Quantity:1,Items:[c]},i.TargetOriginId=c.Id,Rn(r),e}static setCustomDomain(e,n,r){return e.Properties.DistributionConfig.Aliases=[n],e.Properties.DistributionConfig.ViewerCertificate={AcmCertificateArn:r,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"},e}static setErrorPages(e,n){return e.Properties.DistributionConfig.CustomErrorResponses=n.map((r)=>({ErrorCode:r.errorCode,ResponseCode:r.responseCode,ResponsePagePath:r.responsePagePath})),e}static enableHttp3(e){return e.Properties.DistributionConfig.HttpVersion="http2and3",e}static addEdgeFunction(e,n,r){if(!e.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations)e.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations=[];return e.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations.push({EventType:n,LambdaFunctionARN:r}),e}static setCachePolicy(e,n){return e.Properties.DistributionConfig.Comment=`${e.Properties.DistributionConfig.Comment||""} (TTL: ${n.default||86400}s)`,e}static createSpaDistribution(e){return Ge.createDistribution({...e,errorPages:[{errorCode:404,responseCode:200,responsePagePath:"/index.html"},{errorCode:403,responseCode:200,responsePagePath:"/index.html"}]})}static createDocsOriginRequestFunction(e){let{slug:n,environment:r}=e,i=l({slug:n,environment:r,resourceType:"edge-docs"}),s=o(i),a=o(`${i}-role`),c=o(`${i}-version`),u={Type:"AWS::IAM::Role",Properties:{RoleName:`${i}-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"]}},d=`
|
|
95
95
|
'use strict';
|
|
96
96
|
|
|
97
97
|
exports.handler = async (event) => {
|
|
@@ -1345,7 +1345,7 @@ catch (error) {
|
|
|
1345
1345
|
};
|
|
1346
1346
|
}
|
|
1347
1347
|
};
|
|
1348
|
-
`;var
|
|
1348
|
+
`;var rn=`
|
|
1349
1349
|
const { SNSClient, PublishCommand } = require('@aws-sdk/client-sns');
|
|
1350
1350
|
const { DynamoDBClient, UpdateItemCommand } = require('@aws-sdk/client-dynamodb');
|
|
1351
1351
|
|
|
@@ -1452,7 +1452,7 @@ catch (error) {
|
|
|
1452
1452
|
};
|
|
1453
1453
|
}
|
|
1454
1454
|
};
|
|
1455
|
-
`;var
|
|
1455
|
+
`;var sn=`
|
|
1456
1456
|
const { S3Client, GetObjectCommand, PutObjectCommand } = require('@aws-sdk/client-s3');
|
|
1457
1457
|
const { TranscribeClient, StartTranscriptionJobCommand, GetTranscriptionJobCommand } = require('@aws-sdk/client-transcribe');
|
|
1458
1458
|
const { SNSClient, PublishCommand } = require('@aws-sdk/client-sns');
|
|
@@ -1623,7 +1623,7 @@ catch (error) {
|
|
|
1623
1623
|
|
|
1624
1624
|
return { statusCode: 200, body: 'OK' };
|
|
1625
1625
|
};
|
|
1626
|
-
`;class Dt{static LambdaCode={incomingCall:yt,voicemail:an,missedCall:sn};static createConnectInstance(e){let{slug:n,environment:r,instanceAlias:i,inboundCallsEnabled:s=!0,outboundCallsEnabled:a=!0}=e;return{[`${n}ConnectInstance`]:{Type:"AWS::Connect::Instance",Properties:{InstanceAlias:i,IdentityManagementType:"CONNECT_MANAGED",Attributes:{InboundCalls:s,OutboundCalls:a,ContactflowLogs:!0,ContactLens:!0,AutoResolveBestVoices:!0,UseCustomTTSVoices:!1,EarlyMedia:!0}}}}}static createHoursOfOperation(e){return{[`${e.slug}HoursOfOperation`]:{Type:"AWS::Connect::HoursOfOperation",Properties:{InstanceArn:e.instanceArn,Name:e.name,TimeZone:e.timezone,Config:e.schedule.map((n)=>({Day:n.day,StartTime:{Hours:n.startHour,Minutes:n.startMinute},EndTime:{Hours:n.endHour,Minutes:n.endMinute}}))}}}}static createQueue(e){return{[`${e.slug}Queue`]:{Type:"AWS::Connect::Queue",Properties:{InstanceArn:e.instanceArn,Name:e.name,HoursOfOperationArn:e.hoursOfOperationArn,MaxContacts:e.maxContacts||10}}}}static createContactFlow(e){return{[`${e.slug}ContactFlow`]:{Type:"AWS::Connect::ContactFlow",Properties:{InstanceArn:e.instanceArn,Name:e.name,Type:e.type,Content:e.content}}}}static createBasicIvrFlow(e){let n={Version:"2019-10-30",StartAction:"greeting",Actions:[{Identifier:"greeting",Type:"MessageParticipant",Parameters:{Text:e.greeting},Transitions:{NextAction:"transfer_to_queue",Errors:[{NextAction:"disconnect"}]}},{Identifier:"transfer_to_queue",Type:"TransferToQueue",Parameters:{QueueId:e.queueArn},Transitions:{NextAction:e.voicemailLambdaArn?"voicemail":"disconnect",Errors:[{NextAction:"disconnect"}]}},...e.voicemailLambdaArn?[{Identifier:"voicemail",Type:"InvokeLambdaFunction",Parameters:{LambdaFunctionARN:e.voicemailLambdaArn},Transitions:{NextAction:"disconnect",Errors:[{NextAction:"disconnect"}]}}]:[],{Identifier:"disconnect",Type:"DisconnectParticipant",Parameters:{},Transitions:{}}]};return JSON.stringify(n)}static createPhoneLambdaRole(e){return{[`${e.slug}PhoneLambdaRole`]:{Type:"AWS::IAM::Role",Properties:{RoleName:`${e.slug}-phone-lambda-role`,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"],Policies:[{PolicyName:"PhoneLambdaPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["dynamodb:PutItem","dynamodb:UpdateItem","dynamodb:GetItem"],Resource:"*"},{Effect:"Allow",Action:["sns:Publish"],Resource:"*"},{Effect:"Allow",Action:["s3:GetObject","s3:PutObject"],Resource:"*"},{Effect:"Allow",Action:["transcribe:StartTranscriptionJob","transcribe:GetTranscriptionJob"],Resource:"*"},{Effect:"Allow",Action:["connect:*"],Resource:"*"}]}}]}}}}static createIncomingCallLambda(e){return{[`${e.slug}IncomingCallLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${e.slug}-incoming-call`,Runtime:"nodejs20.x",Handler:"index.handler",Role:e.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:Dt.LambdaCode.incomingCall},Environment:{Variables:{NOTIFICATION_TOPIC_ARN:e.notificationTopicArn||"",CALL_LOG_TABLE:e.callLogTable||"",WEBHOOK_URL:e.webhookUrl||""}}}}}}static createVoicemailLambda(e){return{[`${e.slug}VoicemailLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${e.slug}-voicemail`,Runtime:"nodejs20.x",Handler:"index.handler",Role:e.roleArn,Timeout:300,MemorySize:512,Code:{ZipFile:Dt.LambdaCode.voicemail},Environment:{Variables:{VOICEMAIL_BUCKET:e.voicemailBucket,NOTIFICATION_TOPIC_ARN:e.notificationTopicArn||"",CALL_LOG_TABLE:e.callLogTable||"",TRANSCRIPTION_ENABLED:e.transcriptionEnabled?"true":"false"}}}}}}static createMissedCallLambda(e){return{[`${e.slug}MissedCallLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${e.slug}-missed-call`,Runtime:"nodejs20.x",Handler:"index.handler",Role:e.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:Dt.LambdaCode.missedCall},Environment:{Variables:{NOTIFICATION_TOPIC_ARN:e.notificationTopicArn||"",CALL_LOG_TABLE:e.callLogTable||"",WEBHOOK_URL:e.webhookUrl||""}}}}}}static createCallLogTable(e){return{[`${e.slug}CallLogTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${e.slug}-call-log`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"contactId",AttributeType:"S"}],KeySchema:[{AttributeName:"contactId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createCompleteSetup(e){let n={},r={};Object.assign(n,Dt.createPhoneLambdaRole({slug:e.slug})),Object.assign(n,Dt.createCallLogTable({slug:e.slug})),n[`${e.slug}PhoneNotificationTopic`]={Type:"AWS::SNS::Topic",Properties:{TopicName:`${e.slug}-phone-notifications`}},n[`${e.slug}VoicemailBucket`]={Type:"AWS::S3::Bucket",Properties:{BucketName:`${e.slug}-voicemails`,LifecycleConfiguration:{Rules:[{Id:"DeleteOldVoicemails",Status:"Enabled",ExpirationInDays:90}]}}};let i={"Fn::GetAtt":[`${e.slug}PhoneLambdaRole`,"Arn"]},s={Ref:`${e.slug}PhoneNotificationTopic`},a={Ref:`${e.slug}CallLogTable`},c={Ref:`${e.slug}VoicemailBucket`};if(Object.assign(n,Dt.createIncomingCallLambda({slug:e.slug,roleArn:i,notificationTopicArn:s,callLogTable:a,webhookUrl:e.webhookUrl})),e.voicemailEnabled!==!1)Object.assign(n,Dt.createVoicemailLambda({slug:e.slug,roleArn:i,voicemailBucket:c,notificationTopicArn:s,callLogTable:a,transcriptionEnabled:e.transcriptionEnabled}));return Object.assign(n,Dt.createMissedCallLambda({slug:e.slug,roleArn:i,notificationTopicArn:s,callLogTable:a,webhookUrl:e.webhookUrl})),r[`${e.slug}PhoneNotificationTopicArn`]={Description:"Phone notification topic ARN",Value:{Ref:`${e.slug}PhoneNotificationTopic`}},r[`${e.slug}CallLogTableName`]={Description:"Call log table name",Value:{Ref:`${e.slug}CallLogTable`}},r[`${e.slug}VoicemailBucketName`]={Description:"Voicemail bucket name",Value:{Ref:`${e.slug}VoicemailBucket`}},{resources:n,outputs:r}}}class ye{static createQueue(e){let{slug:n,environment:r,name:i,delaySeconds:s=0,visibilityTimeout:a=30,messageRetentionPeriod:c=345600,maxMessageSize:u=262144,receiveMessageWaitTime:d=0,fifo:m=!1,contentBasedDeduplication:p=!1,encrypted:g=!0,kmsKeyId:y}=e,f=i||l({slug:n,environment:r,resourceType:"queue"}),h=m?`${f}.fifo`:f,S=o(f),C={Type:"AWS::SQS::Queue",Properties:{QueueName:h,DelaySeconds:s,MaximumMessageSize:u,MessageRetentionPeriod:c,ReceiveMessageWaitTimeSeconds:d,VisibilityTimeout:a,Tags:[{Key:"Name",Value:h},{Key:"Environment",Value:r}]}};if(m)C.Properties.FifoQueue=!0,C.Properties.ContentBasedDeduplication=p;if(g)if(y)C.Properties.KmsMasterKeyId=y;else C.Properties.SqsManagedSseEnabled=!0;return{queue:C,logicalId:S}}static createDeadLetterQueue(e,n){let{slug:r,environment:i,maxReceiveCount:s=3}=n,a=l({slug:r,environment:i,resourceType:"dlq"}),c=o(a),u={Type:"AWS::SQS::Queue",Properties:{QueueName:a,MessageRetentionPeriod:1209600,Tags:[{Key:"Name",Value:a},{Key:"Environment",Value:i},{Key:"Type",Value:"DeadLetterQueue"}]}},d={Type:"AWS::SQS::Queue",Properties:{RedrivePolicy:{deadLetterTargetArn:R.GetAtt(c,"Arn"),maxReceiveCount:s}}};return{deadLetterQueue:u,updatedSourceQueue:d,deadLetterLogicalId:c}}static createSchedule(e,n){let{slug:r,environment:i,name:s,description:a,enabled:c=!0}=n,u=s||l({slug:r,environment:i,resourceType:"schedule"}),d=o(u);return{rule:{Type:"AWS::Events::Rule",Properties:{Name:u,Description:a,ScheduleExpression:e,State:c?"ENABLED":"DISABLED",Targets:[]}},logicalId:d}}static scheduleEcsTask(e,n,r){let{slug:i,environment:s,name:a,description:c,enabled:u=!0,taskDefinitionArn:d,clusterArn:m,subnets:p,securityGroups:g=[],assignPublicIp:y=!1,taskCount:f=1,containerOverrides:h}=r,S=a||l({slug:i,environment:s,resourceType:"ecs-schedule"}),C=o(S),E={Id:"1",Arn:m,RoleArn:n,EcsParameters:{TaskDefinitionArn:d,TaskCount:f,LaunchType:"FARGATE",NetworkConfiguration:{awsvpcConfiguration:{Subnets:p,SecurityGroups:g,AssignPublicIp:y?"ENABLED":"DISABLED"}},PlatformVersion:"LATEST"}};if(h&&h.length>0)E.Input=JSON.stringify({containerOverrides:h});return{rule:{Type:"AWS::Events::Rule",Properties:{Name:S,Description:c||`Scheduled ECS task: ${d}`,ScheduleExpression:e,State:u?"ENABLED":"DISABLED",Targets:[E]}},logicalId:C}}static scheduleLambda(e,n){let{slug:r,environment:i,name:s,description:a,enabled:c=!0,functionArn:u,input:d}=n,m=s||l({slug:r,environment:i,resourceType:"lambda-schedule"}),p=o(m),g={Id:"1",Arn:u};if(d)g.Input=JSON.stringify(d);return{rule:{Type:"AWS::Events::Rule",Properties:{Name:m,Description:a||`Scheduled Lambda: ${u}`,ScheduleExpression:e,State:c?"ENABLED":"DISABLED",Targets:[g]}},logicalId:p}}static scheduleSqsMessage(e,n){let{slug:r,environment:i,name:s,description:a,enabled:c=!0,queueArn:u,messageGroupId:d}=n,m=s||l({slug:r,environment:i,resourceType:"sqs-schedule"}),p=o(m),g={Id:"1",Arn:u};if(d)g.SqsParameters={MessageGroupId:d};return{rule:{Type:"AWS::Events::Rule",Properties:{Name:m,Description:a||`Scheduled SQS message: ${u}`,ScheduleExpression:e,State:c?"ENABLED":"DISABLED",Targets:[g]}},logicalId:p}}static addTarget(e,n){if(!e.Properties.Targets)e.Properties.Targets=[];let r={Id:n.id,Arn:n.arn};if(n.roleArn)r.RoleArn=n.roleArn;if(n.input)r.Input=JSON.stringify(n.input);return e.Properties.Targets.push(r),e}static toCronExpression(e){if(e.startsWith("cron(")||e.startsWith("rate("))return e;return`cron(${e})`}static rateExpression(e,n){return`rate(${e} ${n})`}static CronExpressions={EveryMinute:"cron(* * * * ? *)",Every5Minutes:"cron(*/5 * * * ? *)",Every15Minutes:"cron(*/15 * * * ? *)",Every30Minutes:"cron(*/30 * * * ? *)",Hourly:"cron(0 * * * ? *)",Daily:"cron(0 0 * * ? *)",DailyAt9AM:"cron(0 9 * * ? *)",DailyAtMidnight:"cron(0 0 * * ? *)",Weekly:"cron(0 0 ? * SUN *)",Monthly:"cron(0 0 1 * ? *)"};static RateExpressions={Every1Minute:"rate(1 minute)",Every5Minutes:"rate(5 minutes)",Every10Minutes:"rate(10 minutes)",Every15Minutes:"rate(15 minutes)",Every30Minutes:"rate(30 minutes)",Every1Hour:"rate(1 hour)",Every6Hours:"rate(6 hours)",Every12Hours:"rate(12 hours)",Every1Day:"rate(1 day)"};static rateStringToExpression(e){let n=e.toLowerCase().trim(),r=n.match(/^every\s+(\d+)\s+(minute|minutes|hour|hours|day|days)$/i);if(r){let m=parseInt(r[1],10),p=r[2].toLowerCase(),g=p.endsWith("s")&&m===1?p.slice(0,-1):p,y=!p.endsWith("s")&&m>1?`${p}s`:p;return`rate(${m} ${m===1?g:y})`}let i=n.match(/^every\s+(minute|hour|day)$/i);if(i)return`rate(1 ${i[1]})`;let s={"every minute":"rate(1 minute)","every hour":"rate(1 hour)","every day":"rate(1 day)",hourly:"cron(0 * * * ? *)",daily:"cron(0 0 * * ? *)","daily at midnight":"cron(0 0 * * ? *)",weekly:"cron(0 0 ? * SUN *)",monthly:"cron(0 0 1 * ? *)",yearly:"cron(0 0 1 1 ? *)"};if(s[n])return s[n];let a=n.match(/^daily\s+at\s+(\d{1,2})\s*(am|pm)?$/i);if(a){let m=parseInt(a[1],10),p=a[2]?.toLowerCase();if(p==="pm"&&m!==12)m+=12;else if(p==="am"&&m===12)m=0;return`cron(0 ${m} * * ? *)`}let c=n.match(/^at\s+(\d{1,2}):(\d{2})$/i);if(c){let m=parseInt(c[1],10);return`cron(${parseInt(c[2],10)} ${m} * * ? *)`}let u={monday:"MON",tuesday:"TUE",wednesday:"WED",thursday:"THU",friday:"FRI",saturday:"SAT",sunday:"SUN"},d=n.match(/^every\s+(monday|tuesday|wednesday|thursday|friday|saturday|sunday)$/i);if(d)return`cron(0 0 ? * ${u[d[1].toLowerCase()]} *)`;return ye.toCronExpression(e)}static JobConfig={create:(e)=>{let{name:n,handler:r,retries:i=3,backoff:s="exponential",backoffDelay:a=1000,maxDelay:c=30000,timeout:u=60000,jitter:d=!0}=e;return{name:n,handler:r,retries:i,backoff:s,backoffDelay:a,maxDelay:c,timeout:u,jitter:d}},calculateDelay:(e,n)=>{let{backoff:r,backoffDelay:i,maxDelay:s,jitter:a}=n,c;switch(r){case"linear":c=i*e;break;case"exponential":c=i*2**(e-1);break;case"fixed":default:c=i}if(c=Math.min(c,s||Number.MAX_SAFE_INTEGER),a){let u=c*0.25*Math.random();c+=u}return Math.floor(c)},presets:{fastRetry:{retries:5,backoff:"exponential",backoffDelay:100,maxDelay:5000,jitter:!0},standard:{retries:3,backoff:"exponential",backoffDelay:1000,maxDelay:30000,jitter:!0},longRunning:{retries:2,backoff:"exponential",backoffDelay:5000,maxDelay:60000,timeout:300000,jitter:!0},critical:{retries:10,backoff:"exponential",backoffDelay:500,maxDelay:60000,jitter:!0},noRetry:{retries:0,backoff:"fixed",backoffDelay:0,maxDelay:0,jitter:!1}}};static createJobContainerOverride(e){let{containerName:n,jobClass:r,jobData:i,environment:s={}}=e,a=[{name:"JOB_CLASS",value:r}];if(i)a.push({name:"JOB_DATA",value:JSON.stringify(i)});for(let[c,u]of Object.entries(s))a.push({name:c,value:u});return{name:n,command:["bun","run","app/Jobs/runner.ts"],environment:a}}static createScheduledJob(e){let{slug:n,environment:r,schedule:i,jobClass:s,jobData:a,taskDefinitionArn:c,clusterArn:u,subnets:d,securityGroups:m=[],roleArn:p,containerName:g="app"}=e,y=ye.rateStringToExpression(i),f=ye.createJobContainerOverride({containerName:g,jobClass:s,jobData:a});return ye.scheduleEcsTask(y,p,{slug:n,environment:r,name:`${n}-${s.toLowerCase().replace(/[^a-z0-9]/g,"-")}`,description:`Scheduled job: ${s}`,taskDefinitionArn:c,clusterArn:u,subnets:d,securityGroups:m,containerOverrides:[f]})}static QueuePresets={highThroughput:(e,n)=>ye.createQueue({slug:e,environment:n,visibilityTimeout:30,receiveMessageWaitTime:0,delaySeconds:0}),longRunning:(e,n)=>ye.createQueue({slug:e,environment:n,visibilityTimeout:300,messageRetentionPeriod:1209600}),fifo:(e,n)=>ye.createQueue({slug:e,environment:n,fifo:!0,contentBasedDeduplication:!0}),delayed:(e,n,r=60)=>ye.createQueue({slug:e,environment:n,delaySeconds:r})}}class Xt{static async discoverJobs(e){let{projectRoot:n,jobsPath:r="app/Jobs"}=e,i=`${n}/${r}`,s=[];try{let a=await import("node:fs"),c=await import("node:path");if(!a.existsSync(i))return[];let u=a.readdirSync(i).filter((d)=>d.endsWith(".ts")&&!d.startsWith("_")&&d!=="runner.ts");for(let d of u){let m=c.join(i,d),p=d.replace(".ts",""),g=a.readFileSync(m,"utf-8"),y=Xt.parseJobMetadata(g,p,m);if(y)s.push(y)}}catch{return[]}return s}static parseJobMetadata(e,n,r){let i=e.match(/export\s + const\s + schedule\s*=\s*['"`]([^'"`]+)['"`]/)||e.match(/schedule:\s*['"`]([^'"`]+)['"`]/),s=e.match(/export\s+const\s+enabled\s*=\s*(true|false)/)||e.match(/enabled:\s*(true|false)/),a=e.match(/export\s+const\s+retries\s*=\s*(\d+)/)||e.match(/retries:\s*(\d+)/),c=e.match(/export\s+const\s+timeout\s*=\s*(\d+)/)||e.match(/timeout:\s*(\d+)/),u=e.match(/export\s+const\s+backoff\s*=\s*['"`](linear|exponential|fixed)['"`]/)||e.match(/backoff:\s*['"`](linear|exponential|fixed)['"`]/),d=e.match(/export\s + const\s + description\s*=\s*['"`]([^'"`]+)['"`]/)||e.match(/description:\s*['"`]([^'"`]+)['"`]/);if(!(e.includes("export async function handle")||e.includes("export function handle")||e.includes("export default")))return null;return{name:n,path:r,schedule:i?.[1],handler:`${n}.handle`,enabled:s?.[1]!=="false",retries:a?parseInt(a[1],10):void 0,backoff:u?.[1],timeout:c?parseInt(c[1],10):void 0,description:d?.[1]}}static async discoverActions(e){let{projectRoot:n,actionsPath:r="app/Actions"}=e,i=`${n}/${r}`,s=[];try{let a=await import("node:fs"),c=await import("node:path");if(!a.existsSync(i))return[];let u=a.readdirSync(i).filter((d)=>d.endsWith(".ts")&&!d.startsWith("_"));for(let d of u){let m=c.join(i,d),p=d.replace(".ts",""),g=a.readFileSync(m,"utf-8"),y=Xt.parseActionMetadata(g,p,m);if(y)s.push(y)}}catch{return[]}return s}static parseActionMetadata(e,n,r){if(!(e.includes("export async function handle")||e.includes("export function handle")||e.includes("export default")))return null;let s=e.match(/export\s + const\s + description\s*=\s*['"`]([^'"`]+)['"`]/)||e.match(/description:\s*['"`]([^'"`]+)['"`]/);return{name:n,path:r,handler:`${n}.handle`,description:s?.[1]}}static generateScheduledJobResources(e){let{slug:n,environment:r,jobs:i,taskDefinitionArn:s,clusterArn:a,subnets:c,securityGroups:u=[],roleArn:d,containerName:m="app"}=e,p={},g=0;for(let y of i){if(!y.schedule||!y.enabled)continue;let{rule:f,logicalId:h}=ye.createScheduledJob({slug:n,environment:r,schedule:y.schedule,jobClass:y.name,taskDefinitionArn:s,clusterArn:a,subnets:c,securityGroups:u,roleArn:d,containerName:m});p[h]=f,g++}return{rules:p,count:g}}static generateJobRunnerScript(){return`#!/usr/bin/env bun
|
|
1626
|
+
`;class kt{static LambdaCode={incomingCall:yt,voicemail:sn,missedCall:rn};static createConnectInstance(e){let{slug:n,environment:r,instanceAlias:i,inboundCallsEnabled:s=!0,outboundCallsEnabled:a=!0}=e;return{[`${n}ConnectInstance`]:{Type:"AWS::Connect::Instance",Properties:{InstanceAlias:i,IdentityManagementType:"CONNECT_MANAGED",Attributes:{InboundCalls:s,OutboundCalls:a,ContactflowLogs:!0,ContactLens:!0,AutoResolveBestVoices:!0,UseCustomTTSVoices:!1,EarlyMedia:!0}}}}}static createHoursOfOperation(e){return{[`${e.slug}HoursOfOperation`]:{Type:"AWS::Connect::HoursOfOperation",Properties:{InstanceArn:e.instanceArn,Name:e.name,TimeZone:e.timezone,Config:e.schedule.map((n)=>({Day:n.day,StartTime:{Hours:n.startHour,Minutes:n.startMinute},EndTime:{Hours:n.endHour,Minutes:n.endMinute}}))}}}}static createQueue(e){return{[`${e.slug}Queue`]:{Type:"AWS::Connect::Queue",Properties:{InstanceArn:e.instanceArn,Name:e.name,HoursOfOperationArn:e.hoursOfOperationArn,MaxContacts:e.maxContacts||10}}}}static createContactFlow(e){return{[`${e.slug}ContactFlow`]:{Type:"AWS::Connect::ContactFlow",Properties:{InstanceArn:e.instanceArn,Name:e.name,Type:e.type,Content:e.content}}}}static createBasicIvrFlow(e){let n={Version:"2019-10-30",StartAction:"greeting",Actions:[{Identifier:"greeting",Type:"MessageParticipant",Parameters:{Text:e.greeting},Transitions:{NextAction:"transfer_to_queue",Errors:[{NextAction:"disconnect"}]}},{Identifier:"transfer_to_queue",Type:"TransferToQueue",Parameters:{QueueId:e.queueArn},Transitions:{NextAction:e.voicemailLambdaArn?"voicemail":"disconnect",Errors:[{NextAction:"disconnect"}]}},...e.voicemailLambdaArn?[{Identifier:"voicemail",Type:"InvokeLambdaFunction",Parameters:{LambdaFunctionARN:e.voicemailLambdaArn},Transitions:{NextAction:"disconnect",Errors:[{NextAction:"disconnect"}]}}]:[],{Identifier:"disconnect",Type:"DisconnectParticipant",Parameters:{},Transitions:{}}]};return JSON.stringify(n)}static createPhoneLambdaRole(e){return{[`${e.slug}PhoneLambdaRole`]:{Type:"AWS::IAM::Role",Properties:{RoleName:`${e.slug}-phone-lambda-role`,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"],Policies:[{PolicyName:"PhoneLambdaPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["dynamodb:PutItem","dynamodb:UpdateItem","dynamodb:GetItem"],Resource:"*"},{Effect:"Allow",Action:["sns:Publish"],Resource:"*"},{Effect:"Allow",Action:["s3:GetObject","s3:PutObject"],Resource:"*"},{Effect:"Allow",Action:["transcribe:StartTranscriptionJob","transcribe:GetTranscriptionJob"],Resource:"*"},{Effect:"Allow",Action:["connect:*"],Resource:"*"}]}}]}}}}static createIncomingCallLambda(e){return{[`${e.slug}IncomingCallLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${e.slug}-incoming-call`,Runtime:"nodejs20.x",Handler:"index.handler",Role:e.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:kt.LambdaCode.incomingCall},Environment:{Variables:{NOTIFICATION_TOPIC_ARN:e.notificationTopicArn||"",CALL_LOG_TABLE:e.callLogTable||"",WEBHOOK_URL:e.webhookUrl||""}}}}}}static createVoicemailLambda(e){return{[`${e.slug}VoicemailLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${e.slug}-voicemail`,Runtime:"nodejs20.x",Handler:"index.handler",Role:e.roleArn,Timeout:300,MemorySize:512,Code:{ZipFile:kt.LambdaCode.voicemail},Environment:{Variables:{VOICEMAIL_BUCKET:e.voicemailBucket,NOTIFICATION_TOPIC_ARN:e.notificationTopicArn||"",CALL_LOG_TABLE:e.callLogTable||"",TRANSCRIPTION_ENABLED:e.transcriptionEnabled?"true":"false"}}}}}}static createMissedCallLambda(e){return{[`${e.slug}MissedCallLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${e.slug}-missed-call`,Runtime:"nodejs20.x",Handler:"index.handler",Role:e.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:kt.LambdaCode.missedCall},Environment:{Variables:{NOTIFICATION_TOPIC_ARN:e.notificationTopicArn||"",CALL_LOG_TABLE:e.callLogTable||"",WEBHOOK_URL:e.webhookUrl||""}}}}}}static createCallLogTable(e){return{[`${e.slug}CallLogTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${e.slug}-call-log`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"contactId",AttributeType:"S"}],KeySchema:[{AttributeName:"contactId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createCompleteSetup(e){let n={},r={};Object.assign(n,kt.createPhoneLambdaRole({slug:e.slug})),Object.assign(n,kt.createCallLogTable({slug:e.slug})),n[`${e.slug}PhoneNotificationTopic`]={Type:"AWS::SNS::Topic",Properties:{TopicName:`${e.slug}-phone-notifications`}},n[`${e.slug}VoicemailBucket`]={Type:"AWS::S3::Bucket",Properties:{BucketName:`${e.slug}-voicemails`,LifecycleConfiguration:{Rules:[{Id:"DeleteOldVoicemails",Status:"Enabled",ExpirationInDays:90}]}}};let i={"Fn::GetAtt":[`${e.slug}PhoneLambdaRole`,"Arn"]},s={Ref:`${e.slug}PhoneNotificationTopic`},a={Ref:`${e.slug}CallLogTable`},c={Ref:`${e.slug}VoicemailBucket`};if(Object.assign(n,kt.createIncomingCallLambda({slug:e.slug,roleArn:i,notificationTopicArn:s,callLogTable:a,webhookUrl:e.webhookUrl})),e.voicemailEnabled!==!1)Object.assign(n,kt.createVoicemailLambda({slug:e.slug,roleArn:i,voicemailBucket:c,notificationTopicArn:s,callLogTable:a,transcriptionEnabled:e.transcriptionEnabled}));return Object.assign(n,kt.createMissedCallLambda({slug:e.slug,roleArn:i,notificationTopicArn:s,callLogTable:a,webhookUrl:e.webhookUrl})),r[`${e.slug}PhoneNotificationTopicArn`]={Description:"Phone notification topic ARN",Value:{Ref:`${e.slug}PhoneNotificationTopic`}},r[`${e.slug}CallLogTableName`]={Description:"Call log table name",Value:{Ref:`${e.slug}CallLogTable`}},r[`${e.slug}VoicemailBucketName`]={Description:"Voicemail bucket name",Value:{Ref:`${e.slug}VoicemailBucket`}},{resources:n,outputs:r}}}class ye{static createQueue(e){let{slug:n,environment:r,name:i,delaySeconds:s=0,visibilityTimeout:a=30,messageRetentionPeriod:c=345600,maxMessageSize:u=262144,receiveMessageWaitTime:d=0,fifo:m=!1,contentBasedDeduplication:p=!1,encrypted:g=!0,kmsKeyId:y}=e,f=i||l({slug:n,environment:r,resourceType:"queue"}),h=m?`${f}.fifo`:f,S=o(f),C={Type:"AWS::SQS::Queue",Properties:{QueueName:h,DelaySeconds:s,MaximumMessageSize:u,MessageRetentionPeriod:c,ReceiveMessageWaitTimeSeconds:d,VisibilityTimeout:a,Tags:[{Key:"Name",Value:h},{Key:"Environment",Value:r}]}};if(m)C.Properties.FifoQueue=!0,C.Properties.ContentBasedDeduplication=p;if(g)if(y)C.Properties.KmsMasterKeyId=y;else C.Properties.SqsManagedSseEnabled=!0;return{queue:C,logicalId:S}}static createDeadLetterQueue(e,n){let{slug:r,environment:i,maxReceiveCount:s=3}=n,a=l({slug:r,environment:i,resourceType:"dlq"}),c=o(a),u={Type:"AWS::SQS::Queue",Properties:{QueueName:a,MessageRetentionPeriod:1209600,Tags:[{Key:"Name",Value:a},{Key:"Environment",Value:i},{Key:"Type",Value:"DeadLetterQueue"}]}},d={Type:"AWS::SQS::Queue",Properties:{RedrivePolicy:{deadLetterTargetArn:R.GetAtt(c,"Arn"),maxReceiveCount:s}}};return{deadLetterQueue:u,updatedSourceQueue:d,deadLetterLogicalId:c}}static createSchedule(e,n){let{slug:r,environment:i,name:s,description:a,enabled:c=!0}=n,u=s||l({slug:r,environment:i,resourceType:"schedule"}),d=o(u);return{rule:{Type:"AWS::Events::Rule",Properties:{Name:u,Description:a,ScheduleExpression:e,State:c?"ENABLED":"DISABLED",Targets:[]}},logicalId:d}}static scheduleEcsTask(e,n,r){let{slug:i,environment:s,name:a,description:c,enabled:u=!0,taskDefinitionArn:d,clusterArn:m,subnets:p,securityGroups:g=[],assignPublicIp:y=!1,taskCount:f=1,containerOverrides:h}=r,S=a||l({slug:i,environment:s,resourceType:"ecs-schedule"}),C=o(S),E={Id:"1",Arn:m,RoleArn:n,EcsParameters:{TaskDefinitionArn:d,TaskCount:f,LaunchType:"FARGATE",NetworkConfiguration:{awsvpcConfiguration:{Subnets:p,SecurityGroups:g,AssignPublicIp:y?"ENABLED":"DISABLED"}},PlatformVersion:"LATEST"}};if(h&&h.length>0)E.Input=JSON.stringify({containerOverrides:h});return{rule:{Type:"AWS::Events::Rule",Properties:{Name:S,Description:c||`Scheduled ECS task: ${d}`,ScheduleExpression:e,State:u?"ENABLED":"DISABLED",Targets:[E]}},logicalId:C}}static scheduleLambda(e,n){let{slug:r,environment:i,name:s,description:a,enabled:c=!0,functionArn:u,input:d}=n,m=s||l({slug:r,environment:i,resourceType:"lambda-schedule"}),p=o(m),g={Id:"1",Arn:u};if(d)g.Input=JSON.stringify(d);return{rule:{Type:"AWS::Events::Rule",Properties:{Name:m,Description:a||`Scheduled Lambda: ${u}`,ScheduleExpression:e,State:c?"ENABLED":"DISABLED",Targets:[g]}},logicalId:p}}static scheduleSqsMessage(e,n){let{slug:r,environment:i,name:s,description:a,enabled:c=!0,queueArn:u,messageGroupId:d}=n,m=s||l({slug:r,environment:i,resourceType:"sqs-schedule"}),p=o(m),g={Id:"1",Arn:u};if(d)g.SqsParameters={MessageGroupId:d};return{rule:{Type:"AWS::Events::Rule",Properties:{Name:m,Description:a||`Scheduled SQS message: ${u}`,ScheduleExpression:e,State:c?"ENABLED":"DISABLED",Targets:[g]}},logicalId:p}}static addTarget(e,n){if(!e.Properties.Targets)e.Properties.Targets=[];let r={Id:n.id,Arn:n.arn};if(n.roleArn)r.RoleArn=n.roleArn;if(n.input)r.Input=JSON.stringify(n.input);return e.Properties.Targets.push(r),e}static toCronExpression(e){if(e.startsWith("cron(")||e.startsWith("rate("))return e;return`cron(${e})`}static rateExpression(e,n){return`rate(${e} ${n})`}static CronExpressions={EveryMinute:"cron(* * * * ? *)",Every5Minutes:"cron(*/5 * * * ? *)",Every15Minutes:"cron(*/15 * * * ? *)",Every30Minutes:"cron(*/30 * * * ? *)",Hourly:"cron(0 * * * ? *)",Daily:"cron(0 0 * * ? *)",DailyAt9AM:"cron(0 9 * * ? *)",DailyAtMidnight:"cron(0 0 * * ? *)",Weekly:"cron(0 0 ? * SUN *)",Monthly:"cron(0 0 1 * ? *)"};static RateExpressions={Every1Minute:"rate(1 minute)",Every5Minutes:"rate(5 minutes)",Every10Minutes:"rate(10 minutes)",Every15Minutes:"rate(15 minutes)",Every30Minutes:"rate(30 minutes)",Every1Hour:"rate(1 hour)",Every6Hours:"rate(6 hours)",Every12Hours:"rate(12 hours)",Every1Day:"rate(1 day)"};static rateStringToExpression(e){let n=e.toLowerCase().trim(),r=n.match(/^every\s+(\d+)\s+(minute|minutes|hour|hours|day|days)$/i);if(r){let m=parseInt(r[1],10),p=r[2].toLowerCase(),g=p.endsWith("s")&&m===1?p.slice(0,-1):p,y=!p.endsWith("s")&&m>1?`${p}s`:p;return`rate(${m} ${m===1?g:y})`}let i=n.match(/^every\s+(minute|hour|day)$/i);if(i)return`rate(1 ${i[1]})`;let s={"every minute":"rate(1 minute)","every hour":"rate(1 hour)","every day":"rate(1 day)",hourly:"cron(0 * * * ? *)",daily:"cron(0 0 * * ? *)","daily at midnight":"cron(0 0 * * ? *)",weekly:"cron(0 0 ? * SUN *)",monthly:"cron(0 0 1 * ? *)",yearly:"cron(0 0 1 1 ? *)"};if(s[n])return s[n];let a=n.match(/^daily\s+at\s+(\d{1,2})\s*(am|pm)?$/i);if(a){let m=parseInt(a[1],10),p=a[2]?.toLowerCase();if(p==="pm"&&m!==12)m+=12;else if(p==="am"&&m===12)m=0;return`cron(0 ${m} * * ? *)`}let c=n.match(/^at\s+(\d{1,2}):(\d{2})$/i);if(c){let m=parseInt(c[1],10);return`cron(${parseInt(c[2],10)} ${m} * * ? *)`}let u={monday:"MON",tuesday:"TUE",wednesday:"WED",thursday:"THU",friday:"FRI",saturday:"SAT",sunday:"SUN"},d=n.match(/^every\s+(monday|tuesday|wednesday|thursday|friday|saturday|sunday)$/i);if(d)return`cron(0 0 ? * ${u[d[1].toLowerCase()]} *)`;return ye.toCronExpression(e)}static JobConfig={create:(e)=>{let{name:n,handler:r,retries:i=3,backoff:s="exponential",backoffDelay:a=1000,maxDelay:c=30000,timeout:u=60000,jitter:d=!0}=e;return{name:n,handler:r,retries:i,backoff:s,backoffDelay:a,maxDelay:c,timeout:u,jitter:d}},calculateDelay:(e,n)=>{let{backoff:r,backoffDelay:i,maxDelay:s,jitter:a}=n,c;switch(r){case"linear":c=i*e;break;case"exponential":c=i*2**(e-1);break;case"fixed":default:c=i}if(c=Math.min(c,s||Number.MAX_SAFE_INTEGER),a){let u=c*0.25*Math.random();c+=u}return Math.floor(c)},presets:{fastRetry:{retries:5,backoff:"exponential",backoffDelay:100,maxDelay:5000,jitter:!0},standard:{retries:3,backoff:"exponential",backoffDelay:1000,maxDelay:30000,jitter:!0},longRunning:{retries:2,backoff:"exponential",backoffDelay:5000,maxDelay:60000,timeout:300000,jitter:!0},critical:{retries:10,backoff:"exponential",backoffDelay:500,maxDelay:60000,jitter:!0},noRetry:{retries:0,backoff:"fixed",backoffDelay:0,maxDelay:0,jitter:!1}}};static createJobContainerOverride(e){let{containerName:n,jobClass:r,jobData:i,environment:s={}}=e,a=[{name:"JOB_CLASS",value:r}];if(i)a.push({name:"JOB_DATA",value:JSON.stringify(i)});for(let[c,u]of Object.entries(s))a.push({name:c,value:u});return{name:n,command:["bun","run","app/Jobs/runner.ts"],environment:a}}static createScheduledJob(e){let{slug:n,environment:r,schedule:i,jobClass:s,jobData:a,taskDefinitionArn:c,clusterArn:u,subnets:d,securityGroups:m=[],roleArn:p,containerName:g="app"}=e,y=ye.rateStringToExpression(i),f=ye.createJobContainerOverride({containerName:g,jobClass:s,jobData:a});return ye.scheduleEcsTask(y,p,{slug:n,environment:r,name:`${n}-${s.toLowerCase().replace(/[^a-z0-9]/g,"-")}`,description:`Scheduled job: ${s}`,taskDefinitionArn:c,clusterArn:u,subnets:d,securityGroups:m,containerOverrides:[f]})}static QueuePresets={highThroughput:(e,n)=>ye.createQueue({slug:e,environment:n,visibilityTimeout:30,receiveMessageWaitTime:0,delaySeconds:0}),longRunning:(e,n)=>ye.createQueue({slug:e,environment:n,visibilityTimeout:300,messageRetentionPeriod:1209600}),fifo:(e,n)=>ye.createQueue({slug:e,environment:n,fifo:!0,contentBasedDeduplication:!0}),delayed:(e,n,r=60)=>ye.createQueue({slug:e,environment:n,delaySeconds:r})}}class Qt{static async discoverJobs(e){let{projectRoot:n,jobsPath:r="app/Jobs"}=e,i=`${n}/${r}`,s=[];try{let a=await import("node:fs"),c=await import("node:path");if(!a.existsSync(i))return[];let u=a.readdirSync(i).filter((d)=>d.endsWith(".ts")&&!d.startsWith("_")&&d!=="runner.ts");for(let d of u){let m=c.join(i,d),p=d.replace(".ts",""),g=a.readFileSync(m,"utf-8"),y=Qt.parseJobMetadata(g,p,m);if(y)s.push(y)}}catch{return[]}return s}static parseJobMetadata(e,n,r){let i=e.match(/export\s + const\s + schedule\s*=\s*['"`]([^'"`]+)['"`]/)||e.match(/schedule:\s*['"`]([^'"`]+)['"`]/),s=e.match(/export\s+const\s+enabled\s*=\s*(true|false)/)||e.match(/enabled:\s*(true|false)/),a=e.match(/export\s+const\s+retries\s*=\s*(\d+)/)||e.match(/retries:\s*(\d+)/),c=e.match(/export\s+const\s+timeout\s*=\s*(\d+)/)||e.match(/timeout:\s*(\d+)/),u=e.match(/export\s+const\s+backoff\s*=\s*['"`](linear|exponential|fixed)['"`]/)||e.match(/backoff:\s*['"`](linear|exponential|fixed)['"`]/),d=e.match(/export\s + const\s + description\s*=\s*['"`]([^'"`]+)['"`]/)||e.match(/description:\s*['"`]([^'"`]+)['"`]/);if(!(e.includes("export async function handle")||e.includes("export function handle")||e.includes("export default")))return null;return{name:n,path:r,schedule:i?.[1],handler:`${n}.handle`,enabled:s?.[1]!=="false",retries:a?parseInt(a[1],10):void 0,backoff:u?.[1],timeout:c?parseInt(c[1],10):void 0,description:d?.[1]}}static async discoverActions(e){let{projectRoot:n,actionsPath:r="app/Actions"}=e,i=`${n}/${r}`,s=[];try{let a=await import("node:fs"),c=await import("node:path");if(!a.existsSync(i))return[];let u=a.readdirSync(i).filter((d)=>d.endsWith(".ts")&&!d.startsWith("_"));for(let d of u){let m=c.join(i,d),p=d.replace(".ts",""),g=a.readFileSync(m,"utf-8"),y=Qt.parseActionMetadata(g,p,m);if(y)s.push(y)}}catch{return[]}return s}static parseActionMetadata(e,n,r){if(!(e.includes("export async function handle")||e.includes("export function handle")||e.includes("export default")))return null;let s=e.match(/export\s + const\s + description\s*=\s*['"`]([^'"`]+)['"`]/)||e.match(/description:\s*['"`]([^'"`]+)['"`]/);return{name:n,path:r,handler:`${n}.handle`,description:s?.[1]}}static generateScheduledJobResources(e){let{slug:n,environment:r,jobs:i,taskDefinitionArn:s,clusterArn:a,subnets:c,securityGroups:u=[],roleArn:d,containerName:m="app"}=e,p={},g=0;for(let y of i){if(!y.schedule||!y.enabled)continue;let{rule:f,logicalId:h}=ye.createScheduledJob({slug:n,environment:r,schedule:y.schedule,jobClass:y.name,taskDefinitionArn:s,clusterArn:a,subnets:c,securityGroups:u,roleArn:d,containerName:m});p[h]=f,g++}return{rules:p,count:g}}static generateJobRunnerScript(){return`#!/usr/bin/env bun
|
|
1627
1627
|
/**
|
|
1628
1628
|
* Job Runner Script
|
|
1629
1629
|
* This script is invoked by ECS scheduled tasks to run jobs
|
|
@@ -1668,7 +1668,7 @@ catch (error) {
|
|
|
1668
1668
|
}
|
|
1669
1669
|
|
|
1670
1670
|
run()
|
|
1671
|
-
`}static async generateJobManifest(e){let n=await
|
|
1671
|
+
`}static async generateJobManifest(e){let n=await Qt.discoverJobs(e),r=n.filter((i)=>i.schedule&&i.enabled);return{jobs:n,scheduledCount:r.length,totalCount:n.length}}}var Nm={loadJobs:Qt.discoverJobs,loadActions:Qt.discoverActions,generateScheduledJobs:Qt.generateScheduledJobResources,generateRunner:Qt.generateJobRunnerScript,paths:{jobs:"app/Jobs",actions:"app/Actions",runner:"app/Jobs/runner.ts"}};var an=`
|
|
1672
1672
|
const { DynamoDBClient, UpdateItemCommand } = require('@aws-sdk/client-dynamodb');
|
|
1673
1673
|
const { SNSClient, PublishCommand } = require('@aws-sdk/client-sns');
|
|
1674
1674
|
|
|
@@ -1791,7 +1791,7 @@ catch (error) {
|
|
|
1791
1791
|
|
|
1792
1792
|
return { statusCode: 200, body: 'OK' };
|
|
1793
1793
|
};
|
|
1794
|
-
`;var
|
|
1794
|
+
`;var on=`
|
|
1795
1795
|
const { DynamoDBClient, PutItemCommand, DeleteItemCommand } = require('@aws-sdk/client-dynamodb');
|
|
1796
1796
|
const { SNSClient, PublishCommand } = require('@aws-sdk/client-sns');
|
|
1797
1797
|
|
|
@@ -2271,14 +2271,14 @@ function resolveTemplate(template, data) {
|
|
|
2271
2271
|
}
|
|
2272
2272
|
return result;
|
|
2273
2273
|
}
|
|
2274
|
-
`;class Re{static LambdaCode={send:ft,receive:cn,deliveryStatus:on};static createPinpointApp(e){return{[`${e.slug}PinpointApp`]:{Type:"AWS::Pinpoint::App",Properties:{Name:e.name||`${e.slug}-sms`}}}}static createSmsChannel(e){let n={ApplicationId:e.applicationId,Enabled:e.enabled!==!1};if(e.senderId)n.SenderId=e.senderId;if(e.shortCode)n.ShortCode=e.shortCode;return{[`${e.slug}SmsChannel`]:{Type:"AWS::Pinpoint::SMSChannel",Properties:n}}}static createSmsLambdaRole(e){return{[`${e.slug}SmsLambdaRole`]:{Type:"AWS::IAM::Role",Properties:{RoleName:`${e.slug}-sms-lambda-role`,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"],Policies:[{PolicyName:"SmsLambdaPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["mobiletargeting:SendMessages","mobiletargeting:GetSmsChannel"],Resource:"*"},{Effect:"Allow",Action:["sns:Publish"],Resource:"*"},{Effect:"Allow",Action:["dynamodb:PutItem","dynamodb:UpdateItem","dynamodb:GetItem","dynamodb:DeleteItem"],Resource:"*"}]}}]}}}}static createSendLambda(e){return{[`${e.slug}SmsSendLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${e.slug}-sms-send`,Runtime:"nodejs20.x",Handler:"index.handler",Role:e.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:Re.LambdaCode.send},Environment:{Variables:{PINPOINT_APP_ID:e.pinpointAppId,MESSAGE_LOG_TABLE:e.messageLogTable||"",SMS_SENDER_ID:e.senderId||"",SMS_ORIGINATION_NUMBER:e.originationNumber||""}}}}}}static createReceiveLambda(e){return{[`${e.slug}SmsReceiveLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${e.slug}-sms-receive`,Runtime:"nodejs20.x",Handler:"index.handler",Role:e.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:Re.LambdaCode.receive},Environment:{Variables:{OPT_OUT_TABLE:e.optOutTable||"",MESSAGE_LOG_TABLE:e.messageLogTable||"",NOTIFICATION_TOPIC_ARN:e.notificationTopicArn||"",WEBHOOK_URL:e.webhookUrl||""}}}}}}static createDeliveryStatusLambda(e){return{[`${e.slug}SmsDeliveryStatusLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${e.slug}-sms-delivery-status`,Runtime:"nodejs20.x",Handler:"index.handler",Role:e.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:Re.LambdaCode.deliveryStatus},Environment:{Variables:{MESSAGE_LOG_TABLE:e.messageLogTable||"",NOTIFICATION_TOPIC_ARN:e.notificationTopicArn||"",WEBHOOK_URL:e.webhookUrl||""}}}}}}static createMessageLogTable(e){return{[`${e.slug}SmsMessageLogTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${e.slug}-sms-messages`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"messageId",AttributeType:"S"}],KeySchema:[{AttributeName:"messageId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createOptOutTable(e){return{[`${e.slug}SmsOptOutTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${e.slug}-sms-optouts`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"phoneNumber",AttributeType:"S"}],KeySchema:[{AttributeName:"phoneNumber",KeyType:"HASH"}]}}}}static createNotificationTopic(e){return{[`${e.slug}SmsNotificationTopic`]:{Type:"AWS::SNS::Topic",Properties:{TopicName:`${e.slug}-sms-notifications`}}}}static createCompleteSetup(e){let n={},r={};Object.assign(n,Re.createPinpointApp({slug:e.slug})),Object.assign(n,Re.createSmsChannel({slug:e.slug,applicationId:{Ref:`${e.slug}PinpointApp`},senderId:e.senderId})),Object.assign(n,Re.createSmsLambdaRole({slug:e.slug})),Object.assign(n,Re.createMessageLogTable({slug:e.slug})),Object.assign(n,Re.createOptOutTable({slug:e.slug})),Object.assign(n,Re.createNotificationTopic({slug:e.slug}));let i={"Fn::GetAtt":[`${e.slug}SmsLambdaRole`,"Arn"]},s={Ref:`${e.slug}PinpointApp`},a={Ref:`${e.slug}SmsMessageLogTable`},c={Ref:`${e.slug}SmsOptOutTable`},u={Ref:`${e.slug}SmsNotificationTopic`};if(Object.assign(n,Re.createSendLambda({slug:e.slug,roleArn:i,pinpointAppId:s,messageLogTable:a,senderId:e.senderId,originationNumber:e.originationNumber})),e.twoWayEnabled)Object.assign(n,Re.createReceiveLambda({slug:e.slug,roleArn:i,optOutTable:c,messageLogTable:a,notificationTopicArn:u,webhookUrl:e.webhookUrl}));return Object.assign(n,Re.createDeliveryStatusLambda({slug:e.slug,roleArn:i,messageLogTable:a,notificationTopicArn:u,webhookUrl:e.webhookUrl})),r[`${e.slug}PinpointAppId`]={Description:"Pinpoint application ID",Value:{Ref:`${e.slug}PinpointApp`}},r[`${e.slug}SmsSendLambdaArn`]={Description:"SMS send Lambda ARN",Value:{"Fn::GetAtt":[`${e.slug}SmsSendLambda`,"Arn"]}},r[`${e.slug}SmsNotificationTopicArn`]={Description:"SMS notification topic ARN",Value:{Ref:`${e.slug}SmsNotificationTopic`}},r[`${e.slug}SmsMessageLogTableName`]={Description:"SMS message log table name",Value:{Ref:`${e.slug}SmsMessageLogTable`}},{resources:n,outputs:r}}}function ht(e){return e.replace(/[^a-zA-Z0-9]/g," ").trim().split(/\s+/).map((i)=>i.charAt(0).toUpperCase()+i.slice(1)).join("")||"User"}function xr(e,n){let r=(e||n).replace(/^\/+|\/+$/g,"");if(!r||r.split("/").includes(".."))throw Error(`sftp: invalid homeDirectory for user ${n}`);return r}function kr(e){let n=e.storage;if(n?.type==="efs"){let i="fileSystemId"in n?n.fileSystemId:void 0;if(!i||typeof i==="string"&&!i.trim())throw Error("sftp: EFS storage requires fileSystemId, or a fileSystem name defined in infrastructure.fileSystem");return{type:"efs",fileSystemId:i,posixProfile:n.posixProfile}}let r=(n?.type==="s3"?n.bucket??e.bucket:e.bucket)?.trim();if(!r)throw Error("sftp: S3 storage requires bucket, or a storageBucket name defined in infrastructure.storage");return{type:"s3",bucket:r}}function Mr(e,n,r){let i=n.posixProfile??r;if(!i)throw Error(`sftp: user ${e} requires a posixProfile (uid/gid) on an EFS-backed server`);for(let s of[i.uid,i.gid,...i.secondaryGids??[]])if(!Number.isInteger(s)||s<0||s>4294967295)throw Error(`sftp: user ${e} has an invalid posixProfile id ${s}`);return{Uid:i.uid,Gid:i.gid,...i.secondaryGids?.length?{SecondaryGids:i.secondaryGids}:{}}}function Lr(e,n){return typeof e==="string"?`/${e}/${n}`:{"Fn::Sub":[`/\${FileSystemId}/${n}`,{FileSystemId:e}]}}function Or(e){return typeof e==="string"?{"Fn::Sub":"arn:aws:elasticfilesystem:${AWS::Region}:${AWS::AccountId}:file-system/${FileSystemId}".replace("${FileSystemId}",e)}:{"Fn::Sub":["arn:aws:elasticfilesystem:${AWS::Region}:${AWS::AccountId}:file-system/${FileSystemId}",{FileSystemId:e}]}}class ts{static create(e){let n=kr(e),r=n.type==="efs"?"EFS":"S3",i=e.endpointType??"PUBLIC";if(i==="VPC"&&(!e.endpointDetails?.vpcId||!e.endpointDetails.subnetIds.length))throw Error("sftp: VPC endpoints require endpointDetails.vpcId and at least one subnet");let s=`${ht(e.slug)}${ht(e.environment)}Sftp`,a=`${s}Server`,c={},u;if(e.logging!==!1){let d=`${s}LoggingRole`;c[d]={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"transfer.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"TransferLogging",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["logs:CreateLogGroup","logs:CreateLogStream","logs:DescribeLogStreams","logs:PutLogEvents"],Resource:"arn:aws:logs:*:*:log-group:/aws/transfer/*"}]}}]}},u={"Fn::GetAtt":[d,"Arn"]}}c[a]={Type:"AWS::Transfer::Server",Properties:{Domain:r,EndpointType:i,IdentityProviderType:"SERVICE_MANAGED",Protocols:["SFTP"],...i==="VPC"?{EndpointDetails:{VpcId:e.endpointDetails.vpcId,SubnetIds:e.endpointDetails.subnetIds,...e.endpointDetails.securityGroupIds?.length?{SecurityGroupIds:e.endpointDetails.securityGroupIds}:{},...e.endpointDetails.addressAllocationIds?.length?{AddressAllocationIds:e.endpointDetails.addressAllocationIds}:{}}}:{},...e.securityPolicyName?{SecurityPolicyName:e.securityPolicyName}:{},...u?{LoggingRole:u}:{},Tags:[{Key:"Project",Value:e.slug},{Key:"Environment",Value:e.environment},{Key:"ManagedBy",Value:"ts-cloud"}]}};for(let[d,m]of Object.entries(e.users)){if(!/^[a-zA-Z0-9_.@-]{3,100}$/.test(d))throw Error(`sftp: invalid username ${d}`);if(!m.sshPublicKeys.length)throw Error(`sftp: user ${d} requires at least one SSH public key`);let p=ht(d),g=xr(m.homeDirectory,d),y=`${s}${p}User`,f=m.roleArn;if(!f){let h=`${s}${p}Role`,S;if(n.type==="efs")S=[{Effect:"Allow",Action:["elasticfilesystem:ClientMount","elasticfilesystem:ClientWrite","elasticfilesystem:DescribeMountTargets"],Resource:Or(n.fileSystemId)}];else{let C=`arn:aws:s3:::${n.bucket}`;S=[{Effect:"Allow",Action:["s3:ListBucket","s3:GetBucketLocation"],Resource:C,Condition:{StringLike:{"s3:prefix":[g,`${g}/*`]}}},{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:GetObjectVersion"],Resource:`${C}/${g}/*`}]}c[h]={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"transfer.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"SftpHomeDirectory",PolicyDocument:{Version:"2012-10-17",Statement:S}}]}},f={"Fn::GetAtt":[h,"Arn"]}}c[y]={Type:"AWS::Transfer::User",DependsOn:[a],Properties:{ServerId:{Ref:a},UserName:d,Role:f,HomeDirectoryType:"PATH",HomeDirectory:n.type==="efs"?Lr(n.fileSystemId,g):`/${n.bucket}/${g}`,...n.type==="efs"?{PosixProfile:Mr(d,m,n.posixProfile)}:{},SshPublicKeys:m.sshPublicKeys}}}return{resources:c,serverLogicalId:a,domain:r}}}class qe{static createBedrockRole(e,n){let{slug:r,environment:i,name:s,models:a=["*"],allowStreaming:c=!0}=n,u=s||l({slug:r,environment:i,resourceType:"bedrock-role"}),d=o(u),m=["bedrock:InvokeModel"];if(c)m.push("bedrock:InvokeModelWithResponseStream");let p=a.map((y)=>y==="*"?"arn:aws:bedrock:*::foundation-model/*":`arn:aws:bedrock:*::foundation-model/${y}`);return{role:{Type:"AWS::IAM::Role",Properties:{RoleName:u,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:e},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:`${u}-policy`,PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:m,Resource:p}]}}],Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:i}]}},logicalId:d}}static createBedrockPolicy(e){let{slug:n,environment:r,name:i,models:s=["*"],allowInvoke:a=!0,allowStreaming:c=!0,allowAsync:u=!1}=e,d=i||l({slug:n,environment:r,resourceType:"bedrock-policy"}),m=o(d),p=[];if(a)p.push("bedrock:InvokeModel");if(c)p.push("bedrock:InvokeModelWithResponseStream");if(u)p.push("bedrock:InvokeModelAsync");let g=s.map((f)=>f==="*"?"arn:aws:bedrock:*::foundation-model/*":`arn:aws:bedrock:*::foundation-model/${f}`);return{policy:{Type:"AWS::IAM::ManagedPolicy",Properties:{ManagedPolicyName:d,PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"BedrockModelInvocation",Effect:"Allow",Action:p,Resource:g}]}}},logicalId:m}}static enableBedrockForLambda(e){return qe.createBedrockRole("lambda.amazonaws.com",e)}static enableBedrockForEcs(e){return qe.createBedrockRole("ecs-tasks.amazonaws.com",e)}static enableBedrockForEc2(e){return qe.createBedrockRole("ec2.amazonaws.com",e)}static addBedrockPermissions(e,n=["*"],r=!0){let i=["bedrock:InvokeModel"];if(r)i.push("bedrock:InvokeModelWithResponseStream");let s=n.map((a)=>a==="*"?"arn:aws:bedrock:*::foundation-model/*":`arn:aws:bedrock:*::foundation-model/${a}`);if(!e.Properties.Policies)e.Properties.Policies=[];return e.Properties.Policies.push({PolicyName:"bedrock-permissions",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:i,Resource:s}]}}),e}static Models={Claude3_5_Sonnet:"anthropic.claude-3-5-sonnet-20241022-v2:0",Claude3_5_Haiku:"anthropic.claude-3-5-haiku-20241022-v1:0",Claude3_Opus:"anthropic.claude-3-opus-20240229-v1:0",Claude3_Sonnet:"anthropic.claude-3-sonnet-20240229-v1:0",Claude3_Haiku:"anthropic.claude-3-haiku-20240307-v1:0",TitanTextG1Express:"amazon.titan-text-express-v1",TitanTextG1Lite:"amazon.titan-text-lite-v1",TitanEmbedG1Text:"amazon.titan-embed-text-v1",TitanImageG1:"amazon.titan-image-generator-v1",JurassicUltra:"ai21.j2-ultra-v1",JurassicMid:"ai21.j2-mid-v1",CommandText:"cohere.command-text-v14",CommandLight:"cohere.command-light-text-v14",EmbedEnglish:"cohere.embed-english-v3",EmbedMultilingual:"cohere.embed-multilingual-v3",Llama3_2_1B:"meta.llama3-2-1b-instruct-v1:0",Llama3_2_3B:"meta.llama3-2-3b-instruct-v1:0",Llama3_2_11B:"meta.llama3-2-11b-instruct-v1:0",Llama3_2_90B:"meta.llama3-2-90b-instruct-v1:0",Llama3_1_8B:"meta.llama3-1-8b-instruct-v1:0",Llama3_1_70B:"meta.llama3-1-70b-instruct-v1:0",Llama3_1_405B:"meta.llama3-1-405b-instruct-v1:0",Mistral7B:"mistral.mistral-7b-instruct-v0:2",Mixtral8x7B:"mistral.mixtral-8x7b-instruct-v0:1",MistralLarge:"mistral.mistral-large-2402-v1:0",StableDiffusionXL:"stability.stable-diffusion-xl-v1"};static ModelGroups={AllClaude:["anthropic.claude-3-5-sonnet-20241022-v2:0","anthropic.claude-3-5-haiku-20241022-v1:0","anthropic.claude-3-opus-20240229-v1:0","anthropic.claude-3-sonnet-20240229-v1:0","anthropic.claude-3-haiku-20240307-v1:0"],AllTitan:["amazon.titan-text-express-v1","amazon.titan-text-lite-v1","amazon.titan-embed-text-v1","amazon.titan-image-generator-v1"],AllLlama:["meta.llama3-2-1b-instruct-v1:0","meta.llama3-2-3b-instruct-v1:0","meta.llama3-2-11b-instruct-v1:0","meta.llama3-2-90b-instruct-v1:0","meta.llama3-1-8b-instruct-v1:0","meta.llama3-1-70b-instruct-v1:0","meta.llama3-1-405b-instruct-v1:0"],TextModels:["anthropic.claude-3-5-sonnet-20241022-v2:0","anthropic.claude-3-5-haiku-20241022-v1:0","amazon.titan-text-express-v1","meta.llama3-2-11b-instruct-v1:0","mistral.mistral-7b-instruct-v0:2"],EmbeddingModels:["amazon.titan-embed-text-v1","cohere.embed-english-v3","cohere.embed-multilingual-v3"],ImageModels:["amazon.titan-image-generator-v1","stability.stable-diffusion-xl-v1"]}}class Qt{static createPostgres(e){return Qt.createRDSInstance("postgres","16.2",e)}static createMysql(e){return Qt.createRDSInstance("mysql","8.0.35",e)}static createRDSInstance(e,n,r){let{slug:i,environment:s,instanceClass:a="db.t3.micro",allocatedStorage:c=20,storageType:u="gp3",masterUsername:d="admin",masterPassword:m,databaseName:p,subnetIds:g,securityGroupIds:y,encrypted:f=!0,kmsKeyId:h,multiAz:S=!1,backupRetentionDays:C=7,publiclyAccessible:P=!1,enableCloudwatchLogs:E=!0,deletionProtection:v=!0}=r,w=l({slug:i,environment:s,resourceType:`${e}-db`}),D=o(w),x,L;if(g&&g.length>0){let O=l({slug:i,environment:s,resourceType:"db-subnet-group"});L=o(O),x={Type:"AWS::RDS::DBSubnetGroup",Properties:{DBSubnetGroupName:O,DBSubnetGroupDescription:`Subnet group for ${w}`,SubnetIds:g,Tags:[{Key:"Name",Value:O},{Key:"Environment",Value:s}]}}}let B={Type:"AWS::RDS::DBInstance",Properties:{DBInstanceIdentifier:w,DBInstanceClass:a,Engine:e,EngineVersion:n,MasterUsername:d,MasterUserPassword:m,AllocatedStorage:c,StorageType:u,StorageEncrypted:f,MultiAZ:S,BackupRetentionPeriod:C,PubliclyAccessible:P,DeletionProtection:v,Tags:[{Key:"Name",Value:w},{Key:"Environment",Value:s}]}};if(p)B.Properties.DBName=p;if(h)B.Properties.KmsKeyId=h;if(L)B.Properties.DBSubnetGroupName=R.Ref(L);if(y&&y.length>0)B.Properties.VPCSecurityGroups=y;if(E)B.Properties.EnableCloudwatchLogsExports=e==="postgres"?["postgresql"]:["error","general","slowquery"];return{dbInstance:B,subnetGroup:x,logicalId:D,subnetGroupId:L}}static createReadReplica(e,n){let{slug:r,environment:i,instanceClass:s="db.t3.micro",securityGroupIds:a,publiclyAccessible:c=!1}=n,u=l({slug:r,environment:i,resourceType:"db-replica"}),d=o(u),m={Type:"AWS::RDS::DBInstance",Properties:{DBInstanceIdentifier:u,DBInstanceClass:s,SourceDBInstanceIdentifier:R.Ref(e),PubliclyAccessible:c,Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:i},{Key:"Type",Value:"ReadReplica"}]}};if(a&&a.length>0)m.Properties.VPCSecurityGroups=a;return{replica:m,logicalId:d}}static createParameterGroup(e,n,r){let{slug:i,environment:s,parameters:a={}}=r,c=l({slug:i,environment:s,resourceType:"db-params"}),u=o(c),d=e==="postgres"?`postgres${n.split(".")[0]}`:`mysql${n.split(".")[0]}.${n.split(".")[1]}`;return{parameterGroup:{Type:"AWS::RDS::DBParameterGroup",Properties:{DBParameterGroupName:c,Description:`Parameter group for ${c}`,Family:d,Parameters:a,Tags:[{Key:"Name",Value:c},{Key:"Environment",Value:s}]}},logicalId:u}}static enableBackup(e,n=7){return e.Properties.BackupRetentionPeriod=n,e}static createTable(e){let{slug:n,environment:r,tableName:i,partitionKey:s,sortKey:a,billingMode:c="PAY_PER_REQUEST",readCapacity:u=5,writeCapacity:d=5,streamEnabled:m=!1,streamViewType:p="NEW_AND_OLD_IMAGES",encrypted:g=!0,kmsKeyId:y,pointInTimeRecovery:f=!0,ttlAttribute:h}=e,S=i||l({slug:n,environment:r,resourceType:"table"}),C=o(S),P=[{AttributeName:s.name,AttributeType:s.type}];if(a)P.push({AttributeName:a.name,AttributeType:a.type});let E=[{AttributeName:s.name,KeyType:"HASH"}];if(a)E.push({AttributeName:a.name,KeyType:"RANGE"});let v={Type:"AWS::DynamoDB::Table",Properties:{TableName:S,BillingMode:c,AttributeDefinitions:P,KeySchema:E,Tags:[{Key:"Name",Value:S},{Key:"Environment",Value:r}]}};if(c==="PROVISIONED")v.Properties.ProvisionedThroughput={ReadCapacityUnits:u,WriteCapacityUnits:d};if(m)v.Properties.StreamSpecification={StreamViewType:p};if(g)v.Properties.SSESpecification={SSEEnabled:!0,SSEType:y?"KMS":"AES256",KMSMasterKeyId:y};if(f)v.Properties.PointInTimeRecoverySpecification={PointInTimeRecoveryEnabled:!0};if(h)v.Properties.TimeToLiveSpecification={AttributeName:h,Enabled:!0};return{table:v,logicalId:C}}static addGlobalSecondaryIndex(e,n){let{indexName:r,partitionKey:i,sortKey:s,projectionType:a="ALL",nonKeyAttributes:c,readCapacity:u=5,writeCapacity:d=5}=n;if(!e.Properties.AttributeDefinitions.some((g)=>g.AttributeName===i.name))e.Properties.AttributeDefinitions.push({AttributeName:i.name,AttributeType:i.type});if(s&&!e.Properties.AttributeDefinitions.some((g)=>g.AttributeName===s.name))e.Properties.AttributeDefinitions.push({AttributeName:s.name,AttributeType:s.type});let m=[{AttributeName:i.name,KeyType:"HASH"}];if(s)m.push({AttributeName:s.name,KeyType:"RANGE"});let p={IndexName:r,KeySchema:m,Projection:{ProjectionType:a,NonKeyAttributes:a==="INCLUDE"?c:void 0},ProvisionedThroughput:void 0};if(e.Properties.BillingMode==="PROVISIONED")p.ProvisionedThroughput={ReadCapacityUnits:u,WriteCapacityUnits:d};if(!e.Properties.GlobalSecondaryIndexes)e.Properties.GlobalSecondaryIndexes=[];return e.Properties.GlobalSecondaryIndexes.push(p),e}static enableStreams(e,n="NEW_AND_OLD_IMAGES"){return e.Properties.StreamSpecification={StreamViewType:n},e}static InstanceClasses={T3_Micro:"db.t3.micro",T3_Small:"db.t3.small",T3_Medium:"db.t3.medium",T3_Large:"db.t3.large",T4g_Micro:"db.t4g.micro",T4g_Small:"db.t4g.small",T4g_Medium:"db.t4g.medium",M5_Large:"db.m5.large",M5_XLarge:"db.m5.xlarge",M5_2XLarge:"db.m5.2xlarge",R5_Large:"db.r5.large",R5_XLarge:"db.r5.xlarge",R5_2XLarge:"db.r5.2xlarge"}}class ji{static createRedis(e){let{slug:n,environment:r,nodeType:i="cache.t3.micro",engineVersion:s="7.1",port:a=6379,subnetIds:c,securityGroupIds:u,numCacheClusters:d=2,automaticFailover:m=!0,multiAz:p=!0,clusterMode:g=!1,numNodeGroups:y=1,replicasPerNodeGroup:f=1,atRestEncryption:h=!0,transitEncryption:S=!0,authToken:C,kmsKeyId:P,snapshotRetentionDays:E=7,snapshotWindow:v,maintenanceWindow:w}=e,D=l({slug:n,environment:r,resourceType:"redis"}),x=o(D),L,B;if(c&&c.length>0){let F=l({slug:n,environment:r,resourceType:"cache-subnet-group"});B=o(F),L={Type:"AWS::ElastiCache::SubnetGroup",Properties:{CacheSubnetGroupName:F,Description:`Subnet group for ${D}`,SubnetIds:c,Tags:[{Key:"Name",Value:F},{Key:"Environment",Value:r}]}}}let O={Type:"AWS::ElastiCache::ReplicationGroup",Properties:{ReplicationGroupId:D,ReplicationGroupDescription:`Redis cluster for ${n} ${r}`,Engine:"redis",EngineVersion:s,CacheNodeType:i,Port:a,AutomaticFailoverEnabled:m,MultiAZEnabled:p,AtRestEncryptionEnabled:h,TransitEncryptionEnabled:S,SnapshotRetentionLimit:E,AutoMinorVersionUpgrade:!0,Tags:[{Key:"Name",Value:D},{Key:"Environment",Value:r}]}};if(g)O.Properties.NumNodeGroups=y,O.Properties.ReplicasPerNodeGroup=f;else O.Properties.NumCacheClusters=d;if(C)O.Properties.AuthToken=C;if(P)O.Properties.KmsKeyId=P;if(B)O.Properties.CacheSubnetGroupName=R.Ref(B);if(u&&u.length>0)O.Properties.SecurityGroupIds=u;if(v)O.Properties.SnapshotWindow=v;if(w)O.Properties.PreferredMaintenanceWindow=w;return{replicationGroup:O,subnetGroup:L,logicalId:x,subnetGroupId:B}}static createMemcached(e){let{slug:n,environment:r,nodeType:i="cache.t3.micro",engineVersion:s="1.6.22",port:a=11211,numCacheNodes:c=2,subnetIds:u,securityGroupIds:d,azMode:m="cross-az",preferredAzs:p,maintenanceWindow:g}=e,y=l({slug:n,environment:r,resourceType:"memcached"}),f=o(y),h,S;if(u&&u.length>0){let P=l({slug:n,environment:r,resourceType:"cache-subnet-group"});S=o(P),h={Type:"AWS::ElastiCache::SubnetGroup",Properties:{CacheSubnetGroupName:P,Description:`Subnet group for ${y}`,SubnetIds:u,Tags:[{Key:"Name",Value:P},{Key:"Environment",Value:r}]}}}let C={Type:"AWS::ElastiCache::CacheCluster",Properties:{ClusterName:y,CacheNodeType:i,Engine:"memcached",EngineVersion:s,NumCacheNodes:c,Port:a,AZMode:m,AutoMinorVersionUpgrade:!0,Tags:[{Key:"Name",Value:y},{Key:"Environment",Value:r}]}};if(S)C.Properties.CacheSubnetGroupName=R.Ref(S);if(d&&d.length>0)C.Properties.VpcSecurityGroupIds=d;if(p&&p.length>0)C.Properties.PreferredAvailabilityZones=p;if(g)C.Properties.PreferredMaintenanceWindow=g;return{cluster:C,subnetGroup:h,logicalId:f,subnetGroupId:S}}static enableClusterMode(e,n=3,r=2){return delete e.Properties.NumCacheClusters,e.Properties.NumNodeGroups=n,e.Properties.ReplicasPerNodeGroup=r,e}static createRedisParameterGroup(e,n){let{slug:r,environment:i,parameters:s={}}=n,a=l({slug:r,environment:i,resourceType:"redis-params"}),c=o(a);return{parameterGroup:{Type:"AWS::ElastiCache::ParameterGroup",Properties:{CacheParameterGroupFamily:`redis${e.split(".")[0]}.x`,Description:`Parameter group for ${a}`,Properties:s,Tags:[{Key:"Name",Value:a},{Key:"Environment",Value:i}]}},logicalId:c}}static createMemcachedParameterGroup(e,n){let{slug:r,environment:i,parameters:s={}}=n,a=l({slug:r,environment:i,resourceType:"memcached-params"}),c=o(a);return{parameterGroup:{Type:"AWS::ElastiCache::ParameterGroup",Properties:{CacheParameterGroupFamily:`memcached${e.split(".")[0]}.${e.split(".")[1]}`,Description:`Parameter group for ${a}`,Properties:s,Tags:[{Key:"Name",Value:a},{Key:"Environment",Value:i}]}},logicalId:c}}static NodeTypes={T3_Micro:"cache.t3.micro",T3_Small:"cache.t3.small",T3_Medium:"cache.t3.medium",T4g_Micro:"cache.t4g.micro",T4g_Small:"cache.t4g.small",T4g_Medium:"cache.t4g.medium",M5_Large:"cache.m5.large",M5_XLarge:"cache.m5.xlarge",M5_2XLarge:"cache.m5.2xlarge",R5_Large:"cache.r5.large",R5_XLarge:"cache.r5.xlarge",R5_2XLarge:"cache.r5.2xlarge",R5_4XLarge:"cache.r5.4xlarge",R6g_Large:"cache.r6g.large",R6g_XLarge:"cache.r6g.xlarge",R6g_2XLarge:"cache.r6g.2xlarge"}}class Ie{static createUser(e){let{slug:n,environment:r,userName:i,groups:s,managedPolicyArns:a}=e,c=i||l({slug:n,environment:r,resourceType:"user"}),u=o(c),d={Type:"AWS::IAM::User",Properties:{UserName:c,Tags:[{Key:"Name",Value:c},{Key:"Environment",Value:r}]}};if(s&&s.length>0)d.Properties.Groups=s;if(a&&a.length>0)d.Properties.ManagedPolicyArns=a;return{user:d,logicalId:u}}static createRole(e){let{slug:n,environment:r,roleName:i,servicePrincipal:s,awsPrincipal:a,managedPolicyArns:c}=e,u=i||l({slug:n,environment:r,resourceType:"role"}),d=o(u),m={};if(s)m.Service=s;if(a)m.AWS=a;let p={Type:"AWS::IAM::Role",Properties:{RoleName:u,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:m,Action:"sts:AssumeRole"}]},Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:r}]}};if(c&&c.length>0)p.Properties.ManagedPolicyArns=c;return{role:p,logicalId:d}}static createGroup(e){let{slug:n,environment:r,groupName:i,managedPolicyArns:s}=e,a=i||l({slug:n,environment:r,resourceType:"group"}),c=o(a),u={Type:"AWS::IAM::Group",Properties:{GroupName:a}};if(s&&s.length>0)u.Properties.ManagedPolicyArns=s;return{group:u,logicalId:c}}static createPolicy(e){let{slug:n,environment:r,policyName:i,description:s,statements:a}=e,c=i||l({slug:n,environment:r,resourceType:"policy"}),u=o(c),d=a.map((p)=>({Sid:p.sid,Effect:p.effect||"Allow",Action:p.actions,Resource:p.resources,Condition:p.conditions}));return{policy:{Type:"AWS::IAM::ManagedPolicy",Properties:{ManagedPolicyName:c,Description:s||`Managed policy for ${c}`,PolicyDocument:{Version:"2012-10-17",Statement:d}}},logicalId:u}}static attachPolicyToRole(e,n){if(!e.Properties.ManagedPolicyArns)e.Properties.ManagedPolicyArns=[];if(!e.Properties.ManagedPolicyArns.includes(n))e.Properties.ManagedPolicyArns.push(n);return e}static attachPolicyToUser(e,n){if(!e.Properties.ManagedPolicyArns)e.Properties.ManagedPolicyArns=[];if(!e.Properties.ManagedPolicyArns.includes(n))e.Properties.ManagedPolicyArns.push(n);return e}static attachPolicyToGroup(e,n){if(!e.Properties.ManagedPolicyArns)e.Properties.ManagedPolicyArns=[];if(!e.Properties.ManagedPolicyArns.includes(n))e.Properties.ManagedPolicyArns.push(n);return e}static addInlinePolicyToRole(e,n,r){if(!e.Properties.Policies)e.Properties.Policies=[];let i=r.map((s)=>({Effect:s.effect||"Allow",Action:s.actions,Resource:s.resources}));return e.Properties.Policies.push({PolicyName:n,PolicyDocument:{Version:"2012-10-17",Statement:i}}),e}static addInlinePolicyToUser(e,n,r){if(!e.Properties.Policies)e.Properties.Policies=[];let i=r.map((s)=>({Effect:s.effect||"Allow",Action:s.actions,Resource:s.resources}));return e.Properties.Policies.push({PolicyName:n,PolicyDocument:{Version:"2012-10-17",Statement:i}}),e}static createAccessKey(e,n){let{slug:r,environment:i,status:s="Active"}=n,a=l({slug:r,environment:i,resourceType:"access-key"}),c=o(a);return{accessKey:{Type:"AWS::IAM::AccessKey",Properties:{UserName:R.Ref(e),Status:s}},logicalId:c}}static createInstanceProfile(e,n){let{slug:r,environment:i,profileName:s}=n,a=s||l({slug:r,environment:i,resourceType:"instance-profile"}),c=o(a);return{instanceProfile:{Type:"AWS::IAM::InstanceProfile",Properties:{InstanceProfileName:a,Roles:[R.Ref(e)]}},logicalId:c}}static ManagedPolicies={AdministratorAccess:"arn:aws:iam::aws:policy/AdministratorAccess",PowerUserAccess:"arn:aws:iam::aws:policy/PowerUserAccess",ReadOnlyAccess:"arn:aws:iam::aws:policy/ReadOnlyAccess",S3FullAccess:"arn:aws:iam::aws:policy/AmazonS3FullAccess",S3ReadOnlyAccess:"arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess",DynamoDBFullAccess:"arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess",DynamoDBReadOnlyAccess:"arn:aws:iam::aws:policy/AmazonDynamoDBReadOnlyAccess",RDSFullAccess:"arn:aws:iam::aws:policy/AmazonRDSFullAccess",RDSReadOnlyAccess:"arn:aws:iam::aws:policy/AmazonRDSReadOnlyAccess",LambdaFullAccess:"arn:aws:iam::aws:policy/AWSLambda_FullAccess",LambdaReadOnlyAccess:"arn:aws:iam::aws:policy/AWSLambda_ReadOnlyAccess",LambdaBasicExecutionRole:"arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole",LambdaVPCAccessExecutionRole:"arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole",EC2FullAccess:"arn:aws:iam::aws:policy/AmazonEC2FullAccess",EC2ReadOnlyAccess:"arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess",EC2ContainerRegistryReadOnly:"arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly",EC2ContainerRegistryPowerUser:"arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryPowerUser",ECSTaskExecutionRole:"arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy",ECSFullAccess:"arn:aws:iam::aws:policy/AmazonECS_FullAccess",CloudWatchFullAccess:"arn:aws:iam::aws:policy/CloudWatchFullAccess",CloudWatchLogsFullAccess:"arn:aws:iam::aws:policy/CloudWatchLogsFullAccess",SESFullAccess:"arn:aws:iam::aws:policy/AmazonSESFullAccess",SNSFullAccess:"arn:aws:iam::aws:policy/AmazonSNSFullAccess",SQSFullAccess:"arn:aws:iam::aws:policy/AmazonSQSFullAccess",SecretsManagerReadWrite:"arn:aws:iam::aws:policy/SecretsManagerReadWrite"};static ServicePrincipals={Lambda:"lambda.amazonaws.com",EC2:"ec2.amazonaws.com",ECS:"ecs.amazonaws.com",ECSTaskExecution:"ecs-tasks.amazonaws.com",APIGateway:"apigateway.amazonaws.com",Events:"events.amazonaws.com",States:"states.amazonaws.com",CodeBuild:"codebuild.amazonaws.com",CodeDeploy:"codedeploy.amazonaws.com",CloudFormation:"cloudformation.amazonaws.com"};static createCiCdUser(e){let{slug:n,environment:r,permissions:i,createAccessKey:s=!0}=e,a={},c=[];if(i.s3Buckets&&i.s3Buckets.length>0)c.push({sid:"S3Access",actions:["s3:GetBucketLocation","s3:ListBucket","s3:GetObject","s3:PutObject","s3:DeleteObject","s3:ListBucketMultipartUploads","s3:AbortMultipartUpload"],resources:[...i.s3Buckets,...i.s3Buckets.map((f)=>`${f}/*`)]});if(i.cloudFrontDistributions&&i.cloudFrontDistributions.length>0)c.push({sid:"CloudFrontAccess",actions:["cloudfront:CreateInvalidation","cloudfront:GetInvalidation","cloudfront:ListInvalidations","cloudfront:GetDistribution"],resources:i.cloudFrontDistributions});if(i.ecrRepositories&&i.ecrRepositories.length>0)c.push({sid:"ECRAccess",actions:["ecr:GetAuthorizationToken","ecr:BatchCheckLayerAvailability","ecr:GetDownloadUrlForLayer","ecr:GetRepositoryPolicy","ecr:DescribeRepositories","ecr:ListImages","ecr:DescribeImages","ecr:BatchGetImage","ecr:InitiateLayerUpload","ecr:UploadLayerPart","ecr:CompleteLayerUpload","ecr:PutImage"],resources:i.ecrRepositories}),c.push({sid:"ECRLogin",actions:["ecr:GetAuthorizationToken"],resources:"*"});if(i.ecsServices&&i.ecsServices.length>0)c.push({sid:"ECSAccess",actions:["ecs:DescribeServices","ecs:DescribeTaskDefinition","ecs:DescribeTasks","ecs:ListTasks","ecs:RegisterTaskDefinition","ecs:UpdateService","ecs:RunTask","ecs:StopTask"],resources:i.ecsServices}),c.push({sid:"ECSTaskDefinitions",actions:["ecs:RegisterTaskDefinition","ecs:DeregisterTaskDefinition"],resources:"*"}),c.push({sid:"ECSPassRole",actions:["iam:PassRole"],resources:"*",conditions:{StringLike:{"iam:PassedToService":"ecs-tasks.amazonaws.com"}}});if(i.cloudFormationStacks&&i.cloudFormationStacks.length>0)c.push({sid:"CloudFormationAccess",actions:["cloudformation:CreateStack","cloudformation:UpdateStack","cloudformation:DeleteStack","cloudformation:DescribeStacks","cloudformation:DescribeStackEvents","cloudformation:DescribeStackResources","cloudformation:GetTemplate","cloudformation:ListStackResources","cloudformation:ValidateTemplate"],resources:i.cloudFormationStacks});if(i.lambdaFunctions&&i.lambdaFunctions.length>0)c.push({sid:"LambdaAccess",actions:["lambda:GetFunction","lambda:UpdateFunctionCode","lambda:UpdateFunctionConfiguration","lambda:PublishVersion","lambda:UpdateAlias","lambda:CreateAlias"],resources:i.lambdaFunctions});if(i.secretsManagerSecrets&&i.secretsManagerSecrets.length>0)c.push({sid:"SecretsManagerAccess",actions:["secretsmanager:GetSecretValue","secretsmanager:DescribeSecret"],resources:i.secretsManagerSecrets});let{policy:u,logicalId:d}=Ie.createPolicy({slug:n,environment:r,policyName:l({slug:n,environment:r,resourceType:"cicd-policy"}),description:`CI/CD deployment policy for ${n} (${r})`,statements:c});a[d]=u;let{user:m,logicalId:p}=Ie.createUser({slug:n,environment:r,userName:l({slug:n,environment:r,resourceType:"cicd-user"}),managedPolicyArns:[R.Ref(d)]});a[p]=m;let g,y;if(s){let f=Ie.createAccessKey(p,{slug:n,environment:r});g=f.accessKey,y=f.logicalId,a[y]=g}return{user:m,accessKey:g,policy:u,userLogicalId:p,accessKeyLogicalId:y,policyLogicalId:d,resources:a}}static createCrossAccountRole(e){let{slug:n,environment:r,trustedAccountIds:i,externalId:s,permissions:a,maxSessionDuration:c=3600}=e,u={},{policy:d,logicalId:m}=Ie.createPolicy({slug:n,environment:r,policyName:l({slug:n,environment:r,resourceType:"cross-account-policy"}),description:`Cross-account access policy for ${n} (${r})`,statements:a});u[m]=d;let p=l({slug:n,environment:r,resourceType:"cross-account-role"}),g=o(p),y={};if(s)y.StringEquals={"sts:ExternalId":s};let f={Type:"AWS::IAM::Role",Properties:{RoleName:p,MaxSessionDuration:c,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:i.map((h)=>`arn:aws:iam::${h}:root`)},Action:"sts:AssumeRole",...Object.keys(y).length>0?{Condition:y}:{}}]},ManagedPolicyArns:[R.Ref(m)],Tags:[{Key:"Name",Value:p},{Key:"Environment",Value:r},{Key:"Purpose",Value:"Cross-Account Access"}]}};return u[g]=f,{role:f,policy:d,roleLogicalId:g,policyLogicalId:m,resources:u}}static createCliUser(e){let{slug:n,environment:r,permissions:i="readonly"}=e,s={},a=[],c=[];switch(i){case"readonly":c=[Ie.ManagedPolicies.ReadOnlyAccess];break;case"deploy":a=[{sid:"S3Deploy",actions:["s3:*"],resources:"*"},{sid:"CloudFrontDeploy",actions:["cloudfront:*"],resources:"*"},{sid:"ECSDeploy",actions:["ecs:*"],resources:"*"},{sid:"ECRDeploy",actions:["ecr:*"],resources:"*"},{sid:"LambdaDeploy",actions:["lambda:*"],resources:"*"},{sid:"CloudFormationDeploy",actions:["cloudformation:*"],resources:"*"},{sid:"IAMPassRole",actions:["iam:PassRole"],resources:"*"}];break;case"admin":c=[Ie.ManagedPolicies.AdministratorAccess];break}let u,d;if(a.length>0){let f=Ie.createPolicy({slug:n,environment:r,policyName:l({slug:n,environment:r,resourceType:"cli-policy"}),description:`CLI access policy for ${n} (${r})`,statements:a});u=f.policy,d=f.logicalId,s[d]=u,c=[R.Ref(d)]}let{user:m,logicalId:p}=Ie.createUser({slug:n,environment:r,userName:l({slug:n,environment:r,resourceType:"cli-user"}),managedPolicyArns:c});s[p]=m;let{accessKey:g,logicalId:y}=Ie.createAccessKey(p,{slug:n,environment:r});return s[y]=g,{user:m,accessKey:g,policy:u,userLogicalId:p,accessKeyLogicalId:y,policyLogicalId:d,resources:s}}static CiCdPolicies={s3Deployment:(e)=>[{sid:"S3ListBuckets",actions:["s3:ListBucket","s3:GetBucketLocation"],resources:e},{sid:"S3Objects",actions:["s3:GetObject","s3:PutObject","s3:DeleteObject"],resources:e.map((n)=>`${n}/*`)}],cloudFrontInvalidation:(e)=>[{sid:"CloudFrontInvalidation",actions:["cloudfront:CreateInvalidation","cloudfront:GetInvalidation","cloudfront:ListInvalidations"],resources:e}],ecsDeployment:()=>[{sid:"ECSServices",actions:["ecs:DescribeServices","ecs:UpdateService","ecs:DescribeTaskDefinition","ecs:RegisterTaskDefinition"],resources:"*"},{sid:"ECSPassRole",actions:["iam:PassRole"],resources:"*",conditions:{StringLike:{"iam:PassedToService":"ecs-tasks.amazonaws.com"}}}],ecrPush:(e)=>[{sid:"ECRAuth",actions:["ecr:GetAuthorizationToken"],resources:"*"},{sid:"ECRPush",actions:["ecr:BatchCheckLayerAvailability","ecr:GetDownloadUrlForLayer","ecr:BatchGetImage","ecr:InitiateLayerUpload","ecr:UploadLayerPart","ecr:CompleteLayerUpload","ecr:PutImage"],resources:e}],lambdaDeployment:(e)=>[{sid:"LambdaDeploy",actions:["lambda:GetFunction","lambda:UpdateFunctionCode","lambda:UpdateFunctionConfiguration","lambda:PublishVersion"],resources:e}],cloudFormationDeployment:(e)=>[{sid:"CloudFormationDeploy",actions:["cloudformation:CreateStack","cloudformation:UpdateStack","cloudformation:DescribeStacks","cloudformation:DescribeStackEvents","cloudformation:GetTemplate"],resources:e}]}}class rs{static createRestApi(e){let{slug:n,environment:r,name:i,description:s,endpointType:a="REGIONAL",binaryMediaTypes:c,compressionSize:u}=e,d=i||l({slug:n,environment:r,resourceType:"rest-api"}),m=o(d),p={Type:"AWS::ApiGateway::RestApi",Properties:{Name:d,Description:s||`REST API for ${n} ${r}`,EndpointConfiguration:{Types:[a]},Tags:[{Key:"Name",Value:d},{Key:"Environment",Value:r}]}};if(c&&c.length>0)p.Properties.BinaryMediaTypes=c;if(u!==void 0)p.Properties.MinimumCompressionSize=u;return{restApi:p,logicalId:m}}static createHttpApi(e){let{slug:n,environment:r,name:i,description:s,corsEnabled:a=!0,corsOrigins:c=["*"],corsMethods:u=["GET","POST","PUT","PATCH","DELETE","OPTIONS"],corsHeaders:d=["*"],corsMaxAge:m=86400,corsAllowCredentials:p=!1}=e,g=i||l({slug:n,environment:r,resourceType:"http-api"}),y=o(g),f={Type:"AWS::ApiGatewayV2::Api",Properties:{Name:g,Description:s||`HTTP API for ${n} ${r}`,ProtocolType:"HTTP",Tags:{Name:g,Environment:r}}};if(a)f.Properties.CorsConfiguration={AllowOrigins:c,AllowMethods:u,AllowHeaders:d,MaxAge:m,AllowCredentials:p};return{httpApi:f,logicalId:y}}static createWebSocketApi(e){let{slug:n,environment:r,name:i,description:s}=e,a=i||l({slug:n,environment:r,resourceType:"ws-api"}),c=o(a);return{webSocketApi:{Type:"AWS::ApiGatewayV2::Api",Properties:{Name:a,Description:s||`WebSocket API for ${n} ${r}`,ProtocolType:"WEBSOCKET",Tags:{Name:a,Environment:r}}},logicalId:c}}static createDeployment(e,n){let{slug:r,environment:i,description:s}=n,a=l({slug:r,environment:i,resourceType:"api-deployment"}),c=o(a);return{deployment:{Type:"AWS::ApiGateway::Deployment",Properties:{RestApiId:R.Ref(e),Description:s||`Deployment for ${a}`}},logicalId:c}}static createStage(e,n,r){let{slug:i,environment:s,stageName:a,description:c,cacheEnabled:u=!1,cacheSize:d="0.5",variables:m,throttling:p}=r,g=l({slug:i,environment:s,resourceType:"api-stage"}),y=o(g),f={Type:"AWS::ApiGateway::Stage",Properties:{StageName:a||s,RestApiId:R.Ref(e),DeploymentId:R.Ref(n),Description:c,CacheClusterEnabled:u,Tags:[{Key:"Name",Value:g},{Key:"Environment",Value:s}]}};if(u)f.Properties.CacheClusterSize=d;if(m)f.Properties.Variables=m;if(p)f.Properties.MethodSettings=[{HttpMethod:"*",ResourcePath:"/*",ThrottlingBurstLimit:p.burstLimit,ThrottlingRateLimit:p.rateLimit}];return{stage:f,logicalId:y}}static createAuthorizer(e,n){let{slug:r,environment:i,name:s,type:a,functionArn:c,identitySource:u,userPoolArns:d,ttl:m=300}=n,p=s||l({slug:r,environment:i,resourceType:"api-authorizer"}),g=o(p),y={Type:"AWS::ApiGateway::Authorizer",Properties:{Name:p,Type:a,RestApiId:R.Ref(e),AuthorizerResultTtlInSeconds:m}};if(a==="TOKEN"||a==="REQUEST"){if(!c)throw Error("Lambda authorizer requires functionArn");y.Properties.AuthorizerUri=c,y.Properties.IdentitySource=u||"method.request.header.Authorization"}if(a==="COGNITO_USER_POOLS"){if(!d||d.length===0)throw Error("Cognito authorizer requires userPoolArns");y.Properties.ProviderARNs=d,y.Properties.IdentitySource=u||"method.request.header.Authorization"}return{authorizer:y,logicalId:g}}static setCors(e,n={}){let{origins:r=["*"],methods:i=["GET","POST","PUT","PATCH","DELETE","OPTIONS"],headers:s=["*"],maxAge:a=86400,allowCredentials:c=!1}=n;return e.Properties.CorsConfiguration={AllowOrigins:r,AllowMethods:i,AllowHeaders:s,MaxAge:a,AllowCredentials:c},e}static addThrottling(e,n=5000,r=1e4){if(!e.Properties.MethodSettings)e.Properties.MethodSettings=[];return e.Properties.MethodSettings.push({HttpMethod:"*",ResourcePath:"/*",ThrottlingBurstLimit:n,ThrottlingRateLimit:r}),e}static enableCaching(e,n="0.5",r=300){if(e.Properties.CacheClusterEnabled=!0,e.Properties.CacheClusterSize=n,!e.Properties.MethodSettings)e.Properties.MethodSettings=[];return e.Properties.MethodSettings.push({HttpMethod:"*",ResourcePath:"/*",CachingEnabled:!0,CacheTtlInSeconds:r}),e}static CacheSizes={Small:"0.5",Medium:"1.6",Large:"6.1",XLarge:"13.5",XXLarge:"28.4",XXXLarge:"58.2",Huge:"118",Massive:"237"};static ThrottlingPresets={Light:{burstLimit:100,rateLimit:50},Medium:{burstLimit:500,rateLimit:250},Heavy:{burstLimit:2000,rateLimit:1000},Default:{burstLimit:5000,rateLimit:1e4}}}class Le{static createTopic(e){let{slug:n,environment:r,topicName:i,displayName:s,encrypted:a=!1,kmsKeyId:c}=e,u=i||l({slug:n,environment:r,resourceType:"topic"}),d=o(u),m={Type:"AWS::SNS::Topic",Properties:{TopicName:u,DisplayName:s||u,Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:r}]}};if(a&&c)m.Properties.KmsMasterKeyId=c;return{topic:m,logicalId:d}}static subscribe(e,n){let{slug:r,environment:i,protocol:s,endpoint:a,filterPolicy:c,rawMessageDelivery:u=!1}=n,d=l({slug:r,environment:i,resourceType:"subscription"}),m=a.replace(/[^a-zA-Z0-9]/g,""),p=m.length>12?m.slice(-12):m,g=o(`${d}-${s}-${p}`),y={Type:"AWS::SNS::Subscription",Properties:{TopicArn:R.Ref(e),Protocol:s,Endpoint:a,RawMessageDelivery:u}};if(c)y.Properties.FilterPolicy=c;return{subscription:y,logicalId:g}}static subscribeEmail(e,n,r){return Le.subscribe(e,{...r,protocol:"email",endpoint:n})}static subscribeLambda(e,n,r){return Le.subscribe(e,{...r,protocol:"lambda",endpoint:n,rawMessageDelivery:!0})}static subscribeSqs(e,n,r){return Le.subscribe(e,{...r,protocol:"sqs",endpoint:n})}static subscribeHttp(e,n,r){let i=n.startsWith("https://")?"https":"http";return Le.subscribe(e,{...r,protocol:i,endpoint:n})}static subscribeSms(e,n,r){return Le.subscribe(e,{...r,protocol:"sms",endpoint:n})}static setTopicPolicy(e,n){let{slug:r,environment:i,allowedPrincipals:s,allowedServices:a,actions:c="SNS:Publish"}=n,u=l({slug:r,environment:i,resourceType:"topic-policy"}),d=o(u),m={};if(s)m.AWS=s;if(a)m.Service=a;return{policy:{Type:"AWS::SNS::TopicPolicy",Properties:{Topics:[R.Ref(e)],PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:m,Action:c,Resource:R.Ref(e)}]}}},logicalId:d}}static allowCloudWatchAlarms(e,n){return Le.setTopicPolicy(e,{...n,allowedServices:"cloudwatch.amazonaws.com",actions:"SNS:Publish"})}static allowEventBridge(e,n){return Le.setTopicPolicy(e,{...n,allowedServices:"events.amazonaws.com",actions:"SNS:Publish"})}static allowS3(e,n){return Le.setTopicPolicy(e,{...n,allowedServices:"s3.amazonaws.com",actions:"SNS:Publish"})}static enableEncryption(e,n){if(!e.Properties)e.Properties={};return e.Properties.KmsMasterKeyId=n,e}static addInlineSubscription(e,n,r){if(!e.Properties)e.Properties={};if(!e.Properties.Subscription)e.Properties.Subscription=[];return e.Properties.Subscription.push({Protocol:n,Endpoint:r}),e}static FilterPolicies={eventType:(e)=>({eventType:e}),status:(e)=>({status:e}),numericRange:(e,n,r)=>({[e]:[{numeric:[">=",n,"<=",r]}]}),prefix:(e,n)=>({[e]:[{prefix:n}]}),and:(...e)=>Object.assign({},...e),exists:(e,n)=>({[e]:[{exists:n}]})};static UseCases={createAlertTopic:(e)=>Le.createTopic({...e,topicName:e.topicName||`${e.slug}-${e.environment}-alerts`,displayName:e.displayName||"Alert Notifications"}),createEventFanout:(e)=>Le.createTopic({...e,topicName:e.topicName||`${e.slug}-${e.environment}-events`,displayName:e.displayName||"Event Fanout"}),createNotificationTopic:(e)=>Le.createTopic({...e,topicName:e.topicName||`${e.slug}-${e.environment}-notifications`,displayName:e.displayName||"User Notifications"})}}class gu{static createStateMachine(e){let{slug:n,environment:r,stateMachineName:i,type:s="STANDARD",definition:a,roleArn:c,loggingConfiguration:u,tracingConfiguration:d}=e,m=i||l({slug:n,environment:r,resourceType:"state-machine"}),p=o(m),g,y,f;if(c)f=c;else{let S=l({slug:n,environment:r,resourceType:"state-machine-role"});y=o(S),g={Type:"AWS::IAM::Role",Properties:{RoleName:S,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"states.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/CloudWatchLogsFullAccess"],Tags:[{Key:"Name",Value:S},{Key:"Environment",Value:r}]}},f=R.GetAtt(y,"Arn")}let h={Type:"AWS::StepFunctions::StateMachine",Properties:{StateMachineName:m,StateMachineType:s,DefinitionString:JSON.stringify(a),RoleArn:f,Tags:[{Key:"Name",Value:m},{Key:"Environment",Value:r}]}};if(u)h.Properties.LoggingConfiguration={Level:u.level,IncludeExecutionData:u.includeExecutionData,Destinations:u.destinations?.map((S)=>({CloudWatchLogsLogGroup:{LogGroupArn:S}}))};if(d)h.Properties.TracingConfiguration={Enabled:d.enabled};return{stateMachine:h,logicalId:p,role:g,roleLogicalId:y}}static createLambdaTask(e,n){return{Type:"Task",Resource:"arn:aws:states:::lambda:invoke",Parameters:{FunctionName:e,Payload:n?.parameters||{"Input.$":"$"}},ResultPath:n?.resultPath,Retry:n?.retry,Catch:n?.catch,Next:n?.next,End:n?.end}}static createDynamoDBTask(e,n,r,i){return{Type:"Task",Resource:{GetItem:"arn:aws:states:::dynamodb:getItem",PutItem:"arn:aws:states:::dynamodb:putItem",UpdateItem:"arn:aws:states:::dynamodb:updateItem",DeleteItem:"arn:aws:states:::dynamodb:deleteItem"}[e],Parameters:{TableName:n,...r},ResultPath:i?.resultPath,Retry:i?.retry,Catch:i?.catch,Next:i?.next,End:i?.end}}static createSNSPublishTask(e,n,r){return{Type:"Task",Resource:"arn:aws:states:::sns:publish",Parameters:{TopicArn:e,Message:n},ResultPath:r?.resultPath,Retry:r?.retry,Catch:r?.catch,Next:r?.next,End:r?.end}}static createSQSSendMessageTask(e,n,r){return{Type:"Task",Resource:"arn:aws:states:::sqs:sendMessage",Parameters:{QueueUrl:e,MessageBody:n},ResultPath:r?.resultPath,Retry:r?.retry,Catch:r?.catch,Next:r?.next,End:r?.end}}static createPassState(e){return{Type:"Pass",Result:e?.result,ResultPath:e?.resultPath,Parameters:e?.parameters,Next:e?.next,End:e?.end}}static createWaitState(e){return{Type:"Wait",Seconds:e.seconds,Timestamp:e.timestamp,SecondsPath:e.secondsPath,TimestampPath:e.timestampPath,Next:e.next,End:e.end}}static createChoiceState(e,n){return{Type:"Choice",Choices:e,Default:n}}static createParallelState(e,n){return{Type:"Parallel",Branches:e,ResultPath:n?.resultPath,Retry:n?.retry,Catch:n?.catch,Next:n?.next,End:n?.end}}static createMapState(e,n){return{Type:"Map",ItemsPath:n?.itemsPath||"$.items",Iterator:e,MaxConcurrency:n?.maxConcurrency,ResultPath:n?.resultPath,Retry:n?.retry,Catch:n?.catch,Next:n?.next,End:n?.end}}static createSucceedState(){return{Type:"Succeed"}}static createFailState(e,n){return{Type:"Fail",Error:e,Cause:n}}static RetryPolicies={standard:()=>({ErrorEquals:["States.ALL"],IntervalSeconds:2,MaxAttempts:3,BackoffRate:2}),aggressive:()=>({ErrorEquals:["States.TaskFailed","States.Timeout"],IntervalSeconds:1,MaxAttempts:5,BackoffRate:1.5}),custom:(e,n,r,i)=>({ErrorEquals:e,IntervalSeconds:n,MaxAttempts:r,BackoffRate:i})};static CatchPolicies={all:(e,n)=>({ErrorEquals:["States.ALL"],Next:e,ResultPath:n||"$.error"}),specific:(e,n,r)=>({ErrorEquals:e,Next:n,ResultPath:r||"$.error"})};static Patterns={sequential:(e,n,r)=>{let i={};return r.forEach((s,a)=>{let c=a===r.length-1;i[s.name]={...s.state,Next:c?void 0:r[a+1].name,End:c}}),{Comment:"Sequential workflow",StartAt:r[0].name,States:i}},fanout:(e,n,r)=>({Comment:"Fan-out workflow",StartAt:"Parallel",States:{Parallel:{Type:"Parallel",Branches:r.map((i)=>i.definition),End:!0}}}),map:(e,n,r,i)=>({Comment:"Map workflow",StartAt:"Map",States:{Map:{Type:"Map",ItemsPath:"$.items",Iterator:r,MaxConcurrency:i,End:!0}}}),withErrorHandling:(e,n,r,i)=>({Comment:"Workflow with error handling",StartAt:"Main",States:{Main:{...r,Catch:[{ErrorEquals:["States.ALL"],Next:"ErrorHandler"}],Next:"Success"},ErrorHandler:i,Success:{Type:"Succeed"}}})}}class Vi{static createAlarm(e){let{slug:n,environment:r,alarmName:i,metricName:s,namespace:a,statistic:c="Average",period:u=300,evaluationPeriods:d=1,threshold:m,comparisonOperator:p,treatMissingData:g="notBreaching",actionsEnabled:y=!0,alarmActions:f,okActions:h,insufficientDataActions:S,dimensions:C,unit:P,datapointsToAlarm:E}=e,v=i||l({slug:n,environment:r,resourceType:"alarm"}),w=o(v),D={Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:v,MetricName:s,Namespace:a,Statistic:c,Period:u,EvaluationPeriods:d,Threshold:m,ComparisonOperator:p,TreatMissingData:g,ActionsEnabled:y}};if(f&&f.length>0)D.Properties.AlarmActions=f;if(h&&h.length>0)D.Properties.OKActions=h;if(S&&S.length>0)D.Properties.InsufficientDataActions=S;if(C)D.Properties.Dimensions=Object.entries(C).map(([x,L])=>({Name:x,Value:L}));if(P)D.Properties.Unit=P;if(E!==void 0)D.Properties.DatapointsToAlarm=E;return{alarm:D,logicalId:w}}static createCompositeAlarm(e){let{slug:n,environment:r,alarmName:i,alarmRule:s,actionsEnabled:a=!0,alarmActions:c,okActions:u,insufficientDataActions:d}=e,m=i||l({slug:n,environment:r,resourceType:"composite-alarm"}),p=o(m),g={Type:"AWS::CloudWatch::CompositeAlarm",Properties:{AlarmName:m,AlarmRule:s,ActionsEnabled:a}};if(c&&c.length>0)g.Properties.AlarmActions=c;if(u&&u.length>0)g.Properties.OKActions=u;if(d&&d.length>0)g.Properties.InsufficientDataActions=d;return{alarm:g,logicalId:p}}static createDashboard(e){let{slug:n,environment:r,dashboardName:i,widgets:s}=e,a=i||l({slug:n,environment:r,resourceType:"dashboard"}),c=o(a),u={widgets:s.map((m)=>({type:m.type,x:m.x,y:m.y,width:m.width,height:m.height,properties:m.properties}))};return{dashboard:{Type:"AWS::CloudWatch::Dashboard",Properties:{DashboardName:a,DashboardBody:JSON.stringify(u)}},logicalId:c}}static createLogGroup(e){let{slug:n,environment:r,logGroupName:i,retentionInDays:s,kmsKeyId:a}=e,c=i||l({slug:n,environment:r,resourceType:"log-group"}),u=o(c),d={Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:c}};if(s!==void 0)d.Properties.RetentionInDays=s;if(a)d.Properties.KmsKeyId=a;return{logGroup:d,logicalId:u}}static createLogStream(e,n){let{slug:r,environment:i,logStreamName:s}=n,a=s||l({slug:r,environment:i,resourceType:"log-stream"}),c=o(a);return{logStream:{Type:"AWS::Logs::LogStream",Properties:{LogGroupName:R.Ref(e),LogStreamName:a}},logicalId:c}}static createMetricFilter(e,n){let{slug:r,environment:i,filterName:s,filterPattern:a,metricTransformations:c}=n,u=s||l({slug:r,environment:i,resourceType:"metric-filter"}),d=o(u);return{metricFilter:{Type:"AWS::Logs::MetricFilter",Properties:{LogGroupName:R.Ref(e),FilterPattern:a,MetricTransformations:c.map((p)=>({MetricName:p.metricName,MetricNamespace:p.metricNamespace,MetricValue:p.metricValue,DefaultValue:p.defaultValue,Unit:p.unit}))}},logicalId:d}}static AlarmTypes={highCpu:(e,n,r,i=80,s)=>({slug:e,environment:n,alarmName:`${e}-${n}-high-cpu`,metricName:"CPUUtilization",namespace:"AWS/EC2",statistic:"Average",period:300,evaluationPeriods:2,threshold:i,comparisonOperator:"GreaterThanThreshold",dimensions:{InstanceId:r},alarmActions:s?[s]:void 0}),highMemory:(e,n,r,i=80,s)=>({slug:e,environment:n,alarmName:`${e}-${n}-high-memory`,metricName:"MemoryUtilization",namespace:"System/Linux",statistic:"Average",period:300,evaluationPeriods:2,threshold:i,comparisonOperator:"GreaterThanThreshold",dimensions:{InstanceId:r},alarmActions:s?[s]:void 0}),highDisk:(e,n,r,i=80,s)=>({slug:e,environment:n,alarmName:`${e}-${n}-high-disk`,metricName:"DiskSpaceUtilization",namespace:"System/Linux",statistic:"Average",period:300,evaluationPeriods:2,threshold:i,comparisonOperator:"GreaterThanThreshold",dimensions:{InstanceId:r,Filesystem:"/dev/xvda1",MountPath:"/"},alarmActions:s?[s]:void 0}),lambdaErrors:(e,n,r,i=5,s)=>({slug:e,environment:n,alarmName:`${e}-${n}-lambda-errors`,metricName:"Errors",namespace:"AWS/Lambda",statistic:"Sum",period:300,evaluationPeriods:1,threshold:i,comparisonOperator:"GreaterThanThreshold",dimensions:{FunctionName:r},alarmActions:s?[s]:void 0}),lambdaThrottles:(e,n,r,i=10,s)=>({slug:e,environment:n,alarmName:`${e}-${n}-lambda-throttles`,metricName:"Throttles",namespace:"AWS/Lambda",statistic:"Sum",period:300,evaluationPeriods:1,threshold:i,comparisonOperator:"GreaterThanThreshold",dimensions:{FunctionName:r},alarmActions:s?[s]:void 0}),apiGateway5xxErrors:(e,n,r,i=10,s)=>({slug:e,environment:n,alarmName:`${e}-${n}-api-5xx-errors`,metricName:"5XXError",namespace:"AWS/ApiGateway",statistic:"Sum",period:300,evaluationPeriods:1,threshold:i,comparisonOperator:"GreaterThanThreshold",dimensions:{ApiName:r},alarmActions:s?[s]:void 0}),apiGateway4xxErrors:(e,n,r,i=50,s)=>({slug:e,environment:n,alarmName:`${e}-${n}-api-4xx-errors`,metricName:"4XXError",namespace:"AWS/ApiGateway",statistic:"Sum",period:300,evaluationPeriods:2,threshold:i,comparisonOperator:"GreaterThanThreshold",dimensions:{ApiName:r},alarmActions:s?[s]:void 0}),dynamoDBThrottles:(e,n,r,i=5,s)=>({slug:e,environment:n,alarmName:`${e}-${n}-dynamodb-throttles`,metricName:"UserErrors",namespace:"AWS/DynamoDB",statistic:"Sum",period:300,evaluationPeriods:1,threshold:i,comparisonOperator:"GreaterThanThreshold",dimensions:{TableName:r},alarmActions:s?[s]:void 0}),rdsCpu:(e,n,r,i=80,s)=>({slug:e,environment:n,alarmName:`${e}-${n}-rds-cpu`,metricName:"CPUUtilization",namespace:"AWS/RDS",statistic:"Average",period:300,evaluationPeriods:2,threshold:i,comparisonOperator:"GreaterThanThreshold",dimensions:{DBInstanceIdentifier:r},alarmActions:s?[s]:void 0}),rdsFreeStorage:(e,n,r,i=5368709120,s)=>({slug:e,environment:n,alarmName:`${e}-${n}-rds-storage`,metricName:"FreeStorageSpace",namespace:"AWS/RDS",statistic:"Average",period:300,evaluationPeriods:1,threshold:i,comparisonOperator:"LessThanThreshold",dimensions:{DBInstanceIdentifier:r},alarmActions:s?[s]:void 0,unit:"Bytes"}),sqsQueueDepth:(e,n,r,i=100,s)=>({slug:e,environment:n,alarmName:`${e}-${n}-sqs-depth`,metricName:"ApproximateNumberOfMessagesVisible",namespace:"AWS/SQS",statistic:"Average",period:300,evaluationPeriods:2,threshold:i,comparisonOperator:"GreaterThanThreshold",dimensions:{QueueName:r},alarmActions:s?[s]:void 0}),albUnhealthyTargets:(e,n,r,i,s=1,a)=>({slug:e,environment:n,alarmName:`${e}-${n}-alb-unhealthy`,metricName:"UnHealthyHostCount",namespace:"AWS/ApplicationELB",statistic:"Average",period:300,evaluationPeriods:2,threshold:s,comparisonOperator:"GreaterThanThreshold",dimensions:{LoadBalancer:r,TargetGroup:i},alarmActions:a?[a]:void 0}),sesBounceRate:(e,n,r=5,i)=>({slug:e,environment:n,alarmName:`${e}-${n}-ses-bounce-rate`,metricName:"Reputation.BounceRate",namespace:"AWS/SES",statistic:"Average",period:3600,evaluationPeriods:1,threshold:r/100,comparisonOperator:"GreaterThanThreshold",alarmActions:i?[i]:void 0}),sesComplaintRate:(e,n,r=0.1,i)=>({slug:e,environment:n,alarmName:`${e}-${n}-ses-complaint-rate`,metricName:"Reputation.ComplaintRate",namespace:"AWS/SES",statistic:"Average",period:3600,evaluationPeriods:1,threshold:r/100,comparisonOperator:"GreaterThanThreshold",alarmActions:i?[i]:void 0}),smsDeliveryFailure:(e,n,r,i=10,s)=>({slug:e,environment:n,alarmName:`${e}-${n}-sms-delivery-failure`,metricName:"DirectSendMessagePermanentFailure",namespace:"AWS/Pinpoint",statistic:"Sum",period:300,evaluationPeriods:1,threshold:i,comparisonOperator:"GreaterThanThreshold",dimensions:{ApplicationId:r},alarmActions:s?[s]:void 0}),smsSpendLimit:(e,n,r=100,i)=>({slug:e,environment:n,alarmName:`${e}-${n}-sms-spend-limit`,metricName:"DirectSendMessageSpend",namespace:"AWS/Pinpoint",statistic:"Sum",period:86400,evaluationPeriods:1,threshold:r,comparisonOperator:"GreaterThanThreshold",alarmActions:i?[i]:void 0}),connectMissedCalls:(e,n,r,i=5,s)=>({slug:e,environment:n,alarmName:`${e}-${n}-connect-missed-calls`,metricName:"MissedCalls",namespace:"AWS/Connect",statistic:"Sum",period:3600,evaluationPeriods:1,threshold:i,comparisonOperator:"GreaterThanThreshold",dimensions:{InstanceId:r},alarmActions:s?[s]:void 0})};static DashboardWidgets={metric:(e,n,r,i,s,a)=>({type:"metric",x:e,y:n,width:r,height:i,properties:{metrics:s,title:a||"Metrics",region:"us-east-1",period:300}}),text:(e,n,r,i,s)=>({type:"text",x:e,y:n,width:r,height:i,properties:{markdown:s}}),log:(e,n,r,i,s,a)=>({type:"log",x:e,y:n,width:r,height:i,properties:{query:`SOURCE '${s.join("' | SOURCE '")}'
|
|
2274
|
+
`;class Re{static LambdaCode={send:ft,receive:on,deliveryStatus:an};static createPinpointApp(e){return{[`${e.slug}PinpointApp`]:{Type:"AWS::Pinpoint::App",Properties:{Name:e.name||`${e.slug}-sms`}}}}static createSmsChannel(e){let n={ApplicationId:e.applicationId,Enabled:e.enabled!==!1};if(e.senderId)n.SenderId=e.senderId;if(e.shortCode)n.ShortCode=e.shortCode;return{[`${e.slug}SmsChannel`]:{Type:"AWS::Pinpoint::SMSChannel",Properties:n}}}static createSmsLambdaRole(e){return{[`${e.slug}SmsLambdaRole`]:{Type:"AWS::IAM::Role",Properties:{RoleName:`${e.slug}-sms-lambda-role`,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"],Policies:[{PolicyName:"SmsLambdaPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["mobiletargeting:SendMessages","mobiletargeting:GetSmsChannel"],Resource:"*"},{Effect:"Allow",Action:["sns:Publish"],Resource:"*"},{Effect:"Allow",Action:["dynamodb:PutItem","dynamodb:UpdateItem","dynamodb:GetItem","dynamodb:DeleteItem"],Resource:"*"}]}}]}}}}static createSendLambda(e){return{[`${e.slug}SmsSendLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${e.slug}-sms-send`,Runtime:"nodejs20.x",Handler:"index.handler",Role:e.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:Re.LambdaCode.send},Environment:{Variables:{PINPOINT_APP_ID:e.pinpointAppId,MESSAGE_LOG_TABLE:e.messageLogTable||"",SMS_SENDER_ID:e.senderId||"",SMS_ORIGINATION_NUMBER:e.originationNumber||""}}}}}}static createReceiveLambda(e){return{[`${e.slug}SmsReceiveLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${e.slug}-sms-receive`,Runtime:"nodejs20.x",Handler:"index.handler",Role:e.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:Re.LambdaCode.receive},Environment:{Variables:{OPT_OUT_TABLE:e.optOutTable||"",MESSAGE_LOG_TABLE:e.messageLogTable||"",NOTIFICATION_TOPIC_ARN:e.notificationTopicArn||"",WEBHOOK_URL:e.webhookUrl||""}}}}}}static createDeliveryStatusLambda(e){return{[`${e.slug}SmsDeliveryStatusLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${e.slug}-sms-delivery-status`,Runtime:"nodejs20.x",Handler:"index.handler",Role:e.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:Re.LambdaCode.deliveryStatus},Environment:{Variables:{MESSAGE_LOG_TABLE:e.messageLogTable||"",NOTIFICATION_TOPIC_ARN:e.notificationTopicArn||"",WEBHOOK_URL:e.webhookUrl||""}}}}}}static createMessageLogTable(e){return{[`${e.slug}SmsMessageLogTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${e.slug}-sms-messages`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"messageId",AttributeType:"S"}],KeySchema:[{AttributeName:"messageId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createOptOutTable(e){return{[`${e.slug}SmsOptOutTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${e.slug}-sms-optouts`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"phoneNumber",AttributeType:"S"}],KeySchema:[{AttributeName:"phoneNumber",KeyType:"HASH"}]}}}}static createNotificationTopic(e){return{[`${e.slug}SmsNotificationTopic`]:{Type:"AWS::SNS::Topic",Properties:{TopicName:`${e.slug}-sms-notifications`}}}}static createCompleteSetup(e){let n={},r={};Object.assign(n,Re.createPinpointApp({slug:e.slug})),Object.assign(n,Re.createSmsChannel({slug:e.slug,applicationId:{Ref:`${e.slug}PinpointApp`},senderId:e.senderId})),Object.assign(n,Re.createSmsLambdaRole({slug:e.slug})),Object.assign(n,Re.createMessageLogTable({slug:e.slug})),Object.assign(n,Re.createOptOutTable({slug:e.slug})),Object.assign(n,Re.createNotificationTopic({slug:e.slug}));let i={"Fn::GetAtt":[`${e.slug}SmsLambdaRole`,"Arn"]},s={Ref:`${e.slug}PinpointApp`},a={Ref:`${e.slug}SmsMessageLogTable`},c={Ref:`${e.slug}SmsOptOutTable`},u={Ref:`${e.slug}SmsNotificationTopic`};if(Object.assign(n,Re.createSendLambda({slug:e.slug,roleArn:i,pinpointAppId:s,messageLogTable:a,senderId:e.senderId,originationNumber:e.originationNumber})),e.twoWayEnabled)Object.assign(n,Re.createReceiveLambda({slug:e.slug,roleArn:i,optOutTable:c,messageLogTable:a,notificationTopicArn:u,webhookUrl:e.webhookUrl}));return Object.assign(n,Re.createDeliveryStatusLambda({slug:e.slug,roleArn:i,messageLogTable:a,notificationTopicArn:u,webhookUrl:e.webhookUrl})),r[`${e.slug}PinpointAppId`]={Description:"Pinpoint application ID",Value:{Ref:`${e.slug}PinpointApp`}},r[`${e.slug}SmsSendLambdaArn`]={Description:"SMS send Lambda ARN",Value:{"Fn::GetAtt":[`${e.slug}SmsSendLambda`,"Arn"]}},r[`${e.slug}SmsNotificationTopicArn`]={Description:"SMS notification topic ARN",Value:{Ref:`${e.slug}SmsNotificationTopic`}},r[`${e.slug}SmsMessageLogTableName`]={Description:"SMS message log table name",Value:{Ref:`${e.slug}SmsMessageLogTable`}},{resources:n,outputs:r}}}function ht(e){return e.replace(/[^a-zA-Z0-9]/g," ").trim().split(/\s+/).map((i)=>i.charAt(0).toUpperCase()+i.slice(1)).join("")||"User"}function xr(e,n){let r=(e||n).replace(/^\/+|\/+$/g,"");if(!r||r.split("/").includes(".."))throw Error(`sftp: invalid homeDirectory for user ${n}`);return r}function kr(e){let n=e.storage;if(n?.type==="efs"){let i="fileSystemId"in n?n.fileSystemId:void 0;if(!i||typeof i==="string"&&!i.trim())throw Error("sftp: EFS storage requires fileSystemId, or a fileSystem name defined in infrastructure.fileSystem");return{type:"efs",fileSystemId:i,posixProfile:n.posixProfile}}let r=(n?.type==="s3"?n.bucket??e.bucket:e.bucket)?.trim();if(!r)throw Error("sftp: S3 storage requires bucket, or a storageBucket name defined in infrastructure.storage");return{type:"s3",bucket:r}}function Mr(e,n,r){let i=n.posixProfile??r;if(!i)throw Error(`sftp: user ${e} requires a posixProfile (uid/gid) on an EFS-backed server`);for(let s of[i.uid,i.gid,...i.secondaryGids??[]])if(!Number.isInteger(s)||s<0||s>4294967295)throw Error(`sftp: user ${e} has an invalid posixProfile id ${s}`);return{Uid:i.uid,Gid:i.gid,...i.secondaryGids?.length?{SecondaryGids:i.secondaryGids}:{}}}function Lr(e,n){return typeof e==="string"?`/${e}/${n}`:{"Fn::Sub":[`/\${FileSystemId}/${n}`,{FileSystemId:e}]}}function Or(e){return typeof e==="string"?{"Fn::Sub":"arn:aws:elasticfilesystem:${AWS::Region}:${AWS::AccountId}:file-system/${FileSystemId}".replace("${FileSystemId}",e)}:{"Fn::Sub":["arn:aws:elasticfilesystem:${AWS::Region}:${AWS::AccountId}:file-system/${FileSystemId}",{FileSystemId:e}]}}class ts{static create(e){let n=kr(e),r=n.type==="efs"?"EFS":"S3",i=e.endpointType??"PUBLIC";if(i==="VPC"&&(!e.endpointDetails?.vpcId||!e.endpointDetails.subnetIds.length))throw Error("sftp: VPC endpoints require endpointDetails.vpcId and at least one subnet");let s=`${ht(e.slug)}${ht(e.environment)}Sftp`,a=`${s}Server`,c={},u;if(e.logging!==!1){let d=`${s}LoggingRole`;c[d]={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"transfer.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"TransferLogging",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["logs:CreateLogGroup","logs:CreateLogStream","logs:DescribeLogStreams","logs:PutLogEvents"],Resource:"arn:aws:logs:*:*:log-group:/aws/transfer/*"}]}}]}},u={"Fn::GetAtt":[d,"Arn"]}}c[a]={Type:"AWS::Transfer::Server",Properties:{Domain:r,EndpointType:i,IdentityProviderType:"SERVICE_MANAGED",Protocols:["SFTP"],...i==="VPC"?{EndpointDetails:{VpcId:e.endpointDetails.vpcId,SubnetIds:e.endpointDetails.subnetIds,...e.endpointDetails.securityGroupIds?.length?{SecurityGroupIds:e.endpointDetails.securityGroupIds}:{},...e.endpointDetails.addressAllocationIds?.length?{AddressAllocationIds:e.endpointDetails.addressAllocationIds}:{}}}:{},...e.securityPolicyName?{SecurityPolicyName:e.securityPolicyName}:{},...u?{LoggingRole:u}:{},Tags:[{Key:"Project",Value:e.slug},{Key:"Environment",Value:e.environment},{Key:"ManagedBy",Value:"ts-cloud"}]}};for(let[d,m]of Object.entries(e.users)){if(!/^[a-zA-Z0-9_.@-]{3,100}$/.test(d))throw Error(`sftp: invalid username ${d}`);if(!m.sshPublicKeys.length)throw Error(`sftp: user ${d} requires at least one SSH public key`);let p=ht(d),g=xr(m.homeDirectory,d),y=`${s}${p}User`,f=m.roleArn;if(!f){let h=`${s}${p}Role`,S;if(n.type==="efs")S=[{Effect:"Allow",Action:["elasticfilesystem:ClientMount","elasticfilesystem:ClientWrite","elasticfilesystem:DescribeMountTargets"],Resource:Or(n.fileSystemId)}];else{let C=`arn:aws:s3:::${n.bucket}`;S=[{Effect:"Allow",Action:["s3:ListBucket","s3:GetBucketLocation"],Resource:C,Condition:{StringLike:{"s3:prefix":[g,`${g}/*`]}}},{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:GetObjectVersion"],Resource:`${C}/${g}/*`}]}c[h]={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"transfer.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"SftpHomeDirectory",PolicyDocument:{Version:"2012-10-17",Statement:S}}]}},f={"Fn::GetAtt":[h,"Arn"]}}c[y]={Type:"AWS::Transfer::User",DependsOn:[a],Properties:{ServerId:{Ref:a},UserName:d,Role:f,HomeDirectoryType:"PATH",HomeDirectory:n.type==="efs"?Lr(n.fileSystemId,g):`/${n.bucket}/${g}`,...n.type==="efs"?{PosixProfile:Mr(d,m,n.posixProfile)}:{},SshPublicKeys:m.sshPublicKeys}}}return{resources:c,serverLogicalId:a,domain:r}}}class qe{static createBedrockRole(e,n){let{slug:r,environment:i,name:s,models:a=["*"],allowStreaming:c=!0}=n,u=s||l({slug:r,environment:i,resourceType:"bedrock-role"}),d=o(u),m=["bedrock:InvokeModel"];if(c)m.push("bedrock:InvokeModelWithResponseStream");let p=a.map((y)=>y==="*"?"arn:aws:bedrock:*::foundation-model/*":`arn:aws:bedrock:*::foundation-model/${y}`);return{role:{Type:"AWS::IAM::Role",Properties:{RoleName:u,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:e},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:`${u}-policy`,PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:m,Resource:p}]}}],Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:i}]}},logicalId:d}}static createBedrockPolicy(e){let{slug:n,environment:r,name:i,models:s=["*"],allowInvoke:a=!0,allowStreaming:c=!0,allowAsync:u=!1}=e,d=i||l({slug:n,environment:r,resourceType:"bedrock-policy"}),m=o(d),p=[];if(a)p.push("bedrock:InvokeModel");if(c)p.push("bedrock:InvokeModelWithResponseStream");if(u)p.push("bedrock:InvokeModelAsync");let g=s.map((f)=>f==="*"?"arn:aws:bedrock:*::foundation-model/*":`arn:aws:bedrock:*::foundation-model/${f}`);return{policy:{Type:"AWS::IAM::ManagedPolicy",Properties:{ManagedPolicyName:d,PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"BedrockModelInvocation",Effect:"Allow",Action:p,Resource:g}]}}},logicalId:m}}static enableBedrockForLambda(e){return qe.createBedrockRole("lambda.amazonaws.com",e)}static enableBedrockForEcs(e){return qe.createBedrockRole("ecs-tasks.amazonaws.com",e)}static enableBedrockForEc2(e){return qe.createBedrockRole("ec2.amazonaws.com",e)}static addBedrockPermissions(e,n=["*"],r=!0){let i=["bedrock:InvokeModel"];if(r)i.push("bedrock:InvokeModelWithResponseStream");let s=n.map((a)=>a==="*"?"arn:aws:bedrock:*::foundation-model/*":`arn:aws:bedrock:*::foundation-model/${a}`);if(!e.Properties.Policies)e.Properties.Policies=[];return e.Properties.Policies.push({PolicyName:"bedrock-permissions",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:i,Resource:s}]}}),e}static Models={Claude3_5_Sonnet:"anthropic.claude-3-5-sonnet-20241022-v2:0",Claude3_5_Haiku:"anthropic.claude-3-5-haiku-20241022-v1:0",Claude3_Opus:"anthropic.claude-3-opus-20240229-v1:0",Claude3_Sonnet:"anthropic.claude-3-sonnet-20240229-v1:0",Claude3_Haiku:"anthropic.claude-3-haiku-20240307-v1:0",TitanTextG1Express:"amazon.titan-text-express-v1",TitanTextG1Lite:"amazon.titan-text-lite-v1",TitanEmbedG1Text:"amazon.titan-embed-text-v1",TitanImageG1:"amazon.titan-image-generator-v1",JurassicUltra:"ai21.j2-ultra-v1",JurassicMid:"ai21.j2-mid-v1",CommandText:"cohere.command-text-v14",CommandLight:"cohere.command-light-text-v14",EmbedEnglish:"cohere.embed-english-v3",EmbedMultilingual:"cohere.embed-multilingual-v3",Llama3_2_1B:"meta.llama3-2-1b-instruct-v1:0",Llama3_2_3B:"meta.llama3-2-3b-instruct-v1:0",Llama3_2_11B:"meta.llama3-2-11b-instruct-v1:0",Llama3_2_90B:"meta.llama3-2-90b-instruct-v1:0",Llama3_1_8B:"meta.llama3-1-8b-instruct-v1:0",Llama3_1_70B:"meta.llama3-1-70b-instruct-v1:0",Llama3_1_405B:"meta.llama3-1-405b-instruct-v1:0",Mistral7B:"mistral.mistral-7b-instruct-v0:2",Mixtral8x7B:"mistral.mixtral-8x7b-instruct-v0:1",MistralLarge:"mistral.mistral-large-2402-v1:0",StableDiffusionXL:"stability.stable-diffusion-xl-v1"};static ModelGroups={AllClaude:["anthropic.claude-3-5-sonnet-20241022-v2:0","anthropic.claude-3-5-haiku-20241022-v1:0","anthropic.claude-3-opus-20240229-v1:0","anthropic.claude-3-sonnet-20240229-v1:0","anthropic.claude-3-haiku-20240307-v1:0"],AllTitan:["amazon.titan-text-express-v1","amazon.titan-text-lite-v1","amazon.titan-embed-text-v1","amazon.titan-image-generator-v1"],AllLlama:["meta.llama3-2-1b-instruct-v1:0","meta.llama3-2-3b-instruct-v1:0","meta.llama3-2-11b-instruct-v1:0","meta.llama3-2-90b-instruct-v1:0","meta.llama3-1-8b-instruct-v1:0","meta.llama3-1-70b-instruct-v1:0","meta.llama3-1-405b-instruct-v1:0"],TextModels:["anthropic.claude-3-5-sonnet-20241022-v2:0","anthropic.claude-3-5-haiku-20241022-v1:0","amazon.titan-text-express-v1","meta.llama3-2-11b-instruct-v1:0","mistral.mistral-7b-instruct-v0:2"],EmbeddingModels:["amazon.titan-embed-text-v1","cohere.embed-english-v3","cohere.embed-multilingual-v3"],ImageModels:["amazon.titan-image-generator-v1","stability.stable-diffusion-xl-v1"]}}class Yt{static createPostgres(e){return Yt.createRDSInstance("postgres","16.2",e)}static createMysql(e){return Yt.createRDSInstance("mysql","8.0.35",e)}static createRDSInstance(e,n,r){let{slug:i,environment:s,instanceClass:a="db.t3.micro",allocatedStorage:c=20,storageType:u="gp3",masterUsername:d="admin",masterPassword:m,databaseName:p,subnetIds:g,securityGroupIds:y,encrypted:f=!0,kmsKeyId:h,multiAz:S=!1,backupRetentionDays:C=7,publiclyAccessible:P=!1,enableCloudwatchLogs:E=!0,deletionProtection:v=!0}=r,w=l({slug:i,environment:s,resourceType:`${e}-db`}),D=o(w),x,L;if(g&&g.length>0){let O=l({slug:i,environment:s,resourceType:"db-subnet-group"});L=o(O),x={Type:"AWS::RDS::DBSubnetGroup",Properties:{DBSubnetGroupName:O,DBSubnetGroupDescription:`Subnet group for ${w}`,SubnetIds:g,Tags:[{Key:"Name",Value:O},{Key:"Environment",Value:s}]}}}let B={Type:"AWS::RDS::DBInstance",Properties:{DBInstanceIdentifier:w,DBInstanceClass:a,Engine:e,EngineVersion:n,MasterUsername:d,MasterUserPassword:m,AllocatedStorage:c,StorageType:u,StorageEncrypted:f,MultiAZ:S,BackupRetentionPeriod:C,PubliclyAccessible:P,DeletionProtection:v,Tags:[{Key:"Name",Value:w},{Key:"Environment",Value:s}]}};if(p)B.Properties.DBName=p;if(h)B.Properties.KmsKeyId=h;if(L)B.Properties.DBSubnetGroupName=R.Ref(L);if(y&&y.length>0)B.Properties.VPCSecurityGroups=y;if(E)B.Properties.EnableCloudwatchLogsExports=e==="postgres"?["postgresql"]:["error","general","slowquery"];return{dbInstance:B,subnetGroup:x,logicalId:D,subnetGroupId:L}}static createReadReplica(e,n){let{slug:r,environment:i,instanceClass:s="db.t3.micro",securityGroupIds:a,publiclyAccessible:c=!1}=n,u=l({slug:r,environment:i,resourceType:"db-replica"}),d=o(u),m={Type:"AWS::RDS::DBInstance",Properties:{DBInstanceIdentifier:u,DBInstanceClass:s,SourceDBInstanceIdentifier:R.Ref(e),PubliclyAccessible:c,Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:i},{Key:"Type",Value:"ReadReplica"}]}};if(a&&a.length>0)m.Properties.VPCSecurityGroups=a;return{replica:m,logicalId:d}}static createParameterGroup(e,n,r){let{slug:i,environment:s,parameters:a={}}=r,c=l({slug:i,environment:s,resourceType:"db-params"}),u=o(c),d=e==="postgres"?`postgres${n.split(".")[0]}`:`mysql${n.split(".")[0]}.${n.split(".")[1]}`;return{parameterGroup:{Type:"AWS::RDS::DBParameterGroup",Properties:{DBParameterGroupName:c,Description:`Parameter group for ${c}`,Family:d,Parameters:a,Tags:[{Key:"Name",Value:c},{Key:"Environment",Value:s}]}},logicalId:u}}static enableBackup(e,n=7){return e.Properties.BackupRetentionPeriod=n,e}static createTable(e){let{slug:n,environment:r,tableName:i,partitionKey:s,sortKey:a,billingMode:c="PAY_PER_REQUEST",readCapacity:u=5,writeCapacity:d=5,streamEnabled:m=!1,streamViewType:p="NEW_AND_OLD_IMAGES",encrypted:g=!0,kmsKeyId:y,pointInTimeRecovery:f=!0,ttlAttribute:h}=e,S=i||l({slug:n,environment:r,resourceType:"table"}),C=o(S),P=[{AttributeName:s.name,AttributeType:s.type}];if(a)P.push({AttributeName:a.name,AttributeType:a.type});let E=[{AttributeName:s.name,KeyType:"HASH"}];if(a)E.push({AttributeName:a.name,KeyType:"RANGE"});let v={Type:"AWS::DynamoDB::Table",Properties:{TableName:S,BillingMode:c,AttributeDefinitions:P,KeySchema:E,Tags:[{Key:"Name",Value:S},{Key:"Environment",Value:r}]}};if(c==="PROVISIONED")v.Properties.ProvisionedThroughput={ReadCapacityUnits:u,WriteCapacityUnits:d};if(m)v.Properties.StreamSpecification={StreamViewType:p};if(g)v.Properties.SSESpecification={SSEEnabled:!0,SSEType:y?"KMS":"AES256",KMSMasterKeyId:y};if(f)v.Properties.PointInTimeRecoverySpecification={PointInTimeRecoveryEnabled:!0};if(h)v.Properties.TimeToLiveSpecification={AttributeName:h,Enabled:!0};return{table:v,logicalId:C}}static addGlobalSecondaryIndex(e,n){let{indexName:r,partitionKey:i,sortKey:s,projectionType:a="ALL",nonKeyAttributes:c,readCapacity:u=5,writeCapacity:d=5}=n;if(!e.Properties.AttributeDefinitions.some((g)=>g.AttributeName===i.name))e.Properties.AttributeDefinitions.push({AttributeName:i.name,AttributeType:i.type});if(s&&!e.Properties.AttributeDefinitions.some((g)=>g.AttributeName===s.name))e.Properties.AttributeDefinitions.push({AttributeName:s.name,AttributeType:s.type});let m=[{AttributeName:i.name,KeyType:"HASH"}];if(s)m.push({AttributeName:s.name,KeyType:"RANGE"});let p={IndexName:r,KeySchema:m,Projection:{ProjectionType:a,NonKeyAttributes:a==="INCLUDE"?c:void 0},ProvisionedThroughput:void 0};if(e.Properties.BillingMode==="PROVISIONED")p.ProvisionedThroughput={ReadCapacityUnits:u,WriteCapacityUnits:d};if(!e.Properties.GlobalSecondaryIndexes)e.Properties.GlobalSecondaryIndexes=[];return e.Properties.GlobalSecondaryIndexes.push(p),e}static enableStreams(e,n="NEW_AND_OLD_IMAGES"){return e.Properties.StreamSpecification={StreamViewType:n},e}static InstanceClasses={T3_Micro:"db.t3.micro",T3_Small:"db.t3.small",T3_Medium:"db.t3.medium",T3_Large:"db.t3.large",T4g_Micro:"db.t4g.micro",T4g_Small:"db.t4g.small",T4g_Medium:"db.t4g.medium",M5_Large:"db.m5.large",M5_XLarge:"db.m5.xlarge",M5_2XLarge:"db.m5.2xlarge",R5_Large:"db.r5.large",R5_XLarge:"db.r5.xlarge",R5_2XLarge:"db.r5.2xlarge"}}class ji{static createRedis(e){let{slug:n,environment:r,nodeType:i="cache.t3.micro",engineVersion:s="7.1",port:a=6379,subnetIds:c,securityGroupIds:u,numCacheClusters:d=2,automaticFailover:m=!0,multiAz:p=!0,clusterMode:g=!1,numNodeGroups:y=1,replicasPerNodeGroup:f=1,atRestEncryption:h=!0,transitEncryption:S=!0,authToken:C,kmsKeyId:P,snapshotRetentionDays:E=7,snapshotWindow:v,maintenanceWindow:w}=e,D=l({slug:n,environment:r,resourceType:"redis"}),x=o(D),L,B;if(c&&c.length>0){let F=l({slug:n,environment:r,resourceType:"cache-subnet-group"});B=o(F),L={Type:"AWS::ElastiCache::SubnetGroup",Properties:{CacheSubnetGroupName:F,Description:`Subnet group for ${D}`,SubnetIds:c,Tags:[{Key:"Name",Value:F},{Key:"Environment",Value:r}]}}}let O={Type:"AWS::ElastiCache::ReplicationGroup",Properties:{ReplicationGroupId:D,ReplicationGroupDescription:`Redis cluster for ${n} ${r}`,Engine:"redis",EngineVersion:s,CacheNodeType:i,Port:a,AutomaticFailoverEnabled:m,MultiAZEnabled:p,AtRestEncryptionEnabled:h,TransitEncryptionEnabled:S,SnapshotRetentionLimit:E,AutoMinorVersionUpgrade:!0,Tags:[{Key:"Name",Value:D},{Key:"Environment",Value:r}]}};if(g)O.Properties.NumNodeGroups=y,O.Properties.ReplicasPerNodeGroup=f;else O.Properties.NumCacheClusters=d;if(C)O.Properties.AuthToken=C;if(P)O.Properties.KmsKeyId=P;if(B)O.Properties.CacheSubnetGroupName=R.Ref(B);if(u&&u.length>0)O.Properties.SecurityGroupIds=u;if(v)O.Properties.SnapshotWindow=v;if(w)O.Properties.PreferredMaintenanceWindow=w;return{replicationGroup:O,subnetGroup:L,logicalId:x,subnetGroupId:B}}static createMemcached(e){let{slug:n,environment:r,nodeType:i="cache.t3.micro",engineVersion:s="1.6.22",port:a=11211,numCacheNodes:c=2,subnetIds:u,securityGroupIds:d,azMode:m="cross-az",preferredAzs:p,maintenanceWindow:g}=e,y=l({slug:n,environment:r,resourceType:"memcached"}),f=o(y),h,S;if(u&&u.length>0){let P=l({slug:n,environment:r,resourceType:"cache-subnet-group"});S=o(P),h={Type:"AWS::ElastiCache::SubnetGroup",Properties:{CacheSubnetGroupName:P,Description:`Subnet group for ${y}`,SubnetIds:u,Tags:[{Key:"Name",Value:P},{Key:"Environment",Value:r}]}}}let C={Type:"AWS::ElastiCache::CacheCluster",Properties:{ClusterName:y,CacheNodeType:i,Engine:"memcached",EngineVersion:s,NumCacheNodes:c,Port:a,AZMode:m,AutoMinorVersionUpgrade:!0,Tags:[{Key:"Name",Value:y},{Key:"Environment",Value:r}]}};if(S)C.Properties.CacheSubnetGroupName=R.Ref(S);if(d&&d.length>0)C.Properties.VpcSecurityGroupIds=d;if(p&&p.length>0)C.Properties.PreferredAvailabilityZones=p;if(g)C.Properties.PreferredMaintenanceWindow=g;return{cluster:C,subnetGroup:h,logicalId:f,subnetGroupId:S}}static enableClusterMode(e,n=3,r=2){return delete e.Properties.NumCacheClusters,e.Properties.NumNodeGroups=n,e.Properties.ReplicasPerNodeGroup=r,e}static createRedisParameterGroup(e,n){let{slug:r,environment:i,parameters:s={}}=n,a=l({slug:r,environment:i,resourceType:"redis-params"}),c=o(a);return{parameterGroup:{Type:"AWS::ElastiCache::ParameterGroup",Properties:{CacheParameterGroupFamily:`redis${e.split(".")[0]}.x`,Description:`Parameter group for ${a}`,Properties:s,Tags:[{Key:"Name",Value:a},{Key:"Environment",Value:i}]}},logicalId:c}}static createMemcachedParameterGroup(e,n){let{slug:r,environment:i,parameters:s={}}=n,a=l({slug:r,environment:i,resourceType:"memcached-params"}),c=o(a);return{parameterGroup:{Type:"AWS::ElastiCache::ParameterGroup",Properties:{CacheParameterGroupFamily:`memcached${e.split(".")[0]}.${e.split(".")[1]}`,Description:`Parameter group for ${a}`,Properties:s,Tags:[{Key:"Name",Value:a},{Key:"Environment",Value:i}]}},logicalId:c}}static NodeTypes={T3_Micro:"cache.t3.micro",T3_Small:"cache.t3.small",T3_Medium:"cache.t3.medium",T4g_Micro:"cache.t4g.micro",T4g_Small:"cache.t4g.small",T4g_Medium:"cache.t4g.medium",M5_Large:"cache.m5.large",M5_XLarge:"cache.m5.xlarge",M5_2XLarge:"cache.m5.2xlarge",R5_Large:"cache.r5.large",R5_XLarge:"cache.r5.xlarge",R5_2XLarge:"cache.r5.2xlarge",R5_4XLarge:"cache.r5.4xlarge",R6g_Large:"cache.r6g.large",R6g_XLarge:"cache.r6g.xlarge",R6g_2XLarge:"cache.r6g.2xlarge"}}class Ie{static createUser(e){let{slug:n,environment:r,userName:i,groups:s,managedPolicyArns:a}=e,c=i||l({slug:n,environment:r,resourceType:"user"}),u=o(c),d={Type:"AWS::IAM::User",Properties:{UserName:c,Tags:[{Key:"Name",Value:c},{Key:"Environment",Value:r}]}};if(s&&s.length>0)d.Properties.Groups=s;if(a&&a.length>0)d.Properties.ManagedPolicyArns=a;return{user:d,logicalId:u}}static createRole(e){let{slug:n,environment:r,roleName:i,servicePrincipal:s,awsPrincipal:a,managedPolicyArns:c}=e,u=i||l({slug:n,environment:r,resourceType:"role"}),d=o(u),m={};if(s)m.Service=s;if(a)m.AWS=a;let p={Type:"AWS::IAM::Role",Properties:{RoleName:u,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:m,Action:"sts:AssumeRole"}]},Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:r}]}};if(c&&c.length>0)p.Properties.ManagedPolicyArns=c;return{role:p,logicalId:d}}static createGroup(e){let{slug:n,environment:r,groupName:i,managedPolicyArns:s}=e,a=i||l({slug:n,environment:r,resourceType:"group"}),c=o(a),u={Type:"AWS::IAM::Group",Properties:{GroupName:a}};if(s&&s.length>0)u.Properties.ManagedPolicyArns=s;return{group:u,logicalId:c}}static createPolicy(e){let{slug:n,environment:r,policyName:i,description:s,statements:a}=e,c=i||l({slug:n,environment:r,resourceType:"policy"}),u=o(c),d=a.map((p)=>({Sid:p.sid,Effect:p.effect||"Allow",Action:p.actions,Resource:p.resources,Condition:p.conditions}));return{policy:{Type:"AWS::IAM::ManagedPolicy",Properties:{ManagedPolicyName:c,Description:s||`Managed policy for ${c}`,PolicyDocument:{Version:"2012-10-17",Statement:d}}},logicalId:u}}static attachPolicyToRole(e,n){if(!e.Properties.ManagedPolicyArns)e.Properties.ManagedPolicyArns=[];if(!e.Properties.ManagedPolicyArns.includes(n))e.Properties.ManagedPolicyArns.push(n);return e}static attachPolicyToUser(e,n){if(!e.Properties.ManagedPolicyArns)e.Properties.ManagedPolicyArns=[];if(!e.Properties.ManagedPolicyArns.includes(n))e.Properties.ManagedPolicyArns.push(n);return e}static attachPolicyToGroup(e,n){if(!e.Properties.ManagedPolicyArns)e.Properties.ManagedPolicyArns=[];if(!e.Properties.ManagedPolicyArns.includes(n))e.Properties.ManagedPolicyArns.push(n);return e}static addInlinePolicyToRole(e,n,r){if(!e.Properties.Policies)e.Properties.Policies=[];let i=r.map((s)=>({Effect:s.effect||"Allow",Action:s.actions,Resource:s.resources}));return e.Properties.Policies.push({PolicyName:n,PolicyDocument:{Version:"2012-10-17",Statement:i}}),e}static addInlinePolicyToUser(e,n,r){if(!e.Properties.Policies)e.Properties.Policies=[];let i=r.map((s)=>({Effect:s.effect||"Allow",Action:s.actions,Resource:s.resources}));return e.Properties.Policies.push({PolicyName:n,PolicyDocument:{Version:"2012-10-17",Statement:i}}),e}static createAccessKey(e,n){let{slug:r,environment:i,status:s="Active"}=n,a=l({slug:r,environment:i,resourceType:"access-key"}),c=o(a);return{accessKey:{Type:"AWS::IAM::AccessKey",Properties:{UserName:R.Ref(e),Status:s}},logicalId:c}}static createInstanceProfile(e,n){let{slug:r,environment:i,profileName:s}=n,a=s||l({slug:r,environment:i,resourceType:"instance-profile"}),c=o(a);return{instanceProfile:{Type:"AWS::IAM::InstanceProfile",Properties:{InstanceProfileName:a,Roles:[R.Ref(e)]}},logicalId:c}}static ManagedPolicies={AdministratorAccess:"arn:aws:iam::aws:policy/AdministratorAccess",PowerUserAccess:"arn:aws:iam::aws:policy/PowerUserAccess",ReadOnlyAccess:"arn:aws:iam::aws:policy/ReadOnlyAccess",S3FullAccess:"arn:aws:iam::aws:policy/AmazonS3FullAccess",S3ReadOnlyAccess:"arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess",DynamoDBFullAccess:"arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess",DynamoDBReadOnlyAccess:"arn:aws:iam::aws:policy/AmazonDynamoDBReadOnlyAccess",RDSFullAccess:"arn:aws:iam::aws:policy/AmazonRDSFullAccess",RDSReadOnlyAccess:"arn:aws:iam::aws:policy/AmazonRDSReadOnlyAccess",LambdaFullAccess:"arn:aws:iam::aws:policy/AWSLambda_FullAccess",LambdaReadOnlyAccess:"arn:aws:iam::aws:policy/AWSLambda_ReadOnlyAccess",LambdaBasicExecutionRole:"arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole",LambdaVPCAccessExecutionRole:"arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole",EC2FullAccess:"arn:aws:iam::aws:policy/AmazonEC2FullAccess",EC2ReadOnlyAccess:"arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess",EC2ContainerRegistryReadOnly:"arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly",EC2ContainerRegistryPowerUser:"arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryPowerUser",ECSTaskExecutionRole:"arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy",ECSFullAccess:"arn:aws:iam::aws:policy/AmazonECS_FullAccess",CloudWatchFullAccess:"arn:aws:iam::aws:policy/CloudWatchFullAccess",CloudWatchLogsFullAccess:"arn:aws:iam::aws:policy/CloudWatchLogsFullAccess",SESFullAccess:"arn:aws:iam::aws:policy/AmazonSESFullAccess",SNSFullAccess:"arn:aws:iam::aws:policy/AmazonSNSFullAccess",SQSFullAccess:"arn:aws:iam::aws:policy/AmazonSQSFullAccess",SecretsManagerReadWrite:"arn:aws:iam::aws:policy/SecretsManagerReadWrite"};static ServicePrincipals={Lambda:"lambda.amazonaws.com",EC2:"ec2.amazonaws.com",ECS:"ecs.amazonaws.com",ECSTaskExecution:"ecs-tasks.amazonaws.com",APIGateway:"apigateway.amazonaws.com",Events:"events.amazonaws.com",States:"states.amazonaws.com",CodeBuild:"codebuild.amazonaws.com",CodeDeploy:"codedeploy.amazonaws.com",CloudFormation:"cloudformation.amazonaws.com"};static createCiCdUser(e){let{slug:n,environment:r,permissions:i,createAccessKey:s=!0}=e,a={},c=[];if(i.s3Buckets&&i.s3Buckets.length>0)c.push({sid:"S3Access",actions:["s3:GetBucketLocation","s3:ListBucket","s3:GetObject","s3:PutObject","s3:DeleteObject","s3:ListBucketMultipartUploads","s3:AbortMultipartUpload"],resources:[...i.s3Buckets,...i.s3Buckets.map((f)=>`${f}/*`)]});if(i.cloudFrontDistributions&&i.cloudFrontDistributions.length>0)c.push({sid:"CloudFrontAccess",actions:["cloudfront:CreateInvalidation","cloudfront:GetInvalidation","cloudfront:ListInvalidations","cloudfront:GetDistribution"],resources:i.cloudFrontDistributions});if(i.ecrRepositories&&i.ecrRepositories.length>0)c.push({sid:"ECRAccess",actions:["ecr:GetAuthorizationToken","ecr:BatchCheckLayerAvailability","ecr:GetDownloadUrlForLayer","ecr:GetRepositoryPolicy","ecr:DescribeRepositories","ecr:ListImages","ecr:DescribeImages","ecr:BatchGetImage","ecr:InitiateLayerUpload","ecr:UploadLayerPart","ecr:CompleteLayerUpload","ecr:PutImage"],resources:i.ecrRepositories}),c.push({sid:"ECRLogin",actions:["ecr:GetAuthorizationToken"],resources:"*"});if(i.ecsServices&&i.ecsServices.length>0)c.push({sid:"ECSAccess",actions:["ecs:DescribeServices","ecs:DescribeTaskDefinition","ecs:DescribeTasks","ecs:ListTasks","ecs:RegisterTaskDefinition","ecs:UpdateService","ecs:RunTask","ecs:StopTask"],resources:i.ecsServices}),c.push({sid:"ECSTaskDefinitions",actions:["ecs:RegisterTaskDefinition","ecs:DeregisterTaskDefinition"],resources:"*"}),c.push({sid:"ECSPassRole",actions:["iam:PassRole"],resources:"*",conditions:{StringLike:{"iam:PassedToService":"ecs-tasks.amazonaws.com"}}});if(i.cloudFormationStacks&&i.cloudFormationStacks.length>0)c.push({sid:"CloudFormationAccess",actions:["cloudformation:CreateStack","cloudformation:UpdateStack","cloudformation:DeleteStack","cloudformation:DescribeStacks","cloudformation:DescribeStackEvents","cloudformation:DescribeStackResources","cloudformation:GetTemplate","cloudformation:ListStackResources","cloudformation:ValidateTemplate"],resources:i.cloudFormationStacks});if(i.lambdaFunctions&&i.lambdaFunctions.length>0)c.push({sid:"LambdaAccess",actions:["lambda:GetFunction","lambda:UpdateFunctionCode","lambda:UpdateFunctionConfiguration","lambda:PublishVersion","lambda:UpdateAlias","lambda:CreateAlias"],resources:i.lambdaFunctions});if(i.secretsManagerSecrets&&i.secretsManagerSecrets.length>0)c.push({sid:"SecretsManagerAccess",actions:["secretsmanager:GetSecretValue","secretsmanager:DescribeSecret"],resources:i.secretsManagerSecrets});let{policy:u,logicalId:d}=Ie.createPolicy({slug:n,environment:r,policyName:l({slug:n,environment:r,resourceType:"cicd-policy"}),description:`CI/CD deployment policy for ${n} (${r})`,statements:c});a[d]=u;let{user:m,logicalId:p}=Ie.createUser({slug:n,environment:r,userName:l({slug:n,environment:r,resourceType:"cicd-user"}),managedPolicyArns:[R.Ref(d)]});a[p]=m;let g,y;if(s){let f=Ie.createAccessKey(p,{slug:n,environment:r});g=f.accessKey,y=f.logicalId,a[y]=g}return{user:m,accessKey:g,policy:u,userLogicalId:p,accessKeyLogicalId:y,policyLogicalId:d,resources:a}}static createCrossAccountRole(e){let{slug:n,environment:r,trustedAccountIds:i,externalId:s,permissions:a,maxSessionDuration:c=3600}=e,u={},{policy:d,logicalId:m}=Ie.createPolicy({slug:n,environment:r,policyName:l({slug:n,environment:r,resourceType:"cross-account-policy"}),description:`Cross-account access policy for ${n} (${r})`,statements:a});u[m]=d;let p=l({slug:n,environment:r,resourceType:"cross-account-role"}),g=o(p),y={};if(s)y.StringEquals={"sts:ExternalId":s};let f={Type:"AWS::IAM::Role",Properties:{RoleName:p,MaxSessionDuration:c,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:i.map((h)=>`arn:aws:iam::${h}:root`)},Action:"sts:AssumeRole",...Object.keys(y).length>0?{Condition:y}:{}}]},ManagedPolicyArns:[R.Ref(m)],Tags:[{Key:"Name",Value:p},{Key:"Environment",Value:r},{Key:"Purpose",Value:"Cross-Account Access"}]}};return u[g]=f,{role:f,policy:d,roleLogicalId:g,policyLogicalId:m,resources:u}}static createCliUser(e){let{slug:n,environment:r,permissions:i="readonly"}=e,s={},a=[],c=[];switch(i){case"readonly":c=[Ie.ManagedPolicies.ReadOnlyAccess];break;case"deploy":a=[{sid:"S3Deploy",actions:["s3:*"],resources:"*"},{sid:"CloudFrontDeploy",actions:["cloudfront:*"],resources:"*"},{sid:"ECSDeploy",actions:["ecs:*"],resources:"*"},{sid:"ECRDeploy",actions:["ecr:*"],resources:"*"},{sid:"LambdaDeploy",actions:["lambda:*"],resources:"*"},{sid:"CloudFormationDeploy",actions:["cloudformation:*"],resources:"*"},{sid:"IAMPassRole",actions:["iam:PassRole"],resources:"*"}];break;case"admin":c=[Ie.ManagedPolicies.AdministratorAccess];break}let u,d;if(a.length>0){let f=Ie.createPolicy({slug:n,environment:r,policyName:l({slug:n,environment:r,resourceType:"cli-policy"}),description:`CLI access policy for ${n} (${r})`,statements:a});u=f.policy,d=f.logicalId,s[d]=u,c=[R.Ref(d)]}let{user:m,logicalId:p}=Ie.createUser({slug:n,environment:r,userName:l({slug:n,environment:r,resourceType:"cli-user"}),managedPolicyArns:c});s[p]=m;let{accessKey:g,logicalId:y}=Ie.createAccessKey(p,{slug:n,environment:r});return s[y]=g,{user:m,accessKey:g,policy:u,userLogicalId:p,accessKeyLogicalId:y,policyLogicalId:d,resources:s}}static CiCdPolicies={s3Deployment:(e)=>[{sid:"S3ListBuckets",actions:["s3:ListBucket","s3:GetBucketLocation"],resources:e},{sid:"S3Objects",actions:["s3:GetObject","s3:PutObject","s3:DeleteObject"],resources:e.map((n)=>`${n}/*`)}],cloudFrontInvalidation:(e)=>[{sid:"CloudFrontInvalidation",actions:["cloudfront:CreateInvalidation","cloudfront:GetInvalidation","cloudfront:ListInvalidations"],resources:e}],ecsDeployment:()=>[{sid:"ECSServices",actions:["ecs:DescribeServices","ecs:UpdateService","ecs:DescribeTaskDefinition","ecs:RegisterTaskDefinition"],resources:"*"},{sid:"ECSPassRole",actions:["iam:PassRole"],resources:"*",conditions:{StringLike:{"iam:PassedToService":"ecs-tasks.amazonaws.com"}}}],ecrPush:(e)=>[{sid:"ECRAuth",actions:["ecr:GetAuthorizationToken"],resources:"*"},{sid:"ECRPush",actions:["ecr:BatchCheckLayerAvailability","ecr:GetDownloadUrlForLayer","ecr:BatchGetImage","ecr:InitiateLayerUpload","ecr:UploadLayerPart","ecr:CompleteLayerUpload","ecr:PutImage"],resources:e}],lambdaDeployment:(e)=>[{sid:"LambdaDeploy",actions:["lambda:GetFunction","lambda:UpdateFunctionCode","lambda:UpdateFunctionConfiguration","lambda:PublishVersion"],resources:e}],cloudFormationDeployment:(e)=>[{sid:"CloudFormationDeploy",actions:["cloudformation:CreateStack","cloudformation:UpdateStack","cloudformation:DescribeStacks","cloudformation:DescribeStackEvents","cloudformation:GetTemplate"],resources:e}]}}class rs{static createRestApi(e){let{slug:n,environment:r,name:i,description:s,endpointType:a="REGIONAL",binaryMediaTypes:c,compressionSize:u}=e,d=i||l({slug:n,environment:r,resourceType:"rest-api"}),m=o(d),p={Type:"AWS::ApiGateway::RestApi",Properties:{Name:d,Description:s||`REST API for ${n} ${r}`,EndpointConfiguration:{Types:[a]},Tags:[{Key:"Name",Value:d},{Key:"Environment",Value:r}]}};if(c&&c.length>0)p.Properties.BinaryMediaTypes=c;if(u!==void 0)p.Properties.MinimumCompressionSize=u;return{restApi:p,logicalId:m}}static createHttpApi(e){let{slug:n,environment:r,name:i,description:s,corsEnabled:a=!0,corsOrigins:c=["*"],corsMethods:u=["GET","POST","PUT","PATCH","DELETE","OPTIONS"],corsHeaders:d=["*"],corsMaxAge:m=86400,corsAllowCredentials:p=!1}=e,g=i||l({slug:n,environment:r,resourceType:"http-api"}),y=o(g),f={Type:"AWS::ApiGatewayV2::Api",Properties:{Name:g,Description:s||`HTTP API for ${n} ${r}`,ProtocolType:"HTTP",Tags:{Name:g,Environment:r}}};if(a)f.Properties.CorsConfiguration={AllowOrigins:c,AllowMethods:u,AllowHeaders:d,MaxAge:m,AllowCredentials:p};return{httpApi:f,logicalId:y}}static createWebSocketApi(e){let{slug:n,environment:r,name:i,description:s}=e,a=i||l({slug:n,environment:r,resourceType:"ws-api"}),c=o(a);return{webSocketApi:{Type:"AWS::ApiGatewayV2::Api",Properties:{Name:a,Description:s||`WebSocket API for ${n} ${r}`,ProtocolType:"WEBSOCKET",Tags:{Name:a,Environment:r}}},logicalId:c}}static createDeployment(e,n){let{slug:r,environment:i,description:s}=n,a=l({slug:r,environment:i,resourceType:"api-deployment"}),c=o(a);return{deployment:{Type:"AWS::ApiGateway::Deployment",Properties:{RestApiId:R.Ref(e),Description:s||`Deployment for ${a}`}},logicalId:c}}static createStage(e,n,r){let{slug:i,environment:s,stageName:a,description:c,cacheEnabled:u=!1,cacheSize:d="0.5",variables:m,throttling:p}=r,g=l({slug:i,environment:s,resourceType:"api-stage"}),y=o(g),f={Type:"AWS::ApiGateway::Stage",Properties:{StageName:a||s,RestApiId:R.Ref(e),DeploymentId:R.Ref(n),Description:c,CacheClusterEnabled:u,Tags:[{Key:"Name",Value:g},{Key:"Environment",Value:s}]}};if(u)f.Properties.CacheClusterSize=d;if(m)f.Properties.Variables=m;if(p)f.Properties.MethodSettings=[{HttpMethod:"*",ResourcePath:"/*",ThrottlingBurstLimit:p.burstLimit,ThrottlingRateLimit:p.rateLimit}];return{stage:f,logicalId:y}}static createAuthorizer(e,n){let{slug:r,environment:i,name:s,type:a,functionArn:c,identitySource:u,userPoolArns:d,ttl:m=300}=n,p=s||l({slug:r,environment:i,resourceType:"api-authorizer"}),g=o(p),y={Type:"AWS::ApiGateway::Authorizer",Properties:{Name:p,Type:a,RestApiId:R.Ref(e),AuthorizerResultTtlInSeconds:m}};if(a==="TOKEN"||a==="REQUEST"){if(!c)throw Error("Lambda authorizer requires functionArn");y.Properties.AuthorizerUri=c,y.Properties.IdentitySource=u||"method.request.header.Authorization"}if(a==="COGNITO_USER_POOLS"){if(!d||d.length===0)throw Error("Cognito authorizer requires userPoolArns");y.Properties.ProviderARNs=d,y.Properties.IdentitySource=u||"method.request.header.Authorization"}return{authorizer:y,logicalId:g}}static setCors(e,n={}){let{origins:r=["*"],methods:i=["GET","POST","PUT","PATCH","DELETE","OPTIONS"],headers:s=["*"],maxAge:a=86400,allowCredentials:c=!1}=n;return e.Properties.CorsConfiguration={AllowOrigins:r,AllowMethods:i,AllowHeaders:s,MaxAge:a,AllowCredentials:c},e}static addThrottling(e,n=5000,r=1e4){if(!e.Properties.MethodSettings)e.Properties.MethodSettings=[];return e.Properties.MethodSettings.push({HttpMethod:"*",ResourcePath:"/*",ThrottlingBurstLimit:n,ThrottlingRateLimit:r}),e}static enableCaching(e,n="0.5",r=300){if(e.Properties.CacheClusterEnabled=!0,e.Properties.CacheClusterSize=n,!e.Properties.MethodSettings)e.Properties.MethodSettings=[];return e.Properties.MethodSettings.push({HttpMethod:"*",ResourcePath:"/*",CachingEnabled:!0,CacheTtlInSeconds:r}),e}static CacheSizes={Small:"0.5",Medium:"1.6",Large:"6.1",XLarge:"13.5",XXLarge:"28.4",XXXLarge:"58.2",Huge:"118",Massive:"237"};static ThrottlingPresets={Light:{burstLimit:100,rateLimit:50},Medium:{burstLimit:500,rateLimit:250},Heavy:{burstLimit:2000,rateLimit:1000},Default:{burstLimit:5000,rateLimit:1e4}}}class Le{static createTopic(e){let{slug:n,environment:r,topicName:i,displayName:s,encrypted:a=!1,kmsKeyId:c}=e,u=i||l({slug:n,environment:r,resourceType:"topic"}),d=o(u),m={Type:"AWS::SNS::Topic",Properties:{TopicName:u,DisplayName:s||u,Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:r}]}};if(a&&c)m.Properties.KmsMasterKeyId=c;return{topic:m,logicalId:d}}static subscribe(e,n){let{slug:r,environment:i,protocol:s,endpoint:a,filterPolicy:c,rawMessageDelivery:u=!1}=n,d=l({slug:r,environment:i,resourceType:"subscription"}),m=a.replace(/[^a-zA-Z0-9]/g,""),p=m.length>12?m.slice(-12):m,g=o(`${d}-${s}-${p}`),y={Type:"AWS::SNS::Subscription",Properties:{TopicArn:R.Ref(e),Protocol:s,Endpoint:a,RawMessageDelivery:u}};if(c)y.Properties.FilterPolicy=c;return{subscription:y,logicalId:g}}static subscribeEmail(e,n,r){return Le.subscribe(e,{...r,protocol:"email",endpoint:n})}static subscribeLambda(e,n,r){return Le.subscribe(e,{...r,protocol:"lambda",endpoint:n,rawMessageDelivery:!0})}static subscribeSqs(e,n,r){return Le.subscribe(e,{...r,protocol:"sqs",endpoint:n})}static subscribeHttp(e,n,r){let i=n.startsWith("https://")?"https":"http";return Le.subscribe(e,{...r,protocol:i,endpoint:n})}static subscribeSms(e,n,r){return Le.subscribe(e,{...r,protocol:"sms",endpoint:n})}static setTopicPolicy(e,n){let{slug:r,environment:i,allowedPrincipals:s,allowedServices:a,actions:c="SNS:Publish"}=n,u=l({slug:r,environment:i,resourceType:"topic-policy"}),d=o(u),m={};if(s)m.AWS=s;if(a)m.Service=a;return{policy:{Type:"AWS::SNS::TopicPolicy",Properties:{Topics:[R.Ref(e)],PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:m,Action:c,Resource:R.Ref(e)}]}}},logicalId:d}}static allowCloudWatchAlarms(e,n){return Le.setTopicPolicy(e,{...n,allowedServices:"cloudwatch.amazonaws.com",actions:"SNS:Publish"})}static allowEventBridge(e,n){return Le.setTopicPolicy(e,{...n,allowedServices:"events.amazonaws.com",actions:"SNS:Publish"})}static allowS3(e,n){return Le.setTopicPolicy(e,{...n,allowedServices:"s3.amazonaws.com",actions:"SNS:Publish"})}static enableEncryption(e,n){if(!e.Properties)e.Properties={};return e.Properties.KmsMasterKeyId=n,e}static addInlineSubscription(e,n,r){if(!e.Properties)e.Properties={};if(!e.Properties.Subscription)e.Properties.Subscription=[];return e.Properties.Subscription.push({Protocol:n,Endpoint:r}),e}static FilterPolicies={eventType:(e)=>({eventType:e}),status:(e)=>({status:e}),numericRange:(e,n,r)=>({[e]:[{numeric:[">=",n,"<=",r]}]}),prefix:(e,n)=>({[e]:[{prefix:n}]}),and:(...e)=>Object.assign({},...e),exists:(e,n)=>({[e]:[{exists:n}]})};static UseCases={createAlertTopic:(e)=>Le.createTopic({...e,topicName:e.topicName||`${e.slug}-${e.environment}-alerts`,displayName:e.displayName||"Alert Notifications"}),createEventFanout:(e)=>Le.createTopic({...e,topicName:e.topicName||`${e.slug}-${e.environment}-events`,displayName:e.displayName||"Event Fanout"}),createNotificationTopic:(e)=>Le.createTopic({...e,topicName:e.topicName||`${e.slug}-${e.environment}-notifications`,displayName:e.displayName||"User Notifications"})}}class gu{static createStateMachine(e){let{slug:n,environment:r,stateMachineName:i,type:s="STANDARD",definition:a,roleArn:c,loggingConfiguration:u,tracingConfiguration:d}=e,m=i||l({slug:n,environment:r,resourceType:"state-machine"}),p=o(m),g,y,f;if(c)f=c;else{let S=l({slug:n,environment:r,resourceType:"state-machine-role"});y=o(S),g={Type:"AWS::IAM::Role",Properties:{RoleName:S,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"states.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/CloudWatchLogsFullAccess"],Tags:[{Key:"Name",Value:S},{Key:"Environment",Value:r}]}},f=R.GetAtt(y,"Arn")}let h={Type:"AWS::StepFunctions::StateMachine",Properties:{StateMachineName:m,StateMachineType:s,DefinitionString:JSON.stringify(a),RoleArn:f,Tags:[{Key:"Name",Value:m},{Key:"Environment",Value:r}]}};if(u)h.Properties.LoggingConfiguration={Level:u.level,IncludeExecutionData:u.includeExecutionData,Destinations:u.destinations?.map((S)=>({CloudWatchLogsLogGroup:{LogGroupArn:S}}))};if(d)h.Properties.TracingConfiguration={Enabled:d.enabled};return{stateMachine:h,logicalId:p,role:g,roleLogicalId:y}}static createLambdaTask(e,n){return{Type:"Task",Resource:"arn:aws:states:::lambda:invoke",Parameters:{FunctionName:e,Payload:n?.parameters||{"Input.$":"$"}},ResultPath:n?.resultPath,Retry:n?.retry,Catch:n?.catch,Next:n?.next,End:n?.end}}static createDynamoDBTask(e,n,r,i){return{Type:"Task",Resource:{GetItem:"arn:aws:states:::dynamodb:getItem",PutItem:"arn:aws:states:::dynamodb:putItem",UpdateItem:"arn:aws:states:::dynamodb:updateItem",DeleteItem:"arn:aws:states:::dynamodb:deleteItem"}[e],Parameters:{TableName:n,...r},ResultPath:i?.resultPath,Retry:i?.retry,Catch:i?.catch,Next:i?.next,End:i?.end}}static createSNSPublishTask(e,n,r){return{Type:"Task",Resource:"arn:aws:states:::sns:publish",Parameters:{TopicArn:e,Message:n},ResultPath:r?.resultPath,Retry:r?.retry,Catch:r?.catch,Next:r?.next,End:r?.end}}static createSQSSendMessageTask(e,n,r){return{Type:"Task",Resource:"arn:aws:states:::sqs:sendMessage",Parameters:{QueueUrl:e,MessageBody:n},ResultPath:r?.resultPath,Retry:r?.retry,Catch:r?.catch,Next:r?.next,End:r?.end}}static createPassState(e){return{Type:"Pass",Result:e?.result,ResultPath:e?.resultPath,Parameters:e?.parameters,Next:e?.next,End:e?.end}}static createWaitState(e){return{Type:"Wait",Seconds:e.seconds,Timestamp:e.timestamp,SecondsPath:e.secondsPath,TimestampPath:e.timestampPath,Next:e.next,End:e.end}}static createChoiceState(e,n){return{Type:"Choice",Choices:e,Default:n}}static createParallelState(e,n){return{Type:"Parallel",Branches:e,ResultPath:n?.resultPath,Retry:n?.retry,Catch:n?.catch,Next:n?.next,End:n?.end}}static createMapState(e,n){return{Type:"Map",ItemsPath:n?.itemsPath||"$.items",Iterator:e,MaxConcurrency:n?.maxConcurrency,ResultPath:n?.resultPath,Retry:n?.retry,Catch:n?.catch,Next:n?.next,End:n?.end}}static createSucceedState(){return{Type:"Succeed"}}static createFailState(e,n){return{Type:"Fail",Error:e,Cause:n}}static RetryPolicies={standard:()=>({ErrorEquals:["States.ALL"],IntervalSeconds:2,MaxAttempts:3,BackoffRate:2}),aggressive:()=>({ErrorEquals:["States.TaskFailed","States.Timeout"],IntervalSeconds:1,MaxAttempts:5,BackoffRate:1.5}),custom:(e,n,r,i)=>({ErrorEquals:e,IntervalSeconds:n,MaxAttempts:r,BackoffRate:i})};static CatchPolicies={all:(e,n)=>({ErrorEquals:["States.ALL"],Next:e,ResultPath:n||"$.error"}),specific:(e,n,r)=>({ErrorEquals:e,Next:n,ResultPath:r||"$.error"})};static Patterns={sequential:(e,n,r)=>{let i={};return r.forEach((s,a)=>{let c=a===r.length-1;i[s.name]={...s.state,Next:c?void 0:r[a+1].name,End:c}}),{Comment:"Sequential workflow",StartAt:r[0].name,States:i}},fanout:(e,n,r)=>({Comment:"Fan-out workflow",StartAt:"Parallel",States:{Parallel:{Type:"Parallel",Branches:r.map((i)=>i.definition),End:!0}}}),map:(e,n,r,i)=>({Comment:"Map workflow",StartAt:"Map",States:{Map:{Type:"Map",ItemsPath:"$.items",Iterator:r,MaxConcurrency:i,End:!0}}}),withErrorHandling:(e,n,r,i)=>({Comment:"Workflow with error handling",StartAt:"Main",States:{Main:{...r,Catch:[{ErrorEquals:["States.ALL"],Next:"ErrorHandler"}],Next:"Success"},ErrorHandler:i,Success:{Type:"Succeed"}}})}}class Vi{static createAlarm(e){let{slug:n,environment:r,alarmName:i,metricName:s,namespace:a,statistic:c="Average",period:u=300,evaluationPeriods:d=1,threshold:m,comparisonOperator:p,treatMissingData:g="notBreaching",actionsEnabled:y=!0,alarmActions:f,okActions:h,insufficientDataActions:S,dimensions:C,unit:P,datapointsToAlarm:E}=e,v=i||l({slug:n,environment:r,resourceType:"alarm"}),w=o(v),D={Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:v,MetricName:s,Namespace:a,Statistic:c,Period:u,EvaluationPeriods:d,Threshold:m,ComparisonOperator:p,TreatMissingData:g,ActionsEnabled:y}};if(f&&f.length>0)D.Properties.AlarmActions=f;if(h&&h.length>0)D.Properties.OKActions=h;if(S&&S.length>0)D.Properties.InsufficientDataActions=S;if(C)D.Properties.Dimensions=Object.entries(C).map(([x,L])=>({Name:x,Value:L}));if(P)D.Properties.Unit=P;if(E!==void 0)D.Properties.DatapointsToAlarm=E;return{alarm:D,logicalId:w}}static createCompositeAlarm(e){let{slug:n,environment:r,alarmName:i,alarmRule:s,actionsEnabled:a=!0,alarmActions:c,okActions:u,insufficientDataActions:d}=e,m=i||l({slug:n,environment:r,resourceType:"composite-alarm"}),p=o(m),g={Type:"AWS::CloudWatch::CompositeAlarm",Properties:{AlarmName:m,AlarmRule:s,ActionsEnabled:a}};if(c&&c.length>0)g.Properties.AlarmActions=c;if(u&&u.length>0)g.Properties.OKActions=u;if(d&&d.length>0)g.Properties.InsufficientDataActions=d;return{alarm:g,logicalId:p}}static createDashboard(e){let{slug:n,environment:r,dashboardName:i,widgets:s}=e,a=i||l({slug:n,environment:r,resourceType:"dashboard"}),c=o(a),u={widgets:s.map((m)=>({type:m.type,x:m.x,y:m.y,width:m.width,height:m.height,properties:m.properties}))};return{dashboard:{Type:"AWS::CloudWatch::Dashboard",Properties:{DashboardName:a,DashboardBody:JSON.stringify(u)}},logicalId:c}}static createLogGroup(e){let{slug:n,environment:r,logGroupName:i,retentionInDays:s,kmsKeyId:a}=e,c=i||l({slug:n,environment:r,resourceType:"log-group"}),u=o(c),d={Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:c}};if(s!==void 0)d.Properties.RetentionInDays=s;if(a)d.Properties.KmsKeyId=a;return{logGroup:d,logicalId:u}}static createLogStream(e,n){let{slug:r,environment:i,logStreamName:s}=n,a=s||l({slug:r,environment:i,resourceType:"log-stream"}),c=o(a);return{logStream:{Type:"AWS::Logs::LogStream",Properties:{LogGroupName:R.Ref(e),LogStreamName:a}},logicalId:c}}static createMetricFilter(e,n){let{slug:r,environment:i,filterName:s,filterPattern:a,metricTransformations:c}=n,u=s||l({slug:r,environment:i,resourceType:"metric-filter"}),d=o(u);return{metricFilter:{Type:"AWS::Logs::MetricFilter",Properties:{LogGroupName:R.Ref(e),FilterPattern:a,MetricTransformations:c.map((p)=>({MetricName:p.metricName,MetricNamespace:p.metricNamespace,MetricValue:p.metricValue,DefaultValue:p.defaultValue,Unit:p.unit}))}},logicalId:d}}static AlarmTypes={highCpu:(e,n,r,i=80,s)=>({slug:e,environment:n,alarmName:`${e}-${n}-high-cpu`,metricName:"CPUUtilization",namespace:"AWS/EC2",statistic:"Average",period:300,evaluationPeriods:2,threshold:i,comparisonOperator:"GreaterThanThreshold",dimensions:{InstanceId:r},alarmActions:s?[s]:void 0}),highMemory:(e,n,r,i=80,s)=>({slug:e,environment:n,alarmName:`${e}-${n}-high-memory`,metricName:"MemoryUtilization",namespace:"System/Linux",statistic:"Average",period:300,evaluationPeriods:2,threshold:i,comparisonOperator:"GreaterThanThreshold",dimensions:{InstanceId:r},alarmActions:s?[s]:void 0}),highDisk:(e,n,r,i=80,s)=>({slug:e,environment:n,alarmName:`${e}-${n}-high-disk`,metricName:"DiskSpaceUtilization",namespace:"System/Linux",statistic:"Average",period:300,evaluationPeriods:2,threshold:i,comparisonOperator:"GreaterThanThreshold",dimensions:{InstanceId:r,Filesystem:"/dev/xvda1",MountPath:"/"},alarmActions:s?[s]:void 0}),lambdaErrors:(e,n,r,i=5,s)=>({slug:e,environment:n,alarmName:`${e}-${n}-lambda-errors`,metricName:"Errors",namespace:"AWS/Lambda",statistic:"Sum",period:300,evaluationPeriods:1,threshold:i,comparisonOperator:"GreaterThanThreshold",dimensions:{FunctionName:r},alarmActions:s?[s]:void 0}),lambdaThrottles:(e,n,r,i=10,s)=>({slug:e,environment:n,alarmName:`${e}-${n}-lambda-throttles`,metricName:"Throttles",namespace:"AWS/Lambda",statistic:"Sum",period:300,evaluationPeriods:1,threshold:i,comparisonOperator:"GreaterThanThreshold",dimensions:{FunctionName:r},alarmActions:s?[s]:void 0}),apiGateway5xxErrors:(e,n,r,i=10,s)=>({slug:e,environment:n,alarmName:`${e}-${n}-api-5xx-errors`,metricName:"5XXError",namespace:"AWS/ApiGateway",statistic:"Sum",period:300,evaluationPeriods:1,threshold:i,comparisonOperator:"GreaterThanThreshold",dimensions:{ApiName:r},alarmActions:s?[s]:void 0}),apiGateway4xxErrors:(e,n,r,i=50,s)=>({slug:e,environment:n,alarmName:`${e}-${n}-api-4xx-errors`,metricName:"4XXError",namespace:"AWS/ApiGateway",statistic:"Sum",period:300,evaluationPeriods:2,threshold:i,comparisonOperator:"GreaterThanThreshold",dimensions:{ApiName:r},alarmActions:s?[s]:void 0}),dynamoDBThrottles:(e,n,r,i=5,s)=>({slug:e,environment:n,alarmName:`${e}-${n}-dynamodb-throttles`,metricName:"UserErrors",namespace:"AWS/DynamoDB",statistic:"Sum",period:300,evaluationPeriods:1,threshold:i,comparisonOperator:"GreaterThanThreshold",dimensions:{TableName:r},alarmActions:s?[s]:void 0}),rdsCpu:(e,n,r,i=80,s)=>({slug:e,environment:n,alarmName:`${e}-${n}-rds-cpu`,metricName:"CPUUtilization",namespace:"AWS/RDS",statistic:"Average",period:300,evaluationPeriods:2,threshold:i,comparisonOperator:"GreaterThanThreshold",dimensions:{DBInstanceIdentifier:r},alarmActions:s?[s]:void 0}),rdsFreeStorage:(e,n,r,i=5368709120,s)=>({slug:e,environment:n,alarmName:`${e}-${n}-rds-storage`,metricName:"FreeStorageSpace",namespace:"AWS/RDS",statistic:"Average",period:300,evaluationPeriods:1,threshold:i,comparisonOperator:"LessThanThreshold",dimensions:{DBInstanceIdentifier:r},alarmActions:s?[s]:void 0,unit:"Bytes"}),sqsQueueDepth:(e,n,r,i=100,s)=>({slug:e,environment:n,alarmName:`${e}-${n}-sqs-depth`,metricName:"ApproximateNumberOfMessagesVisible",namespace:"AWS/SQS",statistic:"Average",period:300,evaluationPeriods:2,threshold:i,comparisonOperator:"GreaterThanThreshold",dimensions:{QueueName:r},alarmActions:s?[s]:void 0}),albUnhealthyTargets:(e,n,r,i,s=1,a)=>({slug:e,environment:n,alarmName:`${e}-${n}-alb-unhealthy`,metricName:"UnHealthyHostCount",namespace:"AWS/ApplicationELB",statistic:"Average",period:300,evaluationPeriods:2,threshold:s,comparisonOperator:"GreaterThanThreshold",dimensions:{LoadBalancer:r,TargetGroup:i},alarmActions:a?[a]:void 0}),sesBounceRate:(e,n,r=5,i)=>({slug:e,environment:n,alarmName:`${e}-${n}-ses-bounce-rate`,metricName:"Reputation.BounceRate",namespace:"AWS/SES",statistic:"Average",period:3600,evaluationPeriods:1,threshold:r/100,comparisonOperator:"GreaterThanThreshold",alarmActions:i?[i]:void 0}),sesComplaintRate:(e,n,r=0.1,i)=>({slug:e,environment:n,alarmName:`${e}-${n}-ses-complaint-rate`,metricName:"Reputation.ComplaintRate",namespace:"AWS/SES",statistic:"Average",period:3600,evaluationPeriods:1,threshold:r/100,comparisonOperator:"GreaterThanThreshold",alarmActions:i?[i]:void 0}),smsDeliveryFailure:(e,n,r,i=10,s)=>({slug:e,environment:n,alarmName:`${e}-${n}-sms-delivery-failure`,metricName:"DirectSendMessagePermanentFailure",namespace:"AWS/Pinpoint",statistic:"Sum",period:300,evaluationPeriods:1,threshold:i,comparisonOperator:"GreaterThanThreshold",dimensions:{ApplicationId:r},alarmActions:s?[s]:void 0}),smsSpendLimit:(e,n,r=100,i)=>({slug:e,environment:n,alarmName:`${e}-${n}-sms-spend-limit`,metricName:"DirectSendMessageSpend",namespace:"AWS/Pinpoint",statistic:"Sum",period:86400,evaluationPeriods:1,threshold:r,comparisonOperator:"GreaterThanThreshold",alarmActions:i?[i]:void 0}),connectMissedCalls:(e,n,r,i=5,s)=>({slug:e,environment:n,alarmName:`${e}-${n}-connect-missed-calls`,metricName:"MissedCalls",namespace:"AWS/Connect",statistic:"Sum",period:3600,evaluationPeriods:1,threshold:i,comparisonOperator:"GreaterThanThreshold",dimensions:{InstanceId:r},alarmActions:s?[s]:void 0})};static DashboardWidgets={metric:(e,n,r,i,s,a)=>({type:"metric",x:e,y:n,width:r,height:i,properties:{metrics:s,title:a||"Metrics",region:"us-east-1",period:300}}),text:(e,n,r,i,s)=>({type:"text",x:e,y:n,width:r,height:i,properties:{markdown:s}}),log:(e,n,r,i,s,a)=>({type:"log",x:e,y:n,width:r,height:i,properties:{query:`SOURCE '${s.join("' | SOURCE '")}'
|
|
2275
2275
|
| fields @timestamp, @message
|
|
2276
2276
|
| sort @timestamp desc
|
|
2277
2277
|
| limit 20`,region:"us-east-1",title:a||"Logs"}})};static RetentionPeriods={ONE_DAY:1,THREE_DAYS:3,FIVE_DAYS:5,ONE_WEEK:7,TWO_WEEKS:14,ONE_MONTH:30,TWO_MONTHS:60,THREE_MONTHS:90,FOUR_MONTHS:120,FIVE_MONTHS:150,SIX_MONTHS:180,ONE_YEAR:365,THIRTEEN_MONTHS:400,EIGHTEEN_MONTHS:545,TWO_YEARS:731,FIVE_YEARS:1827,TEN_YEARS:3653,NEVER_EXPIRE:void 0};static FilterPatterns={errors:"[time, request_id, event_type = ERROR*, ...]",all:"",jsonField:(e,n)=>`{ $.${e} = "${n}" }`,httpStatus:(e)=>`[..., status_code = ${e}, ...]`,http4xx:"[..., status_code = 4*, ...]",http5xx:"[..., status_code = 5*, ...]"};static createApplicationDashboard(e){let{slug:n,environment:r,region:i="us-east-1",components:s={}}=e,a=[],c=0;if(a.push({type:"text",x:0,y:c,width:24,height:1,properties:{markdown:`# ${n.toUpperCase()} Dashboard (${r})`}}),c+=1,s.ec2InstanceIds&&s.ec2InstanceIds.length>0)a.push({type:"text",x:0,y:c,width:24,height:1,properties:{markdown:"## EC2 Instances"}}),c+=1,a.push({type:"metric",x:0,y:c,width:8,height:6,properties:{title:"CPU Utilization",region:i,metrics:s.ec2InstanceIds.map((u)=>["AWS/EC2","CPUUtilization","InstanceId",u]),period:300,stat:"Average"}}),a.push({type:"metric",x:8,y:c,width:8,height:6,properties:{title:"Network Traffic",region:i,metrics:[...s.ec2InstanceIds.flatMap((u)=>[["AWS/EC2","NetworkIn","InstanceId",u,{label:`${u} In`}],["AWS/EC2","NetworkOut","InstanceId",u,{label:`${u} Out`}]])],period:300,stat:"Sum"}}),a.push({type:"metric",x:16,y:c,width:8,height:6,properties:{title:"Status Checks",region:i,metrics:s.ec2InstanceIds.map((u)=>["AWS/EC2","StatusCheckFailed","InstanceId",u]),period:60,stat:"Maximum"}}),c+=6;if(s.lambdaFunctionNames&&s.lambdaFunctionNames.length>0)a.push({type:"text",x:0,y:c,width:24,height:1,properties:{markdown:"## Lambda Functions"}}),c+=1,a.push({type:"metric",x:0,y:c,width:8,height:6,properties:{title:"Invocations",region:i,metrics:s.lambdaFunctionNames.map((u)=>["AWS/Lambda","Invocations","FunctionName",u]),period:300,stat:"Sum"}}),a.push({type:"metric",x:8,y:c,width:8,height:6,properties:{title:"Duration",region:i,metrics:s.lambdaFunctionNames.map((u)=>["AWS/Lambda","Duration","FunctionName",u]),period:300,stat:"Average"}}),a.push({type:"metric",x:16,y:c,width:8,height:6,properties:{title:"Errors",region:i,metrics:s.lambdaFunctionNames.map((u)=>["AWS/Lambda","Errors","FunctionName",u]),period:300,stat:"Sum"}}),c+=6;if(s.ecsClusterName&&s.ecsServiceName)a.push({type:"text",x:0,y:c,width:24,height:1,properties:{markdown:"## ECS Service"}}),c+=1,a.push({type:"metric",x:0,y:c,width:8,height:6,properties:{title:"CPU Utilization",region:i,metrics:[["AWS/ECS","CPUUtilization","ClusterName",s.ecsClusterName,"ServiceName",s.ecsServiceName]],period:300,stat:"Average"}}),a.push({type:"metric",x:8,y:c,width:8,height:6,properties:{title:"Memory Utilization",region:i,metrics:[["AWS/ECS","MemoryUtilization","ClusterName",s.ecsClusterName,"ServiceName",s.ecsServiceName]],period:300,stat:"Average"}}),a.push({type:"metric",x:16,y:c,width:8,height:6,properties:{title:"Running Tasks",region:i,metrics:[["ECS/ContainerInsights","RunningTaskCount","ClusterName",s.ecsClusterName,"ServiceName",s.ecsServiceName]],period:60,stat:"Average"}}),c+=6;if(s.albName)a.push({type:"text",x:0,y:c,width:24,height:1,properties:{markdown:"## Application Load Balancer"}}),c+=1,a.push({type:"metric",x:0,y:c,width:8,height:6,properties:{title:"Request Count",region:i,metrics:[["AWS/ApplicationELB","RequestCount","LoadBalancer",s.albName]],period:60,stat:"Sum"}}),a.push({type:"metric",x:8,y:c,width:8,height:6,properties:{title:"Response Time",region:i,metrics:[["AWS/ApplicationELB","TargetResponseTime","LoadBalancer",s.albName]],period:60,stat:"Average"}}),a.push({type:"metric",x:16,y:c,width:8,height:6,properties:{title:"HTTP Errors",region:i,metrics:[["AWS/ApplicationELB","HTTPCode_Target_4XX_Count","LoadBalancer",s.albName,{label:"4XX"}],["AWS/ApplicationELB","HTTPCode_Target_5XX_Count","LoadBalancer",s.albName,{label:"5XX"}]],period:60,stat:"Sum"}}),c+=6;if(s.rdsInstanceId)a.push({type:"text",x:0,y:c,width:24,height:1,properties:{markdown:"## RDS Database"}}),c+=1,a.push({type:"metric",x:0,y:c,width:8,height:6,properties:{title:"CPU Utilization",region:i,metrics:[["AWS/RDS","CPUUtilization","DBInstanceIdentifier",s.rdsInstanceId]],period:300,stat:"Average"}}),a.push({type:"metric",x:8,y:c,width:8,height:6,properties:{title:"Database Connections",region:i,metrics:[["AWS/RDS","DatabaseConnections","DBInstanceIdentifier",s.rdsInstanceId]],period:60,stat:"Sum"}}),a.push({type:"metric",x:16,y:c,width:8,height:6,properties:{title:"Free Storage Space",region:i,metrics:[["AWS/RDS","FreeStorageSpace","DBInstanceIdentifier",s.rdsInstanceId]],period:300,stat:"Average"}}),c+=6;if(s.sqsQueueNames&&s.sqsQueueNames.length>0)a.push({type:"text",x:0,y:c,width:24,height:1,properties:{markdown:"## SQS Queues"}}),c+=1,a.push({type:"metric",x:0,y:c,width:12,height:6,properties:{title:"Messages Visible",region:i,metrics:s.sqsQueueNames.map((u)=>["AWS/SQS","ApproximateNumberOfMessagesVisible","QueueName",u]),period:60,stat:"Sum"}}),a.push({type:"metric",x:12,y:c,width:12,height:6,properties:{title:"Message Age",region:i,metrics:s.sqsQueueNames.map((u)=>["AWS/SQS","ApproximateAgeOfOldestMessage","QueueName",u]),period:60,stat:"Maximum"}}),c+=6;if(s.logGroupNames&&s.logGroupNames.length>0)a.push({type:"text",x:0,y:c,width:24,height:1,properties:{markdown:"## Application Logs"}}),c+=1,a.push({type:"log",x:0,y:c,width:24,height:6,properties:{query:`SOURCE '${s.logGroupNames.join("' | SOURCE '")}'
|
|
2278
2278
|
| fields @timestamp, @message
|
|
2279
2279
|
| filter @message like /ERROR|WARN|Exception/
|
|
2280
2280
|
| sort @timestamp desc
|
|
2281
|
-
| limit 50`,region:i,title:"Recent Errors and Warnings"}}),c+=6;return Vi.createDashboard({slug:n,environment:r,widgets:a})}static DashboardTemplates={staticWebsite:(e)=>({slug:e.slug,environment:e.environment,widgets:[{type:"text",x:0,y:0,width:24,height:1,properties:{markdown:`# ${e.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",e.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",e.cloudFrontDistributionId,"Region","Global",{label:"4XX"}],["AWS/CloudFront","5xxErrorRate","DistributionId",e.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",e.cloudFrontDistributionId,"Region","Global"]],period:300,stat:"Sum"}},{type:"metric",x:0,y:7,width:12,height:6,properties:{title:"S3 Bucket Size",region:e.region||"us-east-1",metrics:[["AWS/S3","BucketSizeBytes","BucketName",e.s3BucketName,"StorageType","StandardStorage"]],period:86400,stat:"Average"}},{type:"metric",x:12,y:7,width:12,height:6,properties:{title:"S3 Number of Objects",region:e.region||"us-east-1",metrics:[["AWS/S3","NumberOfObjects","BucketName",e.s3BucketName,"StorageType","AllStorageTypes"]],period:86400,stat:"Average"}}]}),serverlessApi:(e)=>({slug:e.slug,environment:e.environment,widgets:[{type:"text",x:0,y:0,width:24,height:1,properties:{markdown:`# ${e.slug.toUpperCase()} Serverless API Dashboard`}},{type:"metric",x:0,y:1,width:8,height:6,properties:{title:"API Requests",region:e.region||"us-east-1",metrics:[["AWS/ApiGateway","Count","ApiName",e.apiGatewayName]],period:60,stat:"Sum"}},{type:"metric",x:8,y:1,width:8,height:6,properties:{title:"API Latency",region:e.region||"us-east-1",metrics:[["AWS/ApiGateway","Latency","ApiName",e.apiGatewayName]],period:60,stat:"Average"}},{type:"metric",x:16,y:1,width:8,height:6,properties:{title:"API Errors",region:e.region||"us-east-1",metrics:[["AWS/ApiGateway","4XXError","ApiName",e.apiGatewayName,{label:"4XX"}],["AWS/ApiGateway","5XXError","ApiName",e.apiGatewayName,{label:"5XX"}]],period:60,stat:"Sum"}},...e.lambdaFunctionNames.map((n,r)=>({type:"metric",x:r%3*8,y:7+Math.floor(r/3)*6,width:8,height:6,properties:{title:`${n} Metrics`,region:e.region||"us-east-1",metrics:[["AWS/Lambda","Invocations","FunctionName",n],["AWS/Lambda","Duration","FunctionName",n],["AWS/Lambda","Errors","FunctionName",n]],period:300,stat:"Sum"}}))]}),containerService:(e)=>({slug:e.slug,environment:e.environment,widgets:[{type:"text",x:0,y:0,width:24,height:1,properties:{markdown:`# ${e.slug.toUpperCase()} Container Service Dashboard`}},{type:"metric",x:0,y:1,width:8,height:6,properties:{title:"ECS CPU",region:e.region||"us-east-1",metrics:[["AWS/ECS","CPUUtilization","ClusterName",e.ecsClusterName,"ServiceName",e.ecsServiceName]],period:60,stat:"Average"}},{type:"metric",x:8,y:1,width:8,height:6,properties:{title:"ECS Memory",region:e.region||"us-east-1",metrics:[["AWS/ECS","MemoryUtilization","ClusterName",e.ecsClusterName,"ServiceName",e.ecsServiceName]],period:60,stat:"Average"}},{type:"metric",x:16,y:1,width:8,height:6,properties:{title:"Running Tasks",region:e.region||"us-east-1",metrics:[["ECS/ContainerInsights","RunningTaskCount","ClusterName",e.ecsClusterName,"ServiceName",e.ecsServiceName]],period:60,stat:"Average"}},{type:"metric",x:0,y:7,width:8,height:6,properties:{title:"ALB Requests",region:e.region||"us-east-1",metrics:[["AWS/ApplicationELB","RequestCount","LoadBalancer",e.albName]],period:60,stat:"Sum"}},{type:"metric",x:8,y:7,width:8,height:6,properties:{title:"Response Time",region:e.region||"us-east-1",metrics:[["AWS/ApplicationELB","TargetResponseTime","LoadBalancer",e.albName]],period:60,stat:"Average"}},{type:"metric",x:16,y:7,width:8,height:6,properties:{title:"Healthy Hosts",region:e.region||"us-east-1",metrics:[["AWS/ApplicationELB","HealthyHostCount","LoadBalancer",e.albName]],period:60,stat:"Average"}},...e.rdsInstanceId?[{type:"metric",x:0,y:13,width:12,height:6,properties:{title:"RDS CPU",region:e.region||"us-east-1",metrics:[["AWS/RDS","CPUUtilization","DBInstanceIdentifier",e.rdsInstanceId]],period:300,stat:"Average"}},{type:"metric",x:12,y:13,width:12,height:6,properties:{title:"RDS Connections",region:e.region||"us-east-1",metrics:[["AWS/RDS","DatabaseConnections","DBInstanceIdentifier",e.rdsInstanceId]],period:60,stat:"Sum"}}]:[]]})};static Config={createAlarmConfig:(e)=>{let{metricName:n,namespace:r,threshold:i,comparisonOperator:s="GreaterThanThreshold",evaluationPeriods:a=1,period:c=300,statistic:u="Average",treatMissingData:d="missing"}=e;return{MetricName:n,Namespace:r,Threshold:i,ComparisonOperator:s,EvaluationPeriods:a,Period:c,Statistic:u,TreatMissingData:d}},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:(e=80)=>({metricName:"CPUUtilization",threshold:e,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),highMemory:(e=80)=>({metricName:"MemoryUtilization",threshold:e,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),highErrors:(e=10)=>({metricName:"Errors",threshold:e,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:1,period:60,statistic:"Sum"}),highLatency:(e=5000)=>({metricName:"Duration",threshold:e,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),lowHealthyHosts:(e=1)=>({metricName:"HealthyHostCount",namespace:"AWS/ApplicationELB",threshold:e,comparisonOperator:"LessThanThreshold",evaluationPeriods:2,period:60,statistic:"Minimum"}),queueDepth:(e=1000)=>({metricName:"ApproximateNumberOfMessagesVisible",namespace:"AWS/SQS",threshold:e,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),lowStorage:(e=10737418240)=>({metricName:"FreeStorageSpace",namespace:"AWS/RDS",threshold:e,comparisonOperator:"LessThanThreshold",evaluationPeriods:1,period:300,statistic:"Average"})}}}class Pe{static createUserPool(e){let{slug:n,environment:r,userPoolName:i,aliasAttributes:s,autoVerifiedAttributes:a,passwordPolicy:c,mfaConfiguration:u,emailConfiguration:d,smsConfiguration:m,lambdaTriggers:p,userPoolAddOns:g,accountRecoverySetting:y}=e,f=i||l({slug:n,environment:r,resourceType:"user-pool"}),h=o(f),S={Type:"AWS::Cognito::UserPool",Properties:{UserPoolName:f,Policies:c?{PasswordPolicy:{MinimumLength:c.minimumLength,RequireLowercase:c.requireLowercase,RequireUppercase:c.requireUppercase,RequireNumbers:c.requireNumbers,RequireSymbols:c.requireSymbols,TemporaryPasswordValidityDays:c.temporaryPasswordValidityDays}}:void 0,MfaConfiguration:u,Schema:[{Name:"email",AttributeDataType:"String",Required:!0,Mutable:!1}]}};if(s&&s.length>0)S.Properties.UsernameAttributes=s;if(a&&a.length>0)S.Properties.AutoVerifiedAttributes=a;if(d)S.Properties.EmailConfiguration={EmailSendingAccount:d.emailSendingAccount,From:d.from,ReplyToEmailAddress:d.replyToEmailAddress,SourceArn:d.sourceArn,ConfigurationSet:d.configurationSet};if(m)S.Properties.SmsConfiguration={ExternalId:m.externalId,SnsCallerArn:m.snsCallerArn};if(p)S.Properties.LambdaConfig={PreSignUp:p.preSignUp,PostConfirmation:p.postConfirmation,PreAuthentication:p.preAuthentication,PostAuthentication:p.postAuthentication,CustomMessage:p.customMessage,DefineAuthChallenge:p.defineAuthChallenge,CreateAuthChallenge:p.createAuthChallenge,VerifyAuthChallengeResponse:p.verifyAuthChallengeResponse,PreTokenGeneration:p.preTokenGeneration,UserMigration:p.userMigration};if(g)S.Properties.UserPoolAddOns={AdvancedSecurityMode:g.advancedSecurityMode};if(y)S.Properties.AccountRecoverySetting={RecoveryMechanisms:y.recoveryMechanisms};return{userPool:S,logicalId:h}}static createUserPoolClient(e,n){let{slug:r,environment:i,clientName:s,generateSecret:a=!1,refreshTokenValidity:c,accessTokenValidity:u,idTokenValidity:d,tokenValidityUnits:m,readAttributes:p,writeAttributes:g,explicitAuthFlows:y,preventUserExistenceErrors:f,enableTokenRevocation:h,callbackURLs:S,logoutURLs:C,allowedOAuthFlows:P,allowedOAuthScopes:E,allowedOAuthFlowsUserPoolClient:v,supportedIdentityProviders:w}=n,D=s||l({slug:r,environment:i,resourceType:"user-pool-client"}),x=o(D);return{client:{Type:"AWS::Cognito::UserPoolClient",Properties:{ClientName:D,UserPoolId:R.Ref(e),GenerateSecret:a,RefreshTokenValidity:c,AccessTokenValidity:u,IdTokenValidity:d,TokenValidityUnits:m,ReadAttributes:p,WriteAttributes:g,ExplicitAuthFlows:y,PreventUserExistenceErrors:f,EnableTokenRevocation:h,CallbackURLs:S,LogoutURLs:C,AllowedOAuthFlows:P,AllowedOAuthScopes:E,AllowedOAuthFlowsUserPoolClient:v,SupportedIdentityProviders:w}},logicalId:x}}static createUserPoolDomain(e,n){let{slug:r,environment:i,domain:s,customDomainConfig:a}=n,c=l({slug:r,environment:i,resourceType:"user-pool-domain"}),u=o(c);return{domain:{Type:"AWS::Cognito::UserPoolDomain",Properties:{Domain:s,UserPoolId:R.Ref(e),CustomDomainConfig:a}},logicalId:u}}static createIdentityPool(e){let{slug:n,environment:r,identityPoolName:i,allowUnauthenticatedIdentities:s=!1,cognitoIdentityProviders:a,supportedLoginProviders:c,samlProviderARNs:u,openIdConnectProviderARNs:d}=e,m=i||l({slug:n,environment:r,resourceType:"identity-pool"}),p=o(m);return{identityPool:{Type:"AWS::Cognito::IdentityPool",Properties:{IdentityPoolName:m,AllowUnauthenticatedIdentities:s,CognitoIdentityProviders:a,SupportedLoginProviders:c,SamlProviderARNs:u,OpenIdConnectProviderARNs:d}},logicalId:p}}static createIdentityPoolRoleAttachment(e,n){let{slug:r,environment:i,authenticatedRole:s,unauthenticatedRole:a,roleMappings:c}=n,u=l({slug:r,environment:i,resourceType:"identity-pool-role-attachment"}),d=o(u),m={authenticated:s};if(a)m.unauthenticated=a;return{attachment:{Type:"AWS::Cognito::IdentityPoolRoleAttachment",Properties:{IdentityPoolId:R.Ref(e),Roles:m,RoleMappings:c}},logicalId:d}}static createAuthenticatedRole(e){let{slug:n,environment:r,identityPoolLogicalId:i}=e,s=l({slug:n,environment:r,resourceType:"cognito-authenticated-role"}),a=o(s);return{role:{Type:"AWS::IAM::Role",Properties:{RoleName:s,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Federated:"cognito-identity.amazonaws.com"},Action:"sts:AssumeRoleWithWebIdentity",Condition:{StringEquals:{"cognito-identity.amazonaws.com:aud":R.Ref(i)},"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:s},{Key:"Environment",Value:r}]}},logicalId:a}}static createUnauthenticatedRole(e){let{slug:n,environment:r,identityPoolLogicalId:i}=e,s=l({slug:n,environment:r,resourceType:"cognito-unauthenticated-role"}),a=o(s);return{role:{Type:"AWS::IAM::Role",Properties:{RoleName:s,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Federated:"cognito-identity.amazonaws.com"},Action:"sts:AssumeRoleWithWebIdentity",Condition:{StringEquals:{"cognito-identity.amazonaws.com:aud":R.Ref(i)},"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:s},{Key:"Environment",Value:r}]}},logicalId:a}}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:(e,n,r)=>{let{userPool:i,logicalId:s}=Pe.createUserPool({slug:e,environment:n,aliasAttributes:["email"],autoVerifiedAttributes:["email"],passwordPolicy:Pe.PasswordPolicies.standard(),mfaConfiguration:"OPTIONAL"}),{client:a,logicalId:c}=Pe.createUserPoolClient(s,{slug:e,environment:n,explicitAuthFlows:[...Pe.AuthFlows.standard],callbackURLs:[r],allowedOAuthFlows:["code"],allowedOAuthScopes:[...Pe.OAuthScopes.basic],allowedOAuthFlowsUserPoolClient:!0});return{userPool:i,poolId:s,client:a,clientId:c}},mobileApp:(e,n)=>{let{userPool:r,logicalId:i}=Pe.createUserPool({slug:e,environment:n,aliasAttributes:["email"],autoVerifiedAttributes:["email"],passwordPolicy:Pe.PasswordPolicies.standard(),mfaConfiguration:"OPTIONAL"}),{client:s,logicalId:a}=Pe.createUserPoolClient(i,{slug:e,environment:n,explicitAuthFlows:[...Pe.AuthFlows.standard]}),{identityPool:c,logicalId:u}=Pe.createIdentityPool({slug:e,environment:n,allowUnauthenticatedIdentities:!1,cognitoIdentityProviders:[{ClientId:R.Ref(a),ProviderName:R.GetAtt(i,"ProviderName")}]}),{role:d,logicalId:m}=Pe.createAuthenticatedRole({slug:e,environment:n,identityPoolLogicalId:u}),{attachment:p,logicalId:g}=Pe.createIdentityPoolRoleAttachment(u,{slug:e,environment:n,authenticatedRole:R.GetAtt(m,"Arn")});return{userPool:r,poolId:i,client:s,clientId:a,identityPool:c,identityPoolId:u,authRole:d,authRoleId:m,attachment:p,attachmentId:g}}}}import{createHash as $r}from"node:crypto";import{copyFileSync as Br,existsSync as bt,readdirSync as _r,readFileSync as Xe,statSync as Wr,writeFileSync as et}from"node:fs";import{basename as Ur,dirname as ln,extname as un,join as Ve}from"node:path";class De{static createApplication(e){let{slug:n,environment:r,applicationName:i,computePlatform:s}=e,a=i||l({slug:n,environment:r,resourceType:"deploy-app"}),c=o(a);return{application:{Type:"AWS::CodeDeploy::Application",Properties:{ApplicationName:a,ComputePlatform:s,Tags:[{Key:"Name",Value:a},{Key:"Environment",Value:r}]}},logicalId:c}}static createDeploymentGroup(e,n){let{slug:r,environment:i,deploymentGroupName:s,serviceRoleArn:a,autoScalingGroups:c,ec2TagFilters:u,deploymentConfigName:d,autoRollbackConfiguration:m,alarmConfiguration:p,loadBalancerInfo:g,blueGreenDeploymentConfiguration:y}=n,f=s||l({slug:r,environment:i,resourceType:"deploy-group"}),h=o(f);return{deploymentGroup:{Type:"AWS::CodeDeploy::DeploymentGroup",Properties:{ApplicationName:R.Ref(e),DeploymentGroupName:f,ServiceRoleArn:a,AutoScalingGroups:c,Ec2TagFilters:u?.map((C)=>({Key:C.key,Value:C.value,Type:C.type})),DeploymentConfigName:d,AutoRollbackConfiguration:m?{Enabled:m.enabled,Events:m.events}:void 0,AlarmConfiguration:p?{Enabled:p.enabled,Alarms:p.alarms?.map((C)=>({Name:C.name})),IgnorePollAlarmFailure:p.ignorePollAlarmFailure}:void 0,LoadBalancerInfo:g?{TargetGroupInfoList:g.targetGroupInfoList?.map((C)=>({Name:C.name})),ElbInfoList:g.elbInfoList?.map((C)=>({Name:C.name}))}:void 0,BlueGreenDeploymentConfiguration:y?{TerminateBlueInstancesOnDeploymentSuccess:y.terminateBlueInstancesOnDeploymentSuccess?{Action:y.terminateBlueInstancesOnDeploymentSuccess.action,TerminationWaitTimeInMinutes:y.terminateBlueInstancesOnDeploymentSuccess.terminationWaitTimeInMinutes}:void 0,DeploymentReadyOption:y.deploymentReadyOption?{ActionOnTimeout:y.deploymentReadyOption.actionOnTimeout,WaitTimeInMinutes:y.deploymentReadyOption.waitTimeInMinutes}:void 0,GreenFleetProvisioningOption:y.greenFleetProvisioningOption?{Action:y.greenFleetProvisioningOption.action}:void 0}:void 0,Tags:[{Key:"Name",Value:f},{Key:"Environment",Value:i}]}},logicalId:h}}static createDeploymentConfig(e){let{slug:n,environment:r,deploymentConfigName:i,minimumHealthyHosts:s,trafficRoutingConfig:a}=e,c=i||l({slug:n,environment:r,resourceType:"deploy-config"}),u=o(c);return{deploymentConfig:{Type:"AWS::CodeDeploy::DeploymentConfig",Properties:{DeploymentConfigName:c,MinimumHealthyHosts:s?{Type:s.type,Value:s.value}:void 0,TrafficRoutingConfig:a?{Type:a.type,TimeBasedCanary:a.timeBasedCanary?{CanaryPercentage:a.timeBasedCanary.canaryPercentage,CanaryInterval:a.timeBasedCanary.canaryInterval}:void 0,TimeBasedLinear:a.timeBasedLinear?{LinearPercentage:a.timeBasedLinear.linearPercentage,LinearInterval:a.timeBasedLinear.linearInterval}:void 0}:void 0}},logicalId:u}}static DeploymentConfigs={allAtOnce:()=>({type:"FLEET_PERCENT",value:0}),halfAtATime:()=>({type:"FLEET_PERCENT",value:50}),oneAtATime:()=>({type:"HOST_COUNT",value:1}),custom:(e,n)=>({type:e,value:n})};static TrafficRouting={allAtOnce:()=>({type:"AllAtOnce"}),canary:(e,n)=>({type:"TimeBasedCanary",timeBasedCanary:{canaryPercentage:e,canaryInterval:n}}),linear:(e,n)=>({type:"TimeBasedLinear",timeBasedLinear:{linearPercentage:e,linearInterval:n}})};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:(e)=>({terminateBlueInstancesOnDeploymentSuccess:{action:"TERMINATE",terminationWaitTimeInMinutes:e},deploymentReadyOption:{actionOnTimeout:"CONTINUE_DEPLOYMENT",waitTimeInMinutes:0},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}}),withManualApproval:(e)=>({terminateBlueInstancesOnDeploymentSuccess:{action:"TERMINATE",terminationWaitTimeInMinutes:5},deploymentReadyOption:{actionOnTimeout:"STOP_DEPLOYMENT",waitTimeInMinutes:e},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:(e,n,r,i)=>{let{application:s,logicalId:a}=De.createApplication({slug:e,environment:n,computePlatform:"Server"}),{deploymentGroup:c,logicalId:u}=De.createDeploymentGroup(a,{slug:e,environment:n,serviceRoleArn:r,autoScalingGroups:i,deploymentConfigName:"CodeDeployDefault.OneAtATime",autoRollbackConfiguration:De.RollbackConfigs.onFailure()});return{application:s,appId:a,deploymentGroup:c,groupId:u}},lambdaCanaryDeployment:(e,n,r,i=10,s=5)=>{let{application:a,logicalId:c}=De.createApplication({slug:e,environment:n,computePlatform:"Lambda"}),{deploymentConfig:u,logicalId:d}=De.createDeploymentConfig({slug:e,environment:n,trafficRoutingConfig:De.TrafficRouting.canary(i,s)}),{deploymentGroup:m,logicalId:p}=De.createDeploymentGroup(c,{slug:e,environment:n,serviceRoleArn:r,deploymentConfigName:R.Ref(d),autoRollbackConfiguration:De.RollbackConfigs.onAlarmOrFailure()});return{application:a,appId:c,deploymentConfig:u,configId:d,deploymentGroup:m,groupId:p}},ecsBlueGreenDeployment:(e,n,r,i)=>{let{application:s,logicalId:a}=De.createApplication({slug:e,environment:n,computePlatform:"ECS"}),{deploymentGroup:c,logicalId:u}=De.createDeploymentGroup(a,{slug:e,environment:n,serviceRoleArn:r,loadBalancerInfo:{targetGroupInfoList:[{name:i}]},blueGreenDeploymentConfiguration:De.BlueGreenConfigs.standard(),autoRollbackConfiguration:De.RollbackConfigs.onFailure()});return{application:s,appId:a,deploymentGroup:c,groupId:u}}};static Strategies={rolling:(e=25)=>({type:"rolling",batchPercentage:e}),blueGreen:()=>({type:"blue-green"}),canary:(e=10,n=5)=>({type:"canary",canaryPercentage:e,canaryInterval:n}),allAtOnce:()=>({type:"all-at-once"})}}class ie{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(e,n="md5"){let r=Xe(e);return $r(n).update(r).digest("hex")}static computeShortHash(e){return ie.computeFileHash(e).slice(0,8)}static getContentType(e){let n=un(e).toLowerCase();return ie.ContentTypes[n]||"application/octet-stream"}static shouldHashFile(e,n){return![...ie.NoHashPatterns,...n||[]].some((i)=>i.test(e))}static generateHashedFilename(e,n){let r=un(e),i=Ur(e,r),s=ln(e);if(s===".")return`${i}.${n}${r}`;return Ve(s,`${i}.${n}${r}`)}static collectFiles(e,n){let r=[],i=n||e;if(!bt(e))return r;let s=_r(e,{withFileTypes:!0});for(let a of s){let c=Ve(e,a.name);if(a.isDirectory())r.push(...ie.collectFiles(c,i));else if(a.isFile())r.push(c)}return r}static hashDirectory(e){let{sourceDir:n,outputDir:r,excludePatterns:i=[],hashAlgorithm:s="md5",copyUnhashed:a=!0}=e,c=ie.collectFiles(n),u=[],d={};for(let p of c){let g=p.replace(n,"").replace(/^[/\\]/,""),y=ie.shouldHashFile(g,i),f=Wr(p),h=y?ie.computeFileHash(p,s).slice(0,8):"",S=y?ie.generateHashedFilename(g,h):g,C={originalPath:g,hashedPath:S,hash:h,size:f.size,contentType:ie.getContentType(p)};if(u.push(C),d[g]=S,r){let P=Ve(r,S),E=ln(P);if(!bt(E)){let{mkdirSync:v}=Gr("node:fs");v(E,{recursive:!0})}if(y||a)Br(p,P)}}let m={version:"1.0",timestamp:new Date().toISOString(),assets:u,hashMap:d};if(r){let p=Ve(r,"asset-manifest.json");et(p,JSON.stringify(m,null,2))}return m}static getInvalidationPaths(e,n){let r=[];if(!e)return["/*"];let i=e.hashMap,s=n.hashMap;for(let[a,c]of Object.entries(s)){let u=i[a];if(!u||u!==c){if(r.push(`/${a}`),u&&u!==c)r.push(`/${u}`)}}for(let[a,c]of Object.entries(i))if(!s[a])r.push(`/${a}`),r.push(`/${c}`);if(r.length>100)return["/*"];return[...new Set(r)]}static updateHtmlReferences(e){let{htmlDir:n,manifest:r,basePath:i=""}=e,s=ie.collectFiles(n).filter((a)=>a.endsWith(".html")||a.endsWith(".htm"));for(let a of s){let c=Xe(a,"utf-8");for(let[u,d]of Object.entries(r.hashMap)){if(u===d)continue;let m=[new RegExp(`(src|href)=["']${i}/?${ie.escapeRegExp(u)}["']`,"g"),new RegExp(`url\\(["']?${i}/?${ie.escapeRegExp(u)}["']?\\)`,"g")];for(let p of m)c=c.replace(p,(g)=>g.replace(u,d))}et(a,c)}}static updateCssReferences(e){let{cssDir:n,manifest:r,basePath:i=""}=e,s=ie.collectFiles(n).filter((a)=>a.endsWith(".css"));for(let a of s){let c=Xe(a,"utf-8");for(let[u,d]of Object.entries(r.hashMap)){if(u===d)continue;let m=new RegExp(`url\\(["']?${i}/?${ie.escapeRegExp(u)}["']?\\)`,"g");c=c.replace(m,`url(${i}/${d})`)}et(a,c)}}static escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}static generateS3DeploymentManifest(e){let{sourceDir:n,keyPrefix:r="",excludePatterns:i=[],cacheControl:s={hashed:"public, max-age=31536000, immutable",unhashed:"public, max-age=3600",html:"public, max-age=0, must-revalidate"}}=e;return ie.hashDirectory({sourceDir:n,excludePatterns:i}).assets.map((c)=>{let u=c.hash!=="",d=c.contentType==="text/html",m=s.unhashed||"public, max-age=3600";if(d)m=s.html||"public, max-age=0, must-revalidate";else if(u)m=s.hashed||"public, max-age=31536000, immutable";return{localPath:Ve(n,c.originalPath),s3Key:r?`${r}/${c.hashedPath}`:c.hashedPath,contentType:c.contentType,cacheControl:m,hash:c.hash}})}static compareManifests(e,n){let r={added:[],removed:[],changed:[],unchanged:[]},i=new Set(Object.keys(e.hashMap)),s=new Set(Object.keys(n.hashMap));for(let a of s)if(!i.has(a))r.added.push(a);for(let a of i)if(!s.has(a))r.removed.push(a);for(let a of s)if(i.has(a))if(e.hashMap[a]!==n.hashMap[a])r.changed.push(a);else r.unchanged.push(a);return r}static loadManifest(e){if(!bt(e))return null;try{let n=Xe(e,"utf-8");return JSON.parse(n)}catch{return null}}static saveManifest(e,n){et(n,JSON.stringify(e,null,2))}}class zi{static createSecret(e){let{slug:n,environment:r,secretName:i,description:s,secretString:a,kmsKeyId:c,tags:u}=e,d=i||l({slug:n,environment:r,resourceType:"secret"}),m=o(d),p={Type:"AWS::SecretsManager::Secret",Properties:{Name:d,Description:s,SecretString:a,Tags:[{Key:"Name",Value:d},{Key:"Environment",Value:r},...u?Object.entries(u).map(([g,y])=>({Key:g,Value:y})):[]]}};if(c)p.Properties.KmsKeyId=c;return{secret:p,logicalId:m}}static createGeneratedSecret(e){let{slug:n,environment:r,secretName:i,description:s,excludeCharacters:a,excludeLowercase:c,excludeNumbers:u,excludePunctuation:d,excludeUppercase:m,passwordLength:p,requireEachIncludedType:g,kmsKeyId:y,tags:f}=e,h=i||l({slug:n,environment:r,resourceType:"secret"}),S=o(h),C={Type:"AWS::SecretsManager::Secret",Properties:{Name:h,Description:s,GenerateSecretString:{ExcludeCharacters:a,ExcludeLowercase:c,ExcludeNumbers:u,ExcludePunctuation:d,ExcludeUppercase:m,PasswordLength:p||32,RequireEachIncludedType:g!==!1},Tags:[{Key:"Name",Value:h},{Key:"Environment",Value:r},...f?Object.entries(f).map(([P,E])=>({Key:P,Value:E})):[]]}};if(y)C.Properties.KmsKeyId=y;return{secret:C,logicalId:S}}static createDatabaseSecret(e){let{slug:n,environment:r,secretName:i,username:s,dbname:a,engine:c,host:u,port:d,kmsKeyId:m}=e,p=i||l({slug:n,environment:r,resourceType:"db-secret"}),g=o(p),y={username:s};if(a)y.dbname=a;if(c)y.engine=c;if(u)y.host=u;if(d)y.port=d;let f={Type:"AWS::SecretsManager::Secret",Properties:{Name:p,Description:`Database credentials for ${s}`,GenerateSecretString:{SecretStringTemplate:JSON.stringify(y),GenerateStringKey:"password",PasswordLength:32,ExcludeCharacters:'"@/\\',RequireEachIncludedType:!0},Tags:[{Key:"Name",Value:p},{Key:"Environment",Value:r},{Key:"Type",Value:"database"}]}};if(m)f.Properties.KmsKeyId=m;return{secret:f,logicalId:g}}static attachToDatabase(e){let{slug:n,environment:r,secretId:i,targetId:s,targetType:a}=e,c=l({slug:n,environment:r,resourceType:"secret-attachment"}),u=o(c);return{attachment:{Type:"AWS::SecretsManager::SecretTargetAttachment",Properties:{SecretId:i,TargetId:s,TargetType:a}},logicalId:u}}static enableRotation(e){let{slug:n,environment:r,secretId:i,rotationLambdaArn:s,automaticallyAfterDays:a,rotationType:c,kmsKeyArn:u,vpcSecurityGroupIds:d,vpcSubnetIds:m}=e,p=l({slug:n,environment:r,resourceType:"secret-rotation"}),g=o(p),y={Type:"AWS::SecretsManager::RotationSchedule",Properties:{SecretId:i,RotationRules:{AutomaticallyAfterDays:a||30}}};if(s)y.Properties.RotationLambdaARN=s;else if(c)y.Properties.HostedRotationLambda={RotationType:c,KmsKeyArn:u,VpcSecurityGroupIds:d,VpcSubnetIds:m};return{rotation:y,logicalId:g}}static SecretTypes={apiKey:(e,n,r)=>zi.createGeneratedSecret({slug:e,environment:n,secretName:`${e}-${n}-${r}-api-key`,description:`API key for ${r}`,passwordLength:32,excludePunctuation:!0,excludeLowercase:!1,excludeUppercase:!1,excludeNumbers:!1}),oauthClientSecret:(e,n,r)=>zi.createGeneratedSecret({slug:e,environment:n,secretName:`${e}-${n}-${r}-oauth-secret`,description:`OAuth client secret for ${r}`,passwordLength:64,excludeCharacters:"\"'`\\/@",requireEachIncludedType:!0}),jwtSecret:(e,n)=>zi.createGeneratedSecret({slug:e,environment:n,secretName:`${e}-${n}-jwt-secret`,description:"JWT signing secret",passwordLength:64,excludePunctuation:!0}),encryptionKey:(e,n)=>zi.createGeneratedSecret({slug:e,environment:n,secretName:`${e}-${n}-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 X{static createParameter(e){let{slug:n,environment:r,parameterName:i,value:s,type:a="String",description:c,tier:u="Standard",tags:d}=e,m=i||l({slug:n,environment:r,resourceType:"parameter"}),p=o(m);return{parameter:{Type:"AWS::SSM::Parameter",Properties:{Name:`/${n}/${r}/${m}`,Type:a,Value:s,Description:c,Tier:u,Tags:{Name:m,Environment:r,...d}}},logicalId:p}}static createString(e,n,r,i,s){return X.createParameter({slug:e,environment:n,parameterName:r,value:i,type:"String",description:s})}static createSecureString(e,n,r,i,s){return X.createParameter({slug:e,environment:n,parameterName:r,value:i,type:"SecureString",description:s})}static createStringList(e,n,r,i,s){return X.createParameter({slug:e,environment:n,parameterName:r,value:i.join(","),type:"StringList",description:s})}static Parameters={databaseUrl:(e,n,r)=>X.createSecureString(e,n,"database-url",r,"Database connection URL"),apiEndpoint:(e,n,r)=>X.createString(e,n,"api-endpoint",r,"API endpoint URL"),appVersion:(e,n,r)=>X.createString(e,n,"app-version",r,"Application version"),featureFlags:(e,n,r)=>X.createStringList(e,n,"feature-flags",r,"Enabled feature flags"),apiKey:(e,n,r,i)=>X.createSecureString(e,n,`${r}-api-key`,i,`API key for ${r}`),oauthCredentials:(e,n,r,i)=>{let s=X.createString(e,n,"oauth-client-id",r,"OAuth client ID"),a=X.createSecureString(e,n,"oauth-client-secret",i,"OAuth client secret");return{clientId:s,clientSecret:a}},smtpCredentials:(e,n,r,i,s,a)=>{let c=X.createString(e,n,"smtp-username",r,"SMTP username"),u=X.createSecureString(e,n,"smtp-password",i,"SMTP password"),d=X.createString(e,n,"smtp-host",s,"SMTP host"),m=X.createString(e,n,"smtp-port",a.toString(),"SMTP port");return{username:c,password:u,host:d,port:m}},redisUrl:(e,n,r)=>X.createSecureString(e,n,"redis-url",r,"Redis connection URL"),s3Bucket:(e,n,r)=>X.createString(e,n,"s3-bucket",r,"S3 bucket name"),cloudFrontDistribution:(e,n,r)=>X.createString(e,n,"cloudfront-distribution-id",r,"CloudFront distribution ID")}}class Yt{static createDomain(e){let{slug:n,environment:r,domainName:i,engineVersion:s="OpenSearch_2.11",instanceType:a="t3.small.search",instanceCount:c=1,volumeSize:u=10,volumeType:d="gp3",dedicatedMaster:m=!1,dedicatedMasterType:p,dedicatedMasterCount:g=3,multiAz:y=!1,availabilityZoneCount:f=2,vpc:h,encryption:S,enforceHttps:C=!0,tlsSecurityPolicy:P="Policy-Min-TLS-1-2-2019-07",advancedSecurity:E,autoSnapshotHour:v=0,autoTune:w=!0,tags:D={}}=e,x=i||l({slug:n,environment:r,resourceType:"search"}),L=o(x);return{domain:{Type:"AWS::OpenSearchService::Domain",Properties:{DomainName:x,EngineVersion:s,ClusterConfig:{InstanceType:a,InstanceCount:c,DedicatedMasterEnabled:m,...m&&{DedicatedMasterType:p||a,DedicatedMasterCount:g},ZoneAwarenessEnabled:y,...y&&{ZoneAwarenessConfig:{AvailabilityZoneCount:f}}},EBSOptions:{EBSEnabled:!0,VolumeType:d,VolumeSize:u},DomainEndpointOptions:{EnforceHTTPS:C,TLSSecurityPolicy:P},SnapshotOptions:{AutomatedSnapshotStartHour:v},...h&&{VPCOptions:{SubnetIds:h.subnetIds,SecurityGroupIds:h.securityGroupIds}},...S&&{EncryptionAtRestOptions:{Enabled:S.atRest??!0,...S.kmsKeyId&&{KmsKeyId:S.kmsKeyId}},NodeToNodeEncryptionOptions:{Enabled:S.nodeToNode??!0}},...E&&{AdvancedSecurityOptions:{Enabled:E.enabled,InternalUserDatabaseEnabled:E.internalUserDatabase??!0,...E.masterUserName&&E.masterUserPassword&&{MasterUserOptions:{MasterUserName:E.masterUserName,MasterUserPassword:E.masterUserPassword}},...E.masterUserArn&&{MasterUserOptions:{MasterUserARN:E.masterUserArn}}}},...w&&{AutoTuneOptions:{DesiredState:"ENABLED"}},Tags:[{Key:"Name",Value:x},{Key:"Environment",Value:r},...Object.entries(D).map(([O,F])=>({Key:O,Value:F}))]}},logicalId:L}}static createAccessPolicy(e,n){let{ipAddresses:r,iamPrincipalArns:i,allowAll:s,vpcEndpoint:a}=n;if(s)return{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:"*"},Action:"es:*",Resource:e}]};let c=[];if(i&&i.length>0)c.push({Effect:"Allow",Principal:{AWS:i},Action:"es:*",Resource:e});if(r&&r.length>0)c.push({Effect:"Allow",Principal:{AWS:"*"},Action:"es:*",Resource:e,Condition:{IpAddress:{"aws:SourceIp":r}}});if(a)return{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:"*"},Action:"es:*",Resource:e}]};return{Version:"2012-10-17",Statement:c}}static DomainPresets={development:(e,n)=>Yt.createDomain({slug:e,environment:n,instanceType:"t3.small.search",instanceCount:1,volumeSize:10,multiAz:!1,dedicatedMaster:!1,encryption:{atRest:!0,nodeToNode:!0},autoTune:!1}),production:(e,n,r)=>Yt.createDomain({slug:e,environment:n,instanceType:"m6g.large.search",instanceCount:3,volumeSize:100,volumeType:"gp3",multiAz:!0,availabilityZoneCount:3,dedicatedMaster:!0,dedicatedMasterType:"m6g.large.search",dedicatedMasterCount:3,vpc:r,encryption:{atRest:!0,nodeToNode:!0},advancedSecurity:{enabled:!0,internalUserDatabase:!0},autoTune:!0}),costOptimized:(e,n)=>Yt.createDomain({slug:e,environment:n,instanceType:"t3.medium.search",instanceCount:2,volumeSize:20,volumeType:"gp3",multiAz:!0,dedicatedMaster:!1,encryption:{atRest:!0,nodeToNode:!0},autoTune:!0}),highPerformance:(e,n,r)=>Yt.createDomain({slug:e,environment:n,instanceType:"r6g.2xlarge.search",instanceCount:6,volumeSize:500,volumeType:"gp3",multiAz:!0,availabilityZoneCount:3,dedicatedMaster:!0,dedicatedMasterType:"c6g.xlarge.search",dedicatedMasterCount:3,vpc:r,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 kt{static createDomainRedirectBucket(e){let{slug:n,environment:r,sourceDomain:i,targetDomain:s,protocol:a="https"}=e,c=l({slug:n,environment:r,resourceType:"s3",suffix:"redirect"}),u=o(c),d=o(`${c}-policy`),m={Type:"AWS::S3::Bucket",Properties:{BucketName:i,WebsiteConfiguration:{RedirectAllRequestsTo:{HostName:s,Protocol:a}},PublicAccessBlockConfiguration:{BlockPublicAcls:!1,BlockPublicPolicy:!1,IgnorePublicAcls:!1,RestrictPublicBuckets:!1},Tags:[{Key:"Name",Value:c},{Key:"Environment",Value:r},{Key:"Purpose",Value:"Domain Redirect"}]}},p={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:R.Ref(u),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadForRedirect",Effect:"Allow",Principal:"*",Action:["s3:GetObject"],Resource:[R.Join("",[R.GetAtt(u,"Arn"),"/*"])]}]}}};return{bucket:m,bucketPolicy:p,logicalId:u,policyLogicalId:d}}static createPathRedirectFunction(e){let{slug:n,environment:r,rules:i}=e,s=l({slug:n,environment:r,resourceType:"cf-redirect"}),a=o(s),c=kt.generateRedirectFunctionCode(i);return{function:{Type:"AWS::CloudFront::Function",Properties:{Name:s,AutoPublish:!0,FunctionConfig:{Comment:`Path redirect function for ${n} (${r})`,Runtime:"cloudfront-js-2.0"},FunctionCode:c}},logicalId:a,functionCode:c}}static generateRedirectFunctionCode(e){return`function handler(event) {
|
|
2281
|
+
| limit 50`,region:i,title:"Recent Errors and Warnings"}}),c+=6;return Vi.createDashboard({slug:n,environment:r,widgets:a})}static DashboardTemplates={staticWebsite:(e)=>({slug:e.slug,environment:e.environment,widgets:[{type:"text",x:0,y:0,width:24,height:1,properties:{markdown:`# ${e.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",e.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",e.cloudFrontDistributionId,"Region","Global",{label:"4XX"}],["AWS/CloudFront","5xxErrorRate","DistributionId",e.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",e.cloudFrontDistributionId,"Region","Global"]],period:300,stat:"Sum"}},{type:"metric",x:0,y:7,width:12,height:6,properties:{title:"S3 Bucket Size",region:e.region||"us-east-1",metrics:[["AWS/S3","BucketSizeBytes","BucketName",e.s3BucketName,"StorageType","StandardStorage"]],period:86400,stat:"Average"}},{type:"metric",x:12,y:7,width:12,height:6,properties:{title:"S3 Number of Objects",region:e.region||"us-east-1",metrics:[["AWS/S3","NumberOfObjects","BucketName",e.s3BucketName,"StorageType","AllStorageTypes"]],period:86400,stat:"Average"}}]}),serverlessApi:(e)=>({slug:e.slug,environment:e.environment,widgets:[{type:"text",x:0,y:0,width:24,height:1,properties:{markdown:`# ${e.slug.toUpperCase()} Serverless API Dashboard`}},{type:"metric",x:0,y:1,width:8,height:6,properties:{title:"API Requests",region:e.region||"us-east-1",metrics:[["AWS/ApiGateway","Count","ApiName",e.apiGatewayName]],period:60,stat:"Sum"}},{type:"metric",x:8,y:1,width:8,height:6,properties:{title:"API Latency",region:e.region||"us-east-1",metrics:[["AWS/ApiGateway","Latency","ApiName",e.apiGatewayName]],period:60,stat:"Average"}},{type:"metric",x:16,y:1,width:8,height:6,properties:{title:"API Errors",region:e.region||"us-east-1",metrics:[["AWS/ApiGateway","4XXError","ApiName",e.apiGatewayName,{label:"4XX"}],["AWS/ApiGateway","5XXError","ApiName",e.apiGatewayName,{label:"5XX"}]],period:60,stat:"Sum"}},...e.lambdaFunctionNames.map((n,r)=>({type:"metric",x:r%3*8,y:7+Math.floor(r/3)*6,width:8,height:6,properties:{title:`${n} Metrics`,region:e.region||"us-east-1",metrics:[["AWS/Lambda","Invocations","FunctionName",n],["AWS/Lambda","Duration","FunctionName",n],["AWS/Lambda","Errors","FunctionName",n]],period:300,stat:"Sum"}}))]}),containerService:(e)=>({slug:e.slug,environment:e.environment,widgets:[{type:"text",x:0,y:0,width:24,height:1,properties:{markdown:`# ${e.slug.toUpperCase()} Container Service Dashboard`}},{type:"metric",x:0,y:1,width:8,height:6,properties:{title:"ECS CPU",region:e.region||"us-east-1",metrics:[["AWS/ECS","CPUUtilization","ClusterName",e.ecsClusterName,"ServiceName",e.ecsServiceName]],period:60,stat:"Average"}},{type:"metric",x:8,y:1,width:8,height:6,properties:{title:"ECS Memory",region:e.region||"us-east-1",metrics:[["AWS/ECS","MemoryUtilization","ClusterName",e.ecsClusterName,"ServiceName",e.ecsServiceName]],period:60,stat:"Average"}},{type:"metric",x:16,y:1,width:8,height:6,properties:{title:"Running Tasks",region:e.region||"us-east-1",metrics:[["ECS/ContainerInsights","RunningTaskCount","ClusterName",e.ecsClusterName,"ServiceName",e.ecsServiceName]],period:60,stat:"Average"}},{type:"metric",x:0,y:7,width:8,height:6,properties:{title:"ALB Requests",region:e.region||"us-east-1",metrics:[["AWS/ApplicationELB","RequestCount","LoadBalancer",e.albName]],period:60,stat:"Sum"}},{type:"metric",x:8,y:7,width:8,height:6,properties:{title:"Response Time",region:e.region||"us-east-1",metrics:[["AWS/ApplicationELB","TargetResponseTime","LoadBalancer",e.albName]],period:60,stat:"Average"}},{type:"metric",x:16,y:7,width:8,height:6,properties:{title:"Healthy Hosts",region:e.region||"us-east-1",metrics:[["AWS/ApplicationELB","HealthyHostCount","LoadBalancer",e.albName]],period:60,stat:"Average"}},...e.rdsInstanceId?[{type:"metric",x:0,y:13,width:12,height:6,properties:{title:"RDS CPU",region:e.region||"us-east-1",metrics:[["AWS/RDS","CPUUtilization","DBInstanceIdentifier",e.rdsInstanceId]],period:300,stat:"Average"}},{type:"metric",x:12,y:13,width:12,height:6,properties:{title:"RDS Connections",region:e.region||"us-east-1",metrics:[["AWS/RDS","DatabaseConnections","DBInstanceIdentifier",e.rdsInstanceId]],period:60,stat:"Sum"}}]:[]]})};static Config={createAlarmConfig:(e)=>{let{metricName:n,namespace:r,threshold:i,comparisonOperator:s="GreaterThanThreshold",evaluationPeriods:a=1,period:c=300,statistic:u="Average",treatMissingData:d="missing"}=e;return{MetricName:n,Namespace:r,Threshold:i,ComparisonOperator:s,EvaluationPeriods:a,Period:c,Statistic:u,TreatMissingData:d}},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:(e=80)=>({metricName:"CPUUtilization",threshold:e,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),highMemory:(e=80)=>({metricName:"MemoryUtilization",threshold:e,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),highErrors:(e=10)=>({metricName:"Errors",threshold:e,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:1,period:60,statistic:"Sum"}),highLatency:(e=5000)=>({metricName:"Duration",threshold:e,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),lowHealthyHosts:(e=1)=>({metricName:"HealthyHostCount",namespace:"AWS/ApplicationELB",threshold:e,comparisonOperator:"LessThanThreshold",evaluationPeriods:2,period:60,statistic:"Minimum"}),queueDepth:(e=1000)=>({metricName:"ApproximateNumberOfMessagesVisible",namespace:"AWS/SQS",threshold:e,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),lowStorage:(e=10737418240)=>({metricName:"FreeStorageSpace",namespace:"AWS/RDS",threshold:e,comparisonOperator:"LessThanThreshold",evaluationPeriods:1,period:300,statistic:"Average"})}}}class Pe{static createUserPool(e){let{slug:n,environment:r,userPoolName:i,aliasAttributes:s,autoVerifiedAttributes:a,passwordPolicy:c,mfaConfiguration:u,emailConfiguration:d,smsConfiguration:m,lambdaTriggers:p,userPoolAddOns:g,accountRecoverySetting:y}=e,f=i||l({slug:n,environment:r,resourceType:"user-pool"}),h=o(f),S={Type:"AWS::Cognito::UserPool",Properties:{UserPoolName:f,Policies:c?{PasswordPolicy:{MinimumLength:c.minimumLength,RequireLowercase:c.requireLowercase,RequireUppercase:c.requireUppercase,RequireNumbers:c.requireNumbers,RequireSymbols:c.requireSymbols,TemporaryPasswordValidityDays:c.temporaryPasswordValidityDays}}:void 0,MfaConfiguration:u,Schema:[{Name:"email",AttributeDataType:"String",Required:!0,Mutable:!1}]}};if(s&&s.length>0)S.Properties.UsernameAttributes=s;if(a&&a.length>0)S.Properties.AutoVerifiedAttributes=a;if(d)S.Properties.EmailConfiguration={EmailSendingAccount:d.emailSendingAccount,From:d.from,ReplyToEmailAddress:d.replyToEmailAddress,SourceArn:d.sourceArn,ConfigurationSet:d.configurationSet};if(m)S.Properties.SmsConfiguration={ExternalId:m.externalId,SnsCallerArn:m.snsCallerArn};if(p)S.Properties.LambdaConfig={PreSignUp:p.preSignUp,PostConfirmation:p.postConfirmation,PreAuthentication:p.preAuthentication,PostAuthentication:p.postAuthentication,CustomMessage:p.customMessage,DefineAuthChallenge:p.defineAuthChallenge,CreateAuthChallenge:p.createAuthChallenge,VerifyAuthChallengeResponse:p.verifyAuthChallengeResponse,PreTokenGeneration:p.preTokenGeneration,UserMigration:p.userMigration};if(g)S.Properties.UserPoolAddOns={AdvancedSecurityMode:g.advancedSecurityMode};if(y)S.Properties.AccountRecoverySetting={RecoveryMechanisms:y.recoveryMechanisms};return{userPool:S,logicalId:h}}static createUserPoolClient(e,n){let{slug:r,environment:i,clientName:s,generateSecret:a=!1,refreshTokenValidity:c,accessTokenValidity:u,idTokenValidity:d,tokenValidityUnits:m,readAttributes:p,writeAttributes:g,explicitAuthFlows:y,preventUserExistenceErrors:f,enableTokenRevocation:h,callbackURLs:S,logoutURLs:C,allowedOAuthFlows:P,allowedOAuthScopes:E,allowedOAuthFlowsUserPoolClient:v,supportedIdentityProviders:w}=n,D=s||l({slug:r,environment:i,resourceType:"user-pool-client"}),x=o(D);return{client:{Type:"AWS::Cognito::UserPoolClient",Properties:{ClientName:D,UserPoolId:R.Ref(e),GenerateSecret:a,RefreshTokenValidity:c,AccessTokenValidity:u,IdTokenValidity:d,TokenValidityUnits:m,ReadAttributes:p,WriteAttributes:g,ExplicitAuthFlows:y,PreventUserExistenceErrors:f,EnableTokenRevocation:h,CallbackURLs:S,LogoutURLs:C,AllowedOAuthFlows:P,AllowedOAuthScopes:E,AllowedOAuthFlowsUserPoolClient:v,SupportedIdentityProviders:w}},logicalId:x}}static createUserPoolDomain(e,n){let{slug:r,environment:i,domain:s,customDomainConfig:a}=n,c=l({slug:r,environment:i,resourceType:"user-pool-domain"}),u=o(c);return{domain:{Type:"AWS::Cognito::UserPoolDomain",Properties:{Domain:s,UserPoolId:R.Ref(e),CustomDomainConfig:a}},logicalId:u}}static createIdentityPool(e){let{slug:n,environment:r,identityPoolName:i,allowUnauthenticatedIdentities:s=!1,cognitoIdentityProviders:a,supportedLoginProviders:c,samlProviderARNs:u,openIdConnectProviderARNs:d}=e,m=i||l({slug:n,environment:r,resourceType:"identity-pool"}),p=o(m);return{identityPool:{Type:"AWS::Cognito::IdentityPool",Properties:{IdentityPoolName:m,AllowUnauthenticatedIdentities:s,CognitoIdentityProviders:a,SupportedLoginProviders:c,SamlProviderARNs:u,OpenIdConnectProviderARNs:d}},logicalId:p}}static createIdentityPoolRoleAttachment(e,n){let{slug:r,environment:i,authenticatedRole:s,unauthenticatedRole:a,roleMappings:c}=n,u=l({slug:r,environment:i,resourceType:"identity-pool-role-attachment"}),d=o(u),m={authenticated:s};if(a)m.unauthenticated=a;return{attachment:{Type:"AWS::Cognito::IdentityPoolRoleAttachment",Properties:{IdentityPoolId:R.Ref(e),Roles:m,RoleMappings:c}},logicalId:d}}static createAuthenticatedRole(e){let{slug:n,environment:r,identityPoolLogicalId:i}=e,s=l({slug:n,environment:r,resourceType:"cognito-authenticated-role"}),a=o(s);return{role:{Type:"AWS::IAM::Role",Properties:{RoleName:s,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Federated:"cognito-identity.amazonaws.com"},Action:"sts:AssumeRoleWithWebIdentity",Condition:{StringEquals:{"cognito-identity.amazonaws.com:aud":R.Ref(i)},"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:s},{Key:"Environment",Value:r}]}},logicalId:a}}static createUnauthenticatedRole(e){let{slug:n,environment:r,identityPoolLogicalId:i}=e,s=l({slug:n,environment:r,resourceType:"cognito-unauthenticated-role"}),a=o(s);return{role:{Type:"AWS::IAM::Role",Properties:{RoleName:s,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Federated:"cognito-identity.amazonaws.com"},Action:"sts:AssumeRoleWithWebIdentity",Condition:{StringEquals:{"cognito-identity.amazonaws.com:aud":R.Ref(i)},"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:s},{Key:"Environment",Value:r}]}},logicalId:a}}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:(e,n,r)=>{let{userPool:i,logicalId:s}=Pe.createUserPool({slug:e,environment:n,aliasAttributes:["email"],autoVerifiedAttributes:["email"],passwordPolicy:Pe.PasswordPolicies.standard(),mfaConfiguration:"OPTIONAL"}),{client:a,logicalId:c}=Pe.createUserPoolClient(s,{slug:e,environment:n,explicitAuthFlows:[...Pe.AuthFlows.standard],callbackURLs:[r],allowedOAuthFlows:["code"],allowedOAuthScopes:[...Pe.OAuthScopes.basic],allowedOAuthFlowsUserPoolClient:!0});return{userPool:i,poolId:s,client:a,clientId:c}},mobileApp:(e,n)=>{let{userPool:r,logicalId:i}=Pe.createUserPool({slug:e,environment:n,aliasAttributes:["email"],autoVerifiedAttributes:["email"],passwordPolicy:Pe.PasswordPolicies.standard(),mfaConfiguration:"OPTIONAL"}),{client:s,logicalId:a}=Pe.createUserPoolClient(i,{slug:e,environment:n,explicitAuthFlows:[...Pe.AuthFlows.standard]}),{identityPool:c,logicalId:u}=Pe.createIdentityPool({slug:e,environment:n,allowUnauthenticatedIdentities:!1,cognitoIdentityProviders:[{ClientId:R.Ref(a),ProviderName:R.GetAtt(i,"ProviderName")}]}),{role:d,logicalId:m}=Pe.createAuthenticatedRole({slug:e,environment:n,identityPoolLogicalId:u}),{attachment:p,logicalId:g}=Pe.createIdentityPoolRoleAttachment(u,{slug:e,environment:n,authenticatedRole:R.GetAtt(m,"Arn")});return{userPool:r,poolId:i,client:s,clientId:a,identityPool:c,identityPoolId:u,authRole:d,authRoleId:m,attachment:p,attachmentId:g}}}}import{createHash as $r}from"node:crypto";import{copyFileSync as Br,existsSync as bt,readdirSync as _r,readFileSync as Xe,statSync as Wr,writeFileSync as et}from"node:fs";import{basename as Ur,dirname as cn,extname as ln,join as Ve}from"node:path";class De{static createApplication(e){let{slug:n,environment:r,applicationName:i,computePlatform:s}=e,a=i||l({slug:n,environment:r,resourceType:"deploy-app"}),c=o(a);return{application:{Type:"AWS::CodeDeploy::Application",Properties:{ApplicationName:a,ComputePlatform:s,Tags:[{Key:"Name",Value:a},{Key:"Environment",Value:r}]}},logicalId:c}}static createDeploymentGroup(e,n){let{slug:r,environment:i,deploymentGroupName:s,serviceRoleArn:a,autoScalingGroups:c,ec2TagFilters:u,deploymentConfigName:d,autoRollbackConfiguration:m,alarmConfiguration:p,loadBalancerInfo:g,blueGreenDeploymentConfiguration:y}=n,f=s||l({slug:r,environment:i,resourceType:"deploy-group"}),h=o(f);return{deploymentGroup:{Type:"AWS::CodeDeploy::DeploymentGroup",Properties:{ApplicationName:R.Ref(e),DeploymentGroupName:f,ServiceRoleArn:a,AutoScalingGroups:c,Ec2TagFilters:u?.map((C)=>({Key:C.key,Value:C.value,Type:C.type})),DeploymentConfigName:d,AutoRollbackConfiguration:m?{Enabled:m.enabled,Events:m.events}:void 0,AlarmConfiguration:p?{Enabled:p.enabled,Alarms:p.alarms?.map((C)=>({Name:C.name})),IgnorePollAlarmFailure:p.ignorePollAlarmFailure}:void 0,LoadBalancerInfo:g?{TargetGroupInfoList:g.targetGroupInfoList?.map((C)=>({Name:C.name})),ElbInfoList:g.elbInfoList?.map((C)=>({Name:C.name}))}:void 0,BlueGreenDeploymentConfiguration:y?{TerminateBlueInstancesOnDeploymentSuccess:y.terminateBlueInstancesOnDeploymentSuccess?{Action:y.terminateBlueInstancesOnDeploymentSuccess.action,TerminationWaitTimeInMinutes:y.terminateBlueInstancesOnDeploymentSuccess.terminationWaitTimeInMinutes}:void 0,DeploymentReadyOption:y.deploymentReadyOption?{ActionOnTimeout:y.deploymentReadyOption.actionOnTimeout,WaitTimeInMinutes:y.deploymentReadyOption.waitTimeInMinutes}:void 0,GreenFleetProvisioningOption:y.greenFleetProvisioningOption?{Action:y.greenFleetProvisioningOption.action}:void 0}:void 0,Tags:[{Key:"Name",Value:f},{Key:"Environment",Value:i}]}},logicalId:h}}static createDeploymentConfig(e){let{slug:n,environment:r,deploymentConfigName:i,minimumHealthyHosts:s,trafficRoutingConfig:a}=e,c=i||l({slug:n,environment:r,resourceType:"deploy-config"}),u=o(c);return{deploymentConfig:{Type:"AWS::CodeDeploy::DeploymentConfig",Properties:{DeploymentConfigName:c,MinimumHealthyHosts:s?{Type:s.type,Value:s.value}:void 0,TrafficRoutingConfig:a?{Type:a.type,TimeBasedCanary:a.timeBasedCanary?{CanaryPercentage:a.timeBasedCanary.canaryPercentage,CanaryInterval:a.timeBasedCanary.canaryInterval}:void 0,TimeBasedLinear:a.timeBasedLinear?{LinearPercentage:a.timeBasedLinear.linearPercentage,LinearInterval:a.timeBasedLinear.linearInterval}:void 0}:void 0}},logicalId:u}}static DeploymentConfigs={allAtOnce:()=>({type:"FLEET_PERCENT",value:0}),halfAtATime:()=>({type:"FLEET_PERCENT",value:50}),oneAtATime:()=>({type:"HOST_COUNT",value:1}),custom:(e,n)=>({type:e,value:n})};static TrafficRouting={allAtOnce:()=>({type:"AllAtOnce"}),canary:(e,n)=>({type:"TimeBasedCanary",timeBasedCanary:{canaryPercentage:e,canaryInterval:n}}),linear:(e,n)=>({type:"TimeBasedLinear",timeBasedLinear:{linearPercentage:e,linearInterval:n}})};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:(e)=>({terminateBlueInstancesOnDeploymentSuccess:{action:"TERMINATE",terminationWaitTimeInMinutes:e},deploymentReadyOption:{actionOnTimeout:"CONTINUE_DEPLOYMENT",waitTimeInMinutes:0},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}}),withManualApproval:(e)=>({terminateBlueInstancesOnDeploymentSuccess:{action:"TERMINATE",terminationWaitTimeInMinutes:5},deploymentReadyOption:{actionOnTimeout:"STOP_DEPLOYMENT",waitTimeInMinutes:e},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:(e,n,r,i)=>{let{application:s,logicalId:a}=De.createApplication({slug:e,environment:n,computePlatform:"Server"}),{deploymentGroup:c,logicalId:u}=De.createDeploymentGroup(a,{slug:e,environment:n,serviceRoleArn:r,autoScalingGroups:i,deploymentConfigName:"CodeDeployDefault.OneAtATime",autoRollbackConfiguration:De.RollbackConfigs.onFailure()});return{application:s,appId:a,deploymentGroup:c,groupId:u}},lambdaCanaryDeployment:(e,n,r,i=10,s=5)=>{let{application:a,logicalId:c}=De.createApplication({slug:e,environment:n,computePlatform:"Lambda"}),{deploymentConfig:u,logicalId:d}=De.createDeploymentConfig({slug:e,environment:n,trafficRoutingConfig:De.TrafficRouting.canary(i,s)}),{deploymentGroup:m,logicalId:p}=De.createDeploymentGroup(c,{slug:e,environment:n,serviceRoleArn:r,deploymentConfigName:R.Ref(d),autoRollbackConfiguration:De.RollbackConfigs.onAlarmOrFailure()});return{application:a,appId:c,deploymentConfig:u,configId:d,deploymentGroup:m,groupId:p}},ecsBlueGreenDeployment:(e,n,r,i)=>{let{application:s,logicalId:a}=De.createApplication({slug:e,environment:n,computePlatform:"ECS"}),{deploymentGroup:c,logicalId:u}=De.createDeploymentGroup(a,{slug:e,environment:n,serviceRoleArn:r,loadBalancerInfo:{targetGroupInfoList:[{name:i}]},blueGreenDeploymentConfiguration:De.BlueGreenConfigs.standard(),autoRollbackConfiguration:De.RollbackConfigs.onFailure()});return{application:s,appId:a,deploymentGroup:c,groupId:u}}};static Strategies={rolling:(e=25)=>({type:"rolling",batchPercentage:e}),blueGreen:()=>({type:"blue-green"}),canary:(e=10,n=5)=>({type:"canary",canaryPercentage:e,canaryInterval:n}),allAtOnce:()=>({type:"all-at-once"})}}class ie{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(e,n="md5"){let r=Xe(e);return $r(n).update(r).digest("hex")}static computeShortHash(e){return ie.computeFileHash(e).slice(0,8)}static getContentType(e){let n=ln(e).toLowerCase();return ie.ContentTypes[n]||"application/octet-stream"}static shouldHashFile(e,n){return![...ie.NoHashPatterns,...n||[]].some((i)=>i.test(e))}static generateHashedFilename(e,n){let r=ln(e),i=Ur(e,r),s=cn(e);if(s===".")return`${i}.${n}${r}`;return Ve(s,`${i}.${n}${r}`)}static collectFiles(e,n){let r=[],i=n||e;if(!bt(e))return r;let s=_r(e,{withFileTypes:!0});for(let a of s){let c=Ve(e,a.name);if(a.isDirectory())r.push(...ie.collectFiles(c,i));else if(a.isFile())r.push(c)}return r}static hashDirectory(e){let{sourceDir:n,outputDir:r,excludePatterns:i=[],hashAlgorithm:s="md5",copyUnhashed:a=!0}=e,c=ie.collectFiles(n),u=[],d={};for(let p of c){let g=p.replace(n,"").replace(/^[/\\]/,""),y=ie.shouldHashFile(g,i),f=Wr(p),h=y?ie.computeFileHash(p,s).slice(0,8):"",S=y?ie.generateHashedFilename(g,h):g,C={originalPath:g,hashedPath:S,hash:h,size:f.size,contentType:ie.getContentType(p)};if(u.push(C),d[g]=S,r){let P=Ve(r,S),E=cn(P);if(!bt(E)){let{mkdirSync:v}=Gr("node:fs");v(E,{recursive:!0})}if(y||a)Br(p,P)}}let m={version:"1.0",timestamp:new Date().toISOString(),assets:u,hashMap:d};if(r){let p=Ve(r,"asset-manifest.json");et(p,JSON.stringify(m,null,2))}return m}static getInvalidationPaths(e,n){let r=[];if(!e)return["/*"];let i=e.hashMap,s=n.hashMap;for(let[a,c]of Object.entries(s)){let u=i[a];if(!u||u!==c){if(r.push(`/${a}`),u&&u!==c)r.push(`/${u}`)}}for(let[a,c]of Object.entries(i))if(!s[a])r.push(`/${a}`),r.push(`/${c}`);if(r.length>100)return["/*"];return[...new Set(r)]}static updateHtmlReferences(e){let{htmlDir:n,manifest:r,basePath:i=""}=e,s=ie.collectFiles(n).filter((a)=>a.endsWith(".html")||a.endsWith(".htm"));for(let a of s){let c=Xe(a,"utf-8");for(let[u,d]of Object.entries(r.hashMap)){if(u===d)continue;let m=[new RegExp(`(src|href)=["']${i}/?${ie.escapeRegExp(u)}["']`,"g"),new RegExp(`url\\(["']?${i}/?${ie.escapeRegExp(u)}["']?\\)`,"g")];for(let p of m)c=c.replace(p,(g)=>g.replace(u,d))}et(a,c)}}static updateCssReferences(e){let{cssDir:n,manifest:r,basePath:i=""}=e,s=ie.collectFiles(n).filter((a)=>a.endsWith(".css"));for(let a of s){let c=Xe(a,"utf-8");for(let[u,d]of Object.entries(r.hashMap)){if(u===d)continue;let m=new RegExp(`url\\(["']?${i}/?${ie.escapeRegExp(u)}["']?\\)`,"g");c=c.replace(m,`url(${i}/${d})`)}et(a,c)}}static escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}static generateS3DeploymentManifest(e){let{sourceDir:n,keyPrefix:r="",excludePatterns:i=[],cacheControl:s={hashed:"public, max-age=31536000, immutable",unhashed:"public, max-age=3600",html:"public, max-age=0, must-revalidate"}}=e;return ie.hashDirectory({sourceDir:n,excludePatterns:i}).assets.map((c)=>{let u=c.hash!=="",d=c.contentType==="text/html",m=s.unhashed||"public, max-age=3600";if(d)m=s.html||"public, max-age=0, must-revalidate";else if(u)m=s.hashed||"public, max-age=31536000, immutable";return{localPath:Ve(n,c.originalPath),s3Key:r?`${r}/${c.hashedPath}`:c.hashedPath,contentType:c.contentType,cacheControl:m,hash:c.hash}})}static compareManifests(e,n){let r={added:[],removed:[],changed:[],unchanged:[]},i=new Set(Object.keys(e.hashMap)),s=new Set(Object.keys(n.hashMap));for(let a of s)if(!i.has(a))r.added.push(a);for(let a of i)if(!s.has(a))r.removed.push(a);for(let a of s)if(i.has(a))if(e.hashMap[a]!==n.hashMap[a])r.changed.push(a);else r.unchanged.push(a);return r}static loadManifest(e){if(!bt(e))return null;try{let n=Xe(e,"utf-8");return JSON.parse(n)}catch{return null}}static saveManifest(e,n){et(n,JSON.stringify(e,null,2))}}class zi{static createSecret(e){let{slug:n,environment:r,secretName:i,description:s,secretString:a,kmsKeyId:c,tags:u}=e,d=i||l({slug:n,environment:r,resourceType:"secret"}),m=o(d),p={Type:"AWS::SecretsManager::Secret",Properties:{Name:d,Description:s,SecretString:a,Tags:[{Key:"Name",Value:d},{Key:"Environment",Value:r},...u?Object.entries(u).map(([g,y])=>({Key:g,Value:y})):[]]}};if(c)p.Properties.KmsKeyId=c;return{secret:p,logicalId:m}}static createGeneratedSecret(e){let{slug:n,environment:r,secretName:i,description:s,excludeCharacters:a,excludeLowercase:c,excludeNumbers:u,excludePunctuation:d,excludeUppercase:m,passwordLength:p,requireEachIncludedType:g,kmsKeyId:y,tags:f}=e,h=i||l({slug:n,environment:r,resourceType:"secret"}),S=o(h),C={Type:"AWS::SecretsManager::Secret",Properties:{Name:h,Description:s,GenerateSecretString:{ExcludeCharacters:a,ExcludeLowercase:c,ExcludeNumbers:u,ExcludePunctuation:d,ExcludeUppercase:m,PasswordLength:p||32,RequireEachIncludedType:g!==!1},Tags:[{Key:"Name",Value:h},{Key:"Environment",Value:r},...f?Object.entries(f).map(([P,E])=>({Key:P,Value:E})):[]]}};if(y)C.Properties.KmsKeyId=y;return{secret:C,logicalId:S}}static createDatabaseSecret(e){let{slug:n,environment:r,secretName:i,username:s,dbname:a,engine:c,host:u,port:d,kmsKeyId:m}=e,p=i||l({slug:n,environment:r,resourceType:"db-secret"}),g=o(p),y={username:s};if(a)y.dbname=a;if(c)y.engine=c;if(u)y.host=u;if(d)y.port=d;let f={Type:"AWS::SecretsManager::Secret",Properties:{Name:p,Description:`Database credentials for ${s}`,GenerateSecretString:{SecretStringTemplate:JSON.stringify(y),GenerateStringKey:"password",PasswordLength:32,ExcludeCharacters:'"@/\\',RequireEachIncludedType:!0},Tags:[{Key:"Name",Value:p},{Key:"Environment",Value:r},{Key:"Type",Value:"database"}]}};if(m)f.Properties.KmsKeyId=m;return{secret:f,logicalId:g}}static attachToDatabase(e){let{slug:n,environment:r,secretId:i,targetId:s,targetType:a}=e,c=l({slug:n,environment:r,resourceType:"secret-attachment"}),u=o(c);return{attachment:{Type:"AWS::SecretsManager::SecretTargetAttachment",Properties:{SecretId:i,TargetId:s,TargetType:a}},logicalId:u}}static enableRotation(e){let{slug:n,environment:r,secretId:i,rotationLambdaArn:s,automaticallyAfterDays:a,rotationType:c,kmsKeyArn:u,vpcSecurityGroupIds:d,vpcSubnetIds:m}=e,p=l({slug:n,environment:r,resourceType:"secret-rotation"}),g=o(p),y={Type:"AWS::SecretsManager::RotationSchedule",Properties:{SecretId:i,RotationRules:{AutomaticallyAfterDays:a||30}}};if(s)y.Properties.RotationLambdaARN=s;else if(c)y.Properties.HostedRotationLambda={RotationType:c,KmsKeyArn:u,VpcSecurityGroupIds:d,VpcSubnetIds:m};return{rotation:y,logicalId:g}}static SecretTypes={apiKey:(e,n,r)=>zi.createGeneratedSecret({slug:e,environment:n,secretName:`${e}-${n}-${r}-api-key`,description:`API key for ${r}`,passwordLength:32,excludePunctuation:!0,excludeLowercase:!1,excludeUppercase:!1,excludeNumbers:!1}),oauthClientSecret:(e,n,r)=>zi.createGeneratedSecret({slug:e,environment:n,secretName:`${e}-${n}-${r}-oauth-secret`,description:`OAuth client secret for ${r}`,passwordLength:64,excludeCharacters:"\"'`\\/@",requireEachIncludedType:!0}),jwtSecret:(e,n)=>zi.createGeneratedSecret({slug:e,environment:n,secretName:`${e}-${n}-jwt-secret`,description:"JWT signing secret",passwordLength:64,excludePunctuation:!0}),encryptionKey:(e,n)=>zi.createGeneratedSecret({slug:e,environment:n,secretName:`${e}-${n}-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 X{static createParameter(e){let{slug:n,environment:r,parameterName:i,value:s,type:a="String",description:c,tier:u="Standard",tags:d}=e,m=i||l({slug:n,environment:r,resourceType:"parameter"}),p=o(m);return{parameter:{Type:"AWS::SSM::Parameter",Properties:{Name:`/${n}/${r}/${m}`,Type:a,Value:s,Description:c,Tier:u,Tags:{Name:m,Environment:r,...d}}},logicalId:p}}static createString(e,n,r,i,s){return X.createParameter({slug:e,environment:n,parameterName:r,value:i,type:"String",description:s})}static createSecureString(e,n,r,i,s){return X.createParameter({slug:e,environment:n,parameterName:r,value:i,type:"SecureString",description:s})}static createStringList(e,n,r,i,s){return X.createParameter({slug:e,environment:n,parameterName:r,value:i.join(","),type:"StringList",description:s})}static Parameters={databaseUrl:(e,n,r)=>X.createSecureString(e,n,"database-url",r,"Database connection URL"),apiEndpoint:(e,n,r)=>X.createString(e,n,"api-endpoint",r,"API endpoint URL"),appVersion:(e,n,r)=>X.createString(e,n,"app-version",r,"Application version"),featureFlags:(e,n,r)=>X.createStringList(e,n,"feature-flags",r,"Enabled feature flags"),apiKey:(e,n,r,i)=>X.createSecureString(e,n,`${r}-api-key`,i,`API key for ${r}`),oauthCredentials:(e,n,r,i)=>{let s=X.createString(e,n,"oauth-client-id",r,"OAuth client ID"),a=X.createSecureString(e,n,"oauth-client-secret",i,"OAuth client secret");return{clientId:s,clientSecret:a}},smtpCredentials:(e,n,r,i,s,a)=>{let c=X.createString(e,n,"smtp-username",r,"SMTP username"),u=X.createSecureString(e,n,"smtp-password",i,"SMTP password"),d=X.createString(e,n,"smtp-host",s,"SMTP host"),m=X.createString(e,n,"smtp-port",a.toString(),"SMTP port");return{username:c,password:u,host:d,port:m}},redisUrl:(e,n,r)=>X.createSecureString(e,n,"redis-url",r,"Redis connection URL"),s3Bucket:(e,n,r)=>X.createString(e,n,"s3-bucket",r,"S3 bucket name"),cloudFrontDistribution:(e,n,r)=>X.createString(e,n,"cloudfront-distribution-id",r,"CloudFront distribution ID")}}class Zt{static createDomain(e){let{slug:n,environment:r,domainName:i,engineVersion:s="OpenSearch_2.11",instanceType:a="t3.small.search",instanceCount:c=1,volumeSize:u=10,volumeType:d="gp3",dedicatedMaster:m=!1,dedicatedMasterType:p,dedicatedMasterCount:g=3,multiAz:y=!1,availabilityZoneCount:f=2,vpc:h,encryption:S,enforceHttps:C=!0,tlsSecurityPolicy:P="Policy-Min-TLS-1-2-2019-07",advancedSecurity:E,autoSnapshotHour:v=0,autoTune:w=!0,tags:D={}}=e,x=i||l({slug:n,environment:r,resourceType:"search"}),L=o(x);return{domain:{Type:"AWS::OpenSearchService::Domain",Properties:{DomainName:x,EngineVersion:s,ClusterConfig:{InstanceType:a,InstanceCount:c,DedicatedMasterEnabled:m,...m&&{DedicatedMasterType:p||a,DedicatedMasterCount:g},ZoneAwarenessEnabled:y,...y&&{ZoneAwarenessConfig:{AvailabilityZoneCount:f}}},EBSOptions:{EBSEnabled:!0,VolumeType:d,VolumeSize:u},DomainEndpointOptions:{EnforceHTTPS:C,TLSSecurityPolicy:P},SnapshotOptions:{AutomatedSnapshotStartHour:v},...h&&{VPCOptions:{SubnetIds:h.subnetIds,SecurityGroupIds:h.securityGroupIds}},...S&&{EncryptionAtRestOptions:{Enabled:S.atRest??!0,...S.kmsKeyId&&{KmsKeyId:S.kmsKeyId}},NodeToNodeEncryptionOptions:{Enabled:S.nodeToNode??!0}},...E&&{AdvancedSecurityOptions:{Enabled:E.enabled,InternalUserDatabaseEnabled:E.internalUserDatabase??!0,...E.masterUserName&&E.masterUserPassword&&{MasterUserOptions:{MasterUserName:E.masterUserName,MasterUserPassword:E.masterUserPassword}},...E.masterUserArn&&{MasterUserOptions:{MasterUserARN:E.masterUserArn}}}},...w&&{AutoTuneOptions:{DesiredState:"ENABLED"}},Tags:[{Key:"Name",Value:x},{Key:"Environment",Value:r},...Object.entries(D).map(([O,F])=>({Key:O,Value:F}))]}},logicalId:L}}static createAccessPolicy(e,n){let{ipAddresses:r,iamPrincipalArns:i,allowAll:s,vpcEndpoint:a}=n;if(s)return{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:"*"},Action:"es:*",Resource:e}]};let c=[];if(i&&i.length>0)c.push({Effect:"Allow",Principal:{AWS:i},Action:"es:*",Resource:e});if(r&&r.length>0)c.push({Effect:"Allow",Principal:{AWS:"*"},Action:"es:*",Resource:e,Condition:{IpAddress:{"aws:SourceIp":r}}});if(a)return{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:"*"},Action:"es:*",Resource:e}]};return{Version:"2012-10-17",Statement:c}}static DomainPresets={development:(e,n)=>Zt.createDomain({slug:e,environment:n,instanceType:"t3.small.search",instanceCount:1,volumeSize:10,multiAz:!1,dedicatedMaster:!1,encryption:{atRest:!0,nodeToNode:!0},autoTune:!1}),production:(e,n,r)=>Zt.createDomain({slug:e,environment:n,instanceType:"m6g.large.search",instanceCount:3,volumeSize:100,volumeType:"gp3",multiAz:!0,availabilityZoneCount:3,dedicatedMaster:!0,dedicatedMasterType:"m6g.large.search",dedicatedMasterCount:3,vpc:r,encryption:{atRest:!0,nodeToNode:!0},advancedSecurity:{enabled:!0,internalUserDatabase:!0},autoTune:!0}),costOptimized:(e,n)=>Zt.createDomain({slug:e,environment:n,instanceType:"t3.medium.search",instanceCount:2,volumeSize:20,volumeType:"gp3",multiAz:!0,dedicatedMaster:!1,encryption:{atRest:!0,nodeToNode:!0},autoTune:!0}),highPerformance:(e,n,r)=>Zt.createDomain({slug:e,environment:n,instanceType:"r6g.2xlarge.search",instanceCount:6,volumeSize:500,volumeType:"gp3",multiAz:!0,availabilityZoneCount:3,dedicatedMaster:!0,dedicatedMasterType:"c6g.xlarge.search",dedicatedMasterCount:3,vpc:r,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 Nt{static createDomainRedirectBucket(e){let{slug:n,environment:r,sourceDomain:i,targetDomain:s,protocol:a="https"}=e,c=l({slug:n,environment:r,resourceType:"s3",suffix:"redirect"}),u=o(c),d=o(`${c}-policy`),m={Type:"AWS::S3::Bucket",Properties:{BucketName:i,WebsiteConfiguration:{RedirectAllRequestsTo:{HostName:s,Protocol:a}},PublicAccessBlockConfiguration:{BlockPublicAcls:!1,BlockPublicPolicy:!1,IgnorePublicAcls:!1,RestrictPublicBuckets:!1},Tags:[{Key:"Name",Value:c},{Key:"Environment",Value:r},{Key:"Purpose",Value:"Domain Redirect"}]}},p={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:R.Ref(u),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadForRedirect",Effect:"Allow",Principal:"*",Action:["s3:GetObject"],Resource:[R.Join("",[R.GetAtt(u,"Arn"),"/*"])]}]}}};return{bucket:m,bucketPolicy:p,logicalId:u,policyLogicalId:d}}static createPathRedirectFunction(e){let{slug:n,environment:r,rules:i}=e,s=l({slug:n,environment:r,resourceType:"cf-redirect"}),a=o(s),c=Nt.generateRedirectFunctionCode(i);return{function:{Type:"AWS::CloudFront::Function",Properties:{Name:s,AutoPublish:!0,FunctionConfig:{Comment:`Path redirect function for ${n} (${r})`,Runtime:"cloudfront-js-2.0"},FunctionCode:c}},logicalId:a,functionCode:c}}static generateRedirectFunctionCode(e){return`function handler(event) {
|
|
2282
2282
|
const request = event.request;
|
|
2283
2283
|
const uri = request.uri;
|
|
2284
2284
|
const querystring = request.querystring;
|
|
@@ -2332,7 +2332,7 @@ ${e.map((r)=>{let i=r.preserveQueryString!==!1,s=r.statusCode||301;return` '${r
|
|
|
2332
2332
|
}
|
|
2333
2333
|
|
|
2334
2334
|
return request;
|
|
2335
|
-
}`}static CommonRedirects={wwwToApex:(e,n="https")=>({slug:e.replace(/\./g,"-"),environment:"production",sourceDomain:`www.${e}`,targetDomain:e,protocol:n,preservePath:!0}),apexToWww:(e,n="https")=>({slug:e.replace(/\./g,"-"),environment:"production",sourceDomain:e,targetDomain:`www.${e}`,protocol:n,preservePath:!0}),httpToHttps:(e="/")=>({source:e,target:e,statusCode:301}),addTrailingSlash:(e)=>e.map((n)=>({source:n.endsWith("/")?n.slice(0,-1):n,target:n.endsWith("/")?n:`${n}/`,statusCode:301})),removeTrailingSlash:(e)=>e.map((n)=>({source:n.endsWith("/")&&n!=="/"?n:`${n}/`,target:n.endsWith("/")&&n!=="/"?n.slice(0,-1):n,statusCode:301}))};static Patterns={flattenBlogUrls:(e)=>e.map(({oldPath:n,newPath:r})=>({source:n,target:r,statusCode:301,preserveQueryString:!0})),categoryRename:(e,n)=>[{source:`/${e}`,target:`/${n}`,statusCode:301},{source:`/${e}/`,target:`/${n}/`,statusCode:301}],productSlugChange:(e)=>e.map(({oldSlug:n,newSlug:r})=>({source:`/products/${n}`,target:`/products/${r}`,statusCode:301})),apiVersionRedirect:(e,n,r)=>r.map((i)=>({source:`/api/${e}/${i}`,target:`/api/${n}/${i}`,statusCode:307,preserveQueryString:!0})),gonePages:(e)=>e.map((n)=>({source:n,target:"/410",statusCode:301}))};static createRedirectSetup(e){let{slug:n,environment:r,domainRedirects:i=[],pathRedirects:s=[]}=e,a={},c=[];for(let d of i){let{bucket:m,bucketPolicy:p,logicalId:g,policyLogicalId:y}=kt.createDomainRedirectBucket({...d,slug:n,environment:r});a[g]=m,a[y]=p,c.push(g)}let u=null;if(s.length>0){let{function:d,logicalId:m}=kt.createPathRedirectFunction({slug:n,environment:r,rules:s});a[m]=d,u=m}return{resources:a,outputs:{domainRedirectBuckets:c,pathRedirectFunctionLogicalId:u}}}static fromMapping(e,n){return Object.entries(e).map(([r,i])=>({source:r,target:i,statusCode:n?.statusCode||301,preserveQueryString:n?.preserveQueryString??!0}))}static validateRules(e){let n=[],r=[],i=new Set;for(let s of e){if(i.has(s.source))n.push(`Duplicate source path: ${s.source}`);if(i.add(s.source),s.source===s.target)n.push(`Redirect loop detected: ${s.source} -> ${s.target}`);if(!s.target.startsWith("/")&&!s.target.startsWith("http"))r.push(`Target URL should start with / or http: ${s.target}`);if(!s.source||s.source.trim()==="")n.push("Source path cannot be empty");if(!s.target||s.target.trim()==="")n.push("Target path cannot be empty")}for(let s of e){let a=e.find((c)=>c.source===s.target);if(a)r.push(`Potential redirect chain: ${s.source} -> ${s.target} -> ${a.target}`)}return{valid:n.length===0,errors:n,warnings:r}}}class ke{static generate(e){let n={},{slug:r,environment:i,region:s="us-east-1"}=e,a=ke.createLambdaExecutionRole(r,i);if(Object.assign(n,a.resources),e.email?.enabled){let c=ke.generateEmailResources(e,a.roleArn);Object.assign(n,c)}if(e.phone?.enabled){let c=ke.generatePhoneResources(e,a.roleArn);Object.assign(n,c)}if(e.sms?.enabled){let c=ke.generateSmsResources(e,a.roleArn);Object.assign(n,c)}return n}static createLambdaExecutionRole(e,n){let r=`${e}-${n}-communication-role`,i=o(r);return{resources:{[i]:{Type:"AWS::IAM::Role",Properties:{RoleName:r,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"],Policies:[{PolicyName:"CommunicationPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:ListBucket"],Resource:"*"},{Effect:"Allow",Action:["ses:SendEmail","ses:SendRawEmail","ses:GetIdentityVerificationAttributes"],Resource:"*"},{Effect:"Allow",Action:["sns:Publish","sns:Subscribe"],Resource:"*"},{Effect:"Allow",Action:["dynamodb:GetItem","dynamodb:PutItem","dynamodb:UpdateItem","dynamodb:DeleteItem","dynamodb:Query","dynamodb:Scan","dynamodb:BatchWriteItem","dynamodb:BatchGetItem"],Resource:"*"},{Effect:"Allow",Action:["connect:*"],Resource:"*"},{Effect:"Allow",Action:["mobiletargeting:SendMessages","mobiletargeting:GetEndpoint","mobiletargeting:UpdateEndpoint"],Resource:"*"},{Effect:"Allow",Action:["transcribe:StartTranscriptionJob","transcribe:GetTranscriptionJob"],Resource:"*"},{Effect:"Allow",Action:["bedrock:InvokeModel"],Resource:"*"},{Effect:"Allow",Action:["es:ESHttpGet","es:ESHttpPost","es:ESHttpPut","es:ESHttpDelete"],Resource:"*"}]}}]}}},roleArn:R.GetAtt(i,"Arn"),roleName:r}}static generateEmailResources(e,n){let{slug:r,environment:i,email:s}=e;if(!s)return{};let a={},c=`${r}-${i}`,u=`${c}-email-storage`,d=o(u);a[d]={Type:"AWS::S3::Bucket",Properties:{BucketName:u,LifecycleConfiguration:{Rules:[{Id:"ArchiveOldEmails",Status:"Enabled",Transitions:s.server?.storage?.archiveAfterDays?[{StorageClass:"GLACIER",TransitionInDays:s.server.storage.archiveAfterDays}]:[],ExpirationInDays:s.server?.storage?.retentionDays||365}]},NotificationConfiguration:{LambdaConfigurations:[]}}};let m=o(`${c}-ses-identity`);if(a[m]={Type:"AWS::SES::EmailIdentity",Properties:{EmailIdentity:s.domain,DkimSigningAttributes:{NextSigningKeyLength:"RSA_2048_BIT"},FeedbackAttributes:{EmailForwardingEnabled:!0}}},s.notifications?.bounces||s.notifications?.complaints){let p=o(`${c}-bounce-topic`);a[p]={Type:"AWS::SNS::Topic",Properties:{TopicName:`${c}-email-bounces`}};let g=o(`${c}-complaint-topic`);a[g]={Type:"AWS::SNS::Topic",Properties:{TopicName:`${c}-email-complaints`}}}if(s.server?.enabled){let p=o(`${c}-inbound-email`);a[p]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${c}-inbound-email`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n,Timeout:60,MemorySize:256,Code:{ZipFile:ke.InboundEmailCode},Environment:{Variables:{EMAIL_BUCKET:u,DOMAIN:s.domain}}}};let g=o(`${c}-outbound-email`);a[g]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${c}-outbound-email`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n,Timeout:30,MemorySize:256,Code:{ZipFile:ke.OutboundEmailCode},Environment:{Variables:{EMAIL_BUCKET:u,DOMAIN:s.domain}}}}}if(s.advanced?.analytics){let p=o(`${c}-email-analytics`);a[p]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${c}-email-analytics`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"messageId",AttributeType:"S"}],KeySchema:[{AttributeName:"messageId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}if(s.advanced?.scheduling){let p=o(`${c}-email-scheduler`);a[p]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${c}-email-scheduler`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n,Timeout:300,MemorySize:256,Code:{ZipFile:ke.EmailSchedulerCode},Environment:{Variables:{EMAIL_BUCKET:u}}}};let g=o(`${c}-email-scheduler-rule`);a[g]={Type:"AWS::Events::Rule",Properties:{Name:`${c}-email-scheduler`,ScheduleExpression:"rate(1 minute)",State:"ENABLED",Targets:[{Id:"EmailSchedulerTarget",Arn:R.GetAtt(p,"Arn")}]}}}if(s.advanced?.threading){let p=o(`${c}-email-threading`);a[p]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${c}-email-threading`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n,Timeout:60,MemorySize:256,Code:{ZipFile:ke.EmailThreadingCode},Environment:{Variables:{EMAIL_BUCKET:u}}}}}if(s.advanced?.rules){let p=o(`${c}-email-rules`);a[p]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${c}-email-rules`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"mailbox",AttributeType:"S"},{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"mailbox",KeyType:"HASH"},{AttributeName:"id",KeyType:"RANGE"}]}}}if(s.advanced?.sharedMailboxes){let p=o(`${c}-shared-mailboxes`);a[p]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${c}-shared-mailboxes`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"},{AttributeName:"type",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}],GlobalSecondaryIndexes:[{IndexName:"type-index",KeySchema:[{AttributeName:"type",KeyType:"HASH"}],Projection:{ProjectionType:"ALL"}}]}}}if(s.advanced?.search){let p=o(`${c}-email-search`);a[p]={Type:"AWS::OpenSearchService::Domain",Properties:{DomainName:`${c}-email-search`.toLowerCase().replace(/[^a-z0-9-]/g,"-").substring(0,28),EngineVersion:"OpenSearch_2.11",ClusterConfig:{InstanceType:"t3.small.search",InstanceCount:1},EBSOptions:{EBSEnabled:!0,VolumeType:"gp3",VolumeSize:10},NodeToNodeEncryptionOptions:{Enabled:!0},EncryptionAtRestOptions:{Enabled:!0},DomainEndpointOptions:{EnforceHTTPS:!0}}}}return a}static generatePhoneResources(e,n){let{slug:r,environment:i,phone:s}=e;if(!s)return{};let a={},c=`${r}-${i}`,u=o(`${c}-call-log`);if(a[u]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${c}-call-log`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"contactId",AttributeType:"S"}],KeySchema:[{AttributeName:"contactId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}},s.voicemail?.enabled){let p=o(`${c}-voicemail`);a[p]={Type:"AWS::S3::Bucket",Properties:{BucketName:`${c}-voicemail`,LifecycleConfiguration:{Rules:[{Id:"DeleteOldVoicemails",Status:"Enabled",ExpirationInDays:90}]}}}}let d=o(`${c}-phone-notifications`);a[d]={Type:"AWS::SNS::Topic",Properties:{TopicName:`${c}-phone-notifications`}};let m=o(`${c}-incoming-call`);if(a[m]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${c}-incoming-call`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n,Timeout:30,MemorySize:256,Code:{ZipFile:ke.IncomingCallCode},Environment:{Variables:{CALL_LOG_TABLE:`${c}-call-log`,NOTIFICATION_TOPIC_ARN:R.Ref(d)}}}},s.voicemail?.enabled){let p=o(`${c}-voicemail-handler`);a[p]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${c}-voicemail-handler`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n,Timeout:s.voicemail.transcription?300:60,MemorySize:256,Code:{ZipFile:ke.VoicemailCode},Environment:{Variables:{VOICEMAIL_BUCKET:`${c}-voicemail`,TRANSCRIPTION_ENABLED:String(s.voicemail.transcription||!1),NOTIFICATION_TOPIC_ARN:R.Ref(d)}}}}}if(s.advanced?.recording){let p=o(`${c}-call-recordings`);a[p]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${c}-call-recordings`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"recordingId",AttributeType:"S"}],KeySchema:[{AttributeName:"recordingId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}if(s.advanced?.callbacks){let p=o(`${c}-callbacks`);a[p]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${c}-callbacks`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}if(s.advanced?.analytics){let p=o(`${c}-call-metrics`);a[p]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${c}-call-metrics`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"period",AttributeType:"S"}],KeySchema:[{AttributeName:"period",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}return a}static generateSmsResources(e,n){let{slug:r,environment:i,sms:s}=e;if(!s)return{};let a={},c=`${r}-${i}`,u=o(`${c}-pinpoint-app`);a[u]={Type:"AWS::Pinpoint::App",Properties:{Name:`${c}-sms`}};let d=o(`${c}-sms-channel`);a[d]={Type:"AWS::Pinpoint::SMSChannel",Properties:{ApplicationId:R.Ref(u),Enabled:!0,SenderId:s.senderId}};let m=o(`${c}-sms-log`);if(a[m]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${c}-sms-log`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"messageId",AttributeType:"S"}],KeySchema:[{AttributeName:"messageId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}},s.optOut?.enabled){let f=o(`${c}-sms-optout`);a[f]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${c}-sms-optout`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"phoneNumber",AttributeType:"S"}],KeySchema:[{AttributeName:"phoneNumber",KeyType:"HASH"}]}}}let p=o(`${c}-sms-notifications`);a[p]={Type:"AWS::SNS::Topic",Properties:{TopicName:`${c}-sms-notifications`}};let g=o(`${c}-send-sms`);a[g]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${c}-send-sms`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n,Timeout:30,MemorySize:256,Code:{ZipFile:ke.SendSmsCode},Environment:{Variables:{PINPOINT_APP_ID:R.Ref(u),MESSAGE_LOG_TABLE:`${c}-sms-log`,OPT_OUT_TABLE:s.optOut?.enabled?`${c}-sms-optout`:"",MESSAGE_TYPE:s.messageType||"TRANSACTIONAL"}}}};let y=o(`${c}-receive-sms`);if(a[y]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${c}-receive-sms`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n,Timeout:30,MemorySize:256,Code:{ZipFile:ke.ReceiveSmsCode},Environment:{Variables:{MESSAGE_LOG_TABLE:`${c}-sms-log`,OPT_OUT_TABLE:s.optOut?.enabled?`${c}-sms-optout`:"",NOTIFICATION_TOPIC_ARN:R.Ref(p)}}}},s.advanced?.campaigns){let f=o(`${c}-sms-campaigns`);a[f]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${c}-sms-campaigns`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}]}}}if(s.advanced?.analytics){let f=o(`${c}-sms-analytics`);a[f]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${c}-sms-analytics`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"period",AttributeType:"S"}],KeySchema:[{AttributeName:"period",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}if(s.advanced?.linkTracking){let f=o(`${c}-short-links`);a[f]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${c}-short-links`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}if(s.advanced?.chatbot){let f=o(`${c}-chatbot-sessions`);a[f]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${c}-chatbot-sessions`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"phoneNumber",AttributeType:"S"}],KeySchema:[{AttributeName:"phoneNumber",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}};let h=o(`${c}-chatbot-rules`);a[h]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${c}-chatbot-rules`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}]}}}if(s.advanced?.abTesting){let f=o(`${c}-ab-tests`);a[f]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${c}-ab-tests`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}]}}}if(s.advanced?.mms){let f=o(`${c}-mms-media`);a[f]={Type:"AWS::S3::Bucket",Properties:{BucketName:`${c}-mms-media`,LifecycleConfiguration:{Rules:[{Id:"DeleteOldMedia",Status:"Enabled",ExpirationInDays:30}]}}}}return a}static InboundEmailCode=`
|
|
2335
|
+
}`}static CommonRedirects={wwwToApex:(e,n="https")=>({slug:e.replace(/\./g,"-"),environment:"production",sourceDomain:`www.${e}`,targetDomain:e,protocol:n,preservePath:!0}),apexToWww:(e,n="https")=>({slug:e.replace(/\./g,"-"),environment:"production",sourceDomain:e,targetDomain:`www.${e}`,protocol:n,preservePath:!0}),httpToHttps:(e="/")=>({source:e,target:e,statusCode:301}),addTrailingSlash:(e)=>e.map((n)=>({source:n.endsWith("/")?n.slice(0,-1):n,target:n.endsWith("/")?n:`${n}/`,statusCode:301})),removeTrailingSlash:(e)=>e.map((n)=>({source:n.endsWith("/")&&n!=="/"?n:`${n}/`,target:n.endsWith("/")&&n!=="/"?n.slice(0,-1):n,statusCode:301}))};static Patterns={flattenBlogUrls:(e)=>e.map(({oldPath:n,newPath:r})=>({source:n,target:r,statusCode:301,preserveQueryString:!0})),categoryRename:(e,n)=>[{source:`/${e}`,target:`/${n}`,statusCode:301},{source:`/${e}/`,target:`/${n}/`,statusCode:301}],productSlugChange:(e)=>e.map(({oldSlug:n,newSlug:r})=>({source:`/products/${n}`,target:`/products/${r}`,statusCode:301})),apiVersionRedirect:(e,n,r)=>r.map((i)=>({source:`/api/${e}/${i}`,target:`/api/${n}/${i}`,statusCode:307,preserveQueryString:!0})),gonePages:(e)=>e.map((n)=>({source:n,target:"/410",statusCode:301}))};static createRedirectSetup(e){let{slug:n,environment:r,domainRedirects:i=[],pathRedirects:s=[]}=e,a={},c=[];for(let d of i){let{bucket:m,bucketPolicy:p,logicalId:g,policyLogicalId:y}=Nt.createDomainRedirectBucket({...d,slug:n,environment:r});a[g]=m,a[y]=p,c.push(g)}let u=null;if(s.length>0){let{function:d,logicalId:m}=Nt.createPathRedirectFunction({slug:n,environment:r,rules:s});a[m]=d,u=m}return{resources:a,outputs:{domainRedirectBuckets:c,pathRedirectFunctionLogicalId:u}}}static fromMapping(e,n){return Object.entries(e).map(([r,i])=>({source:r,target:i,statusCode:n?.statusCode||301,preserveQueryString:n?.preserveQueryString??!0}))}static validateRules(e){let n=[],r=[],i=new Set;for(let s of e){if(i.has(s.source))n.push(`Duplicate source path: ${s.source}`);if(i.add(s.source),s.source===s.target)n.push(`Redirect loop detected: ${s.source} -> ${s.target}`);if(!s.target.startsWith("/")&&!s.target.startsWith("http"))r.push(`Target URL should start with / or http: ${s.target}`);if(!s.source||s.source.trim()==="")n.push("Source path cannot be empty");if(!s.target||s.target.trim()==="")n.push("Target path cannot be empty")}for(let s of e){let a=e.find((c)=>c.source===s.target);if(a)r.push(`Potential redirect chain: ${s.source} -> ${s.target} -> ${a.target}`)}return{valid:n.length===0,errors:n,warnings:r}}}class ke{static generate(e){let n={},{slug:r,environment:i,region:s="us-east-1"}=e,a=ke.createLambdaExecutionRole(r,i);if(Object.assign(n,a.resources),e.email?.enabled){let c=ke.generateEmailResources(e,a.roleArn);Object.assign(n,c)}if(e.phone?.enabled){let c=ke.generatePhoneResources(e,a.roleArn);Object.assign(n,c)}if(e.sms?.enabled){let c=ke.generateSmsResources(e,a.roleArn);Object.assign(n,c)}return n}static createLambdaExecutionRole(e,n){let r=`${e}-${n}-communication-role`,i=o(r);return{resources:{[i]:{Type:"AWS::IAM::Role",Properties:{RoleName:r,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"],Policies:[{PolicyName:"CommunicationPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:ListBucket"],Resource:"*"},{Effect:"Allow",Action:["ses:SendEmail","ses:SendRawEmail","ses:GetIdentityVerificationAttributes"],Resource:"*"},{Effect:"Allow",Action:["sns:Publish","sns:Subscribe"],Resource:"*"},{Effect:"Allow",Action:["dynamodb:GetItem","dynamodb:PutItem","dynamodb:UpdateItem","dynamodb:DeleteItem","dynamodb:Query","dynamodb:Scan","dynamodb:BatchWriteItem","dynamodb:BatchGetItem"],Resource:"*"},{Effect:"Allow",Action:["connect:*"],Resource:"*"},{Effect:"Allow",Action:["mobiletargeting:SendMessages","mobiletargeting:GetEndpoint","mobiletargeting:UpdateEndpoint"],Resource:"*"},{Effect:"Allow",Action:["transcribe:StartTranscriptionJob","transcribe:GetTranscriptionJob"],Resource:"*"},{Effect:"Allow",Action:["bedrock:InvokeModel"],Resource:"*"},{Effect:"Allow",Action:["es:ESHttpGet","es:ESHttpPost","es:ESHttpPut","es:ESHttpDelete"],Resource:"*"}]}}]}}},roleArn:R.GetAtt(i,"Arn"),roleName:r}}static generateEmailResources(e,n){let{slug:r,environment:i,email:s}=e;if(!s)return{};let a={},c=`${r}-${i}`,u=`${c}-email-storage`,d=o(u);a[d]={Type:"AWS::S3::Bucket",Properties:{BucketName:u,LifecycleConfiguration:{Rules:[{Id:"ArchiveOldEmails",Status:"Enabled",Transitions:s.server?.storage?.archiveAfterDays?[{StorageClass:"GLACIER",TransitionInDays:s.server.storage.archiveAfterDays}]:[],ExpirationInDays:s.server?.storage?.retentionDays||365}]},NotificationConfiguration:{LambdaConfigurations:[]}}};let m=o(`${c}-ses-identity`);if(a[m]={Type:"AWS::SES::EmailIdentity",Properties:{EmailIdentity:s.domain,DkimSigningAttributes:{NextSigningKeyLength:"RSA_2048_BIT"},FeedbackAttributes:{EmailForwardingEnabled:!0}}},s.notifications?.bounces||s.notifications?.complaints){let p=o(`${c}-bounce-topic`);a[p]={Type:"AWS::SNS::Topic",Properties:{TopicName:`${c}-email-bounces`}};let g=o(`${c}-complaint-topic`);a[g]={Type:"AWS::SNS::Topic",Properties:{TopicName:`${c}-email-complaints`}}}if(s.server?.enabled){let p=o(`${c}-inbound-email`);a[p]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${c}-inbound-email`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n,Timeout:60,MemorySize:256,Code:{ZipFile:ke.InboundEmailCode},Environment:{Variables:{EMAIL_BUCKET:u,DOMAIN:s.domain}}}};let g=o(`${c}-outbound-email`);a[g]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${c}-outbound-email`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n,Timeout:30,MemorySize:256,Code:{ZipFile:ke.OutboundEmailCode},Environment:{Variables:{EMAIL_BUCKET:u,DOMAIN:s.domain}}}}}if(s.advanced?.analytics){let p=o(`${c}-email-analytics`);a[p]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${c}-email-analytics`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"messageId",AttributeType:"S"}],KeySchema:[{AttributeName:"messageId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}if(s.advanced?.scheduling){let p=o(`${c}-email-scheduler`);a[p]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${c}-email-scheduler`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n,Timeout:300,MemorySize:256,Code:{ZipFile:ke.EmailSchedulerCode},Environment:{Variables:{EMAIL_BUCKET:u}}}};let g=o(`${c}-email-scheduler-rule`);a[g]={Type:"AWS::Events::Rule",Properties:{Name:`${c}-email-scheduler`,ScheduleExpression:"rate(1 minute)",State:"ENABLED",Targets:[{Id:"EmailSchedulerTarget",Arn:R.GetAtt(p,"Arn")}]}}}if(s.advanced?.threading){let p=o(`${c}-email-threading`);a[p]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${c}-email-threading`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n,Timeout:60,MemorySize:256,Code:{ZipFile:ke.EmailThreadingCode},Environment:{Variables:{EMAIL_BUCKET:u}}}}}if(s.advanced?.rules){let p=o(`${c}-email-rules`);a[p]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${c}-email-rules`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"mailbox",AttributeType:"S"},{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"mailbox",KeyType:"HASH"},{AttributeName:"id",KeyType:"RANGE"}]}}}if(s.advanced?.sharedMailboxes){let p=o(`${c}-shared-mailboxes`);a[p]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${c}-shared-mailboxes`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"},{AttributeName:"type",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}],GlobalSecondaryIndexes:[{IndexName:"type-index",KeySchema:[{AttributeName:"type",KeyType:"HASH"}],Projection:{ProjectionType:"ALL"}}]}}}if(s.advanced?.search){let p=o(`${c}-email-search`);a[p]={Type:"AWS::OpenSearchService::Domain",Properties:{DomainName:`${c}-email-search`.toLowerCase().replace(/[^a-z0-9-]/g,"-").substring(0,28),EngineVersion:"OpenSearch_2.11",ClusterConfig:{InstanceType:"t3.small.search",InstanceCount:1},EBSOptions:{EBSEnabled:!0,VolumeType:"gp3",VolumeSize:10},NodeToNodeEncryptionOptions:{Enabled:!0},EncryptionAtRestOptions:{Enabled:!0},DomainEndpointOptions:{EnforceHTTPS:!0}}}}return a}static generatePhoneResources(e,n){let{slug:r,environment:i,phone:s}=e;if(!s)return{};let a={},c=`${r}-${i}`,u=o(`${c}-call-log`);if(a[u]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${c}-call-log`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"contactId",AttributeType:"S"}],KeySchema:[{AttributeName:"contactId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}},s.voicemail?.enabled){let p=o(`${c}-voicemail`);a[p]={Type:"AWS::S3::Bucket",Properties:{BucketName:`${c}-voicemail`,LifecycleConfiguration:{Rules:[{Id:"DeleteOldVoicemails",Status:"Enabled",ExpirationInDays:90}]}}}}let d=o(`${c}-phone-notifications`);a[d]={Type:"AWS::SNS::Topic",Properties:{TopicName:`${c}-phone-notifications`}};let m=o(`${c}-incoming-call`);if(a[m]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${c}-incoming-call`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n,Timeout:30,MemorySize:256,Code:{ZipFile:ke.IncomingCallCode},Environment:{Variables:{CALL_LOG_TABLE:`${c}-call-log`,NOTIFICATION_TOPIC_ARN:R.Ref(d)}}}},s.voicemail?.enabled){let p=o(`${c}-voicemail-handler`);a[p]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${c}-voicemail-handler`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n,Timeout:s.voicemail.transcription?300:60,MemorySize:256,Code:{ZipFile:ke.VoicemailCode},Environment:{Variables:{VOICEMAIL_BUCKET:`${c}-voicemail`,TRANSCRIPTION_ENABLED:String(s.voicemail.transcription||!1),NOTIFICATION_TOPIC_ARN:R.Ref(d)}}}}}if(s.advanced?.recording){let p=o(`${c}-call-recordings`);a[p]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${c}-call-recordings`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"recordingId",AttributeType:"S"}],KeySchema:[{AttributeName:"recordingId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}if(s.advanced?.callbacks){let p=o(`${c}-callbacks`);a[p]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${c}-callbacks`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}if(s.advanced?.analytics){let p=o(`${c}-call-metrics`);a[p]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${c}-call-metrics`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"period",AttributeType:"S"}],KeySchema:[{AttributeName:"period",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}return a}static generateSmsResources(e,n){let{slug:r,environment:i,sms:s}=e;if(!s)return{};let a={},c=`${r}-${i}`,u=o(`${c}-pinpoint-app`);a[u]={Type:"AWS::Pinpoint::App",Properties:{Name:`${c}-sms`}};let d=o(`${c}-sms-channel`);a[d]={Type:"AWS::Pinpoint::SMSChannel",Properties:{ApplicationId:R.Ref(u),Enabled:!0,SenderId:s.senderId}};let m=o(`${c}-sms-log`);if(a[m]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${c}-sms-log`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"messageId",AttributeType:"S"}],KeySchema:[{AttributeName:"messageId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}},s.optOut?.enabled){let f=o(`${c}-sms-optout`);a[f]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${c}-sms-optout`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"phoneNumber",AttributeType:"S"}],KeySchema:[{AttributeName:"phoneNumber",KeyType:"HASH"}]}}}let p=o(`${c}-sms-notifications`);a[p]={Type:"AWS::SNS::Topic",Properties:{TopicName:`${c}-sms-notifications`}};let g=o(`${c}-send-sms`);a[g]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${c}-send-sms`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n,Timeout:30,MemorySize:256,Code:{ZipFile:ke.SendSmsCode},Environment:{Variables:{PINPOINT_APP_ID:R.Ref(u),MESSAGE_LOG_TABLE:`${c}-sms-log`,OPT_OUT_TABLE:s.optOut?.enabled?`${c}-sms-optout`:"",MESSAGE_TYPE:s.messageType||"TRANSACTIONAL"}}}};let y=o(`${c}-receive-sms`);if(a[y]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${c}-receive-sms`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n,Timeout:30,MemorySize:256,Code:{ZipFile:ke.ReceiveSmsCode},Environment:{Variables:{MESSAGE_LOG_TABLE:`${c}-sms-log`,OPT_OUT_TABLE:s.optOut?.enabled?`${c}-sms-optout`:"",NOTIFICATION_TOPIC_ARN:R.Ref(p)}}}},s.advanced?.campaigns){let f=o(`${c}-sms-campaigns`);a[f]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${c}-sms-campaigns`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}]}}}if(s.advanced?.analytics){let f=o(`${c}-sms-analytics`);a[f]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${c}-sms-analytics`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"period",AttributeType:"S"}],KeySchema:[{AttributeName:"period",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}if(s.advanced?.linkTracking){let f=o(`${c}-short-links`);a[f]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${c}-short-links`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}if(s.advanced?.chatbot){let f=o(`${c}-chatbot-sessions`);a[f]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${c}-chatbot-sessions`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"phoneNumber",AttributeType:"S"}],KeySchema:[{AttributeName:"phoneNumber",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}};let h=o(`${c}-chatbot-rules`);a[h]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${c}-chatbot-rules`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}]}}}if(s.advanced?.abTesting){let f=o(`${c}-ab-tests`);a[f]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${c}-ab-tests`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}]}}}if(s.advanced?.mms){let f=o(`${c}-mms-media`);a[f]={Type:"AWS::S3::Bucket",Properties:{BucketName:`${c}-mms-media`,LifecycleConfiguration:{Rules:[{Id:"DeleteOldMedia",Status:"Enabled",ExpirationInDays:30}]}}}}return a}static InboundEmailCode=`
|
|
2336
2336
|
const { S3Client, GetObjectCommand, PutObjectCommand } = require('@aws-sdk/client-s3');
|
|
2337
2337
|
const s3 = new S3Client({});
|
|
2338
2338
|
exports.handler = async (event) => {
|
|
@@ -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 t={ref:(e)=>({Ref:e}),getAtt:(e,n)=>({"Fn::GetAtt":[e,n]}),join:(e,n)=>({"Fn::Join":[e,n]}),sub:(e,n)=>n?{"Fn::Sub":[e,n]}:{"Fn::Sub":e},select:(e,n)=>({"Fn::Select":[e,n]}),split:(e,n)=>({"Fn::Split":[e,n]}),getAZs:(e="")=>({"Fn::GetAZs":e}),importValue:(e)=>({"Fn::ImportValue":e}),findInMap:(e,n,r)=>({"Fn::FindInMap":[e,n,r]}),base64:(e)=>({"Fn::Base64":e}),cidr:(e,n,r)=>({"Fn::Cidr":[e,n,r]}),equals:(e,n)=>({"Fn::Equals":[e,n]}),if:(e,n,r)=>({"Fn::If":[e,n,r]}),not:(e)=>({"Fn::Not":[e]}),and:(...e)=>({"Fn::And":e}),or:(...e)=>({"Fn::Or":e})},Rn={s3Bucket:(e)=>t.sub(`arn:aws:s3:::${e}`),s3Object:(e,n="*")=>t.sub(`arn:aws:s3:::${e}/${n}`),lambda:(e,n,r)=>t.sub(`arn:aws:lambda:\${AWS::Region}:\${AWS::AccountId}:function:${e}`,n&&r?{"AWS::Region":n,"AWS::AccountId":r}:void 0),dynamodb:(e)=>t.sub(`arn:aws:dynamodb:\${AWS::Region}:\${AWS::AccountId}:table/${e}`),sqs:(e)=>t.sub(`arn:aws:sqs:\${AWS::Region}:\${AWS::AccountId}:${e}`),sns:(e)=>t.sub(`arn:aws:sns:\${AWS::Region}:\${AWS::AccountId}:${e}`),kinesis:(e)=>t.sub(`arn:aws:kinesis:\${AWS::Region}:\${AWS::AccountId}:stream/${e}`),iam:(e,n)=>t.sub(`arn:aws:iam::\${AWS::AccountId}:${e}/${n}`),secretsManager:(e)=>t.sub(`arn:aws:secretsmanager:\${AWS::Region}:\${AWS::AccountId}:secret:${e}`),cloudwatch:(e)=>t.sub(`arn:aws:logs:\${AWS::Region}:\${AWS::AccountId}:log-group:${e}`)},xm={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 dn(e,n){if(n.type==="http")Kr(e,n);else if(n.type==="rest")qr(e,n);else if(n.type==="websocket")Qr(e,n)}function Kr(e,n){let r={Name:t.sub("${AWS::StackName}-http-api"),ProtocolType:"HTTP"};if(n.cors)r.CorsConfiguration={AllowOrigins:n.cors.allowOrigins,AllowMethods:n.cors.allowMethods,AllowHeaders:n.cors.allowHeaders||["*"],MaxAge:n.cors.maxAge||300};if(e.addResource("HttpApi","AWS::ApiGatewayV2::Api",r),e.addResource("HttpApiStage","AWS::ApiGatewayV2::Stage",{ApiId:t.ref("HttpApi"),StageName:"$default",AutoDeploy:!0,DefaultRouteSettings:n.throttling?{ThrottlingBurstLimit:n.throttling.burstLimit,ThrottlingRateLimit:n.throttling.rateLimit}:void 0,AccessLogSettings:{DestinationArn:t.getAtt("ApiLogGroup","Arn"),Format:"$context.requestId $context.error.message $context.error.messageString"}},{dependsOn:["HttpApi","ApiLogGroup"]}),e.addResource("ApiLogGroup","AWS::Logs::LogGroup",{LogGroupName:t.sub("/aws/apigateway/${AWS::StackName}-http-api"),RetentionInDays:14}),n.authorizer)Jr(e,"HttpApi",n.authorizer);if(n.customDomain)St(e,"HttpApi",n.customDomain,"HTTP");e.addOutputs({HttpApiId:{Description:"HTTP API ID",Value:t.ref("HttpApi"),Export:{Name:t.sub("${AWS::StackName}-http-api-id")}},HttpApiEndpoint:{Description:"HTTP API endpoint",Value:t.getAtt("HttpApi","ApiEndpoint"),Export:{Name:t.sub("${AWS::StackName}-http-api-endpoint")}}})}function qr(e,n){e.addResource("RestApi","AWS::ApiGateway::RestApi",{Name:t.sub("${AWS::StackName}-rest-api"),Description:t.sub("REST API for ${AWS::StackName}"),EndpointConfiguration:{Types:["REGIONAL"]}}),e.addResource("ApiGatewayAccount","AWS::ApiGateway::Account",{CloudWatchRoleArn:t.getAtt("ApiGatewayCloudWatchRole","Arn")},{dependsOn:"ApiGatewayCloudWatchRole"}),e.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"]}),e.addResource("RestApiDeployment","AWS::ApiGateway::Deployment",{RestApiId:t.ref("RestApi"),Description:"Initial deployment"},{dependsOn:"RestApi"});let r={RestApiId:t.ref("RestApi"),DeploymentId:t.ref("RestApiDeployment"),StageName:"prod",Description:"Production stage",MethodSettings:[{ResourcePath:"/*",HttpMethod:"*",LoggingLevel:"INFO",DataTraceEnabled:!0,MetricsEnabled:!0}]};if(n.throttling)r.MethodSettings[0].ThrottlingBurstLimit=n.throttling.burstLimit,r.MethodSettings[0].ThrottlingRateLimit=n.throttling.rateLimit;if(e.addResource("RestApiStage","AWS::ApiGateway::Stage",r,{dependsOn:["RestApi","RestApiDeployment"]}),n.customDomain)St(e,"RestApi",n.customDomain,"REST");e.addOutputs({RestApiId:{Description:"REST API ID",Value:t.ref("RestApi"),Export:{Name:t.sub("${AWS::StackName}-rest-api-id")}},RestApiEndpoint:{Description:"REST API endpoint",Value:t.sub("https://${RestApi}.execute-api.${AWS::Region}.amazonaws.com/prod"),Export:{Name:t.sub("${AWS::StackName}-rest-api-endpoint")}}})}function Qr(e,n){if(e.addResource("WebSocketApi","AWS::ApiGatewayV2::Api",{Name:t.sub("${AWS::StackName}-websocket-api"),ProtocolType:"WEBSOCKET",RouteSelectionExpression:"$request.body.action"}),n.routes){if(n.routes.connect)tt(e,"$connect",n.routes.connect.functionName);if(n.routes.disconnect)tt(e,"$disconnect",n.routes.disconnect.functionName);if(n.routes.default)tt(e,"$default",n.routes.default.functionName);if(n.routes.custom)n.routes.custom.forEach((r)=>{tt(e,r.routeKey,r.functionName)})}if(e.addResource("WebSocketApiStage","AWS::ApiGatewayV2::Stage",{ApiId:t.ref("WebSocketApi"),StageName:"prod",AutoDeploy:!0,DefaultRouteSettings:n.throttling?{ThrottlingBurstLimit:n.throttling.burstLimit,ThrottlingRateLimit:n.throttling.rateLimit}:void 0},{dependsOn:"WebSocketApi"}),n.customDomain)St(e,"WebSocketApi",n.customDomain,"WEBSOCKET");e.addOutputs({WebSocketApiId:{Description:"WebSocket API ID",Value:t.ref("WebSocketApi"),Export:{Name:t.sub("${AWS::StackName}-websocket-api-id")}},WebSocketApiEndpoint:{Description:"WebSocket API endpoint",Value:t.getAtt("WebSocketApi","ApiEndpoint"),Export:{Name:t.sub("${AWS::StackName}-websocket-api-endpoint")}}})}function tt(e,n,r){let i=e.toLogicalId(`websocket-route-${n}`),s=e.toLogicalId(`websocket-integration-${n}`),a=e.toLogicalId(`${r}-function`);e.addResource(s,"AWS::ApiGatewayV2::Integration",{ApiId:t.ref("WebSocketApi"),IntegrationType:"AWS_PROXY",IntegrationUri:t.sub(`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${a}.Arn}/invocations`)},{dependsOn:["WebSocketApi",a]}),e.addResource(i,"AWS::ApiGatewayV2::Route",{ApiId:t.ref("WebSocketApi"),RouteKey:n,Target:t.join("/",["integrations",t.ref(s)])},{dependsOn:["WebSocketApi",s]}),e.addResource(`${i}Permission`,"AWS::Lambda::Permission",{FunctionName:t.ref(a),Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:t.sub("arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${WebSocketApi}/*")},{dependsOn:[a,"WebSocketApi"]})}function St(e,n,r,i){let s={DomainName:r.domain};if(i==="REST")s.CertificateArn=r.certificateArn,s.EndpointConfiguration={Types:["REGIONAL"]},e.addResource("ApiCustomDomain","AWS::ApiGateway::DomainName",s),e.addResource("ApiBasePathMapping","AWS::ApiGateway::BasePathMapping",{DomainName:t.ref("ApiCustomDomain"),RestApiId:t.ref(n),Stage:t.ref("RestApiStage")},{dependsOn:["ApiCustomDomain",n,"RestApiStage"]});else s.DomainNameConfigurations=[{CertificateArn:r.certificateArn,EndpointType:"REGIONAL"}],e.addResource("ApiCustomDomain","AWS::ApiGatewayV2::DomainName",s),e.addResource("ApiMapping","AWS::ApiGatewayV2::ApiMapping",{ApiId:t.ref(n),DomainName:t.ref("ApiCustomDomain"),Stage:i==="HTTP"?t.ref("HttpApiStage"):t.ref("WebSocketApiStage")},{dependsOn:["ApiCustomDomain",n]});if(r.dnsProvider!=="external")e.addResource("ApiDNSRecord","AWS::Route53::RecordSet",{HostedZoneName:t.sub(`${Yr(r.domain)}.`),Name:r.domain,Type:"A",AliasTarget:{HostedZoneId:t.getAtt("ApiCustomDomain","RegionalHostedZoneId"),DNSName:t.getAtt("ApiCustomDomain","RegionalDomainName"),EvaluateTargetHealth:!1}},{dependsOn:"ApiCustomDomain"});e.addOutputs({ApiCustomDomainName:{Description:"Configured API custom domain",Value:r.domain},ApiCustomDomainTarget:{Description:"DNS target for Route53 or an external DNS provider",Value:t.getAtt("ApiCustomDomain","RegionalDomainName")},ApiCustomDomainHostedZoneId:{Description:"Regional API Gateway hosted zone ID",Value:t.getAtt("ApiCustomDomain","RegionalHostedZoneId")}})}function Jr(e,n,r){if(!r)return;if(r.type==="jwt")e.addResource("ApiAuthorizer","AWS::ApiGatewayV2::Authorizer",{ApiId:t.ref(n),AuthorizerType:"JWT",IdentitySource:[r.identitySource||"$request.header.Authorization"],JwtConfiguration:{Issuer:r.issuer,Audience:r.audience},Name:"JWTAuthorizer"},{dependsOn:n});else if(r.type==="lambda")e.addResource("ApiAuthorizer","AWS::ApiGatewayV2::Authorizer",{ApiId:t.ref(n),AuthorizerType:"REQUEST",AuthorizerUri:r.authorizerUri,IdentitySource:[r.identitySource||"$request.header.Authorization"],Name:"LambdaAuthorizer"},{dependsOn:n})}function Yr(e){let n=e.split(".");if(n.length>=2)return n.slice(-2).join(".");return e}function mn(e,n){if(n.redis)Zr(e,n.redis);if(n.memcached)Xr(e,n.memcached);if(n.elasticache)ei(e,n.elasticache)}function Zr(e,n){if(!n)return;if(e.addResource("CacheSubnetGroup","AWS::ElastiCache::SubnetGroup",{Description:"Subnet group for ElastiCache Redis cluster",SubnetIds:[t.ref("PrivateSubnet1"),t.ref("PrivateSubnet2")],Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-cache-subnet-group")}]},{dependsOn:["PrivateSubnet1","PrivateSubnet2"]}),e.addResource("CacheSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for ElastiCache Redis",VpcId:t.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:n.port||6379,ToPort:n.port||6379,SourceSecurityGroupId:t.ref("AppSecurityGroup")}],Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-cache-sg")}]},{dependsOn:["VPC","AppSecurityGroup"]}),n.parameterGroup&&Object.keys(n.parameterGroup).length>0)e.addResource("CacheParameterGroup","AWS::ElastiCache::ParameterGroup",{Description:"Parameter group for Redis",CacheParameterGroupFamily:`redis${n.engineVersion.split(".")[0]}`,Properties:n.parameterGroup});if(n.numCacheNodes>1||n.automaticFailoverEnabled)e.addResource("RedisReplicationGroup","AWS::ElastiCache::ReplicationGroup",{ReplicationGroupDescription:"Redis replication group",ReplicationGroupId:t.sub("${AWS::StackName}-redis"),Engine:"redis",EngineVersion:n.engineVersion,CacheNodeType:n.nodeType,NumCacheClusters:n.numCacheNodes,AutomaticFailoverEnabled:n.automaticFailoverEnabled||!1,MultiAZEnabled:n.automaticFailoverEnabled||!1,Port:n.port||6379,CacheSubnetGroupName:t.ref("CacheSubnetGroup"),SecurityGroupIds:[t.ref("CacheSecurityGroup")],CacheParameterGroupName:n.parameterGroup?t.ref("CacheParameterGroup"):void 0,SnapshotRetentionLimit:n.snapshotRetentionLimit||5,SnapshotWindow:n.snapshotWindow||"03:00-05:00",PreferredMaintenanceWindow:"sun:05:00-sun:06:00",AtRestEncryptionEnabled:!0,TransitEncryptionEnabled:!0,Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-redis")}]},{dependsOn:n.parameterGroup?["CacheSubnetGroup","CacheSecurityGroup","CacheParameterGroup"]:["CacheSubnetGroup","CacheSecurityGroup"],deletionPolicy:"Snapshot",updateReplacePolicy:"Snapshot"}),e.addOutputs({RedisEndpoint:{Description:"Redis primary endpoint",Value:t.getAtt("RedisReplicationGroup","PrimaryEndPoint.Address"),Export:{Name:t.sub("${AWS::StackName}-redis-endpoint")}},RedisPort:{Description:"Redis port",Value:t.getAtt("RedisReplicationGroup","PrimaryEndPoint.Port"),Export:{Name:t.sub("${AWS::StackName}-redis-port")}}});else e.addResource("RedisCacheCluster","AWS::ElastiCache::CacheCluster",{ClusterName:t.sub("${AWS::StackName}-redis"),Engine:"redis",EngineVersion:n.engineVersion,CacheNodeType:n.nodeType,NumCacheNodes:1,Port:n.port||6379,CacheSubnetGroupName:t.ref("CacheSubnetGroup"),VpcSecurityGroupIds:[t.ref("CacheSecurityGroup")],CacheParameterGroupName:n.parameterGroup?t.ref("CacheParameterGroup"):void 0,SnapshotRetentionLimit:n.snapshotRetentionLimit||5,SnapshotWindow:n.snapshotWindow||"03:00-05:00",PreferredMaintenanceWindow:"sun:05:00-sun:06:00",Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-redis")}]},{dependsOn:n.parameterGroup?["CacheSubnetGroup","CacheSecurityGroup","CacheParameterGroup"]:["CacheSubnetGroup","CacheSecurityGroup"],deletionPolicy:"Snapshot",updateReplacePolicy:"Snapshot"}),e.addOutputs({RedisEndpoint:{Description:"Redis endpoint",Value:t.getAtt("RedisCacheCluster","RedisEndpoint.Address"),Export:{Name:t.sub("${AWS::StackName}-redis-endpoint")}},RedisPort:{Description:"Redis port",Value:t.getAtt("RedisCacheCluster","RedisEndpoint.Port"),Export:{Name:t.sub("${AWS::StackName}-redis-port")}}})}function Xr(e,n){if(!n)return;if(!e.hasResource("CacheSubnetGroup"))e.addResource("CacheSubnetGroup","AWS::ElastiCache::SubnetGroup",{Description:"Subnet group for ElastiCache",SubnetIds:[t.ref("PrivateSubnet1"),t.ref("PrivateSubnet2")]},{dependsOn:["PrivateSubnet1","PrivateSubnet2"]});if(!e.hasResource("CacheSecurityGroup"))e.addResource("CacheSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for ElastiCache Memcached",VpcId:t.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:n.port||11211,ToPort:n.port||11211,SourceSecurityGroupId:t.ref("AppSecurityGroup")}],Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-cache-sg")}]},{dependsOn:["VPC","AppSecurityGroup"]});e.addResource("MemcachedCacheCluster","AWS::ElastiCache::CacheCluster",{ClusterName:t.sub("${AWS::StackName}-memcached"),Engine:"memcached",EngineVersion:n.engineVersion,CacheNodeType:n.nodeType,NumCacheNodes:n.numCacheNodes,Port:n.port||11211,CacheSubnetGroupName:t.ref("CacheSubnetGroup"),VpcSecurityGroupIds:[t.ref("CacheSecurityGroup")],PreferredMaintenanceWindow:"sun:05:00-sun:06:00",Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-memcached")}]},{dependsOn:["CacheSubnetGroup","CacheSecurityGroup"]}),e.addOutputs({MemcachedEndpoint:{Description:"Memcached configuration endpoint",Value:t.getAtt("MemcachedCacheCluster","ConfigurationEndpoint.Address"),Export:{Name:t.sub("${AWS::StackName}-memcached-endpoint")}},MemcachedPort:{Description:"Memcached port",Value:t.getAtt("MemcachedCacheCluster","ConfigurationEndpoint.Port"),Export:{Name:t.sub("${AWS::StackName}-memcached-port")}}})}function ei(e,n){if(!n)return;let r=n.engine==="redis";if(!e.hasResource("CacheSubnetGroup"))e.addResource("CacheSubnetGroup","AWS::ElastiCache::SubnetGroup",{Description:"Subnet group for ElastiCache",SubnetIds:[t.ref("PrivateSubnet1"),t.ref("PrivateSubnet2")]},{dependsOn:["PrivateSubnet1","PrivateSubnet2"]});if(!e.hasResource("CacheSecurityGroup"))e.addResource("CacheSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for ElastiCache",VpcId:t.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:r?6379:11211,ToPort:r?6379:11211,SourceSecurityGroupId:t.ref("AppSecurityGroup")}],Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-cache-sg")}]},{dependsOn:["VPC","AppSecurityGroup"]});e.addResource("CacheCluster","AWS::ElastiCache::CacheCluster",{ClusterName:t.sub(`\${AWS::StackName}-${n.engine}`),Engine:n.engine,EngineVersion:n.engineVersion,CacheNodeType:n.nodeType,NumCacheNodes:n.numCacheNodes,CacheSubnetGroupName:t.ref("CacheSubnetGroup"),VpcSecurityGroupIds:[t.ref("CacheSecurityGroup")],Tags:[{Key:"Name",Value:t.sub(`\${AWS::StackName}-${n.engine}`)}]},{dependsOn:["CacheSubnetGroup","CacheSecurityGroup"]})}function pn(e,n){if(!n.enabled)return;e.addResource("CloudFrontOriginAccessIdentity","AWS::CloudFront::CloudFrontOriginAccessIdentity",{CloudFrontOriginAccessIdentityConfig:{Comment:t.sub("${AWS::StackName} CloudFront OAI")}});let r=[],i=[];if(!n.origins||n.origins.length===0)r.push({Id:"S3Origin",DomainName:t.getAtt("StaticBucket","DomainName"),S3OriginConfig:{OriginAccessIdentity:t.sub("origin-access-identity/cloudfront/${CloudFrontOriginAccessIdentity}")}});else n.origins.forEach((c,u)=>{let d={Id:c.id,DomainName:c.domainName};if(c.originPath)d.OriginPath=c.originPath;if(c.domainName.includes("s3"))d.S3OriginConfig={OriginAccessIdentity:t.sub("origin-access-identity/cloudfront/${CloudFrontOriginAccessIdentity}")};else d.CustomOriginConfig={HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only",OriginSSLProtocols:["TLSv1.2"]};if(r.push(d),u>0||c.pathPattern)i.push({PathPattern:c.pathPattern||`/${c.id}/*`,TargetOriginId:c.id,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD"],Compress:n.compress!==!1,ForwardedValues:{QueryString:!0,Cookies:{Forward:"none"}},MinTTL:n.cachePolicy?.minTTL||0,DefaultTTL:n.cachePolicy?.defaultTTL||86400,MaxTTL:n.cachePolicy?.maxTTL||31536000})});let s={TargetOriginId:r[0].Id,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD"],Compress:n.compress!==!1,ForwardedValues:{QueryString:!0,Cookies:{Forward:"none"}},MinTTL:n.cachePolicy?.minTTL||0,DefaultTTL:n.cachePolicy?.defaultTTL||86400,MaxTTL:n.cachePolicy?.maxTTL||31536000};if(n.edgeFunctions&&n.edgeFunctions.length>0)s.LambdaFunctionAssociations=n.edgeFunctions.map((c)=>({EventType:c.eventType,LambdaFunctionARN:c.functionArn}));let a={Enabled:!0,HttpVersion:n.http3?"http3":"http2",IPV6Enabled:!0,Origins:r,DefaultCacheBehavior:s,PriceClass:n.priceClass||"PriceClass_100",ViewerCertificate:{}};if(i.length>0)a.CacheBehaviors=i;if(n.customDomain)a.Aliases=[n.customDomain.domain],a.ViewerCertificate={AcmCertificateArn:n.customDomain.certificateArn,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};else a.ViewerCertificate={CloudFrontDefaultCertificate:!0};if(n.errorPages)a.CustomErrorResponses=Object.entries(n.errorPages).map(([c,u])=>({ErrorCode:Number.parseInt(c),ResponseCode:200,ResponsePagePath:u,ErrorCachingMinTTL:300}));if(a.DefaultRootObject="index.html",a.Comment=t.sub("${AWS::StackName} CloudFront Distribution"),e.addResource("CloudFrontDistribution","AWS::CloudFront::Distribution",{DistributionConfig:a},{dependsOn:"CloudFrontOriginAccessIdentity"}),!n.origins||n.origins.length===0)e.addResource("StaticBucketPolicyForCloudFront","AWS::S3::BucketPolicy",{Bucket:t.ref("StaticBucket"),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontAccess",Effect:"Allow",Principal:{CanonicalUser:t.getAtt("CloudFrontOriginAccessIdentity","S3CanonicalUserId")},Action:"s3:GetObject",Resource:t.join("",[t.getAtt("StaticBucket","Arn"),"/*"])}]}},{dependsOn:["StaticBucket","CloudFrontOriginAccessIdentity"]});if(n.customDomain)e.addResource("CloudFrontDNSRecord","AWS::Route53::RecordSet",{HostedZoneName:t.sub(`${ti(n.customDomain.domain)}.`),Name:n.customDomain.domain,Type:"A",AliasTarget:{HostedZoneId:"Z2FDTNDATAQYW2",DNSName:t.getAtt("CloudFrontDistribution","DomainName"),EvaluateTargetHealth:!1}},{dependsOn:"CloudFrontDistribution"});if(e.addOutputs({CloudFrontDistributionId:{Description:"CloudFront distribution ID",Value:t.ref("CloudFrontDistribution"),Export:{Name:t.sub("${AWS::StackName}-cloudfront-id")}},CloudFrontDomainName:{Description:"CloudFront distribution domain name",Value:t.getAtt("CloudFrontDistribution","DomainName"),Export:{Name:t.sub("${AWS::StackName}-cloudfront-domain")}}}),n.customDomain)e.addOutputs({CloudFrontURL:{Description:"CloudFront custom domain URL",Value:t.sub(`https://${n.customDomain.domain}`)}})}function ti(e){let n=e.split(".");if(n.length>=2)return n.slice(-2).join(".");return e}function yn(e,n){if(n.server)ni(e,n.server);if(n.fargate)gn(e,"app",n.fargate);if(n.services)n.services.forEach((r)=>{if(r.type==="fargate")gn(e,r.name,{taskDefinition:r.taskDefinition,service:r.service})})}function ni(e,n){if(!n)return;e.addResource("AppSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for application instances",VpcId:t.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:3000,ToPort:3000,SourceSecurityGroupId:t.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:t.sub("${AWS::StackName}-app-sg")}]},{dependsOn:"VPC"}),e.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:t.sub("${AWS::StackName}-ec2-role")}]}),e.addResource("EC2InstanceProfile","AWS::IAM::InstanceProfile",{Roles:[t.ref("EC2InstanceRole")]},{dependsOn:"EC2InstanceRole"});let r=n.userData||`#!/bin/bash
|
|
2433
|
+
};`}var t={ref:(e)=>({Ref:e}),getAtt:(e,n)=>({"Fn::GetAtt":[e,n]}),join:(e,n)=>({"Fn::Join":[e,n]}),sub:(e,n)=>n?{"Fn::Sub":[e,n]}:{"Fn::Sub":e},select:(e,n)=>({"Fn::Select":[e,n]}),split:(e,n)=>({"Fn::Split":[e,n]}),getAZs:(e="")=>({"Fn::GetAZs":e}),importValue:(e)=>({"Fn::ImportValue":e}),findInMap:(e,n,r)=>({"Fn::FindInMap":[e,n,r]}),base64:(e)=>({"Fn::Base64":e}),cidr:(e,n,r)=>({"Fn::Cidr":[e,n,r]}),equals:(e,n)=>({"Fn::Equals":[e,n]}),if:(e,n,r)=>({"Fn::If":[e,n,r]}),not:(e)=>({"Fn::Not":[e]}),and:(...e)=>({"Fn::And":e}),or:(...e)=>({"Fn::Or":e})},In={s3Bucket:(e)=>t.sub(`arn:aws:s3:::${e}`),s3Object:(e,n="*")=>t.sub(`arn:aws:s3:::${e}/${n}`),lambda:(e,n,r)=>t.sub(`arn:aws:lambda:\${AWS::Region}:\${AWS::AccountId}:function:${e}`,n&&r?{"AWS::Region":n,"AWS::AccountId":r}:void 0),dynamodb:(e)=>t.sub(`arn:aws:dynamodb:\${AWS::Region}:\${AWS::AccountId}:table/${e}`),sqs:(e)=>t.sub(`arn:aws:sqs:\${AWS::Region}:\${AWS::AccountId}:${e}`),sns:(e)=>t.sub(`arn:aws:sns:\${AWS::Region}:\${AWS::AccountId}:${e}`),kinesis:(e)=>t.sub(`arn:aws:kinesis:\${AWS::Region}:\${AWS::AccountId}:stream/${e}`),iam:(e,n)=>t.sub(`arn:aws:iam::\${AWS::AccountId}:${e}/${n}`),secretsManager:(e)=>t.sub(`arn:aws:secretsmanager:\${AWS::Region}:\${AWS::AccountId}:secret:${e}`),cloudwatch:(e)=>t.sub(`arn:aws:logs:\${AWS::Region}:\${AWS::AccountId}:log-group:${e}`)},xm={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 un(e,n){if(n.type==="http")Kr(e,n);else if(n.type==="rest")qr(e,n);else if(n.type==="websocket")Qr(e,n)}function Kr(e,n){let r={Name:t.sub("${AWS::StackName}-http-api"),ProtocolType:"HTTP"};if(n.cors)r.CorsConfiguration={AllowOrigins:n.cors.allowOrigins,AllowMethods:n.cors.allowMethods,AllowHeaders:n.cors.allowHeaders||["*"],MaxAge:n.cors.maxAge||300};if(e.addResource("HttpApi","AWS::ApiGatewayV2::Api",r),e.addResource("HttpApiStage","AWS::ApiGatewayV2::Stage",{ApiId:t.ref("HttpApi"),StageName:"$default",AutoDeploy:!0,DefaultRouteSettings:n.throttling?{ThrottlingBurstLimit:n.throttling.burstLimit,ThrottlingRateLimit:n.throttling.rateLimit}:void 0,AccessLogSettings:{DestinationArn:t.getAtt("ApiLogGroup","Arn"),Format:"$context.requestId $context.error.message $context.error.messageString"}},{dependsOn:["HttpApi","ApiLogGroup"]}),e.addResource("ApiLogGroup","AWS::Logs::LogGroup",{LogGroupName:t.sub("/aws/apigateway/${AWS::StackName}-http-api"),RetentionInDays:14}),n.authorizer)Jr(e,"HttpApi",n.authorizer);if(n.customDomain)St(e,"HttpApi",n.customDomain,"HTTP");e.addOutputs({HttpApiId:{Description:"HTTP API ID",Value:t.ref("HttpApi"),Export:{Name:t.sub("${AWS::StackName}-http-api-id")}},HttpApiEndpoint:{Description:"HTTP API endpoint",Value:t.getAtt("HttpApi","ApiEndpoint"),Export:{Name:t.sub("${AWS::StackName}-http-api-endpoint")}}})}function qr(e,n){e.addResource("RestApi","AWS::ApiGateway::RestApi",{Name:t.sub("${AWS::StackName}-rest-api"),Description:t.sub("REST API for ${AWS::StackName}"),EndpointConfiguration:{Types:["REGIONAL"]}}),e.addResource("ApiGatewayAccount","AWS::ApiGateway::Account",{CloudWatchRoleArn:t.getAtt("ApiGatewayCloudWatchRole","Arn")},{dependsOn:"ApiGatewayCloudWatchRole"}),e.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"]}),e.addResource("RestApiDeployment","AWS::ApiGateway::Deployment",{RestApiId:t.ref("RestApi"),Description:"Initial deployment"},{dependsOn:"RestApi"});let r={RestApiId:t.ref("RestApi"),DeploymentId:t.ref("RestApiDeployment"),StageName:"prod",Description:"Production stage",MethodSettings:[{ResourcePath:"/*",HttpMethod:"*",LoggingLevel:"INFO",DataTraceEnabled:!0,MetricsEnabled:!0}]};if(n.throttling)r.MethodSettings[0].ThrottlingBurstLimit=n.throttling.burstLimit,r.MethodSettings[0].ThrottlingRateLimit=n.throttling.rateLimit;if(e.addResource("RestApiStage","AWS::ApiGateway::Stage",r,{dependsOn:["RestApi","RestApiDeployment"]}),n.customDomain)St(e,"RestApi",n.customDomain,"REST");e.addOutputs({RestApiId:{Description:"REST API ID",Value:t.ref("RestApi"),Export:{Name:t.sub("${AWS::StackName}-rest-api-id")}},RestApiEndpoint:{Description:"REST API endpoint",Value:t.sub("https://${RestApi}.execute-api.${AWS::Region}.amazonaws.com/prod"),Export:{Name:t.sub("${AWS::StackName}-rest-api-endpoint")}}})}function Qr(e,n){if(e.addResource("WebSocketApi","AWS::ApiGatewayV2::Api",{Name:t.sub("${AWS::StackName}-websocket-api"),ProtocolType:"WEBSOCKET",RouteSelectionExpression:"$request.body.action"}),n.routes){if(n.routes.connect)tt(e,"$connect",n.routes.connect.functionName);if(n.routes.disconnect)tt(e,"$disconnect",n.routes.disconnect.functionName);if(n.routes.default)tt(e,"$default",n.routes.default.functionName);if(n.routes.custom)n.routes.custom.forEach((r)=>{tt(e,r.routeKey,r.functionName)})}if(e.addResource("WebSocketApiStage","AWS::ApiGatewayV2::Stage",{ApiId:t.ref("WebSocketApi"),StageName:"prod",AutoDeploy:!0,DefaultRouteSettings:n.throttling?{ThrottlingBurstLimit:n.throttling.burstLimit,ThrottlingRateLimit:n.throttling.rateLimit}:void 0},{dependsOn:"WebSocketApi"}),n.customDomain)St(e,"WebSocketApi",n.customDomain,"WEBSOCKET");e.addOutputs({WebSocketApiId:{Description:"WebSocket API ID",Value:t.ref("WebSocketApi"),Export:{Name:t.sub("${AWS::StackName}-websocket-api-id")}},WebSocketApiEndpoint:{Description:"WebSocket API endpoint",Value:t.getAtt("WebSocketApi","ApiEndpoint"),Export:{Name:t.sub("${AWS::StackName}-websocket-api-endpoint")}}})}function tt(e,n,r){let i=e.toLogicalId(`websocket-route-${n}`),s=e.toLogicalId(`websocket-integration-${n}`),a=e.toLogicalId(`${r}-function`);e.addResource(s,"AWS::ApiGatewayV2::Integration",{ApiId:t.ref("WebSocketApi"),IntegrationType:"AWS_PROXY",IntegrationUri:t.sub(`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${a}.Arn}/invocations`)},{dependsOn:["WebSocketApi",a]}),e.addResource(i,"AWS::ApiGatewayV2::Route",{ApiId:t.ref("WebSocketApi"),RouteKey:n,Target:t.join("/",["integrations",t.ref(s)])},{dependsOn:["WebSocketApi",s]}),e.addResource(`${i}Permission`,"AWS::Lambda::Permission",{FunctionName:t.ref(a),Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:t.sub("arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${WebSocketApi}/*")},{dependsOn:[a,"WebSocketApi"]})}function St(e,n,r,i){let s={DomainName:r.domain};if(i==="REST")s.CertificateArn=r.certificateArn,s.EndpointConfiguration={Types:["REGIONAL"]},e.addResource("ApiCustomDomain","AWS::ApiGateway::DomainName",s),e.addResource("ApiBasePathMapping","AWS::ApiGateway::BasePathMapping",{DomainName:t.ref("ApiCustomDomain"),RestApiId:t.ref(n),Stage:t.ref("RestApiStage")},{dependsOn:["ApiCustomDomain",n,"RestApiStage"]});else s.DomainNameConfigurations=[{CertificateArn:r.certificateArn,EndpointType:"REGIONAL"}],e.addResource("ApiCustomDomain","AWS::ApiGatewayV2::DomainName",s),e.addResource("ApiMapping","AWS::ApiGatewayV2::ApiMapping",{ApiId:t.ref(n),DomainName:t.ref("ApiCustomDomain"),Stage:i==="HTTP"?t.ref("HttpApiStage"):t.ref("WebSocketApiStage")},{dependsOn:["ApiCustomDomain",n]});if(r.dnsProvider!=="external")e.addResource("ApiDNSRecord","AWS::Route53::RecordSet",{HostedZoneName:t.sub(`${Yr(r.domain)}.`),Name:r.domain,Type:"A",AliasTarget:{HostedZoneId:t.getAtt("ApiCustomDomain","RegionalHostedZoneId"),DNSName:t.getAtt("ApiCustomDomain","RegionalDomainName"),EvaluateTargetHealth:!1}},{dependsOn:"ApiCustomDomain"});e.addOutputs({ApiCustomDomainName:{Description:"Configured API custom domain",Value:r.domain},ApiCustomDomainTarget:{Description:"DNS target for Route53 or an external DNS provider",Value:t.getAtt("ApiCustomDomain","RegionalDomainName")},ApiCustomDomainHostedZoneId:{Description:"Regional API Gateway hosted zone ID",Value:t.getAtt("ApiCustomDomain","RegionalHostedZoneId")}})}function Jr(e,n,r){if(!r)return;if(r.type==="jwt")e.addResource("ApiAuthorizer","AWS::ApiGatewayV2::Authorizer",{ApiId:t.ref(n),AuthorizerType:"JWT",IdentitySource:[r.identitySource||"$request.header.Authorization"],JwtConfiguration:{Issuer:r.issuer,Audience:r.audience},Name:"JWTAuthorizer"},{dependsOn:n});else if(r.type==="lambda")e.addResource("ApiAuthorizer","AWS::ApiGatewayV2::Authorizer",{ApiId:t.ref(n),AuthorizerType:"REQUEST",AuthorizerUri:r.authorizerUri,IdentitySource:[r.identitySource||"$request.header.Authorization"],Name:"LambdaAuthorizer"},{dependsOn:n})}function Yr(e){let n=e.split(".");if(n.length>=2)return n.slice(-2).join(".");return e}function dn(e,n){if(n.redis)Zr(e,n.redis);if(n.memcached)Xr(e,n.memcached);if(n.elasticache)ei(e,n.elasticache)}function Zr(e,n){if(!n)return;if(e.addResource("CacheSubnetGroup","AWS::ElastiCache::SubnetGroup",{Description:"Subnet group for ElastiCache Redis cluster",SubnetIds:[t.ref("PrivateSubnet1"),t.ref("PrivateSubnet2")],Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-cache-subnet-group")}]},{dependsOn:["PrivateSubnet1","PrivateSubnet2"]}),e.addResource("CacheSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for ElastiCache Redis",VpcId:t.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:n.port||6379,ToPort:n.port||6379,SourceSecurityGroupId:t.ref("AppSecurityGroup")}],Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-cache-sg")}]},{dependsOn:["VPC","AppSecurityGroup"]}),n.parameterGroup&&Object.keys(n.parameterGroup).length>0)e.addResource("CacheParameterGroup","AWS::ElastiCache::ParameterGroup",{Description:"Parameter group for Redis",CacheParameterGroupFamily:`redis${n.engineVersion.split(".")[0]}`,Properties:n.parameterGroup});if(n.numCacheNodes>1||n.automaticFailoverEnabled)e.addResource("RedisReplicationGroup","AWS::ElastiCache::ReplicationGroup",{ReplicationGroupDescription:"Redis replication group",ReplicationGroupId:t.sub("${AWS::StackName}-redis"),Engine:"redis",EngineVersion:n.engineVersion,CacheNodeType:n.nodeType,NumCacheClusters:n.numCacheNodes,AutomaticFailoverEnabled:n.automaticFailoverEnabled||!1,MultiAZEnabled:n.automaticFailoverEnabled||!1,Port:n.port||6379,CacheSubnetGroupName:t.ref("CacheSubnetGroup"),SecurityGroupIds:[t.ref("CacheSecurityGroup")],CacheParameterGroupName:n.parameterGroup?t.ref("CacheParameterGroup"):void 0,SnapshotRetentionLimit:n.snapshotRetentionLimit||5,SnapshotWindow:n.snapshotWindow||"03:00-05:00",PreferredMaintenanceWindow:"sun:05:00-sun:06:00",AtRestEncryptionEnabled:!0,TransitEncryptionEnabled:!0,Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-redis")}]},{dependsOn:n.parameterGroup?["CacheSubnetGroup","CacheSecurityGroup","CacheParameterGroup"]:["CacheSubnetGroup","CacheSecurityGroup"],deletionPolicy:"Snapshot",updateReplacePolicy:"Snapshot"}),e.addOutputs({RedisEndpoint:{Description:"Redis primary endpoint",Value:t.getAtt("RedisReplicationGroup","PrimaryEndPoint.Address"),Export:{Name:t.sub("${AWS::StackName}-redis-endpoint")}},RedisPort:{Description:"Redis port",Value:t.getAtt("RedisReplicationGroup","PrimaryEndPoint.Port"),Export:{Name:t.sub("${AWS::StackName}-redis-port")}}});else e.addResource("RedisCacheCluster","AWS::ElastiCache::CacheCluster",{ClusterName:t.sub("${AWS::StackName}-redis"),Engine:"redis",EngineVersion:n.engineVersion,CacheNodeType:n.nodeType,NumCacheNodes:1,Port:n.port||6379,CacheSubnetGroupName:t.ref("CacheSubnetGroup"),VpcSecurityGroupIds:[t.ref("CacheSecurityGroup")],CacheParameterGroupName:n.parameterGroup?t.ref("CacheParameterGroup"):void 0,SnapshotRetentionLimit:n.snapshotRetentionLimit||5,SnapshotWindow:n.snapshotWindow||"03:00-05:00",PreferredMaintenanceWindow:"sun:05:00-sun:06:00",Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-redis")}]},{dependsOn:n.parameterGroup?["CacheSubnetGroup","CacheSecurityGroup","CacheParameterGroup"]:["CacheSubnetGroup","CacheSecurityGroup"],deletionPolicy:"Snapshot",updateReplacePolicy:"Snapshot"}),e.addOutputs({RedisEndpoint:{Description:"Redis endpoint",Value:t.getAtt("RedisCacheCluster","RedisEndpoint.Address"),Export:{Name:t.sub("${AWS::StackName}-redis-endpoint")}},RedisPort:{Description:"Redis port",Value:t.getAtt("RedisCacheCluster","RedisEndpoint.Port"),Export:{Name:t.sub("${AWS::StackName}-redis-port")}}})}function Xr(e,n){if(!n)return;if(!e.hasResource("CacheSubnetGroup"))e.addResource("CacheSubnetGroup","AWS::ElastiCache::SubnetGroup",{Description:"Subnet group for ElastiCache",SubnetIds:[t.ref("PrivateSubnet1"),t.ref("PrivateSubnet2")]},{dependsOn:["PrivateSubnet1","PrivateSubnet2"]});if(!e.hasResource("CacheSecurityGroup"))e.addResource("CacheSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for ElastiCache Memcached",VpcId:t.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:n.port||11211,ToPort:n.port||11211,SourceSecurityGroupId:t.ref("AppSecurityGroup")}],Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-cache-sg")}]},{dependsOn:["VPC","AppSecurityGroup"]});e.addResource("MemcachedCacheCluster","AWS::ElastiCache::CacheCluster",{ClusterName:t.sub("${AWS::StackName}-memcached"),Engine:"memcached",EngineVersion:n.engineVersion,CacheNodeType:n.nodeType,NumCacheNodes:n.numCacheNodes,Port:n.port||11211,CacheSubnetGroupName:t.ref("CacheSubnetGroup"),VpcSecurityGroupIds:[t.ref("CacheSecurityGroup")],PreferredMaintenanceWindow:"sun:05:00-sun:06:00",Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-memcached")}]},{dependsOn:["CacheSubnetGroup","CacheSecurityGroup"]}),e.addOutputs({MemcachedEndpoint:{Description:"Memcached configuration endpoint",Value:t.getAtt("MemcachedCacheCluster","ConfigurationEndpoint.Address"),Export:{Name:t.sub("${AWS::StackName}-memcached-endpoint")}},MemcachedPort:{Description:"Memcached port",Value:t.getAtt("MemcachedCacheCluster","ConfigurationEndpoint.Port"),Export:{Name:t.sub("${AWS::StackName}-memcached-port")}}})}function ei(e,n){if(!n)return;let r=n.engine==="redis";if(!e.hasResource("CacheSubnetGroup"))e.addResource("CacheSubnetGroup","AWS::ElastiCache::SubnetGroup",{Description:"Subnet group for ElastiCache",SubnetIds:[t.ref("PrivateSubnet1"),t.ref("PrivateSubnet2")]},{dependsOn:["PrivateSubnet1","PrivateSubnet2"]});if(!e.hasResource("CacheSecurityGroup"))e.addResource("CacheSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for ElastiCache",VpcId:t.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:r?6379:11211,ToPort:r?6379:11211,SourceSecurityGroupId:t.ref("AppSecurityGroup")}],Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-cache-sg")}]},{dependsOn:["VPC","AppSecurityGroup"]});e.addResource("CacheCluster","AWS::ElastiCache::CacheCluster",{ClusterName:t.sub(`\${AWS::StackName}-${n.engine}`),Engine:n.engine,EngineVersion:n.engineVersion,CacheNodeType:n.nodeType,NumCacheNodes:n.numCacheNodes,CacheSubnetGroupName:t.ref("CacheSubnetGroup"),VpcSecurityGroupIds:[t.ref("CacheSecurityGroup")],Tags:[{Key:"Name",Value:t.sub(`\${AWS::StackName}-${n.engine}`)}]},{dependsOn:["CacheSubnetGroup","CacheSecurityGroup"]})}function mn(e,n){if(!n.enabled)return;e.addResource("CloudFrontOriginAccessIdentity","AWS::CloudFront::CloudFrontOriginAccessIdentity",{CloudFrontOriginAccessIdentityConfig:{Comment:t.sub("${AWS::StackName} CloudFront OAI")}});let r=[],i=[];if(!n.origins||n.origins.length===0)r.push({Id:"S3Origin",DomainName:t.getAtt("StaticBucket","DomainName"),S3OriginConfig:{OriginAccessIdentity:t.sub("origin-access-identity/cloudfront/${CloudFrontOriginAccessIdentity}")}});else n.origins.forEach((c,u)=>{let d={Id:c.id,DomainName:c.domainName};if(c.originPath)d.OriginPath=c.originPath;if(c.domainName.includes("s3"))d.S3OriginConfig={OriginAccessIdentity:t.sub("origin-access-identity/cloudfront/${CloudFrontOriginAccessIdentity}")};else d.CustomOriginConfig={HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only",OriginSSLProtocols:["TLSv1.2"]};if(r.push(d),u>0||c.pathPattern)i.push({PathPattern:c.pathPattern||`/${c.id}/*`,TargetOriginId:c.id,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD"],Compress:n.compress!==!1,ForwardedValues:{QueryString:!0,Cookies:{Forward:"none"}},MinTTL:n.cachePolicy?.minTTL||0,DefaultTTL:n.cachePolicy?.defaultTTL||86400,MaxTTL:n.cachePolicy?.maxTTL||31536000})});let s={TargetOriginId:r[0].Id,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD"],Compress:n.compress!==!1,ForwardedValues:{QueryString:!0,Cookies:{Forward:"none"}},MinTTL:n.cachePolicy?.minTTL||0,DefaultTTL:n.cachePolicy?.defaultTTL||86400,MaxTTL:n.cachePolicy?.maxTTL||31536000};if(n.edgeFunctions&&n.edgeFunctions.length>0)s.LambdaFunctionAssociations=n.edgeFunctions.map((c)=>({EventType:c.eventType,LambdaFunctionARN:c.functionArn}));let a={Enabled:!0,HttpVersion:n.http3?"http3":"http2",IPV6Enabled:!0,Origins:r,DefaultCacheBehavior:s,PriceClass:n.priceClass||"PriceClass_100",ViewerCertificate:{}};if(i.length>0)a.CacheBehaviors=i;if(n.customDomain)a.Aliases=[n.customDomain.domain],a.ViewerCertificate={AcmCertificateArn:n.customDomain.certificateArn,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};else a.ViewerCertificate={CloudFrontDefaultCertificate:!0};if(n.errorPages)a.CustomErrorResponses=Object.entries(n.errorPages).map(([c,u])=>({ErrorCode:Number.parseInt(c),ResponseCode:200,ResponsePagePath:u,ErrorCachingMinTTL:300}));if(a.DefaultRootObject="index.html",a.Comment=t.sub("${AWS::StackName} CloudFront Distribution"),e.addResource("CloudFrontDistribution","AWS::CloudFront::Distribution",{DistributionConfig:a},{dependsOn:"CloudFrontOriginAccessIdentity"}),!n.origins||n.origins.length===0)e.addResource("StaticBucketPolicyForCloudFront","AWS::S3::BucketPolicy",{Bucket:t.ref("StaticBucket"),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontAccess",Effect:"Allow",Principal:{CanonicalUser:t.getAtt("CloudFrontOriginAccessIdentity","S3CanonicalUserId")},Action:"s3:GetObject",Resource:t.join("",[t.getAtt("StaticBucket","Arn"),"/*"])}]}},{dependsOn:["StaticBucket","CloudFrontOriginAccessIdentity"]});if(n.customDomain)e.addResource("CloudFrontDNSRecord","AWS::Route53::RecordSet",{HostedZoneName:t.sub(`${ti(n.customDomain.domain)}.`),Name:n.customDomain.domain,Type:"A",AliasTarget:{HostedZoneId:"Z2FDTNDATAQYW2",DNSName:t.getAtt("CloudFrontDistribution","DomainName"),EvaluateTargetHealth:!1}},{dependsOn:"CloudFrontDistribution"});if(e.addOutputs({CloudFrontDistributionId:{Description:"CloudFront distribution ID",Value:t.ref("CloudFrontDistribution"),Export:{Name:t.sub("${AWS::StackName}-cloudfront-id")}},CloudFrontDomainName:{Description:"CloudFront distribution domain name",Value:t.getAtt("CloudFrontDistribution","DomainName"),Export:{Name:t.sub("${AWS::StackName}-cloudfront-domain")}}}),n.customDomain)e.addOutputs({CloudFrontURL:{Description:"CloudFront custom domain URL",Value:t.sub(`https://${n.customDomain.domain}`)}})}function ti(e){let n=e.split(".");if(n.length>=2)return n.slice(-2).join(".");return e}function gn(e,n){if(n.server)ni(e,n.server);if(n.fargate)pn(e,"app",n.fargate);if(n.services)n.services.forEach((r)=>{if(r.type==="fargate")pn(e,r.name,{taskDefinition:r.taskDefinition,service:r.service})})}function ni(e,n){if(!n)return;e.addResource("AppSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for application instances",VpcId:t.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:3000,ToPort:3000,SourceSecurityGroupId:t.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:t.sub("${AWS::StackName}-app-sg")}]},{dependsOn:"VPC"}),e.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:t.sub("${AWS::StackName}-ec2-role")}]}),e.addResource("EC2InstanceProfile","AWS::IAM::InstanceProfile",{Roles:[t.ref("EC2InstanceRole")]},{dependsOn:"EC2InstanceRole"});let r=n.userData||`#!/bin/bash
|
|
2434
2434
|
set -e
|
|
2435
2435
|
# Update system
|
|
2436
2436
|
yum update -y || apt-get update -y
|
|
@@ -2445,20 +2445,20 @@ rpm -U ./amazon-cloudwatch-agent.rpm || true
|
|
|
2445
2445
|
|
|
2446
2446
|
# Signal completion
|
|
2447
2447
|
/opt/aws/bin/cfn-signal -e $? --stack \${AWS::StackName} --resource AutoScalingGroup --region \${AWS::Region}
|
|
2448
|
-
`;if(e.addResource("LaunchTemplate","AWS::EC2::LaunchTemplate",{LaunchTemplateName:t.sub("${AWS::StackName}-template"),LaunchTemplateData:{ImageId:n.ami||t.findInMap("RegionMap",t.ref("AWS::Region"),"AMI"),InstanceType:n.instanceType,IamInstanceProfile:{Arn:t.getAtt("EC2InstanceProfile","Arn")},SecurityGroupIds:[t.ref("AppSecurityGroup")],UserData:t.base64(t.sub(r)),TagSpecifications:[{ResourceType:"instance",Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-instance")}]}],MetadataOptions:{HttpTokens:"required",HttpPutResponseHopLimit:1}}},{dependsOn:["AppSecurityGroup","EC2InstanceProfile"]}),n.loadBalancer){ri(e,n.loadBalancer);let i={LaunchTemplate:{LaunchTemplateId:t.ref("LaunchTemplate"),Version:t.getAtt("LaunchTemplate","LatestVersionNumber")},MinSize:n.autoScaling?.min.toString()||"1",MaxSize:n.autoScaling?.max.toString()||"3",DesiredCapacity:n.autoScaling?.min.toString()||"2",VPCZoneIdentifier:[t.ref("PrivateSubnet1"),t.ref("PrivateSubnet2")],TargetGroupARNs:[t.ref("TargetGroup")],HealthCheckType:"ELB",HealthCheckGracePeriod:300,Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-asg"),PropagateAtLaunch:!0}]};if(e.addResource("AutoScalingGroup","AWS::AutoScaling::AutoScalingGroup",i,{dependsOn:["LaunchTemplate","TargetGroup"]}),n.autoScaling)e.addResource("ScaleUpPolicy","AWS::AutoScaling::ScalingPolicy",{AdjustmentType:"ChangeInCapacity",AutoScalingGroupName:t.ref("AutoScalingGroup"),Cooldown:n.autoScaling.scaleUpCooldown?.toString()||"300",ScalingAdjustment:"1"},{dependsOn:"AutoScalingGroup"}),e.addResource("ScaleDownPolicy","AWS::AutoScaling::ScalingPolicy",{AdjustmentType:"ChangeInCapacity",AutoScalingGroupName:t.ref("AutoScalingGroup"),Cooldown:n.autoScaling.scaleDownCooldown?.toString()||"300",ScalingAdjustment:"-1"},{dependsOn:"AutoScalingGroup"}),e.addResource("HighCPUAlarm","AWS::CloudWatch::Alarm",{AlarmDescription:"Scale up when CPU exceeds target",MetricName:"CPUUtilization",Namespace:"AWS/EC2",Statistic:"Average",Period:"300",EvaluationPeriods:"2",Threshold:(n.autoScaling.targetCPU||70).toString(),AlarmActions:[t.ref("ScaleUpPolicy")],Dimensions:[{Name:"AutoScalingGroupName",Value:t.ref("AutoScalingGroup")}],ComparisonOperator:"GreaterThanThreshold"},{dependsOn:["AutoScalingGroup","ScaleUpPolicy"]}),e.addResource("LowCPUAlarm","AWS::CloudWatch::Alarm",{AlarmDescription:"Scale down when CPU is below threshold",MetricName:"CPUUtilization",Namespace:"AWS/EC2",Statistic:"Average",Period:"300",EvaluationPeriods:"2",Threshold:((n.autoScaling.targetCPU||70)-20).toString(),AlarmActions:[t.ref("ScaleDownPolicy")],Dimensions:[{Name:"AutoScalingGroupName",Value:t.ref("AutoScalingGroup")}],ComparisonOperator:"LessThanThreshold"},{dependsOn:["AutoScalingGroup","ScaleDownPolicy"]})}}function ri(e,n){if(!n)return;e.addResource("ALBSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for Application Load Balancer",VpcId:t.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:80,ToPort:80,CidrIp:"0.0.0.0/0"},{IpProtocol:"tcp",FromPort:443,ToPort:443,CidrIp:"0.0.0.0/0"}],SecurityGroupEgress:[{IpProtocol:"-1",CidrIp:"0.0.0.0/0"}],Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-alb-sg")}]},{dependsOn:"VPC"}),e.addResource("LoadBalancer","AWS::ElasticLoadBalancingV2::LoadBalancer",{Name:t.sub("${AWS::StackName}-alb"),Type:n.type||"application",Scheme:"internet-facing",IpAddressType:"ipv4",Subnets:[t.ref("PublicSubnet1"),t.ref("PublicSubnet2")],SecurityGroups:[t.ref("ALBSecurityGroup")],Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-alb")}]},{dependsOn:["PublicSubnet1","PublicSubnet2","ALBSecurityGroup"]}),e.addResource("TargetGroup","AWS::ElasticLoadBalancingV2::TargetGroup",{Name:t.sub("${AWS::StackName}-tg"),Port:3000,Protocol:"HTTP",VpcId:t.ref("VPC"),HealthCheckEnabled:!0,HealthCheckPath:n.healthCheck?.path||"/health",HealthCheckProtocol:"HTTP",HealthCheckIntervalSeconds:n.healthCheck?.interval||30,HealthCheckTimeoutSeconds:n.healthCheck?.timeout||5,HealthyThresholdCount:n.healthCheck?.healthyThreshold||2,UnhealthyThresholdCount:n.healthCheck?.unhealthyThreshold||3,TargetType:"instance",Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-tg")}]},{dependsOn:"VPC"}),e.addResource("LoadBalancerListener","AWS::ElasticLoadBalancingV2::Listener",{LoadBalancerArn:t.ref("LoadBalancer"),Port:80,Protocol:"HTTP",DefaultActions:[{Type:"forward",TargetGroupArn:t.ref("TargetGroup")}]},{dependsOn:["LoadBalancer","TargetGroup"]}),e.addOutputs({LoadBalancerDNS:{Description:"Load Balancer DNS Name",Value:t.getAtt("LoadBalancer","DNSName"),Export:{Name:t.sub("${AWS::StackName}-alb-dns")}}})}function gn(e,n,r){let i=e.toLogicalId(n),s=r.taskDefinition.containerDefinitions?.[0],a=s?.name||s?.Name||n,c=s?.portMappings?.[0]?.containerPort||s?.PortMappings?.[0]?.ContainerPort||3000,u=(r.taskDefinition.containerDefinitions||[]).flatMap((y)=>(y.secrets||y.Secrets||[]).map((f)=>f.valueFrom||f.ValueFrom)).filter(Boolean);if(!e.hasResource("ECSCluster"))e.addResource("ECSCluster","AWS::ECS::Cluster",{ClusterName:t.sub("${AWS::StackName}-cluster"),Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-cluster")}]});if(e.addResource(`${i}TaskExecutionRole`,"AWS::IAM::Role",{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"],...u.length?{Policies:[{PolicyName:"read-task-secrets",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["secretsmanager:GetSecretValue","ssm:GetParameters"],Resource:u},{Effect:"Allow",Action:"kms:Decrypt",Resource:"*"}]}}]}:{}}),e.addResource(`${i}TaskRole`,"AWS::IAM::Role",{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ecs-tasks.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"application-services",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["sqs:ReceiveMessage","sqs:DeleteMessage","sqs:GetQueueAttributes","sqs:SendMessage"],Resource:t.sub("arn:aws:sqs:${AWS::Region}:${AWS::AccountId}:${AWS::StackName}-*")},{Effect:"Allow",Action:["ses:SendEmail","ses:SendRawEmail"],Resource:"*"}]}}]}),!e.hasResource("ALBSecurityGroup"))e.addResource("ALBSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Public ingress for the application load balancer",VpcId:t.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:80,ToPort:80,CidrIp:"0.0.0.0/0"},...r.loadBalancer?.customDomain?.certificateArn?[{IpProtocol:"tcp",FromPort:443,ToPort:443,CidrIp:"0.0.0.0/0"}]:[]],SecurityGroupEgress:[{IpProtocol:"tcp",FromPort:c,ToPort:c,CidrIp:"0.0.0.0/0"}],Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-alb-sg")}]},{dependsOn:"VPC"});if(!e.hasResource("AppSecurityGroup"))e.addResource("AppSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Only the application load balancer may reach Fargate tasks",VpcId:t.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:c,ToPort:c,SourceSecurityGroupId:t.ref("ALBSecurityGroup")}],SecurityGroupEgress:[{IpProtocol:"-1",CidrIp:"0.0.0.0/0"}],Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-app-sg")}]},{dependsOn:["VPC","ALBSecurityGroup"]});let d=(r.taskDefinition.containerDefinitions||[{name:n,image:t.sub(`\${AWS::AccountId}.dkr.ecr.\${AWS::Region}.amazonaws.com/${n}:latest`),portMappings:[{containerPort:3000}]}]).map((y)=>({Name:y.Name||y.name,Image:y.Image||y.image,Essential:y.Essential??y.essential??!0,PortMappings:(y.PortMappings||y.portMappings||[]).map((f)=>({ContainerPort:f.ContainerPort??f.containerPort,Protocol:f.Protocol||f.protocol||"tcp"})),Environment:Array.isArray(y.Environment||y.environment)?(y.Environment||y.environment).map((f)=>({Name:f.Name||f.name,Value:f.Value??f.value})):Object.entries(y.Environment||y.environment||{}).map(([f,h])=>({Name:f,Value:h})),Secrets:(y.Secrets||y.secrets||[]).map((f)=>({Name:f.Name||f.name,ValueFrom:f.ValueFrom||f.valueFrom})),HealthCheck:y.HealthCheck||y.healthCheck,Command:y.Command||y.command,EntryPoint:y.EntryPoint||y.entryPoint,LogConfiguration:y.LogConfiguration||y.logConfiguration||{LogDriver:"awslogs",Options:{"awslogs-group":t.ref(`${i}LogGroup`),"awslogs-region":t.ref("AWS::Region"),"awslogs-stream-prefix":n}}}));e.addResource(`${i}TaskDefinition`,"AWS::ECS::TaskDefinition",{Family:t.sub(`\${AWS::StackName}-${n}`),NetworkMode:"awsvpc",RequiresCompatibilities:["FARGATE"],Cpu:r.taskDefinition.cpu,Memory:r.taskDefinition.memory,ExecutionRoleArn:t.getAtt(`${i}TaskExecutionRole`,"Arn"),TaskRoleArn:t.getAtt(`${i}TaskRole`,"Arn"),ContainerDefinitions:d},{dependsOn:[`${i}TaskExecutionRole`,`${i}TaskRole`,`${i}LogGroup`]}),e.addResource(`${i}LogGroup`,"AWS::Logs::LogGroup",{LogGroupName:t.sub(`/ecs/\${AWS::StackName}/${n}`),RetentionInDays:14});let m=r.service.healthCheck||{};e.addResource(`${i}TargetGroup`,"AWS::ElasticLoadBalancingV2::TargetGroup",{VpcId:t.ref("VPC"),Port:c,Protocol:"HTTP",TargetType:"ip",HealthCheckEnabled:!0,HealthCheckPath:m.path||"/health",HealthCheckProtocol:"HTTP",HealthCheckIntervalSeconds:m.interval||30,HealthCheckTimeoutSeconds:m.timeout||5,HealthyThresholdCount:m.healthyThreshold||2,UnhealthyThresholdCount:m.unhealthyThreshold||3,Matcher:{HttpCode:"200-399"},TargetGroupAttributes:[{Key:"deregistration_delay.timeout_seconds",Value:"30"}]},{dependsOn:"VPC"}),e.addResource(`${i}LoadBalancer`,"AWS::ElasticLoadBalancingV2::LoadBalancer",{Type:"application",Scheme:"internet-facing",IpAddressType:"ipv4",Subnets:[t.ref("PublicSubnet1"),t.ref("PublicSubnet2")],SecurityGroups:[t.ref("ALBSecurityGroup")],LoadBalancerAttributes:[{Key:"routing.http.drop_invalid_header_fields.enabled",Value:"true"},{Key:"deletion_protection.enabled",Value:String(r.loadBalancer?.deletionProtection===!0)}],Tags:[{Key:"Name",Value:t.sub(`\${AWS::StackName}-${n}-alb`)}]},{dependsOn:["PublicSubnet1","PublicSubnet2","ALBSecurityGroup"]});let p=r.loadBalancer?.customDomain?.certificateArn,g=r.loadBalancer?.originVerifyHeader;if(e.addResource(`${i}HttpListener`,"AWS::ElasticLoadBalancingV2::Listener",{LoadBalancerArn:t.ref(`${i}LoadBalancer`),Port:80,Protocol:"HTTP",DefaultActions:p?[{Type:"redirect",RedirectConfig:{Protocol:"HTTPS",Port:"443",StatusCode:"HTTP_301"}}]:g?[{Type:"fixed-response",FixedResponseConfig:{StatusCode:"403",ContentType:"text/plain",MessageBody:"Forbidden"}}]:[{Type:"forward",TargetGroupArn:t.ref(`${i}TargetGroup`)}]},{dependsOn:[`${i}LoadBalancer`,`${i}TargetGroup`]}),p)e.addResource(`${i}HttpsListener`,"AWS::ElasticLoadBalancingV2::Listener",{LoadBalancerArn:t.ref(`${i}LoadBalancer`),Port:443,Protocol:"HTTPS",Certificates:[{CertificateArn:p}],SslPolicy:"ELBSecurityPolicy-TLS13-1-2-2021-06",DefaultActions:g?[{Type:"fixed-response",FixedResponseConfig:{StatusCode:"403",ContentType:"text/plain",MessageBody:"Forbidden"}}]:[{Type:"forward",TargetGroupArn:t.ref(`${i}TargetGroup`)}]},{dependsOn:[`${i}LoadBalancer`,`${i}TargetGroup`]});if(g){let y=p?`${i}HttpsListener`:`${i}HttpListener`;e.addResource(`${i}OriginVerifyRule`,"AWS::ElasticLoadBalancingV2::ListenerRule",{ListenerArn:t.ref(y),Priority:1,Conditions:[{Field:"http-header",HttpHeaderConfig:{HttpHeaderName:g.name,Values:[g.value]}}],Actions:[{Type:"forward",TargetGroupArn:t.ref(`${i}TargetGroup`)}]},{dependsOn:[y,`${i}TargetGroup`]})}if(e.addResource(`${i}Service`,"AWS::ECS::Service",{ServiceName:t.sub(`\${AWS::StackName}-${n}`),Cluster:t.ref("ECSCluster"),TaskDefinition:t.ref(`${i}TaskDefinition`),DesiredCount:r.service.desiredCount,LaunchType:"FARGATE",PlatformVersion:"LATEST",HealthCheckGracePeriodSeconds:60,DeploymentConfiguration:{MinimumHealthyPercent:100,MaximumPercent:200,DeploymentCircuitBreaker:{Enable:!0,Rollback:!0}},LoadBalancers:[{ContainerName:a,ContainerPort:c,TargetGroupArn:t.ref(`${i}TargetGroup`)}],NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"DISABLED",Subnets:[t.ref("PrivateSubnet1"),t.ref("PrivateSubnet2")],SecurityGroups:[t.ref("AppSecurityGroup")]}}},{dependsOn:["ECSCluster",`${i}TaskDefinition`,g?`${i}OriginVerifyRule`:p?`${i}HttpsListener`:`${i}HttpListener`]}),r.service.autoScaling){let y=r.service.autoScaling;e.addResource(`${i}ScalableTarget`,"AWS::ApplicationAutoScaling::ScalableTarget",{MinCapacity:y.min,MaxCapacity:y.max,ResourceId:t.join("/",["service",t.ref("ECSCluster"),t.getAtt(`${i}Service`,"Name")]),RoleARN:t.sub("arn:aws:iam::${AWS::AccountId}:role/aws-service-role/ecs.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_ECSService"),ScalableDimension:"ecs:service:DesiredCount",ServiceNamespace:"ecs"},{dependsOn:`${i}Service`}),e.addResource(`${i}ScalingPolicy`,"AWS::ApplicationAutoScaling::ScalingPolicy",{PolicyType:"TargetTrackingScaling",ScalingTargetId:t.ref(`${i}ScalableTarget`),TargetTrackingScalingPolicyConfiguration:{TargetValue:y.targetCPU||70,PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageCPUUtilization"},ScaleInCooldown:60,ScaleOutCooldown:30}},{dependsOn:`${i}ScalableTarget`})}e.addOutputs({[`${i}ClusterName`]:{Description:"ECS cluster name",Value:t.ref("ECSCluster")},[`${i}ServiceName`]:{Description:"ECS service name",Value:t.getAtt(`${i}Service`,"Name")},[`${i}LoadBalancerDnsName`]:{Description:"ALB origin hostname",Value:t.getAtt(`${i}LoadBalancer`,"DNSName")},[`${i}LoadBalancerHostedZoneId`]:{Description:"ALB canonical hosted zone ID",Value:t.getAtt(`${i}LoadBalancer`,"CanonicalHostedZoneID")},[`${i}TargetGroupArn`]:{Description:"ECS target group ARN",Value:t.ref(`${i}TargetGroup`)}})}function hn(e,n){if(n.postgres)fn(e,"postgres",n.postgres);if(n.mysql)fn(e,"mysql",n.mysql);if(n.dynamodb?.tables)n.dynamodb.tables.forEach((r)=>{ii(e,r)})}function fn(e,n,r){if(!r)return;let i=n==="postgres"?"postgres":"mysql",s=e.toLogicalId(`${i}-db`);e.addResource("DBSubnetGroup","AWS::RDS::DBSubnetGroup",{DBSubnetGroupDescription:"Subnet group for RDS instance",SubnetIds:[t.ref("PrivateSubnet1"),t.ref("PrivateSubnet2")],Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-db-subnet-group")}]},{dependsOn:["PrivateSubnet1","PrivateSubnet2"]}),e.addResource("DBSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for RDS instance",VpcId:t.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:n==="postgres"?5432:3306,ToPort:n==="postgres"?5432:3306,SourceSecurityGroupId:t.ref("AppSecurityGroup")}],Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-db-sg")}]},{dependsOn:["VPC","AppSecurityGroup"]});let a=n==="postgres"?`postgres${r.version.split(".")[0]}`:`mysql${r.version.split(".")[0]}.${r.version.split(".")[1]||"0"}`;if(r.parameters&&Object.keys(r.parameters).length>0)e.addResource("DBParameterGroup","AWS::RDS::DBParameterGroup",{Description:`Parameter group for ${i}`,Family:a,Parameters:r.parameters,Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-db-params")}]});e.addResource("DBSecret","AWS::SecretsManager::Secret",{Description:"Database credentials",GenerateSecretString:{SecretStringTemplate:JSON.stringify({username:"admin"}),GenerateStringKey:"password",PasswordLength:32,ExcludeCharacters:'"@/\\'},Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-db-secret")}]},{deletionPolicy:"Retain",updateReplacePolicy:"Retain"});let c={Engine:i,EngineVersion:r.version,DBInstanceClass:r.instanceClass,AllocatedStorage:r.allocatedStorage.toString(),MaxAllocatedStorage:r.maxAllocatedStorage?.toString(),StorageType:"gp3",StorageEncrypted:!0,MultiAZ:r.multiAZ!==!1,DBSubnetGroupName:t.ref("DBSubnetGroup"),VPCSecurityGroups:[t.ref("DBSecurityGroup")],MasterUsername:t.sub("{{resolve:secretsmanager:${DBSecret}:SecretString:username}}"),MasterUserPassword:t.sub("{{resolve:secretsmanager:${DBSecret}:SecretString:password}}"),BackupRetentionPeriod:r.backupRetentionDays||7,PreferredBackupWindow:r.preferredBackupWindow||"03:00-04:00",PreferredMaintenanceWindow:r.preferredMaintenanceWindow||"sun:04:00-sun:05:00",EnablePerformanceInsights:r.enablePerformanceInsights!==!1,PerformanceInsightsRetentionPeriod:r.performanceInsightsRetention||7,DeletionProtection:r.deletionProtection!==!1,CopyTagsToSnapshot:!0,EnableCloudwatchLogsExports:n==="postgres"?["postgresql"]:["error","general","slowquery"],Tags:[{Key:"Name",Value:t.sub(`\${AWS::StackName}-${i}-db`)}]};if(r.parameters&&Object.keys(r.parameters).length>0)c.DBParameterGroupName=t.ref("DBParameterGroup");e.addResource(s,"AWS::RDS::DBInstance",c,{dependsOn:["DBSubnetGroup","DBSecurityGroup","DBSecret"],deletionPolicy:"Snapshot",updateReplacePolicy:"Snapshot"}),e.addResource("DBSecretAttachment","AWS::SecretsManager::SecretTargetAttachment",{SecretId:t.ref("DBSecret"),TargetId:t.ref(s),TargetType:"AWS::RDS::DBInstance"},{dependsOn:[s,"DBSecret"]}),e.addOutputs({DBEndpoint:{Description:"Database endpoint",Value:t.getAtt(s,"Endpoint.Address"),Export:{Name:t.sub("${AWS::StackName}-db-endpoint")}},DBPort:{Description:"Database port",Value:t.getAtt(s,"Endpoint.Port"),Export:{Name:t.sub("${AWS::StackName}-db-port")}},DBSecretArn:{Description:"ARN of the database credentials secret",Value:t.ref("DBSecret"),Export:{Name:t.sub("${AWS::StackName}-db-secret-arn")}}})}function ii(e,n){let r=e.toLogicalId(`${n.name}-table`),i={TableName:t.sub(`\${AWS::StackName}-${n.name}`),BillingMode:n.billingMode||"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:n.partitionKey,AttributeType:"S"}],KeySchema:[{AttributeName:n.partitionKey,KeyType:"HASH"}],Tags:[{Key:"Name",Value:t.sub(`\${AWS::StackName}-${n.name}`)}]};if(n.sortKey)i.AttributeDefinitions.push({AttributeName:n.sortKey,AttributeType:"S"}),i.KeySchema.push({AttributeName:n.sortKey,KeyType:"RANGE"});if(n.billingMode==="PROVISIONED")i.ProvisionedThroughput={ReadCapacityUnits:n.readCapacity||5,WriteCapacityUnits:n.writeCapacity||5};if(n.streamEnabled)i.StreamSpecification={StreamViewType:"NEW_AND_OLD_IMAGES"};if(n.pointInTimeRecovery)i.PointInTimeRecoverySpecification={PointInTimeRecoveryEnabled:!0};if(n.ttl?.enabled)i.TimeToLiveSpecification={Enabled:!0,AttributeName:n.ttl.attributeName};if(n.globalSecondaryIndexes&&n.globalSecondaryIndexes.length>0)i.GlobalSecondaryIndexes=n.globalSecondaryIndexes.map((s)=>{let a=new Set(i.AttributeDefinitions.map((u)=>u.AttributeName));if(!a.has(s.partitionKey))i.AttributeDefinitions.push({AttributeName:s.partitionKey,AttributeType:"S"});if(s.sortKey&&!a.has(s.sortKey))i.AttributeDefinitions.push({AttributeName:s.sortKey,AttributeType:"S"});let c={IndexName:s.name,KeySchema:[{AttributeName:s.partitionKey,KeyType:"HASH"}],Projection:{ProjectionType:s.projectionType||"ALL"}};if(s.sortKey)c.KeySchema.push({AttributeName:s.sortKey,KeyType:"RANGE"});if(s.projectionType==="INCLUDE"&&s.nonKeyAttributes)c.Projection.NonKeyAttributes=s.nonKeyAttributes;if(n.billingMode==="PROVISIONED")c.ProvisionedThroughput={ReadCapacityUnits:n.readCapacity||5,WriteCapacityUnits:n.writeCapacity||5};return c});if(e.addResource(r,"AWS::DynamoDB::Table",i,{deletionPolicy:"Retain"}),e.addOutputs({[`${r}Name`]:{Description:`${n.name} table name`,Value:t.ref(r),Export:{Name:t.sub(`\${AWS::StackName}-${n.name}-table`)}},[`${r}Arn`]:{Description:`${n.name} table ARN`,Value:t.getAtt(r,"Arn"),Export:{Name:t.sub(`\${AWS::StackName}-${n.name}-table-arn`)}}}),n.streamEnabled)e.addOutputs({[`${r}StreamArn`]:{Description:`${n.name} stream ARN`,Value:t.getAtt(r,"StreamArn"),Export:{Name:t.sub(`\${AWS::StackName}-${n.name}-stream-arn`)}}})}function bn(e,n){for(let[r,i]of Object.entries(n))i.forEach((s)=>{si(e,s,r)})}function si(e,n,r){let i=e.toLogicalId(`${r}-${n.name}-function`),s=`${i}Role`;e.addResource(s,"AWS::IAM::Role",{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","arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole"],Policies:[{PolicyName:"LambdaExecutionPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[...oi(n.events||[])]}}],Tags:[{Key:"Name",Value:t.sub(`\${AWS::StackName}-${n.name}-role`)}]});let a={FunctionName:t.sub(`\${AWS::StackName}-${n.name}`),Runtime:n.runtime,Handler:n.handler,Role:t.getAtt(s,"Arn"),MemorySize:n.memory,Timeout:n.timeout,Code:{ZipFile:`exports.handler = async (event) => {
|
|
2448
|
+
`;if(e.addResource("LaunchTemplate","AWS::EC2::LaunchTemplate",{LaunchTemplateName:t.sub("${AWS::StackName}-template"),LaunchTemplateData:{ImageId:n.ami||t.findInMap("RegionMap",t.ref("AWS::Region"),"AMI"),InstanceType:n.instanceType,IamInstanceProfile:{Arn:t.getAtt("EC2InstanceProfile","Arn")},SecurityGroupIds:[t.ref("AppSecurityGroup")],UserData:t.base64(t.sub(r)),TagSpecifications:[{ResourceType:"instance",Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-instance")}]}],MetadataOptions:{HttpTokens:"required",HttpPutResponseHopLimit:1}}},{dependsOn:["AppSecurityGroup","EC2InstanceProfile"]}),n.loadBalancer){ri(e,n.loadBalancer);let i={LaunchTemplate:{LaunchTemplateId:t.ref("LaunchTemplate"),Version:t.getAtt("LaunchTemplate","LatestVersionNumber")},MinSize:n.autoScaling?.min.toString()||"1",MaxSize:n.autoScaling?.max.toString()||"3",DesiredCapacity:n.autoScaling?.min.toString()||"2",VPCZoneIdentifier:[t.ref("PrivateSubnet1"),t.ref("PrivateSubnet2")],TargetGroupARNs:[t.ref("TargetGroup")],HealthCheckType:"ELB",HealthCheckGracePeriod:300,Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-asg"),PropagateAtLaunch:!0}]};if(e.addResource("AutoScalingGroup","AWS::AutoScaling::AutoScalingGroup",i,{dependsOn:["LaunchTemplate","TargetGroup"]}),n.autoScaling)e.addResource("ScaleUpPolicy","AWS::AutoScaling::ScalingPolicy",{AdjustmentType:"ChangeInCapacity",AutoScalingGroupName:t.ref("AutoScalingGroup"),Cooldown:n.autoScaling.scaleUpCooldown?.toString()||"300",ScalingAdjustment:"1"},{dependsOn:"AutoScalingGroup"}),e.addResource("ScaleDownPolicy","AWS::AutoScaling::ScalingPolicy",{AdjustmentType:"ChangeInCapacity",AutoScalingGroupName:t.ref("AutoScalingGroup"),Cooldown:n.autoScaling.scaleDownCooldown?.toString()||"300",ScalingAdjustment:"-1"},{dependsOn:"AutoScalingGroup"}),e.addResource("HighCPUAlarm","AWS::CloudWatch::Alarm",{AlarmDescription:"Scale up when CPU exceeds target",MetricName:"CPUUtilization",Namespace:"AWS/EC2",Statistic:"Average",Period:"300",EvaluationPeriods:"2",Threshold:(n.autoScaling.targetCPU||70).toString(),AlarmActions:[t.ref("ScaleUpPolicy")],Dimensions:[{Name:"AutoScalingGroupName",Value:t.ref("AutoScalingGroup")}],ComparisonOperator:"GreaterThanThreshold"},{dependsOn:["AutoScalingGroup","ScaleUpPolicy"]}),e.addResource("LowCPUAlarm","AWS::CloudWatch::Alarm",{AlarmDescription:"Scale down when CPU is below threshold",MetricName:"CPUUtilization",Namespace:"AWS/EC2",Statistic:"Average",Period:"300",EvaluationPeriods:"2",Threshold:((n.autoScaling.targetCPU||70)-20).toString(),AlarmActions:[t.ref("ScaleDownPolicy")],Dimensions:[{Name:"AutoScalingGroupName",Value:t.ref("AutoScalingGroup")}],ComparisonOperator:"LessThanThreshold"},{dependsOn:["AutoScalingGroup","ScaleDownPolicy"]})}}function ri(e,n){if(!n)return;e.addResource("ALBSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for Application Load Balancer",VpcId:t.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:80,ToPort:80,CidrIp:"0.0.0.0/0"},{IpProtocol:"tcp",FromPort:443,ToPort:443,CidrIp:"0.0.0.0/0"}],SecurityGroupEgress:[{IpProtocol:"-1",CidrIp:"0.0.0.0/0"}],Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-alb-sg")}]},{dependsOn:"VPC"}),e.addResource("LoadBalancer","AWS::ElasticLoadBalancingV2::LoadBalancer",{Name:t.sub("${AWS::StackName}-alb"),Type:n.type||"application",Scheme:"internet-facing",IpAddressType:"ipv4",Subnets:[t.ref("PublicSubnet1"),t.ref("PublicSubnet2")],SecurityGroups:[t.ref("ALBSecurityGroup")],Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-alb")}]},{dependsOn:["PublicSubnet1","PublicSubnet2","ALBSecurityGroup"]}),e.addResource("TargetGroup","AWS::ElasticLoadBalancingV2::TargetGroup",{Name:t.sub("${AWS::StackName}-tg"),Port:3000,Protocol:"HTTP",VpcId:t.ref("VPC"),HealthCheckEnabled:!0,HealthCheckPath:n.healthCheck?.path||"/health",HealthCheckProtocol:"HTTP",HealthCheckIntervalSeconds:n.healthCheck?.interval||30,HealthCheckTimeoutSeconds:n.healthCheck?.timeout||5,HealthyThresholdCount:n.healthCheck?.healthyThreshold||2,UnhealthyThresholdCount:n.healthCheck?.unhealthyThreshold||3,TargetType:"instance",Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-tg")}]},{dependsOn:"VPC"}),e.addResource("LoadBalancerListener","AWS::ElasticLoadBalancingV2::Listener",{LoadBalancerArn:t.ref("LoadBalancer"),Port:80,Protocol:"HTTP",DefaultActions:[{Type:"forward",TargetGroupArn:t.ref("TargetGroup")}]},{dependsOn:["LoadBalancer","TargetGroup"]}),e.addOutputs({LoadBalancerDNS:{Description:"Load Balancer DNS Name",Value:t.getAtt("LoadBalancer","DNSName"),Export:{Name:t.sub("${AWS::StackName}-alb-dns")}}})}function pn(e,n,r){let i=e.toLogicalId(n),s=r.taskDefinition.containerDefinitions?.[0],a=s?.name||s?.Name||n,c=s?.portMappings?.[0]?.containerPort||s?.PortMappings?.[0]?.ContainerPort||3000,u=(r.taskDefinition.containerDefinitions||[]).flatMap((y)=>(y.secrets||y.Secrets||[]).map((f)=>f.valueFrom||f.ValueFrom)).filter(Boolean);if(!e.hasResource("ECSCluster"))e.addResource("ECSCluster","AWS::ECS::Cluster",{ClusterName:t.sub("${AWS::StackName}-cluster"),Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-cluster")}]});if(e.addResource(`${i}TaskExecutionRole`,"AWS::IAM::Role",{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"],...u.length?{Policies:[{PolicyName:"read-task-secrets",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["secretsmanager:GetSecretValue","ssm:GetParameters"],Resource:u},{Effect:"Allow",Action:"kms:Decrypt",Resource:"*"}]}}]}:{}}),e.addResource(`${i}TaskRole`,"AWS::IAM::Role",{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ecs-tasks.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"application-services",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["sqs:ReceiveMessage","sqs:DeleteMessage","sqs:GetQueueAttributes","sqs:SendMessage"],Resource:t.sub("arn:aws:sqs:${AWS::Region}:${AWS::AccountId}:${AWS::StackName}-*")},{Effect:"Allow",Action:["ses:SendEmail","ses:SendRawEmail"],Resource:"*"}]}}]}),!e.hasResource("ALBSecurityGroup"))e.addResource("ALBSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Public ingress for the application load balancer",VpcId:t.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:80,ToPort:80,CidrIp:"0.0.0.0/0"},...r.loadBalancer?.customDomain?.certificateArn?[{IpProtocol:"tcp",FromPort:443,ToPort:443,CidrIp:"0.0.0.0/0"}]:[]],SecurityGroupEgress:[{IpProtocol:"tcp",FromPort:c,ToPort:c,CidrIp:"0.0.0.0/0"}],Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-alb-sg")}]},{dependsOn:"VPC"});if(!e.hasResource("AppSecurityGroup"))e.addResource("AppSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Only the application load balancer may reach Fargate tasks",VpcId:t.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:c,ToPort:c,SourceSecurityGroupId:t.ref("ALBSecurityGroup")}],SecurityGroupEgress:[{IpProtocol:"-1",CidrIp:"0.0.0.0/0"}],Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-app-sg")}]},{dependsOn:["VPC","ALBSecurityGroup"]});let d=(r.taskDefinition.containerDefinitions||[{name:n,image:t.sub(`\${AWS::AccountId}.dkr.ecr.\${AWS::Region}.amazonaws.com/${n}:latest`),portMappings:[{containerPort:3000}]}]).map((y)=>({Name:y.Name||y.name,Image:y.Image||y.image,Essential:y.Essential??y.essential??!0,PortMappings:(y.PortMappings||y.portMappings||[]).map((f)=>({ContainerPort:f.ContainerPort??f.containerPort,Protocol:f.Protocol||f.protocol||"tcp"})),Environment:Array.isArray(y.Environment||y.environment)?(y.Environment||y.environment).map((f)=>({Name:f.Name||f.name,Value:f.Value??f.value})):Object.entries(y.Environment||y.environment||{}).map(([f,h])=>({Name:f,Value:h})),Secrets:(y.Secrets||y.secrets||[]).map((f)=>({Name:f.Name||f.name,ValueFrom:f.ValueFrom||f.valueFrom})),HealthCheck:y.HealthCheck||y.healthCheck,Command:y.Command||y.command,EntryPoint:y.EntryPoint||y.entryPoint,LogConfiguration:y.LogConfiguration||y.logConfiguration||{LogDriver:"awslogs",Options:{"awslogs-group":t.ref(`${i}LogGroup`),"awslogs-region":t.ref("AWS::Region"),"awslogs-stream-prefix":n}}}));e.addResource(`${i}TaskDefinition`,"AWS::ECS::TaskDefinition",{Family:t.sub(`\${AWS::StackName}-${n}`),NetworkMode:"awsvpc",RequiresCompatibilities:["FARGATE"],Cpu:r.taskDefinition.cpu,Memory:r.taskDefinition.memory,ExecutionRoleArn:t.getAtt(`${i}TaskExecutionRole`,"Arn"),TaskRoleArn:t.getAtt(`${i}TaskRole`,"Arn"),ContainerDefinitions:d},{dependsOn:[`${i}TaskExecutionRole`,`${i}TaskRole`,`${i}LogGroup`]}),e.addResource(`${i}LogGroup`,"AWS::Logs::LogGroup",{LogGroupName:t.sub(`/ecs/\${AWS::StackName}/${n}`),RetentionInDays:14});let m=r.service.healthCheck||{};e.addResource(`${i}TargetGroup`,"AWS::ElasticLoadBalancingV2::TargetGroup",{VpcId:t.ref("VPC"),Port:c,Protocol:"HTTP",TargetType:"ip",HealthCheckEnabled:!0,HealthCheckPath:m.path||"/health",HealthCheckProtocol:"HTTP",HealthCheckIntervalSeconds:m.interval||30,HealthCheckTimeoutSeconds:m.timeout||5,HealthyThresholdCount:m.healthyThreshold||2,UnhealthyThresholdCount:m.unhealthyThreshold||3,Matcher:{HttpCode:"200-399"},TargetGroupAttributes:[{Key:"deregistration_delay.timeout_seconds",Value:"30"}]},{dependsOn:"VPC"}),e.addResource(`${i}LoadBalancer`,"AWS::ElasticLoadBalancingV2::LoadBalancer",{Type:"application",Scheme:"internet-facing",IpAddressType:"ipv4",Subnets:[t.ref("PublicSubnet1"),t.ref("PublicSubnet2")],SecurityGroups:[t.ref("ALBSecurityGroup")],LoadBalancerAttributes:[{Key:"routing.http.drop_invalid_header_fields.enabled",Value:"true"},{Key:"deletion_protection.enabled",Value:String(r.loadBalancer?.deletionProtection===!0)}],Tags:[{Key:"Name",Value:t.sub(`\${AWS::StackName}-${n}-alb`)}]},{dependsOn:["PublicSubnet1","PublicSubnet2","ALBSecurityGroup"]});let p=r.loadBalancer?.customDomain?.certificateArn,g=r.loadBalancer?.originVerifyHeader;if(e.addResource(`${i}HttpListener`,"AWS::ElasticLoadBalancingV2::Listener",{LoadBalancerArn:t.ref(`${i}LoadBalancer`),Port:80,Protocol:"HTTP",DefaultActions:p?[{Type:"redirect",RedirectConfig:{Protocol:"HTTPS",Port:"443",StatusCode:"HTTP_301"}}]:g?[{Type:"fixed-response",FixedResponseConfig:{StatusCode:"403",ContentType:"text/plain",MessageBody:"Forbidden"}}]:[{Type:"forward",TargetGroupArn:t.ref(`${i}TargetGroup`)}]},{dependsOn:[`${i}LoadBalancer`,`${i}TargetGroup`]}),p)e.addResource(`${i}HttpsListener`,"AWS::ElasticLoadBalancingV2::Listener",{LoadBalancerArn:t.ref(`${i}LoadBalancer`),Port:443,Protocol:"HTTPS",Certificates:[{CertificateArn:p}],SslPolicy:"ELBSecurityPolicy-TLS13-1-2-2021-06",DefaultActions:g?[{Type:"fixed-response",FixedResponseConfig:{StatusCode:"403",ContentType:"text/plain",MessageBody:"Forbidden"}}]:[{Type:"forward",TargetGroupArn:t.ref(`${i}TargetGroup`)}]},{dependsOn:[`${i}LoadBalancer`,`${i}TargetGroup`]});if(g){let y=p?`${i}HttpsListener`:`${i}HttpListener`;e.addResource(`${i}OriginVerifyRule`,"AWS::ElasticLoadBalancingV2::ListenerRule",{ListenerArn:t.ref(y),Priority:1,Conditions:[{Field:"http-header",HttpHeaderConfig:{HttpHeaderName:g.name,Values:[g.value]}}],Actions:[{Type:"forward",TargetGroupArn:t.ref(`${i}TargetGroup`)}]},{dependsOn:[y,`${i}TargetGroup`]})}if(e.addResource(`${i}Service`,"AWS::ECS::Service",{ServiceName:t.sub(`\${AWS::StackName}-${n}`),Cluster:t.ref("ECSCluster"),TaskDefinition:t.ref(`${i}TaskDefinition`),DesiredCount:r.service.desiredCount,LaunchType:"FARGATE",PlatformVersion:"LATEST",HealthCheckGracePeriodSeconds:60,DeploymentConfiguration:{MinimumHealthyPercent:100,MaximumPercent:200,DeploymentCircuitBreaker:{Enable:!0,Rollback:!0}},LoadBalancers:[{ContainerName:a,ContainerPort:c,TargetGroupArn:t.ref(`${i}TargetGroup`)}],NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"DISABLED",Subnets:[t.ref("PrivateSubnet1"),t.ref("PrivateSubnet2")],SecurityGroups:[t.ref("AppSecurityGroup")]}}},{dependsOn:["ECSCluster",`${i}TaskDefinition`,g?`${i}OriginVerifyRule`:p?`${i}HttpsListener`:`${i}HttpListener`]}),r.service.autoScaling){let y=r.service.autoScaling;e.addResource(`${i}ScalableTarget`,"AWS::ApplicationAutoScaling::ScalableTarget",{MinCapacity:y.min,MaxCapacity:y.max,ResourceId:t.join("/",["service",t.ref("ECSCluster"),t.getAtt(`${i}Service`,"Name")]),RoleARN:t.sub("arn:aws:iam::${AWS::AccountId}:role/aws-service-role/ecs.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_ECSService"),ScalableDimension:"ecs:service:DesiredCount",ServiceNamespace:"ecs"},{dependsOn:`${i}Service`}),e.addResource(`${i}ScalingPolicy`,"AWS::ApplicationAutoScaling::ScalingPolicy",{PolicyType:"TargetTrackingScaling",ScalingTargetId:t.ref(`${i}ScalableTarget`),TargetTrackingScalingPolicyConfiguration:{TargetValue:y.targetCPU||70,PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageCPUUtilization"},ScaleInCooldown:60,ScaleOutCooldown:30}},{dependsOn:`${i}ScalableTarget`})}e.addOutputs({[`${i}ClusterName`]:{Description:"ECS cluster name",Value:t.ref("ECSCluster")},[`${i}ServiceName`]:{Description:"ECS service name",Value:t.getAtt(`${i}Service`,"Name")},[`${i}LoadBalancerDnsName`]:{Description:"ALB origin hostname",Value:t.getAtt(`${i}LoadBalancer`,"DNSName")},[`${i}LoadBalancerHostedZoneId`]:{Description:"ALB canonical hosted zone ID",Value:t.getAtt(`${i}LoadBalancer`,"CanonicalHostedZoneID")},[`${i}TargetGroupArn`]:{Description:"ECS target group ARN",Value:t.ref(`${i}TargetGroup`)}})}function fn(e,n){if(n.postgres)yn(e,"postgres",n.postgres);if(n.mysql)yn(e,"mysql",n.mysql);if(n.dynamodb?.tables)n.dynamodb.tables.forEach((r)=>{ii(e,r)})}function yn(e,n,r){if(!r)return;let i=n==="postgres"?"postgres":"mysql",s=e.toLogicalId(`${i}-db`);e.addResource("DBSubnetGroup","AWS::RDS::DBSubnetGroup",{DBSubnetGroupDescription:"Subnet group for RDS instance",SubnetIds:[t.ref("PrivateSubnet1"),t.ref("PrivateSubnet2")],Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-db-subnet-group")}]},{dependsOn:["PrivateSubnet1","PrivateSubnet2"]}),e.addResource("DBSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for RDS instance",VpcId:t.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:n==="postgres"?5432:3306,ToPort:n==="postgres"?5432:3306,SourceSecurityGroupId:t.ref("AppSecurityGroup")}],Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-db-sg")}]},{dependsOn:["VPC","AppSecurityGroup"]});let a=n==="postgres"?`postgres${r.version.split(".")[0]}`:`mysql${r.version.split(".")[0]}.${r.version.split(".")[1]||"0"}`;if(r.parameters&&Object.keys(r.parameters).length>0)e.addResource("DBParameterGroup","AWS::RDS::DBParameterGroup",{Description:`Parameter group for ${i}`,Family:a,Parameters:r.parameters,Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-db-params")}]});e.addResource("DBSecret","AWS::SecretsManager::Secret",{Description:"Database credentials",GenerateSecretString:{SecretStringTemplate:JSON.stringify({username:"admin"}),GenerateStringKey:"password",PasswordLength:32,ExcludeCharacters:'"@/\\'},Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-db-secret")}]},{deletionPolicy:"Retain",updateReplacePolicy:"Retain"});let c={Engine:i,EngineVersion:r.version,DBInstanceClass:r.instanceClass,AllocatedStorage:r.allocatedStorage.toString(),MaxAllocatedStorage:r.maxAllocatedStorage?.toString(),StorageType:"gp3",StorageEncrypted:!0,MultiAZ:r.multiAZ!==!1,DBSubnetGroupName:t.ref("DBSubnetGroup"),VPCSecurityGroups:[t.ref("DBSecurityGroup")],MasterUsername:t.sub("{{resolve:secretsmanager:${DBSecret}:SecretString:username}}"),MasterUserPassword:t.sub("{{resolve:secretsmanager:${DBSecret}:SecretString:password}}"),BackupRetentionPeriod:r.backupRetentionDays||7,PreferredBackupWindow:r.preferredBackupWindow||"03:00-04:00",PreferredMaintenanceWindow:r.preferredMaintenanceWindow||"sun:04:00-sun:05:00",EnablePerformanceInsights:r.enablePerformanceInsights!==!1,PerformanceInsightsRetentionPeriod:r.performanceInsightsRetention||7,DeletionProtection:r.deletionProtection!==!1,CopyTagsToSnapshot:!0,EnableCloudwatchLogsExports:n==="postgres"?["postgresql"]:["error","general","slowquery"],Tags:[{Key:"Name",Value:t.sub(`\${AWS::StackName}-${i}-db`)}]};if(r.parameters&&Object.keys(r.parameters).length>0)c.DBParameterGroupName=t.ref("DBParameterGroup");e.addResource(s,"AWS::RDS::DBInstance",c,{dependsOn:["DBSubnetGroup","DBSecurityGroup","DBSecret"],deletionPolicy:"Snapshot",updateReplacePolicy:"Snapshot"}),e.addResource("DBSecretAttachment","AWS::SecretsManager::SecretTargetAttachment",{SecretId:t.ref("DBSecret"),TargetId:t.ref(s),TargetType:"AWS::RDS::DBInstance"},{dependsOn:[s,"DBSecret"]}),e.addOutputs({DBEndpoint:{Description:"Database endpoint",Value:t.getAtt(s,"Endpoint.Address"),Export:{Name:t.sub("${AWS::StackName}-db-endpoint")}},DBPort:{Description:"Database port",Value:t.getAtt(s,"Endpoint.Port"),Export:{Name:t.sub("${AWS::StackName}-db-port")}},DBSecretArn:{Description:"ARN of the database credentials secret",Value:t.ref("DBSecret"),Export:{Name:t.sub("${AWS::StackName}-db-secret-arn")}}})}function ii(e,n){let r=e.toLogicalId(`${n.name}-table`),i={TableName:t.sub(`\${AWS::StackName}-${n.name}`),BillingMode:n.billingMode||"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:n.partitionKey,AttributeType:"S"}],KeySchema:[{AttributeName:n.partitionKey,KeyType:"HASH"}],Tags:[{Key:"Name",Value:t.sub(`\${AWS::StackName}-${n.name}`)}]};if(n.sortKey)i.AttributeDefinitions.push({AttributeName:n.sortKey,AttributeType:"S"}),i.KeySchema.push({AttributeName:n.sortKey,KeyType:"RANGE"});if(n.billingMode==="PROVISIONED")i.ProvisionedThroughput={ReadCapacityUnits:n.readCapacity||5,WriteCapacityUnits:n.writeCapacity||5};if(n.streamEnabled)i.StreamSpecification={StreamViewType:"NEW_AND_OLD_IMAGES"};if(n.pointInTimeRecovery)i.PointInTimeRecoverySpecification={PointInTimeRecoveryEnabled:!0};if(n.ttl?.enabled)i.TimeToLiveSpecification={Enabled:!0,AttributeName:n.ttl.attributeName};if(n.globalSecondaryIndexes&&n.globalSecondaryIndexes.length>0)i.GlobalSecondaryIndexes=n.globalSecondaryIndexes.map((s)=>{let a=new Set(i.AttributeDefinitions.map((u)=>u.AttributeName));if(!a.has(s.partitionKey))i.AttributeDefinitions.push({AttributeName:s.partitionKey,AttributeType:"S"});if(s.sortKey&&!a.has(s.sortKey))i.AttributeDefinitions.push({AttributeName:s.sortKey,AttributeType:"S"});let c={IndexName:s.name,KeySchema:[{AttributeName:s.partitionKey,KeyType:"HASH"}],Projection:{ProjectionType:s.projectionType||"ALL"}};if(s.sortKey)c.KeySchema.push({AttributeName:s.sortKey,KeyType:"RANGE"});if(s.projectionType==="INCLUDE"&&s.nonKeyAttributes)c.Projection.NonKeyAttributes=s.nonKeyAttributes;if(n.billingMode==="PROVISIONED")c.ProvisionedThroughput={ReadCapacityUnits:n.readCapacity||5,WriteCapacityUnits:n.writeCapacity||5};return c});if(e.addResource(r,"AWS::DynamoDB::Table",i,{deletionPolicy:"Retain"}),e.addOutputs({[`${r}Name`]:{Description:`${n.name} table name`,Value:t.ref(r),Export:{Name:t.sub(`\${AWS::StackName}-${n.name}-table`)}},[`${r}Arn`]:{Description:`${n.name} table ARN`,Value:t.getAtt(r,"Arn"),Export:{Name:t.sub(`\${AWS::StackName}-${n.name}-table-arn`)}}}),n.streamEnabled)e.addOutputs({[`${r}StreamArn`]:{Description:`${n.name} stream ARN`,Value:t.getAtt(r,"StreamArn"),Export:{Name:t.sub(`\${AWS::StackName}-${n.name}-stream-arn`)}}})}function hn(e,n){for(let[r,i]of Object.entries(n))i.forEach((s)=>{si(e,s,r)})}function si(e,n,r){let i=e.toLogicalId(`${r}-${n.name}-function`),s=`${i}Role`;e.addResource(s,"AWS::IAM::Role",{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","arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole"],Policies:[{PolicyName:"LambdaExecutionPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[...oi(n.events||[])]}}],Tags:[{Key:"Name",Value:t.sub(`\${AWS::StackName}-${n.name}-role`)}]});let a={FunctionName:t.sub(`\${AWS::StackName}-${n.name}`),Runtime:n.runtime,Handler:n.handler,Role:t.getAtt(s,"Arn"),MemorySize:n.memory,Timeout:n.timeout,Code:{ZipFile:`exports.handler = async (event) => {
|
|
2449
2449
|
console.log('Event:', JSON.stringify(event, null, 2));
|
|
2450
2450
|
return { statusCode: 200, body: 'Function not yet implemented' };
|
|
2451
|
-
};`},Environment:n.environment?{Variables:n.environment}:void 0,Tags:[{Key:"Name",Value:t.sub(`\${AWS::StackName}-${n.name}`)}]};if(r!=="edge")a.VpcConfig={SubnetIds:[t.ref("PrivateSubnet1"),t.ref("PrivateSubnet2")],SecurityGroupIds:[t.ref("AppSecurityGroup")]};if(e.addResource(i,"AWS::Lambda::Function",a,{dependsOn:s}),e.addResource(`${i}LogGroup`,"AWS::Logs::LogGroup",{LogGroupName:t.sub(`/aws/lambda/\${AWS::StackName}-${n.name}`),RetentionInDays:14}),n.events)n.events.forEach((c,u)=>{ai(e,i,c,u)});e.addOutputs({[`${i}Arn`]:{Description:`${n.name} function ARN`,Value:t.getAtt(i,"Arn"),Export:{Name:t.sub(`\${AWS::StackName}-${n.name}-function-arn`)}}})}function ai(e,n,r,i){let s=`${n}EventSource${i}`;switch(r.type){case"http":break;case"s3":if(r.bucket){let a=e.toLogicalId(`${r.bucket}-bucket`);e.addResource(`${s}Permission`,"AWS::Lambda::Permission",{FunctionName:t.ref(n),Action:"lambda:InvokeFunction",Principal:"s3.amazonaws.com",SourceArn:
|
|
2451
|
+
};`},Environment:n.environment?{Variables:n.environment}:void 0,Tags:[{Key:"Name",Value:t.sub(`\${AWS::StackName}-${n.name}`)}]};if(r!=="edge")a.VpcConfig={SubnetIds:[t.ref("PrivateSubnet1"),t.ref("PrivateSubnet2")],SecurityGroupIds:[t.ref("AppSecurityGroup")]};if(e.addResource(i,"AWS::Lambda::Function",a,{dependsOn:s}),e.addResource(`${i}LogGroup`,"AWS::Logs::LogGroup",{LogGroupName:t.sub(`/aws/lambda/\${AWS::StackName}-${n.name}`),RetentionInDays:14}),n.events)n.events.forEach((c,u)=>{ai(e,i,c,u)});e.addOutputs({[`${i}Arn`]:{Description:`${n.name} function ARN`,Value:t.getAtt(i,"Arn"),Export:{Name:t.sub(`\${AWS::StackName}-${n.name}-function-arn`)}}})}function ai(e,n,r,i){let s=`${n}EventSource${i}`;switch(r.type){case"http":break;case"s3":if(r.bucket){let a=e.toLogicalId(`${r.bucket}-bucket`);e.addResource(`${s}Permission`,"AWS::Lambda::Permission",{FunctionName:t.ref(n),Action:"lambda:InvokeFunction",Principal:"s3.amazonaws.com",SourceArn:In.s3Bucket(t.ref(a))},{dependsOn:[n,a]})}break;case"sqs":if(r.queueName){let a=e.toLogicalId(`${r.queueName}-queue`);e.addResource(s,"AWS::Lambda::EventSourceMapping",{EventSourceArn:t.getAtt(a,"Arn"),FunctionName:t.ref(n),BatchSize:r.batchSize||10},{dependsOn:[n,a]})}break;case"kinesis":if(r.streamName){let a=e.toLogicalId(`${r.streamName}-stream`);e.addResource(s,"AWS::Lambda::EventSourceMapping",{EventSourceArn:t.getAtt(a,"Arn"),FunctionName:t.ref(n),BatchSize:r.batchSize||100,StartingPosition:r.startingPosition||"LATEST",ParallelizationFactor:r.parallelizationFactor||1},{dependsOn:[n,a]})}break;case"dynamodb-stream":if(r.tableName){let a=e.toLogicalId(`${r.tableName}-table`);e.addResource(s,"AWS::Lambda::EventSourceMapping",{EventSourceArn:t.getAtt(a,"StreamArn"),FunctionName:t.ref(n),BatchSize:r.batchSize||100,StartingPosition:r.startingPosition||"LATEST"},{dependsOn:[n,a]})}break;case"schedule":if(r.expression)e.addResource(`${s}Rule`,"AWS::Events::Rule",{ScheduleExpression:r.expression,State:"ENABLED",Targets:[{Arn:t.getAtt(n,"Arn"),Id:`${n}Target`}]},{dependsOn:n}),e.addResource(`${s}Permission`,"AWS::Lambda::Permission",{FunctionName:t.ref(n),Action:"lambda:InvokeFunction",Principal:"events.amazonaws.com",SourceArn:t.getAtt(`${s}Rule`,"Arn")},{dependsOn:[n,`${s}Rule`]});break}}function oi(e){let n=[];if(!e)return n;if(e.forEach((r)=>{switch(r.type){case"s3":n.push({Effect:"Allow",Action:["s3:GetObject","s3:GetObjectVersion"],Resource:r.bucket?`arn:aws:s3:::${r.bucket}/*`:"arn:aws:s3:::*/*"});break;case"sqs":n.push({Effect:"Allow",Action:["sqs:ReceiveMessage","sqs:DeleteMessage","sqs:GetQueueAttributes"],Resource:r.queueName?In.sqs(r.queueName):"arn:aws:sqs:*:*:*"});break;case"kinesis":n.push({Effect:"Allow",Action:["kinesis:GetRecords","kinesis:GetShardIterator","kinesis:DescribeStream","kinesis:ListStreams"],Resource:r.streamName?In.kinesis(r.streamName):"arn:aws:kinesis:*:*:stream/*"});break;case"dynamodb-stream":n.push({Effect:"Allow",Action:["dynamodb:GetRecords","dynamodb:GetShardIterator","dynamodb:DescribeStream","dynamodb:ListStreams"],Resource:r.tableName?t.sub(`arn:aws:dynamodb:\${AWS::Region}:\${AWS::AccountId}:table/${r.tableName}/stream/*`):"arn:aws:dynamodb:*:*:table/*/stream/*"});break}}),n.length===0)n.push({Effect:"Allow",Action:["logs:CreateLogGroup","logs:CreateLogStream","logs:PutLogEvents"],Resource:"arn:aws:logs:*:*:*"});return n}function bn(e,n){if(n.topics)n.topics.forEach((r)=>{ci(e,r)})}function ci(e,n){let r=e.toLogicalId(`${n.name}-topic`);if(e.addResource(r,"AWS::SNS::Topic",{TopicName:t.sub(`\${AWS::StackName}-${n.name}`),DisplayName:n.displayName||n.name,Tags:[{Key:"Name",Value:t.sub(`\${AWS::StackName}-${n.name}`)}]}),e.addResource(`${r}Policy`,"AWS::SNS::TopicPolicy",{Topics:[t.ref(r)],PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:["events.amazonaws.com","cloudwatch.amazonaws.com","s3.amazonaws.com"]},Action:"sns:Publish",Resource:t.ref(r)},{Effect:"Allow",Principal:{AWS:t.sub("arn:aws:iam::${AWS::AccountId}:root")},Action:["sns:Subscribe","sns:Publish","sns:Receive"],Resource:t.ref(r)}]}},{dependsOn:r}),n.subscriptions)n.subscriptions.forEach((i,s)=>{let a=`${r}Subscription${s+1}`,c={Protocol:i.protocol,TopicArn:t.ref(r),Endpoint:i.endpoint};if(i.filterPolicy)c.FilterPolicy=i.filterPolicy;if(i.protocol==="sqs"){let u=e.toLogicalId(`${i.endpoint}-queue`);c.Endpoint=t.getAtt(u,"Arn")}if(i.protocol==="lambda"){let u=e.toLogicalId(i.endpoint);c.Endpoint=t.getAtt(u,"Arn"),e.addResource(`${a}Permission`,"AWS::Lambda::Permission",{FunctionName:t.ref(u),Action:"lambda:InvokeFunction",Principal:"sns.amazonaws.com",SourceArn:t.ref(r)},{dependsOn:[u,r]})}e.addResource(a,"AWS::SNS::Subscription",c,{dependsOn:r})});e.addOutputs({[`${r}Arn`]:{Description:`${n.name} topic ARN`,Value:t.ref(r),Export:{Name:t.sub(`\${AWS::StackName}-${n.name}-topic-arn`)}}})}function Sn(e,n){if(n.alarms&&n.alarms.length>0)e.addResource("AlarmTopic","AWS::SNS::Topic",{TopicName:t.sub("${AWS::StackName}-alarms"),DisplayName:"CloudWatch Alarms",Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-alarms")}]}),n.alarms.forEach((r,i)=>{li(e,r,i)});if(n.dashboard)ui(e,n.dashboard);if(n.logs?.groups)n.logs.groups.forEach((r)=>{di(e,r,n.logs?.retention)})}function li(e,n,r){let i=e.toLogicalId(`alarm-${n.name||n.metric}-${r}`),s={AlarmName:n.name||t.sub(`\${AWS::StackName}-${n.metric}`),AlarmDescription:`Alarm for ${n.metric}`,MetricName:n.metric,Namespace:n.namespace||At(n.metric,n.service),Statistic:n.statistic||"Average",Period:n.period||300,EvaluationPeriods:n.evaluationPeriods||1,Threshold:n.threshold,ComparisonOperator:n.comparisonOperator||"GreaterThanThreshold",TreatMissingData:n.treatMissingData||"notBreaching",AlarmActions:[t.ref("AlarmTopic")],OKActions:[t.ref("AlarmTopic")]};if(n.dimensions)s.Dimensions=Object.entries(n.dimensions).map(([a,c])=>({Name:a,Value:c}));else if(n.service)s.Dimensions=mi(n.service);e.addResource(i,"AWS::CloudWatch::Alarm",s,{dependsOn:"AlarmTopic"})}function ui(e,n){if(!n)return;let r=[],i=0,s=0;n.widgets?.forEach((a)=>{let c=a.width||12,u=a.height||6;if(a.type==="metric"&&a.metrics){let d=a.metrics.map((m)=>{if(typeof m==="string")return[At(m),m];else return[At(m.metric,m.service),m.metric]});r.push({type:"metric",x:i,y:s,width:c,height:u,properties:{metrics:d,period:300,stat:"Average",region:t.ref("AWS::Region"),title:a.metrics.length>1?"Multiple Metrics":typeof a.metrics[0]==="string"?a.metrics[0]:a.metrics[0].metric}})}else if(a.type==="log"&&a.logGroup)r.push({type:"log",x:i,y:s,width:c,height:u,properties:{query:`SOURCE '${a.logGroup}'
|
|
2452
2452
|
| fields @timestamp, @message
|
|
2453
2453
|
| sort @timestamp desc
|
|
2454
|
-
| limit 20`,region:t.ref("AWS::Region"),title:`Logs: ${a.logGroup}`}});else if(a.type==="text"&&a.text)r.push({type:"text",x:i,y:s,width:c,height:u,properties:{markdown:a.text}});if(i+=c,i>=24)i=0,s+=u}),e.addResource("CloudWatchDashboard","AWS::CloudWatch::Dashboard",{DashboardName:t.sub(`\${AWS::StackName}-${n.name}`),DashboardBody:JSON.stringify({widgets:r})}),e.addOutputs({DashboardURL:{Description:"CloudWatch Dashboard URL",Value:t.sub("https://console.aws.amazon.com/cloudwatch/home?region=${AWS::Region}#dashboards:name=${CloudWatchDashboard}")}})}function di(e,n,r){let i=e.toLogicalId(`${n}-log-group`);e.addResource(i,"AWS::Logs::LogGroup",{LogGroupName:t.sub(`/aws/\${AWS::StackName}/${n}`),RetentionInDays:r||14,Tags:[{Key:"Name",Value:t.sub(`\${AWS::StackName}-${n}`)}]})}function At(e,n){if(n)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"}[n.toLowerCase()]||"AWS/CloudWatch";let r=e.toLowerCase();if(r.includes("cpu")||r.includes("memory")||r.includes("network"))return"AWS/EC2";if(r.includes("lambda")||r.includes("invocation")||r.includes("duration"))return"AWS/Lambda";if(r.includes("request")||r.includes("latency")||r.includes("target"))return"AWS/ApplicationELB";if(r.includes("database")||r.includes("connection"))return"AWS/RDS";if(r.includes("read")||r.includes("write")||r.includes("consumed"))return"AWS/DynamoDB";return"AWS/CloudWatch"}function mi(e){return{ec2:[{Name:"InstanceId",Value:t.ref("EC2Instance")}],ecs:[{Name:"ClusterName",Value:t.ref("ECSCluster")},{Name:"ServiceName",Value:t.getAtt("ECSService","Name")}],lambda:[{Name:"FunctionName",Value:t.ref("LambdaFunction")}],rds:[{Name:"DBInstanceIdentifier",Value:t.ref("Database")}],dynamodb:[{Name:"TableName",Value:t.ref("DynamoDBTable")}],alb:[{Name:"LoadBalancer",Value:t.getAtt("LoadBalancer","LoadBalancerFullName")}],apigateway:[{Name:"ApiName",Value:t.ref("HttpApi")}]}[e.toLowerCase()]||[]}function vn(e,n){if(!n.vpc)return;let{cidr:r="10.0.0.0/16",availabilityZones:i=2,natGateways:s=1,enableDnsHostnames:a=!0,enableDnsSupport:c=!0}=n.vpc;e.addResource("VPC","AWS::EC2::VPC",{CidrBlock:r,EnableDnsHostnames:a,EnableDnsSupport:c,Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-vpc")}]}),e.addResource("InternetGateway","AWS::EC2::InternetGateway",{Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-igw")}]}),e.addResource("VPCGatewayAttachment","AWS::EC2::VPCGatewayAttachment",{VpcId:t.ref("VPC"),InternetGatewayId:t.ref("InternetGateway")},{dependsOn:["VPC","InternetGateway"]});let u=[];for(let g=0;g<i;g++){let y=`PublicSubnet${g+1}`;u.push(y),e.addResource(y,"AWS::EC2::Subnet",{VpcId:t.ref("VPC"),CidrBlock:t.select(g,t.cidr(t.getAtt("VPC","CidrBlock"),i*2,8)),AvailabilityZone:t.select(g,t.getAZs()),MapPublicIpOnLaunch:!0,Tags:[{Key:"Name",Value:t.sub(`\${AWS::StackName}-public-${g+1}`)},{Key:"Type",Value:"public"}]},{dependsOn:"VPC"})}let d=[];for(let g=0;g<i;g++){let y=`PrivateSubnet${g+1}`;d.push(y),e.addResource(y,"AWS::EC2::Subnet",{VpcId:t.ref("VPC"),CidrBlock:t.select(g+i,t.cidr(t.getAtt("VPC","CidrBlock"),i*2,8)),AvailabilityZone:t.select(g,t.getAZs()),MapPublicIpOnLaunch:!1,Tags:[{Key:"Name",Value:t.sub(`\${AWS::StackName}-private-${g+1}`)},{Key:"Type",Value:"private"}]},{dependsOn:"VPC"})}let m=[];for(let g=0;g<s;g++){let y=`NatEIP${g+1}`;m.push(y),e.addResource(y,"AWS::EC2::EIP",{Domain:"vpc",Tags:[{Key:"Name",Value:t.sub(`\${AWS::StackName}-nat-eip-${g+1}`)}]},{dependsOn:"VPCGatewayAttachment"})}let p=[];for(let g=0;g<s;g++){let y=`NatGateway${g+1}`;p.push(y);let f=g%i;e.addResource(y,"AWS::EC2::NatGateway",{AllocationId:t.getAtt(m[g],"AllocationId"),SubnetId:t.ref(u[f]),Tags:[{Key:"Name",Value:t.sub(`\${AWS::StackName}-nat-${g+1}`)}]},{dependsOn:[m[g],u[f]]})}e.addResource("PublicRouteTable","AWS::EC2::RouteTable",{VpcId:t.ref("VPC"),Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-public-rt")}]},{dependsOn:"VPC"}),e.addResource("PublicRoute","AWS::EC2::Route",{RouteTableId:t.ref("PublicRouteTable"),DestinationCidrBlock:"0.0.0.0/0",GatewayId:t.ref("InternetGateway")},{dependsOn:["PublicRouteTable","VPCGatewayAttachment"]}),u.forEach((g,y)=>{e.addResource(`PublicSubnetRouteTableAssociation${y+1}`,"AWS::EC2::SubnetRouteTableAssociation",{SubnetId:t.ref(g),RouteTableId:t.ref("PublicRouteTable")},{dependsOn:[g,"PublicRouteTable"]})}),d.forEach((g,y)=>{let f=`PrivateRouteTable${y+1}`,h=y%s;e.addResource(f,"AWS::EC2::RouteTable",{VpcId:t.ref("VPC"),Tags:[{Key:"Name",Value:t.sub(`\${AWS::StackName}-private-rt-${y+1}`)}]},{dependsOn:"VPC"}),e.addResource(`PrivateRoute${y+1}`,"AWS::EC2::Route",{RouteTableId:t.ref(f),DestinationCidrBlock:"0.0.0.0/0",NatGatewayId:t.ref(p[h])},{dependsOn:[f,p[h]]}),e.addResource(`PrivateSubnetRouteTableAssociation${y+1}`,"AWS::EC2::SubnetRouteTableAssociation",{SubnetId:t.ref(g),RouteTableId:t.ref(f)},{dependsOn:[g,f]})}),e.addResource("S3VPCEndpoint","AWS::EC2::VPCEndpoint",{VpcId:t.ref("VPC"),ServiceName:t.sub("com.amazonaws.${AWS::Region}.s3"),VpcEndpointType:"Gateway",RouteTableIds:[t.ref("PublicRouteTable"),...Array.from({length:i},(g,y)=>t.ref(`PrivateRouteTable${y+1}`))]},{dependsOn:"VPC"}),e.addResource("NetworkAcl","AWS::EC2::NetworkAcl",{VpcId:t.ref("VPC"),Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-nacl")}]},{dependsOn:"VPC"}),e.addResource("NetworkAclEntryInbound","AWS::EC2::NetworkAclEntry",{NetworkAclId:t.ref("NetworkAcl"),RuleNumber:100,Protocol:-1,RuleAction:"allow",CidrBlock:"0.0.0.0/0"},{dependsOn:"NetworkAcl"}),e.addResource("NetworkAclEntryOutbound","AWS::EC2::NetworkAclEntry",{NetworkAclId:t.ref("NetworkAcl"),RuleNumber:100,Protocol:-1,Egress:!0,RuleAction:"allow",CidrBlock:"0.0.0.0/0"},{dependsOn:"NetworkAcl"}),e.addOutputs({VPCId:{Description:"VPC ID",Value:t.ref("VPC"),Export:{Name:t.sub("${AWS::StackName}-VPC")}},PublicSubnets:{Description:"Public subnet IDs",Value:t.join(",",u.map((g)=>t.ref(g))),Export:{Name:t.sub("${AWS::StackName}-PublicSubnets")}},PrivateSubnets:{Description:"Private subnet IDs",Value:t.join(",",d.map((g)=>t.ref(g))),Export:{Name:t.sub("${AWS::StackName}-PrivateSubnets")}}})}function Tn(e,n){for(let[r,i]of Object.entries(n))pi(e,r,i)}function pi(e,n,r){let i=e.toLogicalId(`${n}-queue`),s=r.fifo||!1,a;if(r.deadLetterQueue){let u=`${i}DLQ`;e.addResource(u,"AWS::SQS::Queue",{QueueName:s?t.sub(`\${AWS::StackName}-${n}-dlq.fifo`):t.sub(`\${AWS::StackName}-${n}-dlq`),FifoQueue:s,MessageRetentionPeriod:1209600,Tags:[{Key:"Name",Value:t.sub(`\${AWS::StackName}-${n}-dlq`)}]},{deletionPolicy:"Retain",updateReplacePolicy:"Retain"}),a=t.getAtt(u,"Arn")}let c={QueueName:s?t.sub(`\${AWS::StackName}-${n}.fifo`):t.sub(`\${AWS::StackName}-${n}`),FifoQueue:s,VisibilityTimeout:r.visibilityTimeout||30,MessageRetentionPeriod:r.messageRetentionPeriod||345600,ReceiveMessageWaitTimeSeconds:r.receiveMessageWaitTime||0,Tags:[{Key:"Name",Value:t.sub(`\${AWS::StackName}-${n}`)}]};if(s&&r.contentBasedDeduplication)c.ContentBasedDeduplication=!0;if(r.deadLetterQueue&&a)c.RedrivePolicy={deadLetterTargetArn:a,maxReceiveCount:r.maxReceiveCount||3};if(e.addResource(i,"AWS::SQS::Queue",c,{dependsOn:r.deadLetterQueue?`${i}DLQ`:void 0,deletionPolicy:"Retain",updateReplacePolicy:"Retain"}),e.addResource(`${i}Policy`,"AWS::SQS::QueuePolicy",{Queues:[t.ref(i)],PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:["lambda.amazonaws.com","events.amazonaws.com","sns.amazonaws.com"]},Action:"sqs:SendMessage",Resource:t.getAtt(i,"Arn"),Condition:{ArnEquals:{"aws:SourceArn":t.sub("arn:aws:*:${AWS::Region}:${AWS::AccountId}:*")}}}]}},{dependsOn:i}),e.addOutputs({[`${i}Url`]:{Description:`${n} queue URL`,Value:t.ref(i),Export:{Name:t.sub(`\${AWS::StackName}-${n}-queue-url`)}},[`${i}Arn`]:{Description:`${n} queue ARN`,Value:t.getAtt(i,"Arn"),Export:{Name:t.sub(`\${AWS::StackName}-${n}-queue-arn`)}}}),r.deadLetterQueue)e.addOutputs({[`${i}DLQUrl`]:{Description:`${n} dead letter queue URL`,Value:t.ref(`${i}DLQ`),Export:{Name:t.sub(`\${AWS::StackName}-${n}-dlq-url`)}}})}function xn(e,n){if(n.certificate)gi(e,n.certificate);if(n.waf?.enabled)yi(e,n.waf);if(n.securityGroups)for(let[r,i]of Object.entries(n.securityGroups))fi(e,r,i)}function gi(e,n){if(!n)return;let r=[n.domain];if(n.subdomains)r.push(...n.subdomains);e.addResource("Certificate","AWS::CertificateManager::Certificate",{DomainName:n.domain,SubjectAlternativeNames:n.subdomains,ValidationMethod:n.validationMethod||"DNS",DomainValidationOptions:r.map((i)=>({DomainName:i,HostedZoneId:t.ref("HostedZone")})),Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-certificate")}]}),e.addOutputs({CertificateArn:{Description:"ACM Certificate ARN",Value:t.ref("Certificate"),Export:{Name:t.sub("${AWS::StackName}-certificate-arn")}}})}function yi(e,n){if(!n)return;let r=[],i=n.rules||["rateLimit","sqlInjection","xss"];if(i.includes("rateLimit"))r.push({Name:"RateLimitRule",Priority:1,Statement:{RateBasedStatement:{Limit:n.rateLimit||2000,AggregateKeyType:"IP"}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"RateLimitRule"}});let s=r.length+1;if(i.includes("sqlInjection"))r.push({Name:"AWSManagedRulesSQLi",Priority:s++,Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:"AWSManagedRulesSQLiRuleSet"}},OverrideAction:{None:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"AWSManagedRulesSQLi"}});if(i.includes("xss"))r.push({Name:"AWSManagedRulesXSS",Priority:s++,Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:"AWSManagedRulesKnownBadInputsRuleSet"}},OverrideAction:{None:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"AWSManagedRulesXSS"}});if(i.includes("knownBadInputs"))r.push({Name:"AWSManagedRulesKnownBadInputs",Priority:s++,Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:"AWSManagedRulesKnownBadInputsRuleSet"}},OverrideAction:{None:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"AWSManagedRulesKnownBadInputs"}});if(i.includes("coreRuleSet"))r.push({Name:"AWSManagedRulesCoreRuleSet",Priority:s++,Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:"AWSManagedRulesCommonRuleSet"}},OverrideAction:{None:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"AWSManagedRulesCoreRuleSet"}});if(i.includes("linuxRuleSet"))r.push({Name:"AWSManagedRulesLinuxRuleSet",Priority:s++,Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:"AWSManagedRulesLinuxRuleSet"}},OverrideAction:{None:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"AWSManagedRulesLinuxRuleSet"}});if(i.includes("apiProtection"))r.push({Name:"AWSManagedRulesAPIProtection",Priority:s++,Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:"AWSManagedRulesAmazonIpReputationList"}},OverrideAction:{None:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"AWSManagedRulesAPIProtection"}});if(i.includes("geoBlock"))r.push({Name:"GeoBlockRule",Priority:s++,Statement:{GeoMatchStatement:{CountryCodes:["CN","RU"]}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"GeoBlockRule"}});if(i.includes("connectionLimit"))r.push({Name:"ConnectionLimitRule",Priority:s++,Statement:{RateBasedStatement:{Limit:100,AggregateKeyType:"IP"}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"ConnectionLimitRule"}});if(e.addResource("WebACL","AWS::WAFv2::WebACL",{Name:t.sub("${AWS::StackName}-waf"),Scope:n.scope||"REGIONAL",DefaultAction:{Allow:{}},Rules:r,VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:t.sub("${AWS::StackName}-waf")},Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-waf")}]}),e.hasResource("LoadBalancer"))e.addResource("WebACLAssociation","AWS::WAFv2::WebACLAssociation",{ResourceArn:t.ref("LoadBalancer"),WebACLArn:t.getAtt("WebACL","Arn")},{dependsOn:["WebACL","LoadBalancer"]});e.addOutputs({WebACLId:{Description:"WAF Web ACL ID",Value:t.ref("WebACL"),Export:{Name:t.sub("${AWS::StackName}-waf-id")}},WebACLArn:{Description:"WAF Web ACL ARN",Value:t.getAtt("WebACL","Arn"),Export:{Name:t.sub("${AWS::StackName}-waf-arn")}}})}function fi(e,n,r){if(!r)return;let i=e.toLogicalId(`${n}-security-group`),s=r.ingress?.map((c)=>({IpProtocol:c.protocol,FromPort:c.port,ToPort:c.port,CidrIp:c.cidr,SourceSecurityGroupId:c.source?t.ref(c.source):void 0}))||[],a=r.egress?.map((c)=>({IpProtocol:c.protocol,FromPort:c.port,ToPort:c.port,CidrIp:c.cidr||"0.0.0.0/0"}))||[{IpProtocol:"-1",CidrIp:"0.0.0.0/0"}];e.addResource(i,"AWS::EC2::SecurityGroup",{GroupDescription:`Security group for ${n}`,VpcId:t.ref("VPC"),SecurityGroupIngress:s,SecurityGroupEgress:a,Tags:[{Key:"Name",Value:t.sub(`\${AWS::StackName}-${n}-sg`)}]},{dependsOn:"VPC"}),e.addOutputs({[`${i}Id`]:{Description:`${n} security group ID`,Value:t.ref(i),Export:{Name:t.sub(`\${AWS::StackName}-${n}-sg-id`)}}})}function Mn(e,n){for(let[r,i]of Object.entries(n)){if(i.type==="efs"){bi(e,r,i);continue}hi(e,r,i)}}function hi(e,n,r){let i=e.toLogicalId(`${n}-bucket`),s={BucketName:t.sub(`\${AWS::StackName}-${n}`),Tags:[{Key:"Name",Value:t.sub(`\${AWS::StackName}-${n}`)}]};if(r.versioning)s.VersioningConfiguration={Status:"Enabled"};if(r.encryption)s.BucketEncryption={ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]};if(!r.public)s.PublicAccessBlockConfiguration={BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0};if(r.website)s.WebsiteConfiguration={IndexDocument:"index.html",ErrorDocument:"index.html"};if(r.cors&&r.cors.length>0)s.CorsConfiguration={CorsRules:r.cors.map((a)=>({AllowedOrigins:a.allowedOrigins,AllowedMethods:a.allowedMethods,AllowedHeaders:a.allowedHeaders||["*"],MaxAge:a.maxAge||3600}))};if(r.lifecycleRules&&r.lifecycleRules.length>0)s.LifecycleConfiguration={Rules:r.lifecycleRules.map((a)=>({Id:a.id,Status:a.enabled?"Enabled":"Disabled",ExpirationInDays:a.expirationDays,Transitions:a.transitions?.map((c)=>({TransitionInDays:c.days,StorageClass:c.storageClass}))}))};if(r.intelligentTiering)s.IntelligentTieringConfigurations=[{Id:"EntireBucket",Status:"Enabled",Tierings:[{AccessTier:"ARCHIVE_ACCESS",Days:90},{AccessTier:"DEEP_ARCHIVE_ACCESS",Days:180}]}];if(e.addResource(i,"AWS::S3::Bucket",s,{deletionPolicy:r.versioning?"Retain":"Delete"}),r.public)e.addResource(`${i}Policy`,"AWS::S3::BucketPolicy",{Bucket:t.ref(i),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadGetObject",Effect:"Allow",Principal:"*",Action:"s3:GetObject",Resource:t.join("",[Rn.s3Bucket(t.ref(i)),"/*"])}]}},{dependsOn:i});if(e.addOutputs({[`${i}Name`]:{Description:`${n} bucket name`,Value:t.ref(i),Export:{Name:t.sub(`\${AWS::StackName}-${n}-bucket`)}},[`${i}Arn`]:{Description:`${n} bucket ARN`,Value:t.getAtt(i,"Arn"),Export:{Name:t.sub(`\${AWS::StackName}-${n}-bucket-arn`)}}}),r.website)e.addOutputs({[`${i}WebsiteURL`]:{Description:`${n} website URL`,Value:t.getAtt(i,"WebsiteURL")}})}function bi(e,n,r){let i=e.toLogicalId(`${n}-efs`),s={Encrypted:r.encryption!==!1,PerformanceMode:r.performanceMode||"generalPurpose",ThroughputMode:r.throughputMode||"bursting",FileSystemTags:[{Key:"Name",Value:t.sub(`\${AWS::StackName}-${n}`)}]};if(r.lifecyclePolicy){if(s.LifecyclePolicies=[],r.lifecyclePolicy.transitionToIA)s.LifecyclePolicies.push({TransitionToIA:`AFTER_${r.lifecyclePolicy.transitionToIA}_DAYS`});if(r.lifecyclePolicy.transitionToPrimaryStorageClass)s.LifecyclePolicies.push({TransitionToPrimaryStorageClass:"AFTER_1_ACCESS"})}e.addResource(i,"AWS::EFS::FileSystem",s,{deletionPolicy:"Retain"});let a=2;for(let c=0;c<a;c++)e.addResource(`${i}MountTarget${c+1}`,"AWS::EFS::MountTarget",{FileSystemId:t.ref(i),SubnetId:t.ref(`PrivateSubnet${c+1}`),SecurityGroups:[t.ref("EFSSecurityGroup")]},{dependsOn:[i,`PrivateSubnet${c+1}`]});e.addResource("EFSSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for EFS mount targets",VpcId:t.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:2049,ToPort:2049,SourceSecurityGroupId:t.ref("AppSecurityGroup")}],Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-efs-sg")}]},{dependsOn:"VPC"}),e.addOutputs({[`${i}Id`]:{Description:`${n} EFS file system ID`,Value:t.ref(i),Export:{Name:t.sub(`\${AWS::StackName}-${n}-efs`)}}})}class gl{template;config;resourceDependencies;constructor(e){this.config=e,this.resourceDependencies=new Map,this.template={AWSTemplateFormatVersion:"2010-09-09",Description:`Infrastructure for ${e.project.name} (${e.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:t.equals(t.ref("Environment"),"production"),HasDomain:t.not([t.equals(this.config.environments?.production?.domain||"","")])}}addResources(){let{infrastructure:e}=this.config;if(!e)return;if(e.network)this.addNetworkResources(e.network);if(e.storage)this.addStorageResources(e.storage);if(e.compute)this.addComputeResources(e.compute);if(e.databases)this.addDatabaseResources(e.databases);if(e.cache)this.addCacheResources(e.cache);if(e.cdn)this.addCDNResources(e.cdn);if(e.apiGateway)this.addApiGatewayResources(e.apiGateway);if(e.functions)this.addFunctionResources(e.functions);if(e.queues)this.addQueueResources(e.queues);if(e.messaging)this.addMessagingResources(e.messaging);if(e.monitoring)this.addMonitoringResources(e.monitoring);if(e.security)this.addSecurityResources(e.security)}initializeOutputs(){let e=this.template.Outputs||{};if(this.template.Outputs={StackName:{Description:"Stack name",Value:t.ref("AWS::StackName"),Export:{Name:t.sub("${AWS::StackName}-Name")}},Region:{Description:"AWS Region",Value:t.ref("AWS::Region"),Export:{Name:t.sub("${AWS::StackName}-Region")}},...e},this.config.environments?.production?.domain)this.template.Outputs.Domain={Description:"Production domain",Value:this.config.environments.production.domain,Condition:"HasDomain"}}addResource(e,n,r,i){let s={Type:n,Properties:r};if(i?.dependsOn)s.DependsOn=i.dependsOn,this.trackDependency(e,i.dependsOn);if(i?.condition)s.Condition=i.condition;if(i?.deletionPolicy)s.DeletionPolicy=i.deletionPolicy;if(i?.updateReplacePolicy)s.UpdateReplacePolicy=i.updateReplacePolicy;this.template.Resources[e]=s}addOutputs(e){this.template.Outputs={...this.template.Outputs,...e}}getOutputs(){return this.template.Outputs||{}}hasResource(e){return e in this.template.Resources}getResource(e){return this.template.Resources[e]}trackDependency(e,n){if(!this.resourceDependencies.has(e))this.resourceDependencies.set(e,new Set);(Array.isArray(n)?n:[n]).forEach((i)=>this.resourceDependencies.get(e).add(i))}resolveDependencies(){let e=new Set,n=new Set,r=(i)=>{if(n.has(i))throw Error(`Circular dependency detected involving resource: ${i}`);if(e.has(i))return!0;e.add(i),n.add(i);let s=this.resourceDependencies.get(i);if(s)for(let a of s)r(a);return n.delete(i),!0};for(let i of this.resourceDependencies.keys())r(i)}toLogicalId(e){return e.split(/[-_\s]/).map((n)=>n.charAt(0).toUpperCase()+n.slice(1).toLowerCase()).join("")}addNetworkResources(e){vn(this,e)}addStorageResources(e){Mn(this,e)}addComputeResources(e){yn(this,e)}addDatabaseResources(e){hn(this,e)}addFunctionResources(e){bn(this,e)}addCacheResources(e){mn(this,e)}addQueueResources(e){Tn(this,e)}addMessagingResources(e){Sn(this,e)}addCDNResources(e){pn(this,e)}addApiGatewayResources(e){dn(this,e)}addMonitoringResources(e){Cn(this,e)}addSecurityResources(e){xn(this,e)}}function Ia(e){return new gl(e).build()}function _m(e){let{name:n,slug:r,domain:i,subdomain:s}=e;return{project:{name:n,slug:r,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:s&&i?`${s}.${i}`:i}},infrastructure:{storage:{assets:{public:!0,versioning:!1,website:!0,encryption:!1,cors:[{allowedOrigins:["*"],allowedMethods:["GET","HEAD"],allowedHeaders:["*"],maxAge:3600}]}},cdn:{enabled:!0,customDomain:i?{domain:s&&i?`${s}.${i}`:i,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 Om(e){let{name:n,slug:r,domain:i,instanceType:s="t3.small",minInstances:a=2,maxInstances:c=10}=e;return{project:{name:n,slug:r,region:"us-east-1"},mode:"server",environments:{production:{type:"production",domain:i}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:2,natGateways:1}},compute:{server:{instanceType:s,ami:"ubuntu-22.04",keyPair:`${r}-key`,autoScaling:{min:a,max:c,desired:a,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:i?{domain:i,subdomains:[`*.${i}`],validationMethod:"DNS"}:void 0}}}}function $m(e){let{name:n,slug:r,domain:i,taskCpu:s="256",taskMemory:a="512",desiredCount:c=2}=e;return{project:{name:n,slug:r,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:i}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:2,natGateways:0}},compute:{fargate:{taskDefinition:{cpu:s,memory:a,containerDefinitions:[{name:"app",image:`${r}-app:latest`,portMappings:[{containerPort:3000}],environment:[],secrets:[]}]},service:{desiredCount:c,healthCheck:{path:"/health",interval:30,timeout:5,healthyThreshold:2,unhealthyThreshold:3},autoScaling:{min:c,max:c*5,targetCPU:70,targetMemory:80}},loadBalancer:{type:"application"}}},databases:{dynamodb:{tables:{[`${r}-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:`${r}-queue`}]}},security:{certificate:i?{domain:i,subdomains:[`*.${i}`],validationMethod:"DNS"}:void 0}}}}function Lm(e){let{name:n,slug:r,entry:i,domain:s,runtime:a="nodejs20.x",memory:c=1024,build:u,deploy:d,assets:m,queues:p=!0,scheduler:g="on",region:y="us-east-1"}=e;return{project:{name:n,slug:r,region:y},mode:"serverless",environments:{production:{type:"production",domain:s,app:{kind:"node",runtime:a,entry:i,memory:c,build:u,deploy:d,assets:m,queues:p,scheduler:g,domain:s}}}}}function Pa(e){let n=e.database!==!1,r=e.cache!==!1,i=e.queue!==!1;return{project:{name:e.name,slug:e.slug,region:"us-east-1"},mode:"server",environments:{production:{type:"production",domain:e.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:e.imageUri,portMappings:[{containerPort:3000}],environment:[{name:"NODE_ENV",value:"production"},{name:"PORT",value:"3000"},{name:"AWS_REGION",value:t.ref("AWS::Region")},...n?[{name:"DB_HOST",value:t.getAtt("PostgresDb","Endpoint.Address")},{name:"DB_PORT",value:t.getAtt("PostgresDb","Endpoint.Port")}]:[],...r?[{name:"REDIS_HOST",value:t.getAtt("RedisReplicationGroup","PrimaryEndPoint.Address")},{name:"REDIS_PORT",value:t.getAtt("RedisReplicationGroup","PrimaryEndPoint.Port")},{name:"REDIS_TLS",value:"true"}]:[],...i?[{name:"QUEUE_URL",value:t.ref("JobsQueue")}]:[],{name:"MAIL_TRANSPORT",value:"ses"}],secrets:n?[{name:"DB_USERNAME",valueFrom:t.sub("${DBSecret}:username::")},{name:"DB_PASSWORD",valueFrom:t.sub("${DBSecret}:password::")}]:[]}]},service:{desiredCount:e.desiredCount||1,healthCheck:{path:"/api/health",interval:30,timeout:5},autoScaling:{min:e.desiredCount||1,max:6,targetCPU:70}},loadBalancer:{type:"application",...e.certificateArn?{customDomain:{domain:e.domain,certificateArn:e.certificateArn}}:{},...e.originVerifySecret?{originVerifyHeader:{name:"X-Origin-Verify",value:e.originVerifySecret}}:{}}}},...n?{databases:{postgres:{engine:"postgres",version:"16",instanceClass:"db.t4g.micro",allocatedStorage:20,maxAllocatedStorage:100,multiAZ:!1,backupRetentionDays:7,deletionProtection:!0}}}:{},...r?{cache:{redis:{nodeType:"cache.t4g.micro",numCacheNodes:2,engine:"redis",engineVersion:"7.1",automaticFailoverEnabled:!0,snapshotRetentionLimit:5}}}:{},...i?{queues:{jobs:{fifo:!1,visibilityTimeout:300,messageRetentionPeriod:345600,deadLetterQueue:!0,maxReceiveCount:3,receiveMessageWaitTime:20}}}:{}}}}function Mm(e){let{name:n,slug:r,domain:i,apiSubdomain:s="api"}=e;return{project:{name:n,slug:r,region:"us-east-1"},mode:"server",environments:{production:{type:"production",domain:i}},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:i,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:`${r}-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:`${s}.${i}`,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:i,subdomains:[`*.${i}`],validationMethod:"DNS"},waf:{enabled:!0,rules:["rateLimit","sqlInjection","xss"]}}}}}function Um(e){let{name:n,slug:r,domain:i}=e;return{project:{name:n,slug:r,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:i}},infrastructure:{apiGateway:{type:"HTTP",cors:{allowOrigins:["*"],allowMethods:["GET","POST","PUT","DELETE","PATCH"],allowHeaders:["Content-Type","Authorization"],maxAge:3600},customDomain:i?{domain:i,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:{[`${r}-users`]:{partitionKey:{name:"userId",type:"S"},billingMode:"PAY_PER_REQUEST",streamEnabled:!0,pointInTimeRecovery:!0,globalSecondaryIndexes:[{name:"EmailIndex",partitionKey:{name:"email",type:"S"},projection:"ALL"}]},[`${r}-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:i?{domain:i,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 Bm(e){let{name:n,slug:r,domain:i,instanceType:s="t3.small"}=e;return{project:{name:n,slug:r,region:"us-east-1"},mode:"server",environments:{production:{type:"production",domain:i}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:2,natGateways:1}},compute:{server:{instanceType:s,ami:"ubuntu-22.04",keyPair:`${r}-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:i,certificateArn:"TO_BE_GENERATED"},cachePolicy:{minTTL:0,defaultTTL:86400,maxTTL:31536000},compress:!0,origins:[{type:"alb",pathPattern:"/wp-content/*"}]},security:{certificate:{domain:i,subdomains:[`www.${i}`],validationMethod:"DNS"},waf:{enabled:!0,rules:["rateLimit","sqlInjection","xss","wordpressRules"]}}}}}function Fm(e){let{name:n,slug:r,domain:i,apiDomain:s}=e;return{project:{name:n,slug:r,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:i}},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:i,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},...s?{api:{runtime:"nodejs20.x",handler:"dist/api/index.handler",memory:1024,timeout:30,events:[{type:"http",path:"/{proxy+}",method:"ANY"}]}}:{}},apiGateway:s?{type:"HTTP",customDomain:{domain:s,certificateArn:"TO_BE_GENERATED"},cors:{allowOrigins:[i],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:i,subdomains:s?[s]:[],validationMethod:"DNS"},waf:{enabled:!0,rules:["rateLimit","geoBlock"]}}}}}function jm(e){let{name:n,slug:r,domain:i,services:s}=e;return{project:{name:n,slug:r,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:i}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:3,natGateways:2}},compute:{services:s.map((a)=>({name:a.name,type:"fargate",taskDefinition:{cpu:a.cpu||"256",memory:a.memory||"512",containerDefinitions:[{name:a.name,image:`${r}-${a.name}:latest`,portMappings:[{containerPort:a.port}],healthCheck:{command:["CMD-SHELL",`curl -f http://localhost:${a.port}/health || exit 1`],interval:30,timeout:5,retries:3}}]},service:{desiredCount:a.desiredCount||2,serviceDiscovery:{enabled:!0,namespace:`${r}.local`},autoScaling:{min:2,max:10,targetCPU:70}}}))},apiGateway:{type:"HTTP",customDomain:{domain:i,certificateArn:"TO_BE_GENERATED"},cors:{allowOrigins:["*"],allowMethods:["GET","POST","PUT","DELETE","PATCH"]},routes:s.map((a)=>({path:`/${a.name}/{proxy+}`,integration:{type:"vpc-link",service:a.name}}))},databases:{dynamodb:{tables:Object.fromEntries(s.map((a)=>[`${r}-${a.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:`${r}-events`,subscriptions:s.map((a)=>({protocol:"sqs",endpoint:`${r}-${a.name}-queue`,filterPolicy:{service:[a.name]}}))}}},monitoring:{dashboard:{name:`${r}-microservices`,widgets:s.map((a)=>({type:"metric",metrics:[{service:a.name,metric:"CPUUtilization"},{service:a.name,metric:"MemoryUtilization"},{service:a.name,metric:"RequestCount"}]}))},alarms:s.flatMap((a)=>[{name:`${a.name}-high-cpu`,metric:"CPUUtilization",threshold:80,service:a.name},{name:`${a.name}-errors`,metric:"Errors",threshold:10,service:a.name}])},security:{certificate:{domain:i,validationMethod:"DNS"},waf:{enabled:!0,rules:["rateLimit","sqlInjection"]}}}}}function Vm(e){let{name:n,slug:r,domain:i}=e;return{project:{name:n,slug:r,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:i}},infrastructure:{apiGateway:{type:"websocket",customDomain:i?{domain:i,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:`${r}-messages`,startingPosition:"LATEST",batchSize:100}]}},databases:{dynamodb:{tables:{[`${r}-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"}]},[`${r}-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"}]},[`${r}-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:`${r}-realtime`,widgets:[{type:"metric",metrics:["WebSocketConnections","MessagesSent","IntegrationLatency"]}]}},security:{certificate:i?{domain:i,validationMethod:"DNS"}:void 0,waf:{enabled:!0,rules:["rateLimit","connectionLimit"]}}}}}function zm(e){let{name:n,slug:r,retentionDays:i=7}=e;return{project:{name:n,slug:r,region:"us-east-1"},mode:"serverless",infrastructure:{streaming:{dataStream:{name:`${r}-stream`,shardCount:2,retentionPeriod:i*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:`${r}-stream`,batchSize:1000,startingPosition:"LATEST",parallelizationFactor:10}]},transformer:{runtime:"nodejs20.x",handler:"dist/processors/transform.handler",memory:3008,timeout:900,events:[{type:"s3",bucket:`${r}-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:`${r}_analytics`,workgroup:`${r}-workgroup`,outputBucket:`${r}-query-results`,tables:[{name:"raw_events",location:`s3://${r}-raw/events/`,format:"parquet",partitionKeys:["year","month","day"]},{name:"processed_events",location:`s3://${r}-processed/events/`,format:"parquet",partitionKeys:["year","month","day"]}]},glue:{crawlers:[{name:`${r}-crawler`,databaseName:`${r}_analytics`,s3Targets:[`s3://${r}-raw/`,`s3://${r}-processed/`],schedule:"cron(0 2 * * ? *)"}],jobs:[{name:`${r}-etl-job`,scriptLocation:`s3://${r}-scripts/etl.py`,role:`${r}-glue-role`,maxCapacity:10,timeout:120}]}},databases:{dynamodb:{tables:{[`${r}-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:`${r}-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:`${r}-pipeline`,widgets:[{type:"metric",metrics:["KinesisIncomingRecords","LambdaInvocations","S3ObjectsCreated","GlueJobsSucceeded"]}]},alarms:[{metric:"LambdaErrors",threshold:10,evaluationPeriods:1},{metric:"KinesisIteratorAge",threshold:60000,evaluationPeriods:2}]}}}}function Hm(e){let{name:n,slug:r,domain:i,modelS3Path:s=`s3://${r}-models/`,instanceType:a="ml.t3.medium"}=e;return{project:{name:n,slug:r,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:i}},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:`${r}-inference`,modelS3Path:s,instanceType:a,initialInstanceCount:1,autoScaling:{minInstances:1,maxInstances:5,targetInvocationsPerInstance:1000}}],trainingJobs:[{name:`${r}-training`,algorithmSpecification:{trainingImage:"TO_BE_SPECIFIED",trainingInputMode:"File"},instanceType:"ml.p3.2xlarge",instanceCount:1,volumeSizeInGB:50,maxRuntimeInSeconds:86400}]}},apiGateway:{type:"HTTP",customDomain:i?{domain:i,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:`${r}-inference`,MODEL_BUCKET:`${r}-models`}},"batch-predict":{runtime:"python3.11",handler:"handlers/batchPredict.handler",memory:3008,timeout:900,events:[{type:"s3",bucket:`${r}-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:{[`${r}-predictions`]:{partitionKey:{name:"requestId",type:"S"},sortKey:{name:"timestamp",type:"S"},billingMode:"PAY_PER_REQUEST",streamEnabled:!0},[`${r}-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:`${r}-ml`,widgets:[{type:"metric",metrics:["SageMakerInvocations","SageMakerModelLatency","APIGatewayRequests","LambdaErrors"]}]},alarms:[{metric:"SageMakerModelLatency",threshold:1000,evaluationPeriods:2},{metric:"SageMakerInvocationErrors",threshold:10,evaluationPeriods:1}]},security:{certificate:i?{domain:i,validationMethod:"DNS"}:void 0,waf:{enabled:!0,rules:["rateLimit","apiProtection"]}}}}}function Gm(e){let{name:n,slug:r,domain:i,instanceType:s="t3.medium",minInstances:a=2,maxInstances:c=10,databaseEngine:u="mysql",sessionStore:d="redis"}=e;return{project:{name:n,slug:r,region:"us-east-1"},mode:"server",environments:{production:{type:"production",domain:i}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:2,natGateways:2}},compute:{server:{instanceType:s,ami:"ubuntu-22.04",autoScaling:{min:a,max:c,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:t.ref("AWS::Region"),title:`Logs: ${a.logGroup}`}});else if(a.type==="text"&&a.text)r.push({type:"text",x:i,y:s,width:c,height:u,properties:{markdown:a.text}});if(i+=c,i>=24)i=0,s+=u}),e.addResource("CloudWatchDashboard","AWS::CloudWatch::Dashboard",{DashboardName:t.sub(`\${AWS::StackName}-${n.name}`),DashboardBody:JSON.stringify({widgets:r})}),e.addOutputs({DashboardURL:{Description:"CloudWatch Dashboard URL",Value:t.sub("https://console.aws.amazon.com/cloudwatch/home?region=${AWS::Region}#dashboards:name=${CloudWatchDashboard}")}})}function di(e,n,r){let i=e.toLogicalId(`${n}-log-group`);e.addResource(i,"AWS::Logs::LogGroup",{LogGroupName:t.sub(`/aws/\${AWS::StackName}/${n}`),RetentionInDays:r||14,Tags:[{Key:"Name",Value:t.sub(`\${AWS::StackName}-${n}`)}]})}function At(e,n){if(n)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"}[n.toLowerCase()]||"AWS/CloudWatch";let r=e.toLowerCase();if(r.includes("cpu")||r.includes("memory")||r.includes("network"))return"AWS/EC2";if(r.includes("lambda")||r.includes("invocation")||r.includes("duration"))return"AWS/Lambda";if(r.includes("request")||r.includes("latency")||r.includes("target"))return"AWS/ApplicationELB";if(r.includes("database")||r.includes("connection"))return"AWS/RDS";if(r.includes("read")||r.includes("write")||r.includes("consumed"))return"AWS/DynamoDB";return"AWS/CloudWatch"}function mi(e){return{ec2:[{Name:"InstanceId",Value:t.ref("EC2Instance")}],ecs:[{Name:"ClusterName",Value:t.ref("ECSCluster")},{Name:"ServiceName",Value:t.getAtt("ECSService","Name")}],lambda:[{Name:"FunctionName",Value:t.ref("LambdaFunction")}],rds:[{Name:"DBInstanceIdentifier",Value:t.ref("Database")}],dynamodb:[{Name:"TableName",Value:t.ref("DynamoDBTable")}],alb:[{Name:"LoadBalancer",Value:t.getAtt("LoadBalancer","LoadBalancerFullName")}],apigateway:[{Name:"ApiName",Value:t.ref("HttpApi")}]}[e.toLowerCase()]||[]}function Cn(e,n){if(!n.vpc)return;let{cidr:r="10.0.0.0/16",availabilityZones:i=2,natGateways:s=1,enableDnsHostnames:a=!0,enableDnsSupport:c=!0}=n.vpc;e.addResource("VPC","AWS::EC2::VPC",{CidrBlock:r,EnableDnsHostnames:a,EnableDnsSupport:c,Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-vpc")}]}),e.addResource("InternetGateway","AWS::EC2::InternetGateway",{Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-igw")}]}),e.addResource("VPCGatewayAttachment","AWS::EC2::VPCGatewayAttachment",{VpcId:t.ref("VPC"),InternetGatewayId:t.ref("InternetGateway")},{dependsOn:["VPC","InternetGateway"]});let u=[];for(let g=0;g<i;g++){let y=`PublicSubnet${g+1}`;u.push(y),e.addResource(y,"AWS::EC2::Subnet",{VpcId:t.ref("VPC"),CidrBlock:t.select(g,t.cidr(t.getAtt("VPC","CidrBlock"),i*2,8)),AvailabilityZone:t.select(g,t.getAZs()),MapPublicIpOnLaunch:!0,Tags:[{Key:"Name",Value:t.sub(`\${AWS::StackName}-public-${g+1}`)},{Key:"Type",Value:"public"}]},{dependsOn:"VPC"})}let d=[];for(let g=0;g<i;g++){let y=`PrivateSubnet${g+1}`;d.push(y),e.addResource(y,"AWS::EC2::Subnet",{VpcId:t.ref("VPC"),CidrBlock:t.select(g+i,t.cidr(t.getAtt("VPC","CidrBlock"),i*2,8)),AvailabilityZone:t.select(g,t.getAZs()),MapPublicIpOnLaunch:!1,Tags:[{Key:"Name",Value:t.sub(`\${AWS::StackName}-private-${g+1}`)},{Key:"Type",Value:"private"}]},{dependsOn:"VPC"})}let m=[];for(let g=0;g<s;g++){let y=`NatEIP${g+1}`;m.push(y),e.addResource(y,"AWS::EC2::EIP",{Domain:"vpc",Tags:[{Key:"Name",Value:t.sub(`\${AWS::StackName}-nat-eip-${g+1}`)}]},{dependsOn:"VPCGatewayAttachment"})}let p=[];for(let g=0;g<s;g++){let y=`NatGateway${g+1}`;p.push(y);let f=g%i;e.addResource(y,"AWS::EC2::NatGateway",{AllocationId:t.getAtt(m[g],"AllocationId"),SubnetId:t.ref(u[f]),Tags:[{Key:"Name",Value:t.sub(`\${AWS::StackName}-nat-${g+1}`)}]},{dependsOn:[m[g],u[f]]})}e.addResource("PublicRouteTable","AWS::EC2::RouteTable",{VpcId:t.ref("VPC"),Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-public-rt")}]},{dependsOn:"VPC"}),e.addResource("PublicRoute","AWS::EC2::Route",{RouteTableId:t.ref("PublicRouteTable"),DestinationCidrBlock:"0.0.0.0/0",GatewayId:t.ref("InternetGateway")},{dependsOn:["PublicRouteTable","VPCGatewayAttachment"]}),u.forEach((g,y)=>{e.addResource(`PublicSubnetRouteTableAssociation${y+1}`,"AWS::EC2::SubnetRouteTableAssociation",{SubnetId:t.ref(g),RouteTableId:t.ref("PublicRouteTable")},{dependsOn:[g,"PublicRouteTable"]})}),d.forEach((g,y)=>{let f=`PrivateRouteTable${y+1}`,h=y%s;e.addResource(f,"AWS::EC2::RouteTable",{VpcId:t.ref("VPC"),Tags:[{Key:"Name",Value:t.sub(`\${AWS::StackName}-private-rt-${y+1}`)}]},{dependsOn:"VPC"}),e.addResource(`PrivateRoute${y+1}`,"AWS::EC2::Route",{RouteTableId:t.ref(f),DestinationCidrBlock:"0.0.0.0/0",NatGatewayId:t.ref(p[h])},{dependsOn:[f,p[h]]}),e.addResource(`PrivateSubnetRouteTableAssociation${y+1}`,"AWS::EC2::SubnetRouteTableAssociation",{SubnetId:t.ref(g),RouteTableId:t.ref(f)},{dependsOn:[g,f]})}),e.addResource("S3VPCEndpoint","AWS::EC2::VPCEndpoint",{VpcId:t.ref("VPC"),ServiceName:t.sub("com.amazonaws.${AWS::Region}.s3"),VpcEndpointType:"Gateway",RouteTableIds:[t.ref("PublicRouteTable"),...Array.from({length:i},(g,y)=>t.ref(`PrivateRouteTable${y+1}`))]},{dependsOn:"VPC"}),e.addResource("NetworkAcl","AWS::EC2::NetworkAcl",{VpcId:t.ref("VPC"),Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-nacl")}]},{dependsOn:"VPC"}),e.addResource("NetworkAclEntryInbound","AWS::EC2::NetworkAclEntry",{NetworkAclId:t.ref("NetworkAcl"),RuleNumber:100,Protocol:-1,RuleAction:"allow",CidrBlock:"0.0.0.0/0"},{dependsOn:"NetworkAcl"}),e.addResource("NetworkAclEntryOutbound","AWS::EC2::NetworkAclEntry",{NetworkAclId:t.ref("NetworkAcl"),RuleNumber:100,Protocol:-1,Egress:!0,RuleAction:"allow",CidrBlock:"0.0.0.0/0"},{dependsOn:"NetworkAcl"}),e.addOutputs({VPCId:{Description:"VPC ID",Value:t.ref("VPC"),Export:{Name:t.sub("${AWS::StackName}-VPC")}},PublicSubnets:{Description:"Public subnet IDs",Value:t.join(",",u.map((g)=>t.ref(g))),Export:{Name:t.sub("${AWS::StackName}-PublicSubnets")}},PrivateSubnets:{Description:"Private subnet IDs",Value:t.join(",",d.map((g)=>t.ref(g))),Export:{Name:t.sub("${AWS::StackName}-PrivateSubnets")}}})}function vn(e,n){for(let[r,i]of Object.entries(n))pi(e,r,i)}function pi(e,n,r){let i=e.toLogicalId(`${n}-queue`),s=r.fifo||!1,a;if(r.deadLetterQueue){let u=`${i}DLQ`;e.addResource(u,"AWS::SQS::Queue",{QueueName:s?t.sub(`\${AWS::StackName}-${n}-dlq.fifo`):t.sub(`\${AWS::StackName}-${n}-dlq`),FifoQueue:s,MessageRetentionPeriod:1209600,Tags:[{Key:"Name",Value:t.sub(`\${AWS::StackName}-${n}-dlq`)}]},{deletionPolicy:"Retain",updateReplacePolicy:"Retain"}),a=t.getAtt(u,"Arn")}let c={QueueName:s?t.sub(`\${AWS::StackName}-${n}.fifo`):t.sub(`\${AWS::StackName}-${n}`),FifoQueue:s,VisibilityTimeout:r.visibilityTimeout||30,MessageRetentionPeriod:r.messageRetentionPeriod||345600,ReceiveMessageWaitTimeSeconds:r.receiveMessageWaitTime||0,Tags:[{Key:"Name",Value:t.sub(`\${AWS::StackName}-${n}`)}]};if(s&&r.contentBasedDeduplication)c.ContentBasedDeduplication=!0;if(r.deadLetterQueue&&a)c.RedrivePolicy={deadLetterTargetArn:a,maxReceiveCount:r.maxReceiveCount||3};if(e.addResource(i,"AWS::SQS::Queue",c,{dependsOn:r.deadLetterQueue?`${i}DLQ`:void 0,deletionPolicy:"Retain",updateReplacePolicy:"Retain"}),e.addResource(`${i}Policy`,"AWS::SQS::QueuePolicy",{Queues:[t.ref(i)],PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:["lambda.amazonaws.com","events.amazonaws.com","sns.amazonaws.com"]},Action:"sqs:SendMessage",Resource:t.getAtt(i,"Arn"),Condition:{ArnEquals:{"aws:SourceArn":t.sub("arn:aws:*:${AWS::Region}:${AWS::AccountId}:*")}}}]}},{dependsOn:i}),e.addOutputs({[`${i}Url`]:{Description:`${n} queue URL`,Value:t.ref(i),Export:{Name:t.sub(`\${AWS::StackName}-${n}-queue-url`)}},[`${i}Arn`]:{Description:`${n} queue ARN`,Value:t.getAtt(i,"Arn"),Export:{Name:t.sub(`\${AWS::StackName}-${n}-queue-arn`)}}}),r.deadLetterQueue)e.addOutputs({[`${i}DLQUrl`]:{Description:`${n} dead letter queue URL`,Value:t.ref(`${i}DLQ`),Export:{Name:t.sub(`\${AWS::StackName}-${n}-dlq-url`)}}})}function Tn(e,n){if(n.certificate)gi(e,n.certificate);if(n.waf?.enabled)yi(e,n.waf);if(n.securityGroups)for(let[r,i]of Object.entries(n.securityGroups))fi(e,r,i)}function gi(e,n){if(!n)return;let r=[n.domain];if(n.subdomains)r.push(...n.subdomains);e.addResource("Certificate","AWS::CertificateManager::Certificate",{DomainName:n.domain,SubjectAlternativeNames:n.subdomains,ValidationMethod:n.validationMethod||"DNS",DomainValidationOptions:r.map((i)=>({DomainName:i,HostedZoneId:t.ref("HostedZone")})),Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-certificate")}]}),e.addOutputs({CertificateArn:{Description:"ACM Certificate ARN",Value:t.ref("Certificate"),Export:{Name:t.sub("${AWS::StackName}-certificate-arn")}}})}function yi(e,n){if(!n)return;let r=[],i=n.rules||["rateLimit","sqlInjection","xss"];if(i.includes("rateLimit"))r.push({Name:"RateLimitRule",Priority:1,Statement:{RateBasedStatement:{Limit:n.rateLimit||2000,AggregateKeyType:"IP"}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"RateLimitRule"}});let s=r.length+1;if(i.includes("sqlInjection"))r.push({Name:"AWSManagedRulesSQLi",Priority:s++,Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:"AWSManagedRulesSQLiRuleSet"}},OverrideAction:{None:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"AWSManagedRulesSQLi"}});if(i.includes("xss"))r.push({Name:"AWSManagedRulesXSS",Priority:s++,Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:"AWSManagedRulesKnownBadInputsRuleSet"}},OverrideAction:{None:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"AWSManagedRulesXSS"}});if(i.includes("knownBadInputs"))r.push({Name:"AWSManagedRulesKnownBadInputs",Priority:s++,Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:"AWSManagedRulesKnownBadInputsRuleSet"}},OverrideAction:{None:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"AWSManagedRulesKnownBadInputs"}});if(i.includes("coreRuleSet"))r.push({Name:"AWSManagedRulesCoreRuleSet",Priority:s++,Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:"AWSManagedRulesCommonRuleSet"}},OverrideAction:{None:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"AWSManagedRulesCoreRuleSet"}});if(i.includes("linuxRuleSet"))r.push({Name:"AWSManagedRulesLinuxRuleSet",Priority:s++,Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:"AWSManagedRulesLinuxRuleSet"}},OverrideAction:{None:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"AWSManagedRulesLinuxRuleSet"}});if(i.includes("apiProtection"))r.push({Name:"AWSManagedRulesAPIProtection",Priority:s++,Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:"AWSManagedRulesAmazonIpReputationList"}},OverrideAction:{None:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"AWSManagedRulesAPIProtection"}});if(i.includes("geoBlock"))r.push({Name:"GeoBlockRule",Priority:s++,Statement:{GeoMatchStatement:{CountryCodes:["CN","RU"]}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"GeoBlockRule"}});if(i.includes("connectionLimit"))r.push({Name:"ConnectionLimitRule",Priority:s++,Statement:{RateBasedStatement:{Limit:100,AggregateKeyType:"IP"}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"ConnectionLimitRule"}});if(e.addResource("WebACL","AWS::WAFv2::WebACL",{Name:t.sub("${AWS::StackName}-waf"),Scope:n.scope||"REGIONAL",DefaultAction:{Allow:{}},Rules:r,VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:t.sub("${AWS::StackName}-waf")},Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-waf")}]}),e.hasResource("LoadBalancer"))e.addResource("WebACLAssociation","AWS::WAFv2::WebACLAssociation",{ResourceArn:t.ref("LoadBalancer"),WebACLArn:t.getAtt("WebACL","Arn")},{dependsOn:["WebACL","LoadBalancer"]});e.addOutputs({WebACLId:{Description:"WAF Web ACL ID",Value:t.ref("WebACL"),Export:{Name:t.sub("${AWS::StackName}-waf-id")}},WebACLArn:{Description:"WAF Web ACL ARN",Value:t.getAtt("WebACL","Arn"),Export:{Name:t.sub("${AWS::StackName}-waf-arn")}}})}function fi(e,n,r){if(!r)return;let i=e.toLogicalId(`${n}-security-group`),s=r.ingress?.map((c)=>({IpProtocol:c.protocol,FromPort:c.port,ToPort:c.port,CidrIp:c.cidr,SourceSecurityGroupId:c.source?t.ref(c.source):void 0}))||[],a=r.egress?.map((c)=>({IpProtocol:c.protocol,FromPort:c.port,ToPort:c.port,CidrIp:c.cidr||"0.0.0.0/0"}))||[{IpProtocol:"-1",CidrIp:"0.0.0.0/0"}];e.addResource(i,"AWS::EC2::SecurityGroup",{GroupDescription:`Security group for ${n}`,VpcId:t.ref("VPC"),SecurityGroupIngress:s,SecurityGroupEgress:a,Tags:[{Key:"Name",Value:t.sub(`\${AWS::StackName}-${n}-sg`)}]},{dependsOn:"VPC"}),e.addOutputs({[`${i}Id`]:{Description:`${n} security group ID`,Value:t.ref(i),Export:{Name:t.sub(`\${AWS::StackName}-${n}-sg-id`)}}})}function En(e,n){for(let[r,i]of Object.entries(n)){if(i.type==="efs"){bi(e,r,i);continue}hi(e,r,i)}}function hi(e,n,r){let i=e.toLogicalId(`${n}-bucket`),s={BucketName:t.sub(`\${AWS::StackName}-${n}`),Tags:[{Key:"Name",Value:t.sub(`\${AWS::StackName}-${n}`)}]};if(r.versioning)s.VersioningConfiguration={Status:"Enabled"};if(r.encryption)s.BucketEncryption={ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]};if(!r.public)s.PublicAccessBlockConfiguration={BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0};if(r.website)s.WebsiteConfiguration={IndexDocument:"index.html",ErrorDocument:"index.html"};if(r.cors&&r.cors.length>0)s.CorsConfiguration={CorsRules:r.cors.map((a)=>({AllowedOrigins:a.allowedOrigins,AllowedMethods:a.allowedMethods,AllowedHeaders:a.allowedHeaders||["*"],MaxAge:a.maxAge||3600}))};if(r.lifecycleRules&&r.lifecycleRules.length>0)s.LifecycleConfiguration={Rules:r.lifecycleRules.map((a)=>({Id:a.id,Status:a.enabled?"Enabled":"Disabled",ExpirationInDays:a.expirationDays,Transitions:a.transitions?.map((c)=>({TransitionInDays:c.days,StorageClass:c.storageClass}))}))};if(r.intelligentTiering)s.IntelligentTieringConfigurations=[{Id:"EntireBucket",Status:"Enabled",Tierings:[{AccessTier:"ARCHIVE_ACCESS",Days:90},{AccessTier:"DEEP_ARCHIVE_ACCESS",Days:180}]}];if(e.addResource(i,"AWS::S3::Bucket",s,{deletionPolicy:r.versioning?"Retain":"Delete"}),r.public)e.addResource(`${i}Policy`,"AWS::S3::BucketPolicy",{Bucket:t.ref(i),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadGetObject",Effect:"Allow",Principal:"*",Action:"s3:GetObject",Resource:t.join("",[In.s3Bucket(t.ref(i)),"/*"])}]}},{dependsOn:i});if(e.addOutputs({[`${i}Name`]:{Description:`${n} bucket name`,Value:t.ref(i),Export:{Name:t.sub(`\${AWS::StackName}-${n}-bucket`)}},[`${i}Arn`]:{Description:`${n} bucket ARN`,Value:t.getAtt(i,"Arn"),Export:{Name:t.sub(`\${AWS::StackName}-${n}-bucket-arn`)}}}),r.website)e.addOutputs({[`${i}WebsiteURL`]:{Description:`${n} website URL`,Value:t.getAtt(i,"WebsiteURL")}})}function bi(e,n,r){let i=e.toLogicalId(`${n}-efs`),s={Encrypted:r.encryption!==!1,PerformanceMode:r.performanceMode||"generalPurpose",ThroughputMode:r.throughputMode||"bursting",FileSystemTags:[{Key:"Name",Value:t.sub(`\${AWS::StackName}-${n}`)}]};if(r.lifecyclePolicy){if(s.LifecyclePolicies=[],r.lifecyclePolicy.transitionToIA)s.LifecyclePolicies.push({TransitionToIA:`AFTER_${r.lifecyclePolicy.transitionToIA}_DAYS`});if(r.lifecyclePolicy.transitionToPrimaryStorageClass)s.LifecyclePolicies.push({TransitionToPrimaryStorageClass:"AFTER_1_ACCESS"})}e.addResource(i,"AWS::EFS::FileSystem",s,{deletionPolicy:"Retain"});let a=2;for(let c=0;c<a;c++)e.addResource(`${i}MountTarget${c+1}`,"AWS::EFS::MountTarget",{FileSystemId:t.ref(i),SubnetId:t.ref(`PrivateSubnet${c+1}`),SecurityGroups:[t.ref("EFSSecurityGroup")]},{dependsOn:[i,`PrivateSubnet${c+1}`]});e.addResource("EFSSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for EFS mount targets",VpcId:t.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:2049,ToPort:2049,SourceSecurityGroupId:t.ref("AppSecurityGroup")}],Tags:[{Key:"Name",Value:t.sub("${AWS::StackName}-efs-sg")}]},{dependsOn:"VPC"}),e.addOutputs({[`${i}Id`]:{Description:`${n} EFS file system ID`,Value:t.ref(i),Export:{Name:t.sub(`\${AWS::StackName}-${n}-efs`)}}})}class gl{template;config;resourceDependencies;constructor(e){this.config=e,this.resourceDependencies=new Map,this.template={AWSTemplateFormatVersion:"2010-09-09",Description:`Infrastructure for ${e.project.name} (${e.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:t.equals(t.ref("Environment"),"production"),HasDomain:t.not([t.equals(this.config.environments?.production?.domain||"","")])}}addResources(){let{infrastructure:e}=this.config;if(!e)return;if(e.network)this.addNetworkResources(e.network);if(e.storage)this.addStorageResources(e.storage);if(e.compute)this.addComputeResources(e.compute);if(e.databases)this.addDatabaseResources(e.databases);if(e.cache)this.addCacheResources(e.cache);if(e.cdn)this.addCDNResources(e.cdn);if(e.apiGateway)this.addApiGatewayResources(e.apiGateway);if(e.functions)this.addFunctionResources(e.functions);if(e.queues)this.addQueueResources(e.queues);if(e.messaging)this.addMessagingResources(e.messaging);if(e.monitoring)this.addMonitoringResources(e.monitoring);if(e.security)this.addSecurityResources(e.security)}initializeOutputs(){let e=this.template.Outputs||{};if(this.template.Outputs={StackName:{Description:"Stack name",Value:t.ref("AWS::StackName"),Export:{Name:t.sub("${AWS::StackName}-Name")}},Region:{Description:"AWS Region",Value:t.ref("AWS::Region"),Export:{Name:t.sub("${AWS::StackName}-Region")}},...e},this.config.environments?.production?.domain)this.template.Outputs.Domain={Description:"Production domain",Value:this.config.environments.production.domain,Condition:"HasDomain"}}addResource(e,n,r,i){let s={Type:n,Properties:r};if(i?.dependsOn)s.DependsOn=i.dependsOn,this.trackDependency(e,i.dependsOn);if(i?.condition)s.Condition=i.condition;if(i?.deletionPolicy)s.DeletionPolicy=i.deletionPolicy;if(i?.updateReplacePolicy)s.UpdateReplacePolicy=i.updateReplacePolicy;this.template.Resources[e]=s}addOutputs(e){this.template.Outputs={...this.template.Outputs,...e}}getOutputs(){return this.template.Outputs||{}}hasResource(e){return e in this.template.Resources}getResource(e){return this.template.Resources[e]}trackDependency(e,n){if(!this.resourceDependencies.has(e))this.resourceDependencies.set(e,new Set);(Array.isArray(n)?n:[n]).forEach((i)=>this.resourceDependencies.get(e).add(i))}resolveDependencies(){let e=new Set,n=new Set,r=(i)=>{if(n.has(i))throw Error(`Circular dependency detected involving resource: ${i}`);if(e.has(i))return!0;e.add(i),n.add(i);let s=this.resourceDependencies.get(i);if(s)for(let a of s)r(a);return n.delete(i),!0};for(let i of this.resourceDependencies.keys())r(i)}toLogicalId(e){return e.split(/[-_\s]/).map((n)=>n.charAt(0).toUpperCase()+n.slice(1).toLowerCase()).join("")}addNetworkResources(e){Cn(this,e)}addStorageResources(e){En(this,e)}addComputeResources(e){gn(this,e)}addDatabaseResources(e){fn(this,e)}addFunctionResources(e){hn(this,e)}addCacheResources(e){dn(this,e)}addQueueResources(e){vn(this,e)}addMessagingResources(e){bn(this,e)}addCDNResources(e){mn(this,e)}addApiGatewayResources(e){un(this,e)}addMonitoringResources(e){Sn(this,e)}addSecurityResources(e){Tn(this,e)}}function Ia(e){return new gl(e).build()}function _m(e){let{name:n,slug:r,domain:i,subdomain:s}=e;return{project:{name:n,slug:r,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:s&&i?`${s}.${i}`:i}},infrastructure:{storage:{assets:{public:!0,versioning:!1,website:!0,encryption:!1,cors:[{allowedOrigins:["*"],allowedMethods:["GET","HEAD"],allowedHeaders:["*"],maxAge:3600}]}},cdn:{enabled:!0,customDomain:i?{domain:s&&i?`${s}.${i}`:i,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 Om(e){let{name:n,slug:r,domain:i,instanceType:s="t3.small",minInstances:a=2,maxInstances:c=10}=e;return{project:{name:n,slug:r,region:"us-east-1"},mode:"server",environments:{production:{type:"production",domain:i}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:2,natGateways:1}},compute:{server:{instanceType:s,ami:"ubuntu-22.04",keyPair:`${r}-key`,autoScaling:{min:a,max:c,desired:a,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:i?{domain:i,subdomains:[`*.${i}`],validationMethod:"DNS"}:void 0}}}}function $m(e){let{name:n,slug:r,domain:i,taskCpu:s="256",taskMemory:a="512",desiredCount:c=2}=e;return{project:{name:n,slug:r,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:i}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:2,natGateways:0}},compute:{fargate:{taskDefinition:{cpu:s,memory:a,containerDefinitions:[{name:"app",image:`${r}-app:latest`,portMappings:[{containerPort:3000}],environment:[],secrets:[]}]},service:{desiredCount:c,healthCheck:{path:"/health",interval:30,timeout:5,healthyThreshold:2,unhealthyThreshold:3},autoScaling:{min:c,max:c*5,targetCPU:70,targetMemory:80}},loadBalancer:{type:"application"}}},databases:{dynamodb:{tables:{[`${r}-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:`${r}-queue`}]}},security:{certificate:i?{domain:i,subdomains:[`*.${i}`],validationMethod:"DNS"}:void 0}}}}function Lm(e){let{name:n,slug:r,entry:i,domain:s,runtime:a="nodejs20.x",memory:c=1024,build:u,deploy:d,assets:m,queues:p=!0,scheduler:g="on",region:y="us-east-1"}=e;return{project:{name:n,slug:r,region:y},mode:"serverless",environments:{production:{type:"production",domain:s,app:{kind:"node",runtime:a,entry:i,memory:c,build:u,deploy:d,assets:m,queues:p,scheduler:g,domain:s}}}}}function Pa(e){let n=e.database!==!1,r=e.cache!==!1,i=e.queue!==!1;return{project:{name:e.name,slug:e.slug,region:"us-east-1"},mode:"server",environments:{production:{type:"production",domain:e.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:e.imageUri,portMappings:[{containerPort:3000}],environment:[{name:"NODE_ENV",value:"production"},{name:"PORT",value:"3000"},{name:"AWS_REGION",value:t.ref("AWS::Region")},...n?[{name:"DB_HOST",value:t.getAtt("PostgresDb","Endpoint.Address")},{name:"DB_PORT",value:t.getAtt("PostgresDb","Endpoint.Port")}]:[],...r?[{name:"REDIS_HOST",value:t.getAtt("RedisReplicationGroup","PrimaryEndPoint.Address")},{name:"REDIS_PORT",value:t.getAtt("RedisReplicationGroup","PrimaryEndPoint.Port")},{name:"REDIS_TLS",value:"true"}]:[],...i?[{name:"QUEUE_URL",value:t.ref("JobsQueue")}]:[],{name:"MAIL_TRANSPORT",value:"ses"}],secrets:n?[{name:"DB_USERNAME",valueFrom:t.sub("${DBSecret}:username::")},{name:"DB_PASSWORD",valueFrom:t.sub("${DBSecret}:password::")}]:[]}]},service:{desiredCount:e.desiredCount||1,healthCheck:{path:"/api/health",interval:30,timeout:5},autoScaling:{min:e.desiredCount||1,max:6,targetCPU:70}},loadBalancer:{type:"application",...e.certificateArn?{customDomain:{domain:e.domain,certificateArn:e.certificateArn}}:{},...e.originVerifySecret?{originVerifyHeader:{name:"X-Origin-Verify",value:e.originVerifySecret}}:{}}}},...n?{databases:{postgres:{engine:"postgres",version:"16",instanceClass:"db.t4g.micro",allocatedStorage:20,maxAllocatedStorage:100,multiAZ:!1,backupRetentionDays:7,deletionProtection:!0}}}:{},...r?{cache:{redis:{nodeType:"cache.t4g.micro",numCacheNodes:2,engine:"redis",engineVersion:"7.1",automaticFailoverEnabled:!0,snapshotRetentionLimit:5}}}:{},...i?{queues:{jobs:{fifo:!1,visibilityTimeout:300,messageRetentionPeriod:345600,deadLetterQueue:!0,maxReceiveCount:3,receiveMessageWaitTime:20}}}:{}}}}function Mm(e){let{name:n,slug:r,domain:i,apiSubdomain:s="api"}=e;return{project:{name:n,slug:r,region:"us-east-1"},mode:"server",environments:{production:{type:"production",domain:i}},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:i,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:`${r}-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:`${s}.${i}`,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:i,subdomains:[`*.${i}`],validationMethod:"DNS"},waf:{enabled:!0,rules:["rateLimit","sqlInjection","xss"]}}}}}function Um(e){let{name:n,slug:r,domain:i}=e;return{project:{name:n,slug:r,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:i}},infrastructure:{apiGateway:{type:"HTTP",cors:{allowOrigins:["*"],allowMethods:["GET","POST","PUT","DELETE","PATCH"],allowHeaders:["Content-Type","Authorization"],maxAge:3600},customDomain:i?{domain:i,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:{[`${r}-users`]:{partitionKey:{name:"userId",type:"S"},billingMode:"PAY_PER_REQUEST",streamEnabled:!0,pointInTimeRecovery:!0,globalSecondaryIndexes:[{name:"EmailIndex",partitionKey:{name:"email",type:"S"},projection:"ALL"}]},[`${r}-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:i?{domain:i,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 Bm(e){let{name:n,slug:r,domain:i,instanceType:s="t3.small"}=e;return{project:{name:n,slug:r,region:"us-east-1"},mode:"server",environments:{production:{type:"production",domain:i}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:2,natGateways:1}},compute:{server:{instanceType:s,ami:"ubuntu-22.04",keyPair:`${r}-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:i,certificateArn:"TO_BE_GENERATED"},cachePolicy:{minTTL:0,defaultTTL:86400,maxTTL:31536000},compress:!0,origins:[{type:"alb",pathPattern:"/wp-content/*"}]},security:{certificate:{domain:i,subdomains:[`www.${i}`],validationMethod:"DNS"},waf:{enabled:!0,rules:["rateLimit","sqlInjection","xss","wordpressRules"]}}}}}function Fm(e){let{name:n,slug:r,domain:i,apiDomain:s}=e;return{project:{name:n,slug:r,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:i}},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:i,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},...s?{api:{runtime:"nodejs20.x",handler:"dist/api/index.handler",memory:1024,timeout:30,events:[{type:"http",path:"/{proxy+}",method:"ANY"}]}}:{}},apiGateway:s?{type:"HTTP",customDomain:{domain:s,certificateArn:"TO_BE_GENERATED"},cors:{allowOrigins:[i],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:i,subdomains:s?[s]:[],validationMethod:"DNS"},waf:{enabled:!0,rules:["rateLimit","geoBlock"]}}}}}function jm(e){let{name:n,slug:r,domain:i,services:s}=e;return{project:{name:n,slug:r,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:i}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:3,natGateways:2}},compute:{services:s.map((a)=>({name:a.name,type:"fargate",taskDefinition:{cpu:a.cpu||"256",memory:a.memory||"512",containerDefinitions:[{name:a.name,image:`${r}-${a.name}:latest`,portMappings:[{containerPort:a.port}],healthCheck:{command:["CMD-SHELL",`curl -f http://localhost:${a.port}/health || exit 1`],interval:30,timeout:5,retries:3}}]},service:{desiredCount:a.desiredCount||2,serviceDiscovery:{enabled:!0,namespace:`${r}.local`},autoScaling:{min:2,max:10,targetCPU:70}}}))},apiGateway:{type:"HTTP",customDomain:{domain:i,certificateArn:"TO_BE_GENERATED"},cors:{allowOrigins:["*"],allowMethods:["GET","POST","PUT","DELETE","PATCH"]},routes:s.map((a)=>({path:`/${a.name}/{proxy+}`,integration:{type:"vpc-link",service:a.name}}))},databases:{dynamodb:{tables:Object.fromEntries(s.map((a)=>[`${r}-${a.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:`${r}-events`,subscriptions:s.map((a)=>({protocol:"sqs",endpoint:`${r}-${a.name}-queue`,filterPolicy:{service:[a.name]}}))}}},monitoring:{dashboard:{name:`${r}-microservices`,widgets:s.map((a)=>({type:"metric",metrics:[{service:a.name,metric:"CPUUtilization"},{service:a.name,metric:"MemoryUtilization"},{service:a.name,metric:"RequestCount"}]}))},alarms:s.flatMap((a)=>[{name:`${a.name}-high-cpu`,metric:"CPUUtilization",threshold:80,service:a.name},{name:`${a.name}-errors`,metric:"Errors",threshold:10,service:a.name}])},security:{certificate:{domain:i,validationMethod:"DNS"},waf:{enabled:!0,rules:["rateLimit","sqlInjection"]}}}}}function Vm(e){let{name:n,slug:r,domain:i}=e;return{project:{name:n,slug:r,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:i}},infrastructure:{apiGateway:{type:"websocket",customDomain:i?{domain:i,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:`${r}-messages`,startingPosition:"LATEST",batchSize:100}]}},databases:{dynamodb:{tables:{[`${r}-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"}]},[`${r}-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"}]},[`${r}-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:`${r}-realtime`,widgets:[{type:"metric",metrics:["WebSocketConnections","MessagesSent","IntegrationLatency"]}]}},security:{certificate:i?{domain:i,validationMethod:"DNS"}:void 0,waf:{enabled:!0,rules:["rateLimit","connectionLimit"]}}}}}function zm(e){let{name:n,slug:r,retentionDays:i=7}=e;return{project:{name:n,slug:r,region:"us-east-1"},mode:"serverless",infrastructure:{streaming:{dataStream:{name:`${r}-stream`,shardCount:2,retentionPeriod:i*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:`${r}-stream`,batchSize:1000,startingPosition:"LATEST",parallelizationFactor:10}]},transformer:{runtime:"nodejs20.x",handler:"dist/processors/transform.handler",memory:3008,timeout:900,events:[{type:"s3",bucket:`${r}-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:`${r}_analytics`,workgroup:`${r}-workgroup`,outputBucket:`${r}-query-results`,tables:[{name:"raw_events",location:`s3://${r}-raw/events/`,format:"parquet",partitionKeys:["year","month","day"]},{name:"processed_events",location:`s3://${r}-processed/events/`,format:"parquet",partitionKeys:["year","month","day"]}]},glue:{crawlers:[{name:`${r}-crawler`,databaseName:`${r}_analytics`,s3Targets:[`s3://${r}-raw/`,`s3://${r}-processed/`],schedule:"cron(0 2 * * ? *)"}],jobs:[{name:`${r}-etl-job`,scriptLocation:`s3://${r}-scripts/etl.py`,role:`${r}-glue-role`,maxCapacity:10,timeout:120}]}},databases:{dynamodb:{tables:{[`${r}-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:`${r}-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:`${r}-pipeline`,widgets:[{type:"metric",metrics:["KinesisIncomingRecords","LambdaInvocations","S3ObjectsCreated","GlueJobsSucceeded"]}]},alarms:[{metric:"LambdaErrors",threshold:10,evaluationPeriods:1},{metric:"KinesisIteratorAge",threshold:60000,evaluationPeriods:2}]}}}}function Hm(e){let{name:n,slug:r,domain:i,modelS3Path:s=`s3://${r}-models/`,instanceType:a="ml.t3.medium"}=e;return{project:{name:n,slug:r,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:i}},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:`${r}-inference`,modelS3Path:s,instanceType:a,initialInstanceCount:1,autoScaling:{minInstances:1,maxInstances:5,targetInvocationsPerInstance:1000}}],trainingJobs:[{name:`${r}-training`,algorithmSpecification:{trainingImage:"TO_BE_SPECIFIED",trainingInputMode:"File"},instanceType:"ml.p3.2xlarge",instanceCount:1,volumeSizeInGB:50,maxRuntimeInSeconds:86400}]}},apiGateway:{type:"HTTP",customDomain:i?{domain:i,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:`${r}-inference`,MODEL_BUCKET:`${r}-models`}},"batch-predict":{runtime:"python3.11",handler:"handlers/batchPredict.handler",memory:3008,timeout:900,events:[{type:"s3",bucket:`${r}-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:{[`${r}-predictions`]:{partitionKey:{name:"requestId",type:"S"},sortKey:{name:"timestamp",type:"S"},billingMode:"PAY_PER_REQUEST",streamEnabled:!0},[`${r}-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:`${r}-ml`,widgets:[{type:"metric",metrics:["SageMakerInvocations","SageMakerModelLatency","APIGatewayRequests","LambdaErrors"]}]},alarms:[{metric:"SageMakerModelLatency",threshold:1000,evaluationPeriods:2},{metric:"SageMakerInvocationErrors",threshold:10,evaluationPeriods:1}]},security:{certificate:i?{domain:i,validationMethod:"DNS"}:void 0,waf:{enabled:!0,rules:["rateLimit","apiProtection"]}}}}}function Gm(e){let{name:n,slug:r,domain:i,instanceType:s="t3.medium",minInstances:a=2,maxInstances:c=10,databaseEngine:u="mysql",sessionStore:d="redis"}=e;return{project:{name:n,slug:r,region:"us-east-1"},mode:"server",environments:{production:{type:"production",domain:i}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:2,natGateways:2}},compute:{server:{instanceType:s,ami:"ubuntu-22.04",autoScaling:{min:a,max:c,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
|
-
`}},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:[i||"*"],allowedMethods:["GET","HEAD"]}]}},cdn:{enabled:!0,origins:[{originId:"static-assets",domainName:`${r}-static.s3.amazonaws.com`,pathPattern:"/static/*"}],customDomain:i?{domain:i,certificateArn:"TO_BE_GENERATED"}:void 0,cachePolicy:{minTTL:0,defaultTTL:86400,maxTTL:31536000},compress:!0,http3:!0},databases:u==="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:d==="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:`${r}-jobs`,batchSize:10}]},"email-sender":{runtime:"nodejs20.x",handler:"dist/workers/email.handler",memory:512,timeout:60,events:[{type:"sqs",queueName:`${r}-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:`${r}-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:[`${r}-app`,`${r}-nginx`,`${r}-workers`]}},security:{certificate:i?{domain:i,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:u==="mysql"?3306:5432,protocol:"tcp",source:"app-sg"}]},...d==="redis"&&{cache:{ingress:[{port:6379,protocol:"tcp",source:"app-sg"}]}}}}}}}function qm(e){let{name:n,slug:r,domain:i,repository:s,phpVersion:a="8.3",size:c="small",database:u=r.replace(/-/g,"_"),databasePassword:d,sslEmail:m,deployStrategy:p="push",provider:g="hetzner"}=e;return{project:{name:n,slug:r,region:"us-east-1"},mode:"server",cloud:{provider:g},environments:{production:{type:"production",domain:i}},infrastructure:{compute:{mode:"server",size:c,runtime:"php",webServer:"nginx",php:{versions:[a],default:a},managedServices:{mysql:!0,redis:!0},firewall:{enabled:!0},autoUpdates:!0,monitoring:!0,backups:{enabled:!0,schedule:"0 2 * * *",retentionCount:7}},appDatabase:{engine:"mysql",name:u,username:u,password:d}},sites:{main:{root:".",type:"laravel",domain:i,phpVersion:a,repository:{...s,strategy:p},scheduler:!0,queues:[{connection:"redis",queue:"default",processes:1}],ssl:{provider:"letsencrypt",email:m}}}}}function Wm(e){let{name:n,slug:r,domain:i,layers:s,phpVersion:a="8.3",architecture:c="x86_64",memory:u=1024,build:d,deploy:m=["migrate --force"],cache:p="dynamodb",scheduler:g="on",region:y="us-east-1"}=e;return{project:{name:n,slug:r,region:y},mode:"serverless",environments:{production:{type:"production",domain:i,app:{kind:"php",runtime:"provided.al2023",phpVersion:a,architecture:c,layers:s,memory:u,build:d,deploy:m,assets:"public",queues:!0,scheduler:g,cache:{driver:p},domain:i}}}}}function Km(e){return{root:e.root??"packages/ui/dist",deploy:"server",type:"static",domain:e.domain,build:e.build??"cd packages/ui && bun install && bun run build",ssl:{provider:"letsencrypt"},auth:{username:e.username??"admin",password:e.password}}}var fu=da,hu="./node_modules/@stacksjs/ts-cloud/dist/bin/dashboard-server.js";function Si(e){let n=e.split(".").filter(Boolean);return n.length<=2?e:n.slice(-2).join(".")}function Ai(e){let n=2166136261;for(let r=0;r<e.length;r++)n^=e.charCodeAt(r),n=Math.imul(n,16777619);return n>>>0}var yu=20000,bu=12000;function Su(e){return yu+Ai(e)%bu}function
|
|
2459
|
-
`),i=null,s,a,c;for(let u of r){let d=u.trim();if(!d||d.startsWith("#")||d.startsWith(";"))continue;let m=d.match(/^\[([^\]]+)\]$/);if(m){if(i===n&&s&&a)return{accessKeyId:s,secretAccessKey:a,sessionToken:c};i=m[1],s=void 0,a=void 0,c=void 0;continue}if(i===n){let[p,...g]=d.split("="),y=g.join("=").trim();switch(p.trim().toLowerCase()){case"aws_access_key_id":s=y;break;case"aws_secret_access_key":a=y;break;case"aws_session_token":c=y;break}}}if(i===n&&s&&a)return{accessKeyId:s,secretAccessKey:a,sessionToken:c};return null}async function wu(e){let n=e?.timeout??1000,r="http://169.254.169.254";try{let i=await je("http://169.254.169.254/latest/api/token",{method:"PUT",headers:{"X-aws-ec2-metadata-token-ttl-seconds":"21600"}},n);if(!i.ok)return null;let s=await i.text(),a=await je("http://169.254.169.254/latest/meta-data/iam/security-credentials/",{headers:{"X-aws-ec2-metadata-token":s}},n);if(!a.ok)return null;let c=(await a.text()).trim(),u=await je(`http://169.254.169.254/latest/meta-data/iam/security-credentials/${c}`,{headers:{"X-aws-ec2-metadata-token":s}},n);if(!u.ok)return null;let d=await u.json();return{accessKeyId:d.AccessKeyId,secretAccessKey:d.SecretAccessKey,sessionToken:d.Token,expiration:new Date(d.Expiration)}}catch{return null}}async function Au(e){let n=e?.timeout??1000,r=process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI,i=process.env.AWS_CONTAINER_CREDENTIALS_FULL_URI,s=null;if(r)s=`http://169.254.170.2${r}`;else if(i)s=i;if(!s)return null;try{let a={},c=process.env.AWS_CONTAINER_AUTHORIZATION_TOKEN;if(c)a.Authorization=c;let u=await je(s,{headers:a},n);if(!u.ok)return null;let d=await u.json();return{accessKeyId:d.AccessKeyId,secretAccessKey:d.SecretAccessKey,sessionToken:d.Token,expiration:new Date(d.Expiration)}}catch{return null}}async function Ru(e){let n=e?.timeout??5000,r=process.env.AWS_WEB_IDENTITY_TOKEN_FILE,i=process.env.AWS_ROLE_ARN,s=process.env.AWS_ROLE_SESSION_NAME||"ts-cloud-session";if(!r||!i)return null;try{let a=vt(r,"utf-8").trim(),c=process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||"us-east-1",u=c.startsWith("us-gov")?`https://sts.${c}.amazonaws.com`:c==="us-east-1"?"https://sts.amazonaws.com":`https://sts.${c}.amazonaws.com`,d=new URLSearchParams({Action:"AssumeRoleWithWebIdentity",Version:"2011-06-15",RoleArn:i,RoleSessionName:s,WebIdentityToken:a}),m=await je(`${u}/?${d.toString()}`,{method:"POST"},n);if(!m.ok)return null;let p=await m.text(),g=Ue(p,"AccessKeyId"),y=Ue(p,"SecretAccessKey"),f=Ue(p,"SessionToken"),h=Ue(p,"Expiration");if(!g||!y)return null;return{accessKeyId:g,secretAccessKey:y,sessionToken:f??void 0,expiration:h?new Date(h):void 0}}catch{return null}}async function Gi(e){let n=Tu();if(n)return n;let r=Eu(e);if(r)return r;let i=await Ru(e);if(i)return i;let s=await Au(e);if(s)return s;let a=await wu(e);if(a)return a;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 ig(e){let n=null,r=null;return async()=>{if(n){if(!n.expiration)return n;let i=300000;if(n.expiration.getTime()-Date.now()>i)return n}if(r)return r;return r=Gi(e).then((i)=>(n=i,r=null,i)).catch((i)=>{throw r=null,i}),r}}async function je(e,n,r){let i=new AbortController,s=setTimeout(()=>i.abort(),r);try{let a=await fetch(e,{...n,signal:i.signal});return clearTimeout(s),a}catch(a){throw clearTimeout(s),a}}function Ue(e,n){let r=new RegExp(`<${n}>([^<]+)</${n}>`),i=e.match(r);return i?i[1]:null}async function
|
|
2460
|
-
`),u=!1;for(let d of c){let m=d.trim();if(m.startsWith("[")){u=m===a;continue}if(u&&m.startsWith("region")){let[,p]=m.split("=");if(p)return p.trim()}}}catch{}return"us-east-1"}async function bl(e){let n=e||await Gi(),r=Iu(),{signRequest:i}=await import("./chunk-
|
|
2461
|
-
Reason: ${u.StackStatusReason||"Unknown"}`);await new Promise((d)=>setTimeout(d,5000))}throw Error(`Timeout waiting for stack ${e} to complete`)}async waitForStackWithProgress(e,n,r){let s={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]}[n];if(!s)throw Error(`Unknown waiter: ${n}`);return this.waitForStack(e,s,r)}async createChangeSet(e){let n={StackName:e.stackName,ChangeSetName:e.changeSetName,ChangeSetType:"UPDATE"};if(e.templateBody)n.TemplateBody=e.templateBody;else if(e.templateURL)n.TemplateURL=e.templateURL;if(e.parameters)for(let[i,[s,a]]of Object.entries(e.parameters).entries())n[`Parameters.member.${i+1}.ParameterKey`]=s,n[`Parameters.member.${i+1}.ParameterValue`]=a;if(e.capabilities)for(let[i,s]of e.capabilities.entries())n[`Capabilities.member.${i+1}`]=s;return(await this.request("CreateChangeSet",n)).ChangeSetId}async executeChangeSet(e,n){await this.request("ExecuteChangeSet",{ChangeSetName:e,StackName:n})}async describeStacks(e){let n=typeof e==="string"?e:e.stackName;try{return{Stacks:[await this.describeStack(n)]}}catch{return{Stacks:[]}}}async getStackOutputs(e){let n=await this.request("DescribeStacks",{StackName:e}),i=(n?.DescribeStacksResult||n?.DescribeStacksResponse?.DescribeStacksResult||n)?.Stacks?.member,s=Array.isArray(i)?i[0]:i;if(!s)return{};let a={},c=s.Outputs?.member;if(c){let u=Array.isArray(c)?c:[c];for(let d of u)if(d.OutputKey&&d.OutputValue)a[d.OutputKey]=d.OutputValue}return a}}function Tt(e,n=""){let r={};for(let[i,s]of Object.entries(e)){let a=n?`${n}.${i}`:i;if(Array.isArray(s))s.forEach((c,u)=>{if(typeof c==="object")Object.assign(r,Tt(c,`${a}.${u+1}`));else r[`${a}.${u+1}`]=String(c)});else if(typeof s==="object"&&s!==null)Object.assign(r,Tt(s,a));else if(s!==void 0&&s!==null)r[a]=String(s)}return r}function vi(e){e=e.replace(/<\?xml[^?]*\?>\s*/,"").trim();function n(s,a,c){let u=1,d=c,m=`<${a}`,p=`</${a}>`;while(d<s.length&&u>0){let g=s.indexOf(m,d),y=s.indexOf(p,d);if(y===-1)return-1;if(g!==-1&&g<y){let f=s[g+m.length];if(f===">"||f===" "||f==="/"){let h=s.indexOf(">",g);if(h!==-1&&s[h-1]==="/")d=h+1;else u++,d=h+1}else d=g+m.length}else{if(u--,u===0)return y;d=y+p.length}}return-1}function r(s,a){while(a<s.length&&/\s/.test(s[a]))a++;if(a>=s.length||s[a]!=="<"){let S=s.indexOf("<",a);if(S===-1)return{value:s.slice(a).trim(),end:s.length};return{value:s.slice(a,S).trim(),end:S}}if(s[a+1]==="/")return{value:void 0,end:a};let c=s.slice(a).match(/^<(\w+)([^>]*?)\/?>/);if(!c)return{value:void 0,end:a+1};let u=c[1];if(c[0].endsWith("/>"))return{value:"",end:a+c[0].length};let m=a+c[0].length,p=`</${u}>`,g=n(s,u,m);if(g===-1)return{value:void 0,end:a+c[0].length};let y=s.slice(m,g).trim();if(!y.includes("<"))return{value:y,end:g+p.length};let f={},h=m;while(h<g){while(h<g&&/\s/.test(s[h]))h++;if(h>=g)break;if(s[h]!=="<"||s[h+1]==="/")break;let S=s.slice(h).match(/^<(\w+)/);if(!S)break;let C=S[1],P=r(s,h);if(P.value===void 0){h++;continue}if(C==="member"||f[C]!==void 0){if(!Array.isArray(f[C]))f[C]=f[C]!==void 0?[f[C]]:[];f[C].push(P.value)}else f[C]=P.value;h=P.end}return{value:f,end:g+p.length}}return r(e,0).value||{}}function Ti(e){return{StackName:e.StackName||"",StackId:e.StackId,StackStatus:e.StackStatus,CreationTime:e.CreationTime,LastUpdatedTime:e.LastUpdatedTime,StackStatusReason:e.StackStatusReason,Description:e.Description}}function Ri(e){let r=(e?.ListStacksResult||e?.ListStacksResponse?.ListStacksResult||e)?.StackSummaries?.member;if(!r)return[];return(Array.isArray(r)?r:[r]).map((s)=>({StackName:s.StackName||"",StackId:s.StackId,StackStatus:s.StackStatus,CreationTime:s.CreationTime,LastUpdatedTime:s.LastUpdatedTime,StackStatusReason:s.StackStatusReason,Description:s.Description}))}function Pi(e){let r=(e?.DescribeStackEventsResult||e?.DescribeStackEventsResponse?.DescribeStackEventsResult||e)?.StackEvents?.member;if(!r)return[];return(Array.isArray(r)?r:[r]).map((s)=>({StackId:s.StackId||"",EventId:s.EventId||"",StackName:s.StackName||"",LogicalResourceId:s.LogicalResourceId||"",PhysicalResourceId:s.PhysicalResourceId,ResourceType:s.ResourceType||"",Timestamp:s.Timestamp||"",ResourceStatus:s.ResourceStatus||"",ResourceStatusReason:s.ResourceStatusReason}))}var Ei=5242880,Rt=5242880;var wi=5242880;class Da{region;endpoint;forcePathStyle;credentials;credentialOptions;retryOptions;constructor(e={}){this.region=e.region||process.env.AWS_REGION||"us-east-1",this.endpoint=e.endpoint||`https://s3.${this.region}.amazonaws.com`,this.forcePathStyle=e.forcePathStyle||!1,this.credentials=e.credentials,this.credentialOptions=e.credentialOptions,this.retryOptions=e.retryOptions||{}}async getCredentials(){if(this.credentials)return this.credentials;return Gi(this.credentialOptions)}buildUrl(e,n){let r=n?encodeURIComponent(n).replace(/%2F/g,"/"):"";if(this.forcePathStyle)return n?`${this.endpoint}/${e}/${r}`:`${this.endpoint}/${e}`;let i=new URL(this.endpoint);return i.hostname=`${e}.${i.hostname}`,n?`${i.origin}/${r}`:i.origin}async get(e,n,r={}){let i=await this.getCredentials(),s=this.buildUrl(e,n),a={};if(r.range)a.Range=r.range;if(r.ifModifiedSince)a["If-Modified-Since"]=r.ifModifiedSince.toUTCString();if(r.ifMatch)a["If-Match"]=r.ifMatch;if(r.ifNoneMatch)a["If-None-Match"]=r.ifNoneMatch;let c=new URL(s);if(r.responseContentType)c.searchParams.set("response-content-type",r.responseContentType);if(r.responseContentDisposition)c.searchParams.set("response-content-disposition",r.responseContentDisposition);let u=Y({method:"GET",url:c.toString(),headers:a,...i,service:"s3",region:this.region}),d=await fetch(u.url,{method:u.method,headers:u.headers});if(!d.ok&&d.status!==304){let m=await d.text();throw new be(`Failed to get object: ${m}`,d.status,e,n)}return d}async getText(e,n,r={}){return(await this.get(e,n,r)).text()}async getJSON(e,n,r={}){return(await this.get(e,n,r)).json()}async getBuffer(e,n,r={}){return(await this.get(e,n,r)).arrayBuffer()}async put(e,n,r,i={}){let s,a;if(typeof r==="string")s=new TextEncoder().encode(r).length,a=r;else if(r instanceof ArrayBuffer)s=r.byteLength,a=r;else if(r instanceof Uint8Array)s=r.byteLength,a=r;else if(r instanceof Blob)s=r.size,a=r;else return this.uploadMultipart(e,n,r,{...i,partSize:Rt});if(s>wi){let c=Ni(a).stream();return this.uploadMultipart(e,n,c,{...i,partSize:Rt})}return this.putSimple(e,n,a,s,i)}async putSimple(e,n,r,i,s){let a=await this.getCredentials(),c=this.buildUrl(e,n),u={"Content-Length":String(i),"Content-Type":s.contentType||Gn(n)};if(s.contentEncoding)u["Content-Encoding"]=s.contentEncoding;if(s.cacheControl)u["Cache-Control"]=s.cacheControl;if(s.contentDisposition)u["Content-Disposition"]=s.contentDisposition;if(s.storageClass)u["x-amz-storage-class"]=s.storageClass;if(s.serverSideEncryption)u["x-amz-server-side-encryption"]=s.serverSideEncryption;if(s.acl)u["x-amz-acl"]=s.acl;if(s.tagging)u["x-amz-tagging"]=s.tagging;if(s.metadata)for(let[y,f]of Object.entries(s.metadata))u[`x-amz-meta-${y.toLowerCase()}`]=f;let d;if(typeof r==="string")d=r;else if(r instanceof Blob)d=await r.text();else d=new TextDecoder().decode(r instanceof ArrayBuffer?new Uint8Array(r):r);let m=Y({method:"PUT",url:c,headers:u,body:d,...a,service:"s3",region:this.region}),p=await fetch(m.url,{method:m.method,headers:m.headers,body:r});if(!p.ok){let y=await p.text();throw new be(`Failed to put object: ${y}`,p.status,e,n)}return{etag:(p.headers.get("ETag")||"").replace(/"/g,"")}}async delete(e,n){let r=await this.getCredentials(),i=this.buildUrl(e,n),s=Y({method:"DELETE",url:i,...r,service:"s3",region:this.region}),a=await fetch(s.url,{method:s.method,headers:s.headers});if(!a.ok&&a.status!==204){let c=await a.text();throw new be(`Failed to delete object: ${c}`,a.status,e,n)}}async deleteMany(e,n){let r=await this.getCredentials(),i=`${this.buildUrl(e)}?delete`,a=`<?xml version="1.0" encoding="UTF-8"?><Delete><Quiet>false</Quiet>${n.map((h)=>`<Object><Key>${Di(h)}</Key></Object>`).join("")}</Delete>`,c=Y({method:"POST",url:i,headers:{"Content-Type":"application/xml"},body:a,...r,service:"s3",region:this.region}),u=await fetch(c.url,{method:c.method,headers:c.headers,body:a});if(!u.ok){let h=await u.text();throw new be(`Failed to delete objects: ${h}`,u.status,e)}let d=await u.text(),m=[],p=[],g=/<Deleted><Key>([^<]+)<\/Key>/g,y;while((y=g.exec(d))!==null)m.push(y[1]);let f=/<Error><Key>([^<]+)<\/Key><Code>([^<]+)<\/Code><Message>([^<]+)<\/Message>/g;while((y=f.exec(d))!==null)p.push({key:y[1],error:`${y[2]}: ${y[3]}`});return{deleted:m,errors:p}}async list(e,n={}){let r=await this.getCredentials(),i=new URL(this.buildUrl(e));if(i.searchParams.set("list-type","2"),n.prefix)i.searchParams.set("prefix",n.prefix);if(n.delimiter)i.searchParams.set("delimiter",n.delimiter);if(n.maxKeys)i.searchParams.set("max-keys",String(n.maxKeys));if(n.continuationToken)i.searchParams.set("continuation-token",n.continuationToken);if(n.startAfter)i.searchParams.set("start-after",n.startAfter);let s=Y({method:"GET",url:i.toString(),...r,service:"s3",region:this.region}),a=await fetch(s.url,{method:s.method,headers:s.headers});if(!a.ok){let u=await a.text();throw new be(`Failed to list objects: ${u}`,a.status,e)}let c=await a.text();return Ii(c)}async*listAll(e,n={}){let r;do{let i=await this.list(e,{...n,continuationToken:r});for(let s of i.contents)yield s;r=i.nextContinuationToken}while(r)}async head(e,n){let r=await this.getCredentials(),i=this.buildUrl(e,n),s=Y({method:"HEAD",url:i,...r,service:"s3",region:this.region}),a=await fetch(s.url,{method:s.method,headers:s.headers});if(a.status===404)return null;if(!a.ok){let u=await a.text();throw new be(`Failed to head object: ${u}`,a.status,e,n)}let c={};return a.headers.forEach((u,d)=>{if(d.toLowerCase().startsWith("x-amz-meta-"))c[d.slice(11)]=u}),{contentLength:Number(a.headers.get("Content-Length")||0),contentType:a.headers.get("Content-Type")||"application/octet-stream",etag:(a.headers.get("ETag")||"").replace(/"/g,""),lastModified:new Date(a.headers.get("Last-Modified")||0),metadata:c,storageClass:a.headers.get("x-amz-storage-class")||void 0,serverSideEncryption:a.headers.get("x-amz-server-side-encryption")||void 0}}async exists(e,n){return await this.head(e,n)!==null}async copy(e,n,r,i,s={}){let a=await this.getCredentials(),c=this.buildUrl(r,i),u={"x-amz-copy-source":`/${e}/${encodeURIComponent(n)}`};if(s.metadataDirective)u["x-amz-metadata-directive"]=s.metadataDirective;if(s.contentType)u["Content-Type"]=s.contentType;if(s.storageClass)u["x-amz-storage-class"]=s.storageClass;if(s.acl)u["x-amz-acl"]=s.acl;if(s.metadata)for(let[f,h]of Object.entries(s.metadata))u[`x-amz-meta-${f.toLowerCase()}`]=h;let d=Y({method:"PUT",url:c,headers:u,...a,service:"s3",region:this.region}),m=await fetch(d.url,{method:d.method,headers:d.headers});if(!m.ok){let f=await m.text();throw new be(`Failed to copy object: ${f}`,m.status,r,i)}let g=(await m.text()).match(/<ETag>"?([^"<]+)"?<\/ETag>/);return{etag:g?g[1]:""}}async getPresignedUrl(e,n,r={}){let i=await this.getCredentials(),s=this.buildUrl(e,n);return cs({url:s,method:r.method||"GET",expiresIn:r.expiresIn||3600,...i,service:"s3",region:this.region})}async uploadMultipart(e,n,r,i={}){let s=await this.getCredentials(),a=Math.max(i.partSize||Rt,Ei),c,u;if(r instanceof ReadableStream)c=r;else if(r instanceof Blob)c=r.stream(),u=r.size;else{let p=new Blob([r]);c=p.stream(),u=p.size}let{uploadId:d,baseUrl:m}=await this.initiateMultipartUpload(e,n,i);try{let p=await this.uploadParts(e,n,m,d,c,a,s,u,i.concurrency||4,i.onProgress);return await this.completeMultipartUpload(e,n,m,d,p)}catch(p){throw await this.abortMultipartUpload(e,n,d,m).catch(()=>{}),p}}async initiateMultipartUpload(e,n,r){let i=await this.getCredentials(),s=this.buildUrl(e,n),a=`${s}?uploads`,c={"Content-Type":r.contentType||Gn(n)};if(r.storageClass)c["x-amz-storage-class"]=r.storageClass;if(r.serverSideEncryption)c["x-amz-server-side-encryption"]=r.serverSideEncryption;if(r.acl)c["x-amz-acl"]=r.acl;if(r.metadata)for(let[y,f]of Object.entries(r.metadata))c[`x-amz-meta-${y.toLowerCase()}`]=f;let u=Y({method:"POST",url:a,headers:c,...i,service:"s3",region:this.region}),d=await fetch(u.url,{method:u.method,headers:u.headers});if(!d.ok){let y=await d.text();throw new be(`Failed to initiate multipart upload: ${y}`,d.status,e,n)}let p=(await d.text()).match(/<UploadId>([^<]+)<\/UploadId>/);if(!p)throw new be("Failed to parse upload ID from response",0,e,n);let g=s;if(d.url)try{let y=new URL(d.url);y.search="",g=y.toString()}catch{}return{uploadId:p[1],baseUrl:g}}async uploadParts(e,n,r,i,s,a,c,u,d,m){let p=[],g=s.getReader(),y=1,f=new Uint8Array(0),h=0,S=u?Math.ceil(u/a):void 0,C=new Map,P=async(v,w)=>{let D=`${r}?partNumber=${w}&uploadId=${encodeURIComponent(i)}`,x={"Content-Length":String(v.byteLength),"x-amz-content-sha256":"UNSIGNED-PAYLOAD"},L=Y({method:"PUT",url:D,headers:x,...c,service:"s3",region:this.region}),B=await fetch(L.url,{method:L.method,headers:L.headers,body:v,redirect:"error"});if(!B.ok){let F=await B.text();throw new be(`Failed to upload part ${w}: ${F}`,B.status,e,n)}let O=(B.headers.get("ETag")||"").replace(/"/g,"");if(!O)throw new be(`Missing ETag for part ${w}`,B.status,e,n);return{partNumber:w,etag:O}},E=async()=>{let v=await Promise.race(C.values());C.delete(v.partNumber),p.push(v)};while(!0){let{done:v,value:w}=await g.read();if(w){let D=new Uint8Array(f.length+w.length);D.set(f),D.set(w,f.length),f=D}while(f.length>=a||v&&f.length>0){let D=f.slice(0,a);f=f.slice(a);let x=y++;if(C.size>=d)await E();if(C.set(x,P(D,x)),h+=D.byteLength,m)m({loaded:h,total:u||h,part:x,totalParts:S||x})}if(v)break}while(C.size>0)await E();return p.sort((v,w)=>v.partNumber-w.partNumber),p}async completeMultipartUpload(e,n,r,i,s){let a=await this.getCredentials(),c=`${r}?uploadId=${encodeURIComponent(i)}`,d=`<?xml version="1.0" encoding="UTF-8"?><CompleteMultipartUpload>${s.map((h)=>`<Part><PartNumber>${h.partNumber}</PartNumber><ETag>"${h.etag}"</ETag></Part>`).join("")}</CompleteMultipartUpload>`,m=Y({method:"POST",url:c,headers:{"Content-Type":"application/xml"},body:d,...a,service:"s3",region:this.region}),p=await fetch(m.url,{method:m.method,headers:m.headers,body:d});if(!p.ok){let h=await p.text();throw new be(`Failed to complete multipart upload: ${h}`,p.status,e,n)}let y=(await p.text()).match(/<ETag>"?([^"<]+)"?<\/ETag>/);return{etag:y?y[1]:""}}async abortMultipartUpload(e,n,r,i){let s=await this.getCredentials(),a=`${i??this.buildUrl(e,n)}?uploadId=${encodeURIComponent(r)}`,c=Y({method:"DELETE",url:a,...s,service:"s3",region:this.region});await fetch(c.url,{method:c.method,headers:c.headers})}async emptyAndDeleteBucket(e){let r=[];for await(let c of this.listAll(e,{}))if(r.push(c.key),r.length>=1000)await this.deleteMany(e,r),r=[];if(r.length>0)await this.deleteMany(e,r);let i=await this.getCredentials(),s=this.buildUrl(e),a=Y({method:"DELETE",url:s,...i,service:"s3",region:this.region});await fetch(a.url,{method:a.method,headers:a.headers})}}class be extends Error{statusCode;bucket;key;constructor(e,n,r,i){super(e);this.statusCode=n;this.bucket=r;this.key=i;this.name="S3Error"}}function Ii(e){let n=[],r=[],i=/<Contents>([\s\S]*?)<\/Contents>/g,s;while((s=i.exec(e))!==null){let c=s[1];n.push({key:z(c,"Key")||"",lastModified:new Date(z(c,"LastModified")||0),etag:(z(c,"ETag")||"").replace(/"/g,""),size:Number(z(c,"Size")||0),storageClass:z(c,"StorageClass")||"STANDARD"})}let a=/<CommonPrefixes><Prefix>([^<]+)<\/Prefix><\/CommonPrefixes>/g;while((s=a.exec(e))!==null)r.push(s[1]);return{contents:n,commonPrefixes:r,isTruncated:z(e,"IsTruncated")==="true",continuationToken:z(e,"ContinuationToken")||void 0,nextContinuationToken:z(e,"NextContinuationToken")||void 0,keyCount:Number(z(e,"KeyCount")||0),maxKeys:Number(z(e,"MaxKeys")||1000),prefix:z(e,"Prefix")||void 0,delimiter:z(e,"Delimiter")||void 0}}function z(e,n){let r=new RegExp(`<${n}>([^<]*)</${n}>`),i=e.match(r);return i?i[1]:null}function Di(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Gn(e){let n=e.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"}[n||""]||"application/octet-stream"}function Ni(e){if(e instanceof Blob)return e;if(typeof e==="string")return new Blob([e],{type:"text/plain"});return new Blob([e])}function Du(e){return new Da(e)}class ku{profile;credentials=null;constructor(e="default"){this.profile=e}async init(){this.credentials=await Pn(this.profile)}async ensureCredentials(){if(!this.credentials)await this.init();return this.credentials}async createInvalidation(e){let n=await this.ensureCredentials(),r=e.callerReference||`invalidation-${Date.now()}`,i=`<?xml version="1.0" encoding="UTF-8"?>
|
|
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:[i||"*"],allowedMethods:["GET","HEAD"]}]}},cdn:{enabled:!0,origins:[{originId:"static-assets",domainName:`${r}-static.s3.amazonaws.com`,pathPattern:"/static/*"}],customDomain:i?{domain:i,certificateArn:"TO_BE_GENERATED"}:void 0,cachePolicy:{minTTL:0,defaultTTL:86400,maxTTL:31536000},compress:!0,http3:!0},databases:u==="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:d==="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:`${r}-jobs`,batchSize:10}]},"email-sender":{runtime:"nodejs20.x",handler:"dist/workers/email.handler",memory:512,timeout:60,events:[{type:"sqs",queueName:`${r}-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:`${r}-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:[`${r}-app`,`${r}-nginx`,`${r}-workers`]}},security:{certificate:i?{domain:i,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:u==="mysql"?3306:5432,protocol:"tcp",source:"app-sg"}]},...d==="redis"&&{cache:{ingress:[{port:6379,protocol:"tcp",source:"app-sg"}]}}}}}}}function qm(e){let{name:n,slug:r,domain:i,repository:s,phpVersion:a="8.3",size:c="small",database:u=r.replace(/-/g,"_"),databasePassword:d,sslEmail:m,deployStrategy:p="push",provider:g="hetzner"}=e;return{project:{name:n,slug:r,region:"us-east-1"},mode:"server",cloud:{provider:g},environments:{production:{type:"production",domain:i}},infrastructure:{compute:{mode:"server",size:c,runtime:"php",webServer:"nginx",php:{versions:[a],default:a},managedServices:{mysql:!0,redis:!0},firewall:{enabled:!0},autoUpdates:!0,monitoring:!0,backups:{enabled:!0,schedule:"0 2 * * *",retentionCount:7}},appDatabase:{engine:"mysql",name:u,username:u,password:d}},sites:{main:{root:".",type:"laravel",domain:i,phpVersion:a,repository:{...s,strategy:p},scheduler:!0,queues:[{connection:"redis",queue:"default",processes:1}],ssl:{provider:"letsencrypt",email:m}}}}}function Wm(e){let{name:n,slug:r,domain:i,layers:s,phpVersion:a="8.3",architecture:c="x86_64",memory:u=1024,build:d,deploy:m=["migrate --force"],cache:p="dynamodb",scheduler:g="on",region:y="us-east-1"}=e;return{project:{name:n,slug:r,region:y},mode:"serverless",environments:{production:{type:"production",domain:i,app:{kind:"php",runtime:"provided.al2023",phpVersion:a,architecture:c,layers:s,memory:u,build:d,deploy:m,assets:"public",queues:!0,scheduler:g,cache:{driver:p},domain:i}}}}}function Km(e){return{root:e.root??"packages/ui/dist",deploy:"server",type:"static",domain:e.domain,build:e.build??"cd packages/ui && bun install && bun run build",ssl:{provider:"letsencrypt"},auth:{username:e.username??"admin",password:e.password}}}var fu=da,hu="./node_modules/@stacksjs/ts-cloud/dist/bin/dashboard-server.js";function Si(e){let n=e.split(".").filter(Boolean);return n.length<=2?e:n.slice(-2).join(".")}function Ai(e){let n=2166136261;for(let r=0;r<e.length;r++)n^=e.charCodeAt(r),n=Math.imul(n,16777619);return n>>>0}var yu=20000,bu=12000;function Su(e){return yu+Ai(e)%bu}function Mn(e,n){let r=Si(e);if(r===e)return`dashboard.${r}`;for(let i of n)if(i===r)return`dashboard.${r}`;return`dashboard.${e}`}function Ln(e,n){let r=[],i=e.infrastructure?.dns?.domain;if(i&&!e.cloud?.attachTo)r.push(i);if(n&&e.environments?.[n]?.domain)r.push(e.environments[n].domain);for(let s of Object.values(e.sites??{})){let a=s;if(!a||a.redirect)continue;let c=a.domain;if(typeof c==="string")r.push(c);else if(Array.isArray(c))r.push(...c.filter((u)=>typeof u==="string"))}return r.filter((s)=>s&&!s.startsWith("dashboard."))}function vu(e,n,r){if(r)return r;let i=Ln(e,n),s=i[0];if(!s)return null;return Mn(s,i)}function Cu(e,n,r){if(r)return[r];let i=Ln(e,n),s=[];for(let a of i){let c=Mn(a,i);if(!s.includes(c))s.push(c)}return s}function er(e){return Object.entries(e.sites??{}).some(([n,r])=>{if(!r)return!1;let i=r.root??"";return Vr(n)||i==="ui/dist"||i.endsWith("/ui/dist")||i.endsWith("/dist/ui")})}var fl="dashboard-";function hl(e){return fl+e.replace(/^dashboard\./,"").replace(/\./g,"-")}function Vr(e){return e==="dashboard"||e.startsWith(fl)}function Hi(e,n,r){if(er(e))return[];if(e.cloud?.attachTo)return[];let i=r.password?{auth:{username:r.username||"admin",password:r.password,realm:r.realm}}:{},s=r.build===!1||r.build===void 0?{}:{build:r.build};if(r.live!==!1){let c=vu(e,n,r.domain);if(!c)return[];let u=r.port??Su(c),d=e.infrastructure?.appDatabase??e.infrastructure?.compute?.database,m={root:r.uiRoot,deploy:"server",domain:c,preStart:["bun install --production --no-save"],start:`bun ${hu} --box --host 127.0.0.1 --port ${u}`,port:u,cpuWeight:10,ioWeight:10,tasksMax:128,env:{APP_ENV:"production",NODE_ENV:"production",TS_CLOUD_DASHBOARD_TELEMETRY:"1",...d?.password?{TS_CLOUD_DASHBOARD_DB_PASSWORD:d.password}:{}},zeroDowntime:!1,sharedPaths:[fu],healthCheck:{path:"/login"},ssl:{provider:"letsencrypt"}};return[{name:hl(c),site:m}]}return Cu(e,n,r.domain).map((c)=>({name:hl(c),site:{root:r.uiRoot,deploy:"server",type:"static",domain:c,ssl:{provider:"letsencrypt"},...s,...i}}))}function Jm(e,n,r){return Hi(e,n,r)[0]??null}function Ct(e,n){let r={...e};for(let i in n){let s=n[i],a=r[i];if(s===void 0)continue;if(Array.isArray(s)&&Array.isArray(a))r[i]=[...a,...s];else if(typeof s==="object"&&s!==null&&!Array.isArray(s)&&typeof a==="object"&&a!==null&&!Array.isArray(a))r[i]=Ct(a,s);else r[i]=s}return r}function yl(e,n){return Ct(e,n)}function Xm(...e){return e.reduce((n,r)=>Ct(n,r),{})}function Qm(e,n){return(r)=>{let i=e(r);if(typeof n==="function")return yl(i,n(i,r));return yl(i,n)}}function Pn(e){return{infrastructure:e}}function Ym(e){return Pn({monitoring:e})}function Zm(e){return Pn({security:e})}function eg(e){return Pn({databases:e})}function tg(e){return Pn({cache:e})}function rg(e){return Pn({cdn:e})}function ng(e){return Pn({queues:e})}import{existsSync as On,readFileSync as vt}from"node:fs";import{homedir as $n}from"node:os";import{join as Bn}from"node:path";function Tu(){let e=process.env.AWS_ACCESS_KEY_ID,n=process.env.AWS_SECRET_ACCESS_KEY;if(!e||!n)return null;return{accessKeyId:e,secretAccessKey:n,sessionToken:process.env.AWS_SESSION_TOKEN}}function Eu(e){let n=e?.profile||process.env.AWS_PROFILE||"default",r=e?.credentialsFile||Bn($n(),".aws","credentials");if(!On(r))return null;try{let i=vt(r,"utf-8");return Ci(i,n)}catch{return null}}function Ci(e,n){let r=e.split(`
|
|
2459
|
+
`),i=null,s,a,c;for(let u of r){let d=u.trim();if(!d||d.startsWith("#")||d.startsWith(";"))continue;let m=d.match(/^\[([^\]]+)\]$/);if(m){if(i===n&&s&&a)return{accessKeyId:s,secretAccessKey:a,sessionToken:c};i=m[1],s=void 0,a=void 0,c=void 0;continue}if(i===n){let[p,...g]=d.split("="),y=g.join("=").trim();switch(p.trim().toLowerCase()){case"aws_access_key_id":s=y;break;case"aws_secret_access_key":a=y;break;case"aws_session_token":c=y;break}}}if(i===n&&s&&a)return{accessKeyId:s,secretAccessKey:a,sessionToken:c};return null}async function wu(e){let n=e?.timeout??1000,r="http://169.254.169.254";try{let i=await je("http://169.254.169.254/latest/api/token",{method:"PUT",headers:{"X-aws-ec2-metadata-token-ttl-seconds":"21600"}},n);if(!i.ok)return null;let s=await i.text(),a=await je("http://169.254.169.254/latest/meta-data/iam/security-credentials/",{headers:{"X-aws-ec2-metadata-token":s}},n);if(!a.ok)return null;let c=(await a.text()).trim(),u=await je(`http://169.254.169.254/latest/meta-data/iam/security-credentials/${c}`,{headers:{"X-aws-ec2-metadata-token":s}},n);if(!u.ok)return null;let d=await u.json();return{accessKeyId:d.AccessKeyId,secretAccessKey:d.SecretAccessKey,sessionToken:d.Token,expiration:new Date(d.Expiration)}}catch{return null}}async function Au(e){let n=e?.timeout??1000,r=process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI,i=process.env.AWS_CONTAINER_CREDENTIALS_FULL_URI,s=null;if(r)s=`http://169.254.170.2${r}`;else if(i)s=i;if(!s)return null;try{let a={},c=process.env.AWS_CONTAINER_AUTHORIZATION_TOKEN;if(c)a.Authorization=c;let u=await je(s,{headers:a},n);if(!u.ok)return null;let d=await u.json();return{accessKeyId:d.AccessKeyId,secretAccessKey:d.SecretAccessKey,sessionToken:d.Token,expiration:new Date(d.Expiration)}}catch{return null}}async function Ru(e){let n=e?.timeout??5000,r=process.env.AWS_WEB_IDENTITY_TOKEN_FILE,i=process.env.AWS_ROLE_ARN,s=process.env.AWS_ROLE_SESSION_NAME||"ts-cloud-session";if(!r||!i)return null;try{let a=vt(r,"utf-8").trim(),c=process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||"us-east-1",u=c.startsWith("us-gov")?`https://sts.${c}.amazonaws.com`:c==="us-east-1"?"https://sts.amazonaws.com":`https://sts.${c}.amazonaws.com`,d=new URLSearchParams({Action:"AssumeRoleWithWebIdentity",Version:"2011-06-15",RoleArn:i,RoleSessionName:s,WebIdentityToken:a}),m=await je(`${u}/?${d.toString()}`,{method:"POST"},n);if(!m.ok)return null;let p=await m.text(),g=Ue(p,"AccessKeyId"),y=Ue(p,"SecretAccessKey"),f=Ue(p,"SessionToken"),h=Ue(p,"Expiration");if(!g||!y)return null;return{accessKeyId:g,secretAccessKey:y,sessionToken:f??void 0,expiration:h?new Date(h):void 0}}catch{return null}}async function Gi(e){let n=Tu();if(n)return n;let r=Eu(e);if(r)return r;let i=await Ru(e);if(i)return i;let s=await Au(e);if(s)return s;let a=await wu(e);if(a)return a;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 ig(e){let n=null,r=null;return async()=>{if(n){if(!n.expiration)return n;let i=300000;if(n.expiration.getTime()-Date.now()>i)return n}if(r)return r;return r=Gi(e).then((i)=>(n=i,r=null,i)).catch((i)=>{throw r=null,i}),r}}async function je(e,n,r){let i=new AbortController,s=setTimeout(()=>i.abort(),r);try{let a=await fetch(e,{...n,signal:i.signal});return clearTimeout(s),a}catch(a){throw clearTimeout(s),a}}function Ue(e,n){let r=new RegExp(`<${n}>([^<]+)</${n}>`),i=e.match(r);return i?i[1]:null}async function Dn(e){return Gi({profile:e})}function Iu(e){let n=process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION;if(n)return n;let r=Bn($n(),".aws","config");if(On(r))try{let i=vt(r,"utf-8"),s=e||process.env.AWS_PROFILE||"default",a=s==="default"?"[default]":`[profile ${s}]`,c=i.split(`
|
|
2460
|
+
`),u=!1;for(let d of c){let m=d.trim();if(m.startsWith("[")){u=m===a;continue}if(u&&m.startsWith("region")){let[,p]=m.split("=");if(p)return p.trim()}}}catch{}return"us-east-1"}async function bl(e){let n=e||await Gi(),r=Iu(),{signRequest:i}=await import("./chunk-ww4r3r7x.js"),s=r.startsWith("us-gov")?`https://sts.${r}.amazonaws.com`:r==="us-east-1"?"https://sts.amazonaws.com":`https://sts.${r}.amazonaws.com`,a="Action=GetCallerIdentity&Version=2011-06-15",c=i({method:"POST",url:s,body:"Action=GetCallerIdentity&Version=2011-06-15",headers:{"Content-Type":"application/x-www-form-urlencoded"},...n,service:"sts",region:r}),u=await fetch(c.url,{method:c.method,headers:c.headers,body:c.body});if(!u.ok)throw Error(`Failed to get account ID: ${await u.text()}`);let d=await u.text(),m=Ue(d,"Account");if(!m)throw Error("Failed to parse account ID from response");return m}class Pu{profile;credentials=null;region;constructor(e="us-east-1",n="default"){this.profile=n;this.region=e}async init(){if(this.credentials=await Dn(this.profile),this.credentials.region)this.region=this.credentials.region}async ensureCredentials(){if(!this.credentials)await this.init();return this.credentials}async request(e,n){let r=await this.ensureCredentials(),i={Action:e,Version:"2010-05-15",...Tt(n)},s=new URLSearchParams(i).toString(),c=await(await Ot({method:"POST",url:`https://cloudformation.${this.region}.amazonaws.com/`,service:"cloudformation",region:this.region,headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s,accessKeyId:r.accessKeyId,secretAccessKey:r.secretAccessKey,sessionToken:r.sessionToken})).text();return vi(c)}async createStack(e){let n={StackName:e.stackName};if(e.templateBody)n.TemplateBody=e.templateBody;else if(e.templateURL)n.TemplateURL=e.templateURL;else throw Error("Either templateBody or templateURL must be provided");if(e.parameters)for(let[s,[a,c]]of Object.entries(e.parameters).entries())n[`Parameters.member.${s+1}.ParameterKey`]=a,n[`Parameters.member.${s+1}.ParameterValue`]=c;if(e.capabilities)for(let[s,a]of e.capabilities.entries())n[`Capabilities.member.${s+1}`]=a;if(e.tags)for(let[s,[a,c]]of Object.entries(e.tags).entries())n[`Tags.member.${s+1}.Key`]=a,n[`Tags.member.${s+1}.Value`]=c;if(e.timeoutInMinutes)n.TimeoutInMinutes=e.timeoutInMinutes;if(e.onFailure)n.OnFailure=e.onFailure;let r=await this.request("CreateStack",n);return(r?.CreateStackResult||r?.CreateStackResponse?.CreateStackResult||r)?.StackId}async updateStack(e){let n={StackName:e.stackName};if(e.templateBody)n.TemplateBody=e.templateBody;else if(e.templateURL)n.TemplateURL=e.templateURL;if(e.parameters)for(let[s,[a,c]]of Object.entries(e.parameters).entries())n[`Parameters.member.${s+1}.ParameterKey`]=a,n[`Parameters.member.${s+1}.ParameterValue`]=c;if(e.capabilities)for(let[s,a]of e.capabilities.entries())n[`Capabilities.member.${s+1}`]=a;if(e.tags)for(let[s,[a,c]]of Object.entries(e.tags).entries())n[`Tags.member.${s+1}.Key`]=a,n[`Tags.member.${s+1}.Value`]=c;let r=await this.request("UpdateStack",n);return(r?.UpdateStackResult||r?.UpdateStackResponse?.UpdateStackResult||r)?.StackId}async deleteStack(e){await this.request("DeleteStack",{StackName:e})}async describeStack(e){let n=await this.request("DescribeStacks",{StackName:e}),i=(n?.DescribeStacksResult||n?.DescribeStacksResponse?.DescribeStacksResult||n)?.Stacks?.member,s=Array.isArray(i)?i[0]:i;if(!s)throw Error(`Stack ${e} not found`);return Ti(s)}async listStacks(e){let n={};if(e)for(let[i,s]of e.entries())n[`StackStatusFilter.member.${i+1}`]=s;let r=await this.request("ListStacks",n);return Ri(r)}async describeStackEvents(e){let n=await this.request("DescribeStackEvents",{StackName:e});return Pi(n)}async waitForStack(e,n,r){let a=0,c=null;while(a<360){a++;let u=await this.describeStack(e);if(r)try{let d=await this.describeStackEvents(e),m=[];if(c){for(let p of d){if(p.EventId===c)break;m.push(p)}m.reverse()}else if(d.length>0)m=[d[0]];for(let p of m)r(p);if(d.length>0)c=d[0].EventId}catch{}if(u.StackStatus&&n.includes(u.StackStatus))return u;if(u.StackStatus?.includes("FAILED")||u.StackStatus?.includes("ROLLBACK"))throw Error(`Stack reached failed state: ${u.StackStatus}
|
|
2461
|
+
Reason: ${u.StackStatusReason||"Unknown"}`);await new Promise((d)=>setTimeout(d,5000))}throw Error(`Timeout waiting for stack ${e} to complete`)}async waitForStackWithProgress(e,n,r){let s={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]}[n];if(!s)throw Error(`Unknown waiter: ${n}`);return this.waitForStack(e,s,r)}async createChangeSet(e){let n={StackName:e.stackName,ChangeSetName:e.changeSetName,ChangeSetType:"UPDATE"};if(e.templateBody)n.TemplateBody=e.templateBody;else if(e.templateURL)n.TemplateURL=e.templateURL;if(e.parameters)for(let[i,[s,a]]of Object.entries(e.parameters).entries())n[`Parameters.member.${i+1}.ParameterKey`]=s,n[`Parameters.member.${i+1}.ParameterValue`]=a;if(e.capabilities)for(let[i,s]of e.capabilities.entries())n[`Capabilities.member.${i+1}`]=s;return(await this.request("CreateChangeSet",n)).ChangeSetId}async executeChangeSet(e,n){await this.request("ExecuteChangeSet",{ChangeSetName:e,StackName:n})}async describeStacks(e){let n=typeof e==="string"?e:e.stackName;try{return{Stacks:[await this.describeStack(n)]}}catch{return{Stacks:[]}}}async getStackOutputs(e){let n=await this.request("DescribeStacks",{StackName:e}),i=(n?.DescribeStacksResult||n?.DescribeStacksResponse?.DescribeStacksResult||n)?.Stacks?.member,s=Array.isArray(i)?i[0]:i;if(!s)return{};let a={},c=s.Outputs?.member;if(c){let u=Array.isArray(c)?c:[c];for(let d of u)if(d.OutputKey&&d.OutputValue)a[d.OutputKey]=d.OutputValue}return a}}function Tt(e,n=""){let r={};for(let[i,s]of Object.entries(e)){let a=n?`${n}.${i}`:i;if(Array.isArray(s))s.forEach((c,u)=>{if(typeof c==="object")Object.assign(r,Tt(c,`${a}.${u+1}`));else r[`${a}.${u+1}`]=String(c)});else if(typeof s==="object"&&s!==null)Object.assign(r,Tt(s,a));else if(s!==void 0&&s!==null)r[a]=String(s)}return r}function vi(e){e=e.replace(/<\?xml[^?]*\?>\s*/,"").trim();function n(s,a,c){let u=1,d=c,m=`<${a}`,p=`</${a}>`;while(d<s.length&&u>0){let g=s.indexOf(m,d),y=s.indexOf(p,d);if(y===-1)return-1;if(g!==-1&&g<y){let f=s[g+m.length];if(f===">"||f===" "||f==="/"){let h=s.indexOf(">",g);if(h!==-1&&s[h-1]==="/")d=h+1;else u++,d=h+1}else d=g+m.length}else{if(u--,u===0)return y;d=y+p.length}}return-1}function r(s,a){while(a<s.length&&/\s/.test(s[a]))a++;if(a>=s.length||s[a]!=="<"){let S=s.indexOf("<",a);if(S===-1)return{value:s.slice(a).trim(),end:s.length};return{value:s.slice(a,S).trim(),end:S}}if(s[a+1]==="/")return{value:void 0,end:a};let c=s.slice(a).match(/^<(\w+)([^>]*?)\/?>/);if(!c)return{value:void 0,end:a+1};let u=c[1];if(c[0].endsWith("/>"))return{value:"",end:a+c[0].length};let m=a+c[0].length,p=`</${u}>`,g=n(s,u,m);if(g===-1)return{value:void 0,end:a+c[0].length};let y=s.slice(m,g).trim();if(!y.includes("<"))return{value:y,end:g+p.length};let f={},h=m;while(h<g){while(h<g&&/\s/.test(s[h]))h++;if(h>=g)break;if(s[h]!=="<"||s[h+1]==="/")break;let S=s.slice(h).match(/^<(\w+)/);if(!S)break;let C=S[1],P=r(s,h);if(P.value===void 0){h++;continue}if(C==="member"||f[C]!==void 0){if(!Array.isArray(f[C]))f[C]=f[C]!==void 0?[f[C]]:[];f[C].push(P.value)}else f[C]=P.value;h=P.end}return{value:f,end:g+p.length}}return r(e,0).value||{}}function Ti(e){return{StackName:e.StackName||"",StackId:e.StackId,StackStatus:e.StackStatus,CreationTime:e.CreationTime,LastUpdatedTime:e.LastUpdatedTime,StackStatusReason:e.StackStatusReason,Description:e.Description}}function Ri(e){let r=(e?.ListStacksResult||e?.ListStacksResponse?.ListStacksResult||e)?.StackSummaries?.member;if(!r)return[];return(Array.isArray(r)?r:[r]).map((s)=>({StackName:s.StackName||"",StackId:s.StackId,StackStatus:s.StackStatus,CreationTime:s.CreationTime,LastUpdatedTime:s.LastUpdatedTime,StackStatusReason:s.StackStatusReason,Description:s.Description}))}function Pi(e){let r=(e?.DescribeStackEventsResult||e?.DescribeStackEventsResponse?.DescribeStackEventsResult||e)?.StackEvents?.member;if(!r)return[];return(Array.isArray(r)?r:[r]).map((s)=>({StackId:s.StackId||"",EventId:s.EventId||"",StackName:s.StackName||"",LogicalResourceId:s.LogicalResourceId||"",PhysicalResourceId:s.PhysicalResourceId,ResourceType:s.ResourceType||"",Timestamp:s.Timestamp||"",ResourceStatus:s.ResourceStatus||"",ResourceStatusReason:s.ResourceStatusReason}))}var Ei=5242880,Rt=5242880;var wi=5242880;class Da{region;endpoint;forcePathStyle;credentials;credentialOptions;retryOptions;constructor(e={}){this.region=e.region||process.env.AWS_REGION||"us-east-1",this.endpoint=e.endpoint||`https://s3.${this.region}.amazonaws.com`,this.forcePathStyle=e.forcePathStyle||!1,this.credentials=e.credentials,this.credentialOptions=e.credentialOptions,this.retryOptions=e.retryOptions||{}}async getCredentials(){if(this.credentials)return this.credentials;return Gi(this.credentialOptions)}buildUrl(e,n){let r=n?encodeURIComponent(n).replace(/%2F/g,"/"):"";if(this.forcePathStyle)return n?`${this.endpoint}/${e}/${r}`:`${this.endpoint}/${e}`;let i=new URL(this.endpoint);return i.hostname=`${e}.${i.hostname}`,n?`${i.origin}/${r}`:i.origin}async get(e,n,r={}){let i=await this.getCredentials(),s=this.buildUrl(e,n),a={};if(r.range)a.Range=r.range;if(r.ifModifiedSince)a["If-Modified-Since"]=r.ifModifiedSince.toUTCString();if(r.ifMatch)a["If-Match"]=r.ifMatch;if(r.ifNoneMatch)a["If-None-Match"]=r.ifNoneMatch;let c=new URL(s);if(r.responseContentType)c.searchParams.set("response-content-type",r.responseContentType);if(r.responseContentDisposition)c.searchParams.set("response-content-disposition",r.responseContentDisposition);let u=Y({method:"GET",url:c.toString(),headers:a,...i,service:"s3",region:this.region}),d=await fetch(u.url,{method:u.method,headers:u.headers});if(!d.ok&&d.status!==304){let m=await d.text();throw new be(`Failed to get object: ${m}`,d.status,e,n)}return d}async getText(e,n,r={}){return(await this.get(e,n,r)).text()}async getJSON(e,n,r={}){return(await this.get(e,n,r)).json()}async getBuffer(e,n,r={}){return(await this.get(e,n,r)).arrayBuffer()}async put(e,n,r,i={}){let s,a;if(typeof r==="string")s=new TextEncoder().encode(r).length,a=r;else if(r instanceof ArrayBuffer)s=r.byteLength,a=r;else if(r instanceof Uint8Array)s=r.byteLength,a=r;else if(r instanceof Blob)s=r.size,a=r;else return this.uploadMultipart(e,n,r,{...i,partSize:Rt});if(s>wi){let c=Ni(a).stream();return this.uploadMultipart(e,n,c,{...i,partSize:Rt})}return this.putSimple(e,n,a,s,i)}async putSimple(e,n,r,i,s){let a=await this.getCredentials(),c=this.buildUrl(e,n),u={"Content-Length":String(i),"Content-Type":s.contentType||Fn(n)};if(s.contentEncoding)u["Content-Encoding"]=s.contentEncoding;if(s.cacheControl)u["Cache-Control"]=s.cacheControl;if(s.contentDisposition)u["Content-Disposition"]=s.contentDisposition;if(s.storageClass)u["x-amz-storage-class"]=s.storageClass;if(s.serverSideEncryption)u["x-amz-server-side-encryption"]=s.serverSideEncryption;if(s.acl)u["x-amz-acl"]=s.acl;if(s.tagging)u["x-amz-tagging"]=s.tagging;if(s.metadata)for(let[y,f]of Object.entries(s.metadata))u[`x-amz-meta-${y.toLowerCase()}`]=f;let d;if(typeof r==="string")d=r;else if(r instanceof Blob)d=await r.text();else d=new TextDecoder().decode(r instanceof ArrayBuffer?new Uint8Array(r):r);let m=Y({method:"PUT",url:c,headers:u,body:d,...a,service:"s3",region:this.region}),p=await fetch(m.url,{method:m.method,headers:m.headers,body:r});if(!p.ok){let y=await p.text();throw new be(`Failed to put object: ${y}`,p.status,e,n)}return{etag:(p.headers.get("ETag")||"").replace(/"/g,"")}}async delete(e,n){let r=await this.getCredentials(),i=this.buildUrl(e,n),s=Y({method:"DELETE",url:i,...r,service:"s3",region:this.region}),a=await fetch(s.url,{method:s.method,headers:s.headers});if(!a.ok&&a.status!==204){let c=await a.text();throw new be(`Failed to delete object: ${c}`,a.status,e,n)}}async deleteMany(e,n){let r=await this.getCredentials(),i=`${this.buildUrl(e)}?delete`,a=`<?xml version="1.0" encoding="UTF-8"?><Delete><Quiet>false</Quiet>${n.map((h)=>`<Object><Key>${Di(h)}</Key></Object>`).join("")}</Delete>`,c=Y({method:"POST",url:i,headers:{"Content-Type":"application/xml"},body:a,...r,service:"s3",region:this.region}),u=await fetch(c.url,{method:c.method,headers:c.headers,body:a});if(!u.ok){let h=await u.text();throw new be(`Failed to delete objects: ${h}`,u.status,e)}let d=await u.text(),m=[],p=[],g=/<Deleted><Key>([^<]+)<\/Key>/g,y;while((y=g.exec(d))!==null)m.push(y[1]);let f=/<Error><Key>([^<]+)<\/Key><Code>([^<]+)<\/Code><Message>([^<]+)<\/Message>/g;while((y=f.exec(d))!==null)p.push({key:y[1],error:`${y[2]}: ${y[3]}`});return{deleted:m,errors:p}}async list(e,n={}){let r=await this.getCredentials(),i=new URL(this.buildUrl(e));if(i.searchParams.set("list-type","2"),n.prefix)i.searchParams.set("prefix",n.prefix);if(n.delimiter)i.searchParams.set("delimiter",n.delimiter);if(n.maxKeys)i.searchParams.set("max-keys",String(n.maxKeys));if(n.continuationToken)i.searchParams.set("continuation-token",n.continuationToken);if(n.startAfter)i.searchParams.set("start-after",n.startAfter);let s=Y({method:"GET",url:i.toString(),...r,service:"s3",region:this.region}),a=await fetch(s.url,{method:s.method,headers:s.headers});if(!a.ok){let u=await a.text();throw new be(`Failed to list objects: ${u}`,a.status,e)}let c=await a.text();return Ii(c)}async*listAll(e,n={}){let r;do{let i=await this.list(e,{...n,continuationToken:r});for(let s of i.contents)yield s;r=i.nextContinuationToken}while(r)}async head(e,n){let r=await this.getCredentials(),i=this.buildUrl(e,n),s=Y({method:"HEAD",url:i,...r,service:"s3",region:this.region}),a=await fetch(s.url,{method:s.method,headers:s.headers});if(a.status===404)return null;if(!a.ok){let u=await a.text();throw new be(`Failed to head object: ${u}`,a.status,e,n)}let c={};return a.headers.forEach((u,d)=>{if(d.toLowerCase().startsWith("x-amz-meta-"))c[d.slice(11)]=u}),{contentLength:Number(a.headers.get("Content-Length")||0),contentType:a.headers.get("Content-Type")||"application/octet-stream",etag:(a.headers.get("ETag")||"").replace(/"/g,""),lastModified:new Date(a.headers.get("Last-Modified")||0),metadata:c,storageClass:a.headers.get("x-amz-storage-class")||void 0,serverSideEncryption:a.headers.get("x-amz-server-side-encryption")||void 0}}async exists(e,n){return await this.head(e,n)!==null}async copy(e,n,r,i,s={}){let a=await this.getCredentials(),c=this.buildUrl(r,i),u={"x-amz-copy-source":`/${e}/${encodeURIComponent(n)}`};if(s.metadataDirective)u["x-amz-metadata-directive"]=s.metadataDirective;if(s.contentType)u["Content-Type"]=s.contentType;if(s.storageClass)u["x-amz-storage-class"]=s.storageClass;if(s.acl)u["x-amz-acl"]=s.acl;if(s.metadata)for(let[f,h]of Object.entries(s.metadata))u[`x-amz-meta-${f.toLowerCase()}`]=h;let d=Y({method:"PUT",url:c,headers:u,...a,service:"s3",region:this.region}),m=await fetch(d.url,{method:d.method,headers:d.headers});if(!m.ok){let f=await m.text();throw new be(`Failed to copy object: ${f}`,m.status,r,i)}let g=(await m.text()).match(/<ETag>"?([^"<]+)"?<\/ETag>/);return{etag:g?g[1]:""}}async getPresignedUrl(e,n,r={}){let i=await this.getCredentials(),s=this.buildUrl(e,n);return cs({url:s,method:r.method||"GET",expiresIn:r.expiresIn||3600,...i,service:"s3",region:this.region})}async uploadMultipart(e,n,r,i={}){let s=await this.getCredentials(),a=Math.max(i.partSize||Rt,Ei),c,u;if(r instanceof ReadableStream)c=r;else if(r instanceof Blob)c=r.stream(),u=r.size;else{let p=new Blob([r]);c=p.stream(),u=p.size}let{uploadId:d,baseUrl:m}=await this.initiateMultipartUpload(e,n,i);try{let p=await this.uploadParts(e,n,m,d,c,a,s,u,i.concurrency||4,i.onProgress);return await this.completeMultipartUpload(e,n,m,d,p)}catch(p){throw await this.abortMultipartUpload(e,n,d,m).catch(()=>{}),p}}async initiateMultipartUpload(e,n,r){let i=await this.getCredentials(),s=this.buildUrl(e,n),a=`${s}?uploads`,c={"Content-Type":r.contentType||Fn(n)};if(r.storageClass)c["x-amz-storage-class"]=r.storageClass;if(r.serverSideEncryption)c["x-amz-server-side-encryption"]=r.serverSideEncryption;if(r.acl)c["x-amz-acl"]=r.acl;if(r.metadata)for(let[y,f]of Object.entries(r.metadata))c[`x-amz-meta-${y.toLowerCase()}`]=f;let u=Y({method:"POST",url:a,headers:c,...i,service:"s3",region:this.region}),d=await fetch(u.url,{method:u.method,headers:u.headers});if(!d.ok){let y=await d.text();throw new be(`Failed to initiate multipart upload: ${y}`,d.status,e,n)}let p=(await d.text()).match(/<UploadId>([^<]+)<\/UploadId>/);if(!p)throw new be("Failed to parse upload ID from response",0,e,n);let g=s;if(d.url)try{let y=new URL(d.url);y.search="",g=y.toString()}catch{}return{uploadId:p[1],baseUrl:g}}async uploadParts(e,n,r,i,s,a,c,u,d,m){let p=[],g=s.getReader(),y=1,f=new Uint8Array(0),h=0,S=u?Math.ceil(u/a):void 0,C=new Map,P=async(v,w)=>{let D=`${r}?partNumber=${w}&uploadId=${encodeURIComponent(i)}`,x={"Content-Length":String(v.byteLength),"x-amz-content-sha256":"UNSIGNED-PAYLOAD"},L=Y({method:"PUT",url:D,headers:x,...c,service:"s3",region:this.region}),B=await fetch(L.url,{method:L.method,headers:L.headers,body:v,redirect:"error"});if(!B.ok){let F=await B.text();throw new be(`Failed to upload part ${w}: ${F}`,B.status,e,n)}let O=(B.headers.get("ETag")||"").replace(/"/g,"");if(!O)throw new be(`Missing ETag for part ${w}`,B.status,e,n);return{partNumber:w,etag:O}},E=async()=>{let v=await Promise.race(C.values());C.delete(v.partNumber),p.push(v)};while(!0){let{done:v,value:w}=await g.read();if(w){let D=new Uint8Array(f.length+w.length);D.set(f),D.set(w,f.length),f=D}while(f.length>=a||v&&f.length>0){let D=f.slice(0,a);f=f.slice(a);let x=y++;if(C.size>=d)await E();if(C.set(x,P(D,x)),h+=D.byteLength,m)m({loaded:h,total:u||h,part:x,totalParts:S||x})}if(v)break}while(C.size>0)await E();return p.sort((v,w)=>v.partNumber-w.partNumber),p}async completeMultipartUpload(e,n,r,i,s){let a=await this.getCredentials(),c=`${r}?uploadId=${encodeURIComponent(i)}`,d=`<?xml version="1.0" encoding="UTF-8"?><CompleteMultipartUpload>${s.map((h)=>`<Part><PartNumber>${h.partNumber}</PartNumber><ETag>"${h.etag}"</ETag></Part>`).join("")}</CompleteMultipartUpload>`,m=Y({method:"POST",url:c,headers:{"Content-Type":"application/xml"},body:d,...a,service:"s3",region:this.region}),p=await fetch(m.url,{method:m.method,headers:m.headers,body:d});if(!p.ok){let h=await p.text();throw new be(`Failed to complete multipart upload: ${h}`,p.status,e,n)}let y=(await p.text()).match(/<ETag>"?([^"<]+)"?<\/ETag>/);return{etag:y?y[1]:""}}async abortMultipartUpload(e,n,r,i){let s=await this.getCredentials(),a=`${i??this.buildUrl(e,n)}?uploadId=${encodeURIComponent(r)}`,c=Y({method:"DELETE",url:a,...s,service:"s3",region:this.region});await fetch(c.url,{method:c.method,headers:c.headers})}async emptyAndDeleteBucket(e){let r=[];for await(let c of this.listAll(e,{}))if(r.push(c.key),r.length>=1000)await this.deleteMany(e,r),r=[];if(r.length>0)await this.deleteMany(e,r);let i=await this.getCredentials(),s=this.buildUrl(e),a=Y({method:"DELETE",url:s,...i,service:"s3",region:this.region});await fetch(a.url,{method:a.method,headers:a.headers})}}class be extends Error{statusCode;bucket;key;constructor(e,n,r,i){super(e);this.statusCode=n;this.bucket=r;this.key=i;this.name="S3Error"}}function Ii(e){let n=[],r=[],i=/<Contents>([\s\S]*?)<\/Contents>/g,s;while((s=i.exec(e))!==null){let c=s[1];n.push({key:z(c,"Key")||"",lastModified:new Date(z(c,"LastModified")||0),etag:(z(c,"ETag")||"").replace(/"/g,""),size:Number(z(c,"Size")||0),storageClass:z(c,"StorageClass")||"STANDARD"})}let a=/<CommonPrefixes><Prefix>([^<]+)<\/Prefix><\/CommonPrefixes>/g;while((s=a.exec(e))!==null)r.push(s[1]);return{contents:n,commonPrefixes:r,isTruncated:z(e,"IsTruncated")==="true",continuationToken:z(e,"ContinuationToken")||void 0,nextContinuationToken:z(e,"NextContinuationToken")||void 0,keyCount:Number(z(e,"KeyCount")||0),maxKeys:Number(z(e,"MaxKeys")||1000),prefix:z(e,"Prefix")||void 0,delimiter:z(e,"Delimiter")||void 0}}function z(e,n){let r=new RegExp(`<${n}>([^<]*)</${n}>`),i=e.match(r);return i?i[1]:null}function Di(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Fn(e){let n=e.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"}[n||""]||"application/octet-stream"}function Ni(e){if(e instanceof Blob)return e;if(typeof e==="string")return new Blob([e],{type:"text/plain"});return new Blob([e])}function Du(e){return new Da(e)}class ku{profile;credentials=null;constructor(e="default"){this.profile=e}async init(){this.credentials=await Dn(this.profile)}async ensureCredentials(){if(!this.credentials)await this.init();return this.credentials}async createInvalidation(e){let n=await this.ensureCredentials(),r=e.callerReference||`invalidation-${Date.now()}`,i=`<?xml version="1.0" encoding="UTF-8"?>
|
|
2462
2462
|
<InvalidationBatch>
|
|
2463
2463
|
<Paths>
|
|
2464
2464
|
<Quantity>${e.paths.length}</Quantity>
|
|
@@ -2467,23 +2467,23 @@ Reason: ${u.StackStatusReason||"Unknown"}`);await new Promise((d)=>setTimeout(d,
|
|
|
2467
2467
|
</Items>
|
|
2468
2468
|
</Paths>
|
|
2469
2469
|
<CallerReference>${r}</CallerReference>
|
|
2470
|
-
</InvalidationBatch>`,s=`https://cloudfront.amazonaws.com/2020-05-31/distribution/${e.distributionId}/invalidation`,a=await
|
|
2470
|
+
</InvalidationBatch>`,s=`https://cloudfront.amazonaws.com/2020-05-31/distribution/${e.distributionId}/invalidation`,a=await Ot({method:"POST",url:s,service:"cloudfront",region:"us-east-1",headers:{"Content-Type":"text/xml"},body:i,accessKeyId:n.accessKeyId,secretAccessKey:n.secretAccessKey,sessionToken:n.sessionToken});return(await xn(a)).Id}async getInvalidation(e,n){let r=await this.ensureCredentials(),i=`https://cloudfront.amazonaws.com/2020-05-31/distribution/${e}/invalidation/${n}`,s=await Ot({method:"GET",url:i,service:"cloudfront",region:"us-east-1",accessKeyId:r.accessKeyId,secretAccessKey:r.secretAccessKey,sessionToken:r.sessionToken});return await xn(s)}async listInvalidations(e){let n=await this.ensureCredentials(),r=`https://cloudfront.amazonaws.com/2020-05-31/distribution/${e}/invalidation`,i=await Ot({method:"GET",url:r,service:"cloudfront",region:"us-east-1",accessKeyId:n.accessKeyId,secretAccessKey:n.secretAccessKey,sessionToken:n.sessionToken});return(await xn(i)).Items||[]}async waitForInvalidation(e,n,r=60,i=5000){for(let s=0;s<r;s++){if((await this.getInvalidation(e,n)).Status==="Completed")return;if(s<r-1)await new Promise((c)=>setTimeout(c,i))}throw Error(`Invalidation ${n} did not complete within the expected time`)}async invalidateAll(e){return await this.createInvalidation({distributionId:e,paths:["/*"]})}}class xt extends Error{code;solution;details;constructor(e,n,r,i){super(e);this.code=n;this.solution=r;this.details=i;this.name="CloudError",Error.captureStackTrace?.(this,xt)}toString(){let e=`${this.name} [${this.code}]: ${this.message}`;if(this.solution)e+=`
|
|
2471
2471
|
|
|
2472
2472
|
\uD83D\uDCA1 Solution: ${this.solution}`;if(this.details&&Object.keys(this.details).length>0){e+=`
|
|
2473
2473
|
|
|
2474
2474
|
Details:`;for(let[n,r]of Object.entries(this.details))e+=`
|
|
2475
|
-
${n}: ${JSON.stringify(r)}`}return e}}class ns extends
|
|
2475
|
+
${n}: ${JSON.stringify(r)}`}return e}}class ns extends xt{constructor(e,n,r){super(e,"CONFIG_ERROR",n,r);this.name="ConfigurationError"}}class tr extends xt{constructor(e,n,r){super(e,"CREDENTIAL_ERROR",n,r);this.name="CredentialError"}}class Nu extends xt{constructor(e,n,r){super(e,"DEPLOYMENT_ERROR",n,r);this.name="DeploymentError"}}class Sl extends xt{constructor(e,n,r){super(e,"VALIDATION_ERROR",n,r);this.name="ValidationError"}}class xu extends xt{statusCode;constructor(e,n,r,i){super(e,"AWS_API_ERROR",r,i);this.statusCode=n;this.name="AWSAPIError"}}var _u={NO_CREDENTIALS:{message:"AWS credentials not found",solution:`Configure AWS credentials using one of these methods:
|
|
2476
2476
|
1. Set environment variables: AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY
|
|
2477
2477
|
2. Create ~/.aws/credentials file with your credentials
|
|
2478
2478
|
3. Use an IAM role (for EC2 instances)
|
|
2479
|
-
4. Run 'aws configure' if you have AWS CLI installed`},INVALID_CREDENTIALS:{message:"AWS credentials are invalid",solution:"Verify your AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are correct. Run: aws sts get-caller-identity"},EXPIRED_CREDENTIALS:{message:"AWS credentials have expired",solution:"Refresh your AWS credentials. If using temporary credentials, generate new ones."},MISSING_CONFIG:{message:"Configuration file not found",solution:"Create a cloud.config.ts file in your project root. Use: cloud init"},INVALID_CONFIG:{message:"Configuration is invalid",solution:"Check your cloud.config.ts file for syntax errors. Use: cloud config:validate"},MISSING_REQUIRED_FIELD:{message:"Required configuration field is missing",solution:"Add the missing field to your cloud.config.ts file"},INVALID_REGION:{message:"AWS region is invalid",solution:"Use a valid AWS region like us-east-1, us-west-2, eu-west-1, etc."},STACK_ALREADY_EXISTS:{message:"CloudFormation stack already exists",solution:"Use: cloud deploy --update to update the existing stack, or cloud destroy to delete it first"},STACK_IN_PROGRESS:{message:"Stack operation already in progress",solution:"Wait for the current operation to complete, or cancel it in the AWS Console"},INSUFFICIENT_PERMISSIONS:{message:"Insufficient IAM permissions",solution:"Ensure your IAM user/role has the necessary permissions for CloudFormation and the resources you're deploying"},RESOURCE_LIMIT_EXCEEDED:{message:"AWS service limit exceeded",solution:"Request a service limit increase in the AWS Console, or clean up unused resources"},ROLLBACK_COMPLETE:{message:"Stack creation failed and rolled back",solution:"Check the CloudFormation events to see which resource failed. Fix the issue and try again."},CIRCULAR_DEPENDENCY:{message:"Circular dependency detected in resources",solution:"Review your resource dependencies and remove the circular reference"},INVALID_RESOURCE_NAME:{message:"Resource name contains invalid characters",solution:"Use only alphanumeric characters and hyphens in resource names"},DUPLICATE_RESOURCE:{message:"Duplicate resource name detected",solution:"Ensure all resource names are unique in your configuration"},VPC_CIDR_CONFLICT:{message:"VPC CIDR block conflicts with existing VPC",solution:"Use a different CIDR block that doesn't overlap with existing VPCs"},SUBNET_CIDR_INVALID:{message:"Subnet CIDR block is invalid or outside VPC range",solution:"Ensure subnet CIDR is within the VPC CIDR range and properly sized"},DB_INSTANCE_LIMIT:{message:"RDS instance limit reached",solution:"Delete unused RDS instances or request a limit increase"},INVALID_DB_NAME:{message:"Database name contains invalid characters",solution:"Use only alphanumeric characters and underscores, starting with a letter"},BUCKET_ALREADY_EXISTS:{message:"S3 bucket name already exists globally",solution:"S3 bucket names must be globally unique. Try a different name with your organization prefix"},INVALID_BUCKET_NAME:{message:"S3 bucket name is invalid",solution:"Use lowercase letters, numbers, and hyphens. Must start/end with letter/number. 3-63 characters."},TEMPLATE_TOO_LARGE:{message:"CloudFormation template exceeds size limit",solution:"Split your infrastructure into multiple stacks or use nested stacks"},INVALID_TEMPLATE:{message:"CloudFormation template is invalid",solution:"Validate your template with: cloud config:validate"},PARAMETER_NOT_FOUND:{message:"CloudFormation parameter not found",solution:"Check that all referenced parameters are defined in your template"}};function Ou(e){return _u[e]}function vl(e,n){let r=Ou(e);return new
|
|
2480
|
-
Stack trace:`),console.error(n.stack)}}static success(e){console.log(`✔ ${e}`)}}function og(e){if(!e)throw vl("MISSING_CONFIG");if(!e.project)throw new ns("Missing required field: project","Add a project configuration with name, slug, and region",{field:"project"});if(!e.project.name)throw new ns("Missing required field: project.name","Add a project name to your configuration",{field:"project.name"});if(!e.project.slug)throw new ns("Missing required field: project.slug","Add a project slug (lowercase, alphanumeric with hyphens)",{field:"project.slug"});if(!/^[a-z0-9-]+$/.test(e.project.slug))throw new Sl("Invalid project slug format","Use only lowercase letters, numbers, and hyphens",{slug:e.project.slug});if(e.project.region){if(!["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"].includes(e.project.region))throw vl("INVALID_REGION",{region:e.project.region})}Se.success("Configuration validation passed")}function sg(e){let n=[];if(e.environments?.production&&e.infrastructure?.database){let r=e.infrastructure.database;if((r.postgres||r.mysql)&&!r.postgres?.multiAZ&&!r.mysql?.multiAZ)n.push("Production database should use Multi-AZ for high availability")}if(e.infrastructure?.storage){for(let[r,i]of Object.entries(e.infrastructure.storage))if(i.encryption===!1)n.push(`Storage "${r}" is not encrypted - consider enabling encryption for security`)}if(e.infrastructure?.storage){for(let[r,i]of Object.entries(e.infrastructure.storage))if(i.public===!0)n.push(`Storage "${r}" is publicly accessible - ensure this is intentional`)}if(e.infrastructure?.database){let r=e.infrastructure.database;if(r.postgres||r.mysql){let i=r.postgres?.backupRetentionDays||r.mysql?.backupRetentionDays;if(!i||i<7)n.push("Database backup retention is less than 7 days - consider increasing for production")}}if(!e.infrastructure?.monitoring)n.push("No monitoring configured - consider adding CloudWatch alarms");return n}async function ag(e="default"){try{Se.verbose("Resolving AWS credentials...");let n=await
|
|
2479
|
+
4. Run 'aws configure' if you have AWS CLI installed`},INVALID_CREDENTIALS:{message:"AWS credentials are invalid",solution:"Verify your AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are correct. Run: aws sts get-caller-identity"},EXPIRED_CREDENTIALS:{message:"AWS credentials have expired",solution:"Refresh your AWS credentials. If using temporary credentials, generate new ones."},MISSING_CONFIG:{message:"Configuration file not found",solution:"Create a cloud.config.ts file in your project root. Use: cloud init"},INVALID_CONFIG:{message:"Configuration is invalid",solution:"Check your cloud.config.ts file for syntax errors. Use: cloud config:validate"},MISSING_REQUIRED_FIELD:{message:"Required configuration field is missing",solution:"Add the missing field to your cloud.config.ts file"},INVALID_REGION:{message:"AWS region is invalid",solution:"Use a valid AWS region like us-east-1, us-west-2, eu-west-1, etc."},STACK_ALREADY_EXISTS:{message:"CloudFormation stack already exists",solution:"Use: cloud deploy --update to update the existing stack, or cloud destroy to delete it first"},STACK_IN_PROGRESS:{message:"Stack operation already in progress",solution:"Wait for the current operation to complete, or cancel it in the AWS Console"},INSUFFICIENT_PERMISSIONS:{message:"Insufficient IAM permissions",solution:"Ensure your IAM user/role has the necessary permissions for CloudFormation and the resources you're deploying"},RESOURCE_LIMIT_EXCEEDED:{message:"AWS service limit exceeded",solution:"Request a service limit increase in the AWS Console, or clean up unused resources"},ROLLBACK_COMPLETE:{message:"Stack creation failed and rolled back",solution:"Check the CloudFormation events to see which resource failed. Fix the issue and try again."},CIRCULAR_DEPENDENCY:{message:"Circular dependency detected in resources",solution:"Review your resource dependencies and remove the circular reference"},INVALID_RESOURCE_NAME:{message:"Resource name contains invalid characters",solution:"Use only alphanumeric characters and hyphens in resource names"},DUPLICATE_RESOURCE:{message:"Duplicate resource name detected",solution:"Ensure all resource names are unique in your configuration"},VPC_CIDR_CONFLICT:{message:"VPC CIDR block conflicts with existing VPC",solution:"Use a different CIDR block that doesn't overlap with existing VPCs"},SUBNET_CIDR_INVALID:{message:"Subnet CIDR block is invalid or outside VPC range",solution:"Ensure subnet CIDR is within the VPC CIDR range and properly sized"},DB_INSTANCE_LIMIT:{message:"RDS instance limit reached",solution:"Delete unused RDS instances or request a limit increase"},INVALID_DB_NAME:{message:"Database name contains invalid characters",solution:"Use only alphanumeric characters and underscores, starting with a letter"},BUCKET_ALREADY_EXISTS:{message:"S3 bucket name already exists globally",solution:"S3 bucket names must be globally unique. Try a different name with your organization prefix"},INVALID_BUCKET_NAME:{message:"S3 bucket name is invalid",solution:"Use lowercase letters, numbers, and hyphens. Must start/end with letter/number. 3-63 characters."},TEMPLATE_TOO_LARGE:{message:"CloudFormation template exceeds size limit",solution:"Split your infrastructure into multiple stacks or use nested stacks"},INVALID_TEMPLATE:{message:"CloudFormation template is invalid",solution:"Validate your template with: cloud config:validate"},PARAMETER_NOT_FOUND:{message:"CloudFormation parameter not found",solution:"Check that all referenced parameters are defined in your template"}};function Ou(e){return _u[e]}function vl(e,n){let r=Ou(e);return new xt(r.message,e,r.solution,n)}class Se{static verboseMode=!1;static debugMode=!1;static setVerbose(e){this.verboseMode=e}static setDebug(e){this.debugMode=e}static verbose(e,...n){if(this.verboseMode)console.log(`[VERBOSE] ${e}`,...n)}static debug(e,...n){if(this.debugMode)console.log(`[DEBUG] ${e}`,...n)}static info(e,...n){console.log(`ℹ ${e}`,...n)}static warn(e,...n){console.warn(`⚠ ${e}`,...n)}static error(e,n){if(console.error(`✖ ${e}`),n){if(n instanceof xt)console.error(n.toString());else console.error(n.message);if(this.debugMode&&n.stack)console.error(`
|
|
2480
|
+
Stack trace:`),console.error(n.stack)}}static success(e){console.log(`✔ ${e}`)}}function og(e){if(!e)throw vl("MISSING_CONFIG");if(!e.project)throw new ns("Missing required field: project","Add a project configuration with name, slug, and region",{field:"project"});if(!e.project.name)throw new ns("Missing required field: project.name","Add a project name to your configuration",{field:"project.name"});if(!e.project.slug)throw new ns("Missing required field: project.slug","Add a project slug (lowercase, alphanumeric with hyphens)",{field:"project.slug"});if(!/^[a-z0-9-]+$/.test(e.project.slug))throw new Sl("Invalid project slug format","Use only lowercase letters, numbers, and hyphens",{slug:e.project.slug});if(e.project.region){if(!["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"].includes(e.project.region))throw vl("INVALID_REGION",{region:e.project.region})}Se.success("Configuration validation passed")}function sg(e){let n=[];if(e.environments?.production&&e.infrastructure?.database){let r=e.infrastructure.database;if((r.postgres||r.mysql)&&!r.postgres?.multiAZ&&!r.mysql?.multiAZ)n.push("Production database should use Multi-AZ for high availability")}if(e.infrastructure?.storage){for(let[r,i]of Object.entries(e.infrastructure.storage))if(i.encryption===!1)n.push(`Storage "${r}" is not encrypted - consider enabling encryption for security`)}if(e.infrastructure?.storage){for(let[r,i]of Object.entries(e.infrastructure.storage))if(i.public===!0)n.push(`Storage "${r}" is publicly accessible - ensure this is intentional`)}if(e.infrastructure?.database){let r=e.infrastructure.database;if(r.postgres||r.mysql){let i=r.postgres?.backupRetentionDays||r.mysql?.backupRetentionDays;if(!i||i<7)n.push("Database backup retention is less than 7 days - consider increasing for production")}}if(!e.infrastructure?.monitoring)n.push("No monitoring configured - consider adding CloudWatch alarms");return n}async function ag(e="default"){try{Se.verbose("Resolving AWS credentials...");let n=await Dn(e);if(!n.accessKeyId||!n.secretAccessKey)throw new tr("AWS credentials are incomplete","Ensure both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are set");Se.verbose("Credentials resolved successfully"),Se.debug("Access Key ID:",n.accessKeyId.substring(0,8)+"..."),Se.verbose("Testing credentials with GetCallerIdentity...");let r;try{r=await bl(n),Se.verbose("Credentials are valid"),Se.debug("Account ID:",r)}catch(i){if(i instanceof Error)if(i.message.includes("InvalidClientTokenId"))throw new tr("Invalid AWS access key ID","Check that your AWS_ACCESS_KEY_ID is correct");else if(i.message.includes("SignatureDoesNotMatch"))throw new tr("Invalid AWS secret access key","Check that your AWS_SECRET_ACCESS_KEY is correct");else if(i.message.includes("ExpiredToken"))throw new tr("AWS credentials have expired","Refresh your temporary credentials or use long-term credentials");else throw new tr(`Failed to validate credentials: ${i.message}`,"Verify your AWS credentials are correct and have the necessary permissions");throw i}return{valid:!0,accountId:r,region:n.region}}catch(n){if(n instanceof tr)throw n;return{valid:!1,error:n instanceof Error?n.message:"Unknown error"}}}async function cg(e,n){return{allowed:n,denied:[]}}function $u(e){let n=new Set(["cloudformation:CreateStack","cloudformation:UpdateStack","cloudformation:DeleteStack","cloudformation:DescribeStacks","cloudformation:DescribeStackEvents","cloudformation:GetTemplate","cloudformation:ListStacks"]);if(e.infrastructure){if(e.infrastructure.storage)n.add("s3:CreateBucket"),n.add("s3:DeleteBucket"),n.add("s3:PutBucketPolicy"),n.add("s3:PutBucketVersioning"),n.add("s3:PutBucketEncryption"),n.add("s3:PutObject"),n.add("s3:GetObject");if(e.infrastructure.compute){if(e.infrastructure.compute.server)n.add("ec2:RunInstances"),n.add("ec2:TerminateInstances"),n.add("ec2:DescribeInstances"),n.add("autoscaling:CreateAutoScalingGroup"),n.add("autoscaling:UpdateAutoScalingGroup"),n.add("autoscaling:DeleteAutoScalingGroup"),n.add("elasticloadbalancing:CreateLoadBalancer"),n.add("elasticloadbalancing:DeleteLoadBalancer");if(e.infrastructure.compute.fargate)n.add("ecs:CreateCluster"),n.add("ecs:DeleteCluster"),n.add("ecs:CreateService"),n.add("ecs:UpdateService"),n.add("ecs:DeleteService"),n.add("ecs:RegisterTaskDefinition")}if(e.infrastructure.database){if(e.infrastructure.database.postgres||e.infrastructure.database.mysql)n.add("rds:CreateDBInstance"),n.add("rds:DeleteDBInstance"),n.add("rds:ModifyDBInstance"),n.add("rds:DescribeDBInstances");if(e.infrastructure.database.dynamodb)n.add("dynamodb:CreateTable"),n.add("dynamodb:DeleteTable"),n.add("dynamodb:UpdateTable"),n.add("dynamodb:DescribeTable")}if(e.infrastructure.functions)n.add("lambda:CreateFunction"),n.add("lambda:DeleteFunction"),n.add("lambda:UpdateFunctionCode"),n.add("lambda:UpdateFunctionConfiguration"),n.add("lambda:AddPermission");if(e.infrastructure.cdn)n.add("cloudfront:CreateDistribution"),n.add("cloudfront:UpdateDistribution"),n.add("cloudfront:DeleteDistribution"),n.add("cloudfront:GetDistribution");if(e.infrastructure.network)n.add("ec2:CreateVpc"),n.add("ec2:DeleteVpc"),n.add("ec2:CreateSubnet"),n.add("ec2:DeleteSubnet"),n.add("ec2:CreateInternetGateway"),n.add("ec2:DeleteInternetGateway"),n.add("ec2:CreateNatGateway"),n.add("ec2:DeleteNatGateway"),n.add("ec2:CreateRouteTable"),n.add("ec2:DeleteRouteTable"),n.add("ec2:CreateSecurityGroup"),n.add("ec2:DeleteSecurityGroup")}return n.add("iam:CreateRole"),n.add("iam:DeleteRole"),n.add("iam:AttachRolePolicy"),n.add("iam:DetachRolePolicy"),n.add("iam:PutRolePolicy"),n.add("iam:GetRole"),n.add("iam:PassRole"),Array.from(n).sort()}function lg(e){let n=$u(e);return JSON.stringify({Version:"2012-10-17",Statement:[{Effect:"Allow",Action:n,Resource:"*"}]},null,2)}var Ne={ec2:{"Running On-Demand Instances":20,"Elastic IPs":5,VPCs:5,"Internet Gateways":5,"NAT Gateways":5,"Security Groups":500},rds:{"DB Instances":40,"DB Snapshots":100,"DB Parameter Groups":50},lambda:{"Concurrent Executions":1000,"Function Storage":80530636800},s3:{Buckets:100},cloudformation:{Stacks:200,StackSets:100},elasticache:{Nodes:100,Clusters:100},dynamodb:{Tables:256},ecs:{Clusters:1e4,"Services per Cluster":2000}};async function dg(e){let n=[];if(Se.verbose("Checking AWS service quotas..."),e.infrastructure?.compute?.server){let i=e.infrastructure.compute.server.autoScaling?.max||1;n.push({service:"EC2",quotaName:"Running On-Demand Instances",currentValue:i,limit:Ne.ec2["Running On-Demand Instances"],percentage:i/Ne.ec2["Running On-Demand Instances"]*100,warning:i>Ne.ec2["Running On-Demand Instances"]*0.8})}if(e.infrastructure?.network?.vpc)n.push({service:"EC2",quotaName:"VPCs",currentValue:1,limit:Ne.ec2.VPCs,percentage:1/Ne.ec2.VPCs*100,warning:!1});if(e.infrastructure?.database?.postgres||e.infrastructure?.database?.mysql)n.push({service:"RDS",quotaName:"DB Instances",currentValue:1,limit:Ne.rds["DB Instances"],percentage:1/Ne.rds["DB Instances"]*100,warning:!1});if(e.infrastructure?.storage){let i=Object.keys(e.infrastructure.storage).length;n.push({service:"S3",quotaName:"Buckets",currentValue:i,limit:Ne.s3.Buckets,percentage:i/Ne.s3.Buckets*100,warning:i>Ne.s3.Buckets*0.8})}if(e.infrastructure?.functions){let i=0;for(let s of Object.values(e.infrastructure.functions))if(Array.isArray(s))i+=s.length;n.push({service:"Lambda",quotaName:"Functions (estimated)",currentValue:i,limit:1000,percentage:i/1000*100,warning:i>800})}if(e.infrastructure?.database?.dynamodb){let i=e.infrastructure.database.dynamodb.tables?.length||0;n.push({service:"DynamoDB",quotaName:"Tables",currentValue:i,limit:Ne.dynamodb.Tables,percentage:i/Ne.dynamodb.Tables*100,warning:i>Ne.dynamodb.Tables*0.8})}let r=n.filter((i)=>i.warning);if(r.length>0){Se.warn("Service quota warnings detected:");for(let i of r)Se.warn(` ${i.service} - ${i.quotaName}: ${i.currentValue}/${i.limit} (${i.percentage.toFixed(1)}%)`)}else Se.verbose("All service quotas are within limits");return n}function ug(e){if(e.length===0)return"No quotas to check";let n=`Service Quota Usage:
|
|
2481
2481
|
|
|
2482
2482
|
`,r=e.reduce((i,s)=>{if(!i[s.service])i[s.service]=[];return i[s.service].push(s),i},{});for(let[i,s]of Object.entries(r)){n+=`${i}:
|
|
2483
2483
|
`;for(let a of s){let c=a.warning?"⚠":"✓";n+=` ${c} ${a.quotaName}: ${a.currentValue}/${a.limit} (${a.percentage.toFixed(1)}%)
|
|
2484
2484
|
`}n+=`
|
|
2485
|
-
`}return n}function pg(e){let n=[];for(let r of e)if(r.percentage>=100)n.push(`Request quota increase for ${r.service} - ${r.quotaName} (currently ${r.limit})`);else if(r.warning)n.push(`Consider requesting quota increase for ${r.service} - ${r.quotaName} (${r.percentage.toFixed(1)}% used)`);return n}import{createHash as
|
|
2486
|
-
`);return Tl(r)}function hg(e){let n=rt(e);return Tl(`${e}:${n.size}:${n.mtimeMs}`)}function yg(e,n){let r=new Map(e.map((u)=>[u.path,u])),i=new Map(n.map((u)=>[u.path,u])),s=[],a=[],c=[];for(let[u,d]of i){let m=r.get(u);if(!m)s.push(d);else if(m.hash!==d.hash)a.push(d)}for(let[u,d]of r)if(!i.has(u))c.push(d);return{added:s,modified:a,deleted:c}}class Mu{cache;constructor(){this.cache=new Map}get(e){let n=rt(e),r=this.cache.get(e);if(r&&r.mtime===n.mtimeMs&&r.size===n.size)return r.hash;return}set(e,n){let r=rt(e);this.cache.set(e,{hash:n,mtime:r.mtimeMs,size:r.size})}async getOrCompute(e,n={}){let r=this.get(e);if(r)return r;let i=await Cl(e,n);return this.set(e,i),i}clear(){this.cache.clear()}}async function xa(e,n={}){let r=n.concurrency||5,i=n.stopOnError??!0,s=[],a=[],c=Date.now(),u=[...e],d=[];async function m(y,f){try{let h=await y();s[f]=h}catch(h){let S=h instanceof Error?h:Error(String(h));if(a.push(S),i)throw u.length=0,S}}let p=0;while(u.length>0||d.length>0){while(d.length<r&&u.length>0){let y=u.shift(),f=p++,h=m(y,f);d.push(h)}if(d.length>0){await Promise.race(d);for(let y=d.length-1;y>=0;y--)if(await Promise.race([d[y].then(()=>!0),Promise.resolve(!1)]))d.splice(y,1)}if(i&&a.length>0)break}let g=Date.now()-c;return{results:s.filter((y)=>y!==void 0),errors:a,duration:g}}async function bg(e,n,r={}){let i=e.map((s)=>()=>n(s));return xa(i,r)}async function Sg(e,n,r=5){let i=e.map((a,c)=>()=>n(a,c)),s=await xa(i,{concurrency:r,stopOnError:!1});if(s.errors.length>0)throw AggregateError(s.errors,"Parallel map failed");return s.results}async function vg(e,n={}){let r=n.retries||3,i=n.retryDelay||1000,s=e.map((a)=>async()=>{let c;for(let u=0;u<=r;u++)try{return await a()}catch(d){if(c=d instanceof Error?d:Error(String(d)),u<r)await
|
|
2485
|
+
`}return n}function pg(e){let n=[];for(let r of e)if(r.percentage>=100)n.push(`Request quota increase for ${r.service} - ${r.quotaName} (currently ${r.limit})`);else if(r.warning)n.push(`Consider requesting quota increase for ${r.service} - ${r.quotaName} (${r.percentage.toFixed(1)}% used)`);return n}import{createHash as Wn}from"node:crypto";import{existsSync as nt,mkdirSync as xi,readdirSync as Gn,readFileSync as _n,unlinkSync as Ke,writeFileSync as ki}from"node:fs";import{join as Pt}from"node:path";class ka{cacheDir;ttl;constructor(e,n={}){this.cacheDir=e,this.ttl=n.ttl||86400000}ensureCacheDir(){if(!nt(this.cacheDir))xi(this.cacheDir,{recursive:!0})}getCachePath(e){let n=Wn("sha256").update(e).digest("hex");return Pt(this.cacheDir,`${n}.json`)}get(e){let n=this.getCachePath(e);if(!nt(n))return;try{let r=_n(n,"utf-8"),i=JSON.parse(r);if(Date.now()-i.timestamp>this.ttl){Ke(n);return}return i.value}catch{Ke(n);return}}set(e,n,r){this.ensureCacheDir();let i=this.getCachePath(e),s={value:n,timestamp:Date.now(),hash:r};ki(i,JSON.stringify(s),"utf-8")}has(e){return this.get(e)!==void 0}clear(){if(!nt(this.cacheDir))return;let e=Gn(this.cacheDir);for(let n of e)Ke(Pt(this.cacheDir,n))}prune(){if(!nt(this.cacheDir))return;let e=Gn(this.cacheDir),n=Date.now();for(let r of e){let i=Pt(this.cacheDir,r);try{let s=_n(i,"utf-8"),a=JSON.parse(s);if(n-a.timestamp>this.ttl)Ke(i)}catch{Ke(i)}}}}class Na{cache;constructor(e=ze("cache","templates")){this.cache=new ka(e,{ttl:86400000})}getTemplate(e){return this.cache.get(`template:${e}`)}setTemplate(e,n){let r=this.hashTemplate(n);this.cache.set(`template:${e}`,n,r)}hasChanged(e,n){let r=this.cache.get(`template:${e}`);if(!r)return!0;let i=this.hashTemplate(r),s=this.hashTemplate(n);return i!==s}hashTemplate(e){return Wn("sha256").update(e).digest("hex")}clear(){this.cache.clear()}prune(){this.cache.prune()}}var Et=null;function Lu(){if(!Et)Et=new Na;return Et}import{createHash as wt}from"node:crypto";import{createReadStream as Mi,readdirSync as Li,statSync as rt}from"node:fs";import{join as Oi,relative as $i}from"node:path";async function Cl(e,n={}){let r=n.algorithm||"sha256",i=n.chunkSize||65536;return new Promise((s,a)=>{let c=wt(r),u=Mi(e,{highWaterMark:i});u.on("data",(d)=>c.update(d)),u.on("end",()=>s(c.digest("hex"))),u.on("error",a)})}function Tl(e,n="sha256"){return wt(n).update(e).digest("hex")}function mg(e,n="sha256"){return wt(n).update(e).digest("hex")}async function gg(e,n={}){let r=n.ignorePatterns||["node_modules",".git","dist","build",wn()],i=[];async function s(a){let c=Li(a,{withFileTypes:!0});for(let u of c){let d=Oi(a,u.name),m=$i(e,d);if(r.some((p)=>m.includes(p)))continue;if(u.isDirectory())await s(d);else if(u.isFile()){let p=rt(d),g=await Cl(d,n);i.push({path:m,hash:g,size:p.size,mtime:p.mtimeMs})}}}return await s(e),i}function fg(e){let r=[...e].sort((i,s)=>i.path.localeCompare(s.path)).map((i)=>`${i.path}:${i.hash}`).join(`
|
|
2486
|
+
`);return Tl(r)}function hg(e){let n=rt(e);return Tl(`${e}:${n.size}:${n.mtimeMs}`)}function yg(e,n){let r=new Map(e.map((u)=>[u.path,u])),i=new Map(n.map((u)=>[u.path,u])),s=[],a=[],c=[];for(let[u,d]of i){let m=r.get(u);if(!m)s.push(d);else if(m.hash!==d.hash)a.push(d)}for(let[u,d]of r)if(!i.has(u))c.push(d);return{added:s,modified:a,deleted:c}}class Mu{cache;constructor(){this.cache=new Map}get(e){let n=rt(e),r=this.cache.get(e);if(r&&r.mtime===n.mtimeMs&&r.size===n.size)return r.hash;return}set(e,n){let r=rt(e);this.cache.set(e,{hash:n,mtime:r.mtimeMs,size:r.size})}async getOrCompute(e,n={}){let r=this.get(e);if(r)return r;let i=await Cl(e,n);return this.set(e,i),i}clear(){this.cache.clear()}}async function xa(e,n={}){let r=n.concurrency||5,i=n.stopOnError??!0,s=[],a=[],c=Date.now(),u=[...e],d=[];async function m(y,f){try{let h=await y();s[f]=h}catch(h){let S=h instanceof Error?h:Error(String(h));if(a.push(S),i)throw u.length=0,S}}let p=0;while(u.length>0||d.length>0){while(d.length<r&&u.length>0){let y=u.shift(),f=p++,h=m(y,f);d.push(h)}if(d.length>0){await Promise.race(d);for(let y=d.length-1;y>=0;y--)if(await Promise.race([d[y].then(()=>!0),Promise.resolve(!1)]))d.splice(y,1)}if(i&&a.length>0)break}let g=Date.now()-c;return{results:s.filter((y)=>y!==void 0),errors:a,duration:g}}async function bg(e,n,r={}){let i=e.map((s)=>()=>n(s));return xa(i,r)}async function Sg(e,n,r=5){let i=e.map((a,c)=>()=>n(a,c)),s=await xa(i,{concurrency:r,stopOnError:!1});if(s.errors.length>0)throw AggregateError(s.errors,"Parallel map failed");return s.results}async function vg(e,n={}){let r=n.retries||3,i=n.retryDelay||1000,s=e.map((a)=>async()=>{let c;for(let u=0;u<=r;u++)try{return await a()}catch(d){if(c=d instanceof Error?d:Error(String(d)),u<r)await Vn(i*(u+1))}throw c});return xa(s,n)}async function Cg(e){let n=[];for(let r of e){let i=await r();n.push(i)}return n}function Vn(e){return new Promise((n)=>setTimeout(n,e))}async function Tg(e,n,r="Operation timed out"){return Promise.race([e(),new Promise((i,s)=>setTimeout(()=>s(Error(r)),n))])}class Uu{maxConcurrent;minInterval;queue=[];running=0;lastExecution=0;constructor(e=5,n=100){this.maxConcurrent=e;this.minInterval=n}async execute(e){await this.waitForSlot(),this.running++,this.lastExecution=Date.now();try{return await e()}finally{this.running--,this.processQueue()}}waitForSlot(){if(this.running<this.maxConcurrent){let e=Date.now()-this.lastExecution;if(e>=this.minInterval)return Promise.resolve();return Vn(this.minInterval-e)}return new Promise((e)=>this.queue.push(e))}processQueue(){if(this.queue.length>0&&this.running<this.maxConcurrent)this.queue.shift()()}stats(){return{running:this.running,queued:this.queue.length}}}function Bu(e,n){let r=[];for(let i=0;i<e.length;i+=n)r.push(e.slice(i,i+n));return r}async function Eg(e,n,r){let i=Bu(e,n),s=[];for(let a of i){let c=await r(a);s.push(...c)}return s}function wg(e,n){let r=[],i=[],s=[],a=[],c=e.Resources||{},u=n.Resources||{},d=new Set(Object.keys(c)),m=new Set(Object.keys(u));for(let y of m)if(!d.has(y))r.push(y);for(let y of d)if(!m.has(y))s.push(y);for(let y of m)if(d.has(y)){let f=c[y],h=u[y];if(JSON.stringify(f)!==JSON.stringify(h))i.push(y);else a.push(y)}let p=JSON.stringify(e.Parameters||{})!==JSON.stringify(n.Parameters||{}),g=JSON.stringify(e.Outputs||{})!==JSON.stringify(n.Outputs||{});return{added:r,modified:i,deleted:s,unchanged:a,parametersChanged:p,outputsChanged:g,hasChanges:r.length>0||i.length>0||s.length>0||p||g}}function Ag(e){let n=[];if(!e.hasChanges)return"No changes detected";if(e.added.length>0){n.push(`Added resources (${e.added.length}):`);for(let r of e.added)n.push(` + ${r}`)}if(e.modified.length>0){n.push(`Modified resources (${e.modified.length}):`);for(let r of e.modified)n.push(` ~ ${r}`)}if(e.deleted.length>0){n.push(`Deleted resources (${e.deleted.length}):`);for(let r of e.deleted)n.push(` - ${r}`)}if(e.parametersChanged)n.push("Parameters changed");if(e.outputsChanged)n.push("Outputs changed");return n.join(`
|
|
2487
2487
|
`)}function Rg(e,n,r){if(e.deleted.length>0)return!0;for(let i of e.modified){let s=n.Resources[i],a=r.Resources[i];if(s.Type!==a.Type)return!0;let c=_i(a.Type);for(let u of c){let d=s.Properties?.[u],m=a.Properties?.[u];if(JSON.stringify(d)!==JSON.stringify(m))return!0}}return!1}function _i(e){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"]}[e]||[]}function Ig(e){let n=[],r=[],i=[];n.push(...e.added);for(let s of e.modified)r.push(s);return i.push(...e.deleted),{safe:n,caution:r,dangerous:i}}function Pg(e){if(!e.hasChanges)return{strategy:"skip",reason:"No changes detected"};if(e.deleted.length>0)return{strategy:"replace",reason:"Resources will be deleted"};if(e.added.length>0&&e.modified.length===0)return{strategy:"update",reason:"Only new resources added"};return{strategy:"update",reason:"Resources will be updated"}}function Dg(e){let n=e.added.length+e.modified.length+e.deleted.length+e.unchanged.length,r=e.added.length+e.modified.length+e.deleted.length,i=n>0?r/n*100:0;return{total:n,added:e.added.length,modified:e.modified.length,deleted:e.deleted.length,unchanged:e.unchanged.length,changePercentage:i}}var Fu={$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 kg(e){let n=[];if(!e.project)n.push("Missing required field: project");else{if(!e.project.name)n.push("Missing required field: project.name");if(!e.project.slug)n.push("Missing required field: project.slug")}if(e.project?.slug&&!/^[a-z0-9-]+$/.test(e.project.slug))n.push("Invalid project.slug: must contain only lowercase letters, numbers, and hyphens");let r=["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(e.project?.region&&!r.includes(e.project.region))n.push(`Invalid region: ${e.project.region}. Must be one of: ${r.join(", ")}`);if(e.mode&&!["server","serverless"].includes(e.mode))n.push("Invalid mode: must be one of server or serverless");return{valid:n.length===0,errors:n}}var El={enabled:process.env.TS_CLOUD_LOCAL==="true"||!1,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 _a(){return El}function Ng(){return El.enabled}function xg(e){let n=_a();if(!n.enabled)return"";switch(e.toLowerCase()){case"dynamodb":return n.dynamodbEndpoint;case"s3":return n.s3Endpoint;case"localstack":case"cloudformation":case"lambda":case"apigateway":case"sns":case"sqs":case"cloudwatch":case"iam":case"sts":return n.localstackEndpoint;default:return n.localstackEndpoint}}function _g(){let e=_a();return{accessKeyId:e.awsAccessKeyId,secretAccessKey:e.awsSecretAccessKey,region:e.awsRegion}}function Og(){let e=_a();if(!e.enabled)return{};return{AWS_ACCESS_KEY_ID:e.awsAccessKeyId,AWS_SECRET_ACCESS_KEY:e.awsSecretAccessKey,AWS_REGION:e.awsRegion,AWS_ENDPOINT_URL:e.localstackEndpoint,LOCALSTACK_ENDPOINT:e.localstackEndpoint,TS_CLOUD_LOCAL:"true"}}class wl{stacks=new Map;stackEvents=new Map;async createStack(e){let n=`arn:aws:cloudformation:${e.region||"us-east-1"}:123456789012:stack/${e.StackName}/${Date.now()}`;return this.stacks.set(e.StackName,{StackId:n,StackName:e.StackName,StackStatus:"CREATE_IN_PROGRESS",CreationTime:new Date().toISOString(),TemplateBody:e.TemplateBody,Parameters:e.Parameters||[]}),this.addEvent(e.StackName,{EventId:Date.now().toString(),StackName:e.StackName,LogicalResourceId:e.StackName,ResourceType:"AWS::CloudFormation::Stack",Timestamp:new Date().toISOString(),ResourceStatus:"CREATE_IN_PROGRESS"}),setTimeout(()=>{let r=this.stacks.get(e.StackName);if(r)r.StackStatus="CREATE_COMPLETE",this.addEvent(e.StackName,{EventId:(Date.now()+1).toString(),StackName:e.StackName,LogicalResourceId:e.StackName,ResourceType:"AWS::CloudFormation::Stack",Timestamp:new Date().toISOString(),ResourceStatus:"CREATE_COMPLETE"})},100),{StackId:n}}async updateStack(e){let n=this.stacks.get(e.StackName);if(!n)throw Error(`Stack ${e.StackName} does not exist`);return n.StackStatus="UPDATE_IN_PROGRESS",n.TemplateBody=e.TemplateBody||n.TemplateBody,this.addEvent(e.StackName,{EventId:Date.now().toString(),StackName:e.StackName,LogicalResourceId:e.StackName,ResourceType:"AWS::CloudFormation::Stack",Timestamp:new Date().toISOString(),ResourceStatus:"UPDATE_IN_PROGRESS"}),setTimeout(()=>{n.StackStatus="UPDATE_COMPLETE",this.addEvent(e.StackName,{EventId:(Date.now()+1).toString(),StackName:e.StackName,LogicalResourceId:e.StackName,ResourceType:"AWS::CloudFormation::Stack",Timestamp:new Date().toISOString(),ResourceStatus:"UPDATE_COMPLETE"})},100),{StackId:n.StackId}}async deleteStack(e){let n=this.stacks.get(e.StackName);if(!n)throw Error(`Stack ${e.StackName} does not exist`);n.StackStatus="DELETE_IN_PROGRESS",this.addEvent(e.StackName,{EventId:Date.now().toString(),StackName:e.StackName,LogicalResourceId:e.StackName,ResourceType:"AWS::CloudFormation::Stack",Timestamp:new Date().toISOString(),ResourceStatus:"DELETE_IN_PROGRESS"}),setTimeout(()=>{this.stacks.delete(e.StackName),this.addEvent(e.StackName,{EventId:(Date.now()+1).toString(),StackName:e.StackName,LogicalResourceId:e.StackName,ResourceType:"AWS::CloudFormation::Stack",Timestamp:new Date().toISOString(),ResourceStatus:"DELETE_COMPLETE"})},100)}async describeStacks(e){if(e.StackName){let n=this.stacks.get(e.StackName);if(!n)throw Error(`Stack ${e.StackName} does not exist`);return{Stacks:[n]}}return{Stacks:Array.from(this.stacks.values())}}async describeStackEvents(e){return{StackEvents:this.stackEvents.get(e.StackName)||[]}}addEvent(e,n){if(!this.stackEvents.has(e))this.stackEvents.set(e,[]);this.stackEvents.get(e).unshift(n)}reset(){this.stacks.clear(),this.stackEvents.clear()}}class Al{buckets=new Map;async createBucket(e){return this.buckets.set(e.Bucket,new Map),{Location:`/${e.Bucket}`}}async deleteBucket(e){this.buckets.delete(e.Bucket)}async putObject(e){let n=this.buckets.get(e.Bucket);if(!n)n=new Map,this.buckets.set(e.Bucket,n);return n.set(e.Key,Buffer.from(e.Body||"")),{ETag:`"${Date.now()}"`}}async getObject(e){let n=this.buckets.get(e.Bucket);if(!n)throw Error(`Bucket ${e.Bucket} does not exist`);let r=n.get(e.Key);if(!r)throw Error(`Object ${e.Key} does not exist`);return{Body:r,ContentLength:r.length}}async deleteObject(e){let n=this.buckets.get(e.Bucket);if(n)n.delete(e.Key)}async listObjects(e){let n=this.buckets.get(e.Bucket);if(!n)throw Error(`Bucket ${e.Bucket} does not exist`);return{Contents:Array.from(n.keys()).map((i)=>({Key:i,Size:n.get(i).length,LastModified:new Date().toISOString()}))}}reset(){this.buckets.clear()}}class Rl{tables=new Map;data=new Map;async createTable(e){return this.tables.set(e.TableName,{TableName:e.TableName,KeySchema:e.KeySchema,AttributeDefinitions:e.AttributeDefinitions,TableStatus:"ACTIVE",CreationDateTime:new Date().toISOString()}),this.data.set(e.TableName,new Map),{TableDescription:this.tables.get(e.TableName)}}async deleteTable(e){this.tables.delete(e.TableName),this.data.delete(e.TableName)}async putItem(e){let n=this.data.get(e.TableName);if(!n)n=new Map,this.data.set(e.TableName,n);let r=JSON.stringify(e.Item);n.set(r,e.Item)}async getItem(e){let n=this.data.get(e.TableName);if(!n)return{};let r=JSON.stringify(e.Key),i=n.get(r);return i?{Item:i}:{}}async deleteItem(e){let n=this.data.get(e.TableName);if(n){let r=JSON.stringify(e.Key);n.delete(r)}}async scan(e){let n=this.data.get(e.TableName);if(!n)return{Items:[]};return{Items:Array.from(n.values())}}reset(){this.tables.clear(),this.data.clear()}}function $g(e){return{cloudformation:new wl,s3:new Al,dynamodb:new Rl}}class Oa{environments=new Map;async createPreviewEnvironment(e){let{branch:n,pr:r,commitSha:i,ttl:s=24,baseConfig:a,region:c="us-east-1"}=e,u=this.generatePreviewId(n,r,i),d=this.generatePreviewName(n,r),m=`preview-${d}`,p=new Date,g=new Date(p.getTime()+s*60*60*1000),y={id:u,name:d,branch:n,pr:r,commitSha:i,createdAt:p,expiresAt:g,status:"creating",stackName:m,region:c,resources:[]};this.environments.set(u,y);try{let f=this.createPreviewConfig(a,d);return y.status="active",y.url=`https://${d}.preview.example.com`,y}catch(f){throw y.status="failed",f}}async destroyPreviewEnvironment(e){let n=this.environments.get(e);if(!n)throw Error(`Preview environment ${e} not found`);n.status="destroying";try{n.status="destroyed",this.environments.delete(e)}catch(r){throw Error(`Failed to destroy preview environment: ${r}`)}}getPreviewEnvironment(e){return this.environments.get(e)}getPreviewEnvironmentByBranch(e){return Array.from(this.environments.values()).find((n)=>n.branch===e)}getPreviewEnvironmentByPR(e){return Array.from(this.environments.values()).find((n)=>n.pr===e)}listPreviewEnvironments(){return Array.from(this.environments.values())}listActivePreviewEnvironments(){return this.listPreviewEnvironments().filter((e)=>e.status==="active")}async cleanupExpiredEnvironments(e={}){let{maxAge:n,keepCount:r,dryRun:i=!1}=e,s=[],a=[],c=new Date,u=this.listPreviewEnvironments().sort((d,m)=>m.createdAt.getTime()-d.createdAt.getTime());for(let d=0;d<u.length;d++){let m=u[d];if(m.status!=="active")continue;let p=!1;if(m.expiresAt<c)p=!0;if(n){if((c.getTime()-m.createdAt.getTime())/3600000>n)p=!0}if(r&&d>=r)p=!0;if(p)if(i)s.push(m.id);else try{await this.destroyPreviewEnvironment(m.id),s.push(m.id)}catch(g){a.push(m.id)}}return{destroyed:s,failed:a}}async updatePreviewEnvironment(e,n){let r=this.environments.get(e);if(!r)throw Error(`Preview environment ${e} not found`);r.commitSha=n,r.status="creating";try{return r.status="active",r}catch(i){throw r.status="failed",i}}async getPreviewEnvironmentsCost(){let e={},n=0;for(let r of this.environments.values())e[r.id]=0,n+=0;return{total:n,byEnvironment:e}}generatePreviewId(e,n,r){let i=e.replace(/[^a-z0-9-]/gi,"-").toLowerCase(),s=r?.substring(0,7)||Date.now().toString();return n?`pr-${n}-${s}`:`${i}-${s}`}generatePreviewName(e,n){let r=e.replace(/[^a-z0-9-]/gi,"-").toLowerCase();return n?`pr-${n}`:r}createPreviewConfig(e,n){return{...e,project:{...e.project,name:`${e.project.name} Preview (${n})`,slug:`${e.project.slug}-preview-${n}`}}}}var ju=new Oa;function Vu(e={}){let{workflowName:n="Preview Environment",trigger:r="pull_request",branches:i=["main","develop"],awsRegion:s="us-east-1",awsRole:a,configFile:c="cloud.config.ts",ttl:u=24}=e;return`name: ${n}
|
|
2488
2488
|
|
|
2489
2489
|
on:
|
|
@@ -2712,8 +2712,8 @@ jobs:
|
|
|
2712
2712
|
curl -X POST -H 'Content-type: application/json' \\
|
|
2713
2713
|
--data '{"text":"Preview Environment Cost Report\\n\${{ steps.cost.outputs.cost_json }}"}' \\
|
|
2714
2714
|
$SLACK_WEBHOOK_URL`:'run: |\n echo "${{ steps.cost.outputs.cost_json }}"'}
|
|
2715
|
-
`}class $a{channels=[];addChannel(e){this.channels.push(e)}removeChannel(e){this.channels=this.channels.filter((n)=>n.type!==e)}async notify(e){let n=this.channels.map((r)=>this.sendToChannel(r,e));await Promise.allSettled(n)}async sendToChannel(e,n){switch(e.type){case"slack":await this.sendToSlack(e.config,n);break;case"discord":await this.sendToDiscord(e.config,n);break;case"email":await this.sendToEmail(e.config,n);break;case"webhook":await this.sendToWebhook(e.config,n);break}}async sendToSlack(e,n){let r=this.formatSlackMessage(n,e),i=await fetch(e.webhookUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!i.ok)throw Error(`Failed to send Slack notification: ${i.statusText}`)}formatSlackMessage(e,n){let{environment:r,type:i}=e,s={created:":rocket:",updated:":arrows_counterclockwise:",destroyed:":wastebasket:",failed:":x:",expired:":hourglass_flowing_sand:"}[i],a={created:"#36a64f",updated:"#2196F3",destroyed:"#808080",failed:"#f44336",expired:"#ff9800"}[i],c={created:"Preview Environment Created",updated:"Preview Environment Updated",destroyed:"Preview Environment Destroyed",failed:"Preview Environment Failed",expired:"Preview Environment Expired"}[i];return{username:n.username||"ts-cloud",icon_emoji:n.iconEmoji||":cloud:",channel:n.channel,attachments:[{color:a,title:`${s} ${c}`,fields:[{title:"Environment",value:r.name,short:!0},{title:"Branch",value:r.branch,short:!0},...r.pr?[{title:"PR",value:`#${r.pr}`,short:!0}]:[],{title:"Commit",value:r.commitSha.substring(0,7),short:!0},...r.url?[{title:"URL",value:r.url,short:!1}]:[],...i==="created"?[{title:"Expires",value:r.expiresAt.toLocaleString(),short:!0}]:[]],footer:"ts-cloud Preview Environments",ts:Math.floor(e.timestamp.getTime()/1000)}]}}async sendToDiscord(e,n){let r=this.formatDiscordMessage(n,e),i=await fetch(e.webhookUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!i.ok)throw Error(`Failed to send Discord notification: ${i.statusText}`)}formatDiscordMessage(e,n){let{environment:r,type:i}=e,s={created:":rocket:",updated:":arrows_counterclockwise:",destroyed:":wastebasket:",failed:":x:",expired:":hourglass:"}[i],a={created:3581519,updated:2201331,destroyed:8421504,failed:16007990,expired:16750592}[i],c={created:"Preview Environment Created",updated:"Preview Environment Updated",destroyed:"Preview Environment Destroyed",failed:"Preview Environment Failed",expired:"Preview Environment Expired"}[i];return{username:n.username||"ts-cloud",avatar_url:n.avatarUrl,embeds:[{title:`${s} ${c}`,color:a,fields:[{name:"Environment",value:r.name,inline:!0},{name:"Branch",value:r.branch,inline:!0},...r.pr?[{name:"PR",value:`#${r.pr}`,inline:!0}]:[],{name:"Commit",value:`\`${r.commitSha.substring(0,7)}\``,inline:!0},...r.url?[{name:"URL",value:r.url,inline:!1}]:[]],timestamp:e.timestamp.toISOString(),footer:{text:"ts-cloud Preview Environments"}}]}}async sendToEmail(e,n){console.log(`Email notification would be sent to ${e.to.join(", ")}`)}async sendToWebhook(e,n){let r=await fetch(e.url,{method:e.method||"POST",headers:{"Content-Type":"application/json",...e.headers},body:JSON.stringify({event:n.type,environment:n.environment,timestamp:n.timestamp.toISOString(),metadata:n.metadata})});if(!r.ok)throw Error(`Failed to send webhook notification: ${r.statusText}`)}}var Gu=new $a;function Lg(e){let{columns:n,data:r,border:i=!0,header:s=!0,compact:a=!1,maxWidth:c}=e;if(r.length===0)return"No data to display";let u=n.map((m)=>{let p=m.label.length,g=Math.max(...r.map((f)=>(m.formatter?m.formatter(f[m.key]):String(f[m.key]||"")).length)),y=m.width||Math.max(p,g);if(c&&y>c)y=c;return y}),d=[];if(i)d.push(
|
|
2716
|
-
`)}function
|
|
2715
|
+
`}class $a{channels=[];addChannel(e){this.channels.push(e)}removeChannel(e){this.channels=this.channels.filter((n)=>n.type!==e)}async notify(e){let n=this.channels.map((r)=>this.sendToChannel(r,e));await Promise.allSettled(n)}async sendToChannel(e,n){switch(e.type){case"slack":await this.sendToSlack(e.config,n);break;case"discord":await this.sendToDiscord(e.config,n);break;case"email":await this.sendToEmail(e.config,n);break;case"webhook":await this.sendToWebhook(e.config,n);break}}async sendToSlack(e,n){let r=this.formatSlackMessage(n,e),i=await fetch(e.webhookUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!i.ok)throw Error(`Failed to send Slack notification: ${i.statusText}`)}formatSlackMessage(e,n){let{environment:r,type:i}=e,s={created:":rocket:",updated:":arrows_counterclockwise:",destroyed:":wastebasket:",failed:":x:",expired:":hourglass_flowing_sand:"}[i],a={created:"#36a64f",updated:"#2196F3",destroyed:"#808080",failed:"#f44336",expired:"#ff9800"}[i],c={created:"Preview Environment Created",updated:"Preview Environment Updated",destroyed:"Preview Environment Destroyed",failed:"Preview Environment Failed",expired:"Preview Environment Expired"}[i];return{username:n.username||"ts-cloud",icon_emoji:n.iconEmoji||":cloud:",channel:n.channel,attachments:[{color:a,title:`${s} ${c}`,fields:[{title:"Environment",value:r.name,short:!0},{title:"Branch",value:r.branch,short:!0},...r.pr?[{title:"PR",value:`#${r.pr}`,short:!0}]:[],{title:"Commit",value:r.commitSha.substring(0,7),short:!0},...r.url?[{title:"URL",value:r.url,short:!1}]:[],...i==="created"?[{title:"Expires",value:r.expiresAt.toLocaleString(),short:!0}]:[]],footer:"ts-cloud Preview Environments",ts:Math.floor(e.timestamp.getTime()/1000)}]}}async sendToDiscord(e,n){let r=this.formatDiscordMessage(n,e),i=await fetch(e.webhookUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!i.ok)throw Error(`Failed to send Discord notification: ${i.statusText}`)}formatDiscordMessage(e,n){let{environment:r,type:i}=e,s={created:":rocket:",updated:":arrows_counterclockwise:",destroyed:":wastebasket:",failed:":x:",expired:":hourglass:"}[i],a={created:3581519,updated:2201331,destroyed:8421504,failed:16007990,expired:16750592}[i],c={created:"Preview Environment Created",updated:"Preview Environment Updated",destroyed:"Preview Environment Destroyed",failed:"Preview Environment Failed",expired:"Preview Environment Expired"}[i];return{username:n.username||"ts-cloud",avatar_url:n.avatarUrl,embeds:[{title:`${s} ${c}`,color:a,fields:[{name:"Environment",value:r.name,inline:!0},{name:"Branch",value:r.branch,inline:!0},...r.pr?[{name:"PR",value:`#${r.pr}`,inline:!0}]:[],{name:"Commit",value:`\`${r.commitSha.substring(0,7)}\``,inline:!0},...r.url?[{name:"URL",value:r.url,inline:!1}]:[]],timestamp:e.timestamp.toISOString(),footer:{text:"ts-cloud Preview Environments"}}]}}async sendToEmail(e,n){console.log(`Email notification would be sent to ${e.to.join(", ")}`)}async sendToWebhook(e,n){let r=await fetch(e.url,{method:e.method||"POST",headers:{"Content-Type":"application/json",...e.headers},body:JSON.stringify({event:n.type,environment:n.environment,timestamp:n.timestamp.toISOString(),metadata:n.metadata})});if(!r.ok)throw Error(`Failed to send webhook notification: ${r.statusText}`)}}var Gu=new $a;function Lg(e){let{columns:n,data:r,border:i=!0,header:s=!0,compact:a=!1,maxWidth:c}=e;if(r.length===0)return"No data to display";let u=n.map((m)=>{let p=m.label.length,g=Math.max(...r.map((f)=>(m.formatter?m.formatter(f[m.key]):String(f[m.key]||"")).length)),y=m.width||Math.max(p,g);if(c&&y>c)y=c;return y}),d=[];if(i)d.push(It(u,"top",a));if(s){if(d.push(Un(n.map((m)=>m.label),u,n.map((m)=>m.align||"left"),i)),i)d.push(It(u,"middle",a))}for(let m of r){let p=n.map((g)=>{let y=g.formatter?g.formatter(m[g.key]):String(m[g.key]||"");return Yi(y,u[n.indexOf(g)])});d.push(Un(p,u,n.map((g)=>g.align||"left"),i))}if(i)d.push(It(u,"bottom",a));return d.join(`
|
|
2716
|
+
`)}function Un(e,n,r,i){let s=e.map((a,c)=>{let u=n[c],d=r[c];return Qi(a,u,d)});if(i)return`│ ${s.join(" │ ")} │`;return s.join(" ")}function It(e,n,r){let i=n==="top"?"┌":n==="middle"?"├":"└",s=n==="top"?"┐":n==="middle"?"┤":"┘",a=n==="top"?"┬":n==="middle"?"┼":"┴",c="─";if(r)return i+e.map((u)=>"─".repeat(u+2)).join(a)+s;return i+e.map((u)=>"─".repeat(u+2)).join(a)+s}function Qi(e,n,r){let i=Hn(e).length;if(i>=n)return e;let s=n-i;switch(r){case"right":return" ".repeat(s)+e;case"center":{let a=Math.floor(s/2),c=s-a;return" ".repeat(a)+e+" ".repeat(c)}default:return e+" ".repeat(s)}}function Yi(e,n){if(Hn(e).length<=n)return e;return e.substring(0,n-1)+"…"}function Hn(e){return e.replace(/\x1B\[[0-9;]*m/g,"")}function Mg(e,n={}){let{indent:r=" ",showMetadata:i=!1}=n,s=[];function a(c,u,d){let p=u+(d?"└─ ":"├─ ")+c.label;if(s.push(p),i&&c.metadata){let g=u+(d?" ":"│ ");for(let[y,f]of Object.entries(c.metadata))s.push(`${g}${y}: ${f}`)}if(c.children&&c.children.length>0){let g=u+(d?" ":"│ ");c.children.forEach((y,f)=>{a(y,g,f===c.children.length-1)})}}return e.forEach((c,u)=>{a(c,"",u===e.length-1)}),s.join(`
|
|
2717
2717
|
`)}function Ug(e){let{total:n,current:r,width:i=40,format:s=":bar :percent :current/:total",complete:a="█",incomplete:c="░"}=e,u=Math.min(100,Math.max(0,r/n*100)),d=Math.floor(i*r/n),m=i-d,p=a.repeat(d)+c.repeat(m);return s.replace(":bar",p).replace(":percent",`${u.toFixed(0)}%`).replace(":current",String(r)).replace(":total",String(n))}function Bg(e,n=2){if(e===0)return"0 Bytes";let r=1024,i=n<0?0:n,s=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],a=Math.floor(Math.log(e)/Math.log(r));return`${Number.parseFloat((e/Math.pow(r,a)).toFixed(i))} ${s[a]}`}function Fg(e){if(e<1000)return`${e}ms`;let n=Math.floor(e/1000);if(n<60)return`${n}s`;let r=Math.floor(n/60),i=n%60;if(r<60)return i>0?`${r}m ${i}s`:`${r}m`;let s=Math.floor(r/60),a=r%60;if(s<24)return a>0?`${s}h ${a}m`:`${s}h`;let c=Math.floor(s/24),u=s%24;return u>0?`${c}d ${u}h`:`${c}d`}function jg(e,n="•"){return e.map((r)=>`${n} ${r}`).join(`
|
|
2718
2718
|
`)}function Vg(e,n={}){let{indent:r="",separator:i=": "}=n,s=Math.max(...Object.keys(e).map((a)=>a.length));return Object.entries(e).map(([a,c])=>{let u=a.padEnd(s);return`${r}${u}${i}${c}`}).join(`
|
|
2719
2719
|
`)}class qu{total;current=0;width;format;message;showETA;showPercentage;showCounter;startTime=Date.now();lastUpdate=0;constructor(e){this.total=e.total,this.current=e.current||0,this.width=e.width||40,this.format=e.format||":message :bar :percent :eta",this.message=e.message||"Progress",this.showETA=e.showETA!==!1,this.showPercentage=e.showPercentage!==!1,this.showCounter=e.showCounter!==!1}tick(e=1){this.current=Math.min(this.total,this.current+e),this.lastUpdate=Date.now()}update(e){this.current=Math.min(this.total,Math.max(0,e)),this.lastUpdate=Date.now()}setMessage(e){this.message=e}getPercentage(){return Math.min(100,this.current/this.total*100)}getETA(){if(this.current===0)return 0;let e=Date.now()-this.startTime,n=this.current/e,r=this.total-this.current;return Math.round(r/n)}getETAFormatted(){if(this.current===0)return"calculating...";if(this.current===this.total)return"complete";let e=this.getETA();if(e<1000)return"< 1s";if(e<60000)return`${Math.round(e/1000)}s`;let n=Math.floor(e/60000);if(n<60)return`${n}m`;let r=Math.floor(n/60),i=n%60;if(r<24)return i>0?`${r}h ${i}m`:`${r}h`;let s=Math.floor(r/24),a=r%24;return a>0?`${s}d ${a}h`:`${s}d`}render(){let e=this.getPercentage(),n=Math.floor(this.width*this.current/this.total),r=this.width-n,i="█".repeat(n)+"░".repeat(r),s=`${e.toFixed(1)}%`,a=`${this.current}/${this.total}`,c=this.showETA?`ETA: ${this.getETAFormatted()}`:"",u=this.format.replace(":message",this.message).replace(":bar",i).replace(":percent",this.showPercentage?s:"").replace(":counter",this.showCounter?a:"").replace(":eta",c).replace(":current",String(this.current)).replace(":total",String(this.total));return u=u.replace(/\s+/g," ").trim(),u}isComplete(){return this.current>=this.total}}class Wu{steps;currentStepIndex=0;constructor(e){this.steps=e.map((n)=>({name:n,status:"pending"}))}startStep(e,n){if(e>=0&&e<this.steps.length)this.steps[e].status="active",this.steps[e].message=n,this.currentStepIndex=e}completeStep(e){if(this.currentStepIndex>=0&&this.currentStepIndex<this.steps.length)this.steps[this.currentStepIndex].status="completed",this.steps[this.currentStepIndex].message=e,this.currentStepIndex++}failStep(e){if(this.currentStepIndex>=0&&this.currentStepIndex<this.steps.length)this.steps[this.currentStepIndex].status="failed",this.steps[this.currentStepIndex].error=e}skipStep(e){if(this.currentStepIndex>=0&&this.currentStepIndex<this.steps.length)this.steps[this.currentStepIndex].status="skipped",this.steps[this.currentStepIndex].message=e,this.currentStepIndex++}getStep(e){return this.steps[e]}getSteps(){return this.steps}render(){let e=[];for(let n of this.steps){let i=`${this.getStatusIcon(n.status)} ${n.name}`;if(n.message)i+=` - ${n.message}`;if(n.error)i+=`
|
|
@@ -3768,7 +3768,7 @@ COPY . .`,impact:"Improve build time by 60-80% on subsequent builds"});let u={si
|
|
|
3768
3768
|
<p>If you didn't request this, please ignore this email.</p>
|
|
3769
3769
|
</body>
|
|
3770
3770
|
</html>
|
|
3771
|
-
`,textPart:"Hi {{userName}}, reset your password at: {{resetUrl}}. This link expires in {{expirationHours}} hours."})}updateTemplate(e,n,r){let i=this.templates.get(e);if(!i)throw Error(`Template not found: ${e}`);if(n.subject)i.subject=n.subject;if(n.htmlPart)i.htmlPart=n.htmlPart;if(n.textPart)i.textPart=n.textPart;return i.version++,i.updatedAt=new Date,i.variables=this.extractVariables(i.subject+i.htmlPart+i.textPart),this.addVersion({templateId:e,version:i.version,subject:i.subject,htmlPart:i.htmlPart,textPart:i.textPart,createdBy:"system",changelog:r}),i}addVersion(e){let r={id:`version-${e.templateId}-${e.version}`,createdAt:new Date,...e},i=this.versions.get(e.templateId)||[];return i.push(r),this.versions.set(e.templateId,i),r}extractVariables(e){let n=/\{\{([^}]+)\}\}/g,r=new Set,i;while((i=n.exec(e))!==null)r.add(i[1].trim());return Array.from(r)}renderTemplate(e,n){let r=this.templates.get(e);if(!r)throw Error(`Template not found: ${e}`);let i=(s)=>s.replace(/\{\{([^}]+)\}\}/g,(a,c)=>{let u=c.trim();return n[u]!==void 0?String(n[u]):a});return{subject:i(r.subject),html:i(r.htmlPart),text:i(r.textPart)}}testTemplate(e,n){let r=`test-${Date.now()}-${this.testCounter++}`,i=this.renderTemplate(e,n),s={id:r,templateId:e,testData:n,renderedSubject:i.subject,renderedHtml:i.html,renderedText:i.text,timestamp:new Date};return this.tests.set(r,s),s}getTemplate(e){return this.templates.get(e)}listTemplates(){return Array.from(this.templates.values())}getTemplateVersions(e){return this.versions.get(e)||[]}revertToVersion(e,n){let r=this.templates.get(e);if(!r)throw Error(`Template not found: ${e}`);let s=(this.versions.get(e)||[]).find((a)=>a.version===n);if(!s)throw Error(`Version ${n} not found for template ${e}`);return r.subject=s.subject,r.htmlPart=s.htmlPart,r.textPart=s.textPart,r.version++,r.updatedAt=new Date,this.addVersion({templateId:e,version:r.version,subject:r.subject,htmlPart:r.htmlPart,textPart:r.textPart,createdBy:"system",changelog:`Reverted to version ${n}`}),r}generateTemplateCF(e){return{Type:"AWS::SES::Template",Properties:{Template:{TemplateName:e.name,SubjectPart:e.subject,HtmlPart:e.htmlPart,TextPart:e.textPart}}}}clear(){this.templates.clear(),this.versions.clear(),this.tests.clear(),this.templateCounter=0,this.testCounter=0}}var sh=new rd;class
|
|
3771
|
+
`,textPart:"Hi {{userName}}, reset your password at: {{resetUrl}}. This link expires in {{expirationHours}} hours."})}updateTemplate(e,n,r){let i=this.templates.get(e);if(!i)throw Error(`Template not found: ${e}`);if(n.subject)i.subject=n.subject;if(n.htmlPart)i.htmlPart=n.htmlPart;if(n.textPart)i.textPart=n.textPart;return i.version++,i.updatedAt=new Date,i.variables=this.extractVariables(i.subject+i.htmlPart+i.textPart),this.addVersion({templateId:e,version:i.version,subject:i.subject,htmlPart:i.htmlPart,textPart:i.textPart,createdBy:"system",changelog:r}),i}addVersion(e){let r={id:`version-${e.templateId}-${e.version}`,createdAt:new Date,...e},i=this.versions.get(e.templateId)||[];return i.push(r),this.versions.set(e.templateId,i),r}extractVariables(e){let n=/\{\{([^}]+)\}\}/g,r=new Set,i;while((i=n.exec(e))!==null)r.add(i[1].trim());return Array.from(r)}renderTemplate(e,n){let r=this.templates.get(e);if(!r)throw Error(`Template not found: ${e}`);let i=(s)=>s.replace(/\{\{([^}]+)\}\}/g,(a,c)=>{let u=c.trim();return n[u]!==void 0?String(n[u]):a});return{subject:i(r.subject),html:i(r.htmlPart),text:i(r.textPart)}}testTemplate(e,n){let r=`test-${Date.now()}-${this.testCounter++}`,i=this.renderTemplate(e,n),s={id:r,templateId:e,testData:n,renderedSubject:i.subject,renderedHtml:i.html,renderedText:i.text,timestamp:new Date};return this.tests.set(r,s),s}getTemplate(e){return this.templates.get(e)}listTemplates(){return Array.from(this.templates.values())}getTemplateVersions(e){return this.versions.get(e)||[]}revertToVersion(e,n){let r=this.templates.get(e);if(!r)throw Error(`Template not found: ${e}`);let s=(this.versions.get(e)||[]).find((a)=>a.version===n);if(!s)throw Error(`Version ${n} not found for template ${e}`);return r.subject=s.subject,r.htmlPart=s.htmlPart,r.textPart=s.textPart,r.version++,r.updatedAt=new Date,this.addVersion({templateId:e,version:r.version,subject:r.subject,htmlPart:r.htmlPart,textPart:r.textPart,createdBy:"system",changelog:`Reverted to version ${n}`}),r}generateTemplateCF(e){return{Type:"AWS::SES::Template",Properties:{Template:{TemplateName:e.name,SubjectPart:e.subject,HtmlPart:e.htmlPart,TextPart:e.textPart}}}}clear(){this.templates.clear(),this.versions.clear(),this.tests.clear(),this.templateCounter=0,this.testCounter=0}}var sh=new rd;class Mt{static createSearchDomain(e){let{slug:n,environment:r,domainName:i,instanceType:s="t3.small.search",instanceCount:a=1,ebsVolumeSize:c=10,masterUserName:u="admin",masterUserPassword:d}=e,m=i||`${n}-${r}-email-search`;return{[`${n}EmailSearchDomain`]:{Type:"AWS::OpenSearchService::Domain",Properties:{DomainName:m,EngineVersion:"OpenSearch_2.11",ClusterConfig:{InstanceType:s,InstanceCount:a,DedicatedMasterEnabled:!1,ZoneAwarenessEnabled:!1},EBSOptions:{EBSEnabled:!0,VolumeType:"gp3",VolumeSize:c},NodeToNodeEncryptionOptions:{Enabled:!0},EncryptionAtRestOptions:{Enabled:!0},DomainEndpointOptions:{EnforceHTTPS:!0},AdvancedSecurityOptions:{Enabled:!0,InternalUserDatabaseEnabled:!0,MasterUserOptions:{MasterUserName:u,MasterUserPassword:d||`${n}-search-${Date.now()}`}},AccessPolicies:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:"*"},Action:"es:*",Resource:`arn:aws:es:*:*:domain/${m}/*`}]}}}}}static createIndexerLambda(e){return{[`${e.slug}EmailIndexerLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${e.slug}-email-indexer`,Runtime:"nodejs20.x",Handler:"index.handler",Role:e.roleArn,Timeout:60,MemorySize:512,Code:{ZipFile:Mt.IndexerLambdaCode},Environment:{Variables:{OPENSEARCH_ENDPOINT:e.searchDomainEndpoint,EMAIL_BUCKET:e.emailBucket}}}}}}static IndexerLambdaCode=`
|
|
3772
3772
|
const { S3Client, GetObjectCommand } = require('@aws-sdk/client-s3');
|
|
3773
3773
|
const https = require('https');
|
|
3774
3774
|
|
|
@@ -3868,7 +3868,7 @@ async function indexDocument(doc) {
|
|
|
3868
3868
|
req.end();
|
|
3869
3869
|
});
|
|
3870
3870
|
}
|
|
3871
|
-
`;static getIndexMapping(){return{mappings:{properties:{messageId:{type:"keyword"},from:{type:"keyword"},fromName:{type:"text"},to:{type:"keyword"},toName:{type:"text"},cc:{type:"keyword"},subject:{type:"text",analyzer:"standard",fields:{keyword:{type:"keyword"}}},body:{type:"text",analyzer:"standard"},bodyPreview:{type:"text"},date:{type:"date"},receivedAt:{type:"date"},hasAttachments:{type:"boolean"},attachmentNames:{type:"keyword"},labels:{type:"keyword"},folder:{type:"keyword"},threadId:{type:"keyword"},isRead:{type:"boolean"},isStarred:{type:"boolean"},mailbox:{type:"keyword"}}},settings:{number_of_shards:1,number_of_replicas:0}}}static buildSearchQuery(e){let n=[],r=[];if(e.query)n.push({multi_match:{query:e.query,fields:["subject^3","body","fromName","toName"],type:"best_fields",fuzziness:"AUTO"}});if(e.from)r.push({term:{from:e.from}});if(e.to)r.push({term:{to:e.to}});if(e.subject)n.push({match_phrase:{subject:e.subject}});if(e.hasAttachments!==void 0)r.push({term:{hasAttachments:e.hasAttachments}});if(e.folder)r.push({term:{folder:e.folder}});if(e.labels&&e.labels.length>0)r.push({terms:{labels:e.labels}});if(e.isRead!==void 0)r.push({term:{isRead:e.isRead}});if(e.dateFrom||e.dateTo){let a={date:{}};if(e.dateFrom)a.date.gte=e.dateFrom;if(e.dateTo)a.date.lte=e.dateTo;r.push({range:a})}let i={bool:{}};if(n.length>0)i.bool.must=n;if(r.length>0)i.bool.filter=r;if(n.length===0&&r.length===0)i.bool.must=[{match_all:{}}];let s=[];if(e.sort==="relevance"&&e.query)s.push({_score:e.sortOrder||"desc"});return s.push({date:e.sortOrder||"desc"}),{query:i,sort:s,from:e.offset||0,size:e.limit||20,highlight:{fields:{subject:{},body:{fragment_size:150,number_of_fragments:3}}}}}}class
|
|
3871
|
+
`;static getIndexMapping(){return{mappings:{properties:{messageId:{type:"keyword"},from:{type:"keyword"},fromName:{type:"text"},to:{type:"keyword"},toName:{type:"text"},cc:{type:"keyword"},subject:{type:"text",analyzer:"standard",fields:{keyword:{type:"keyword"}}},body:{type:"text",analyzer:"standard"},bodyPreview:{type:"text"},date:{type:"date"},receivedAt:{type:"date"},hasAttachments:{type:"boolean"},attachmentNames:{type:"keyword"},labels:{type:"keyword"},folder:{type:"keyword"},threadId:{type:"keyword"},isRead:{type:"boolean"},isStarred:{type:"boolean"},mailbox:{type:"keyword"}}},settings:{number_of_shards:1,number_of_replicas:0}}}static buildSearchQuery(e){let n=[],r=[];if(e.query)n.push({multi_match:{query:e.query,fields:["subject^3","body","fromName","toName"],type:"best_fields",fuzziness:"AUTO"}});if(e.from)r.push({term:{from:e.from}});if(e.to)r.push({term:{to:e.to}});if(e.subject)n.push({match_phrase:{subject:e.subject}});if(e.hasAttachments!==void 0)r.push({term:{hasAttachments:e.hasAttachments}});if(e.folder)r.push({term:{folder:e.folder}});if(e.labels&&e.labels.length>0)r.push({terms:{labels:e.labels}});if(e.isRead!==void 0)r.push({term:{isRead:e.isRead}});if(e.dateFrom||e.dateTo){let a={date:{}};if(e.dateFrom)a.date.gte=e.dateFrom;if(e.dateTo)a.date.lte=e.dateTo;r.push({range:a})}let i={bool:{}};if(n.length>0)i.bool.must=n;if(r.length>0)i.bool.filter=r;if(n.length===0&&r.length===0)i.bool.must=[{match_all:{}}];let s=[];if(e.sort==="relevance"&&e.query)s.push({_score:e.sortOrder||"desc"});return s.push({date:e.sortOrder||"desc"}),{query:i,sort:s,from:e.offset||0,size:e.limit||20,highlight:{fields:{subject:{},body:{fragment_size:150,number_of_fragments:3}}}}}}class Lt{static ThreadingLambdaCode=`
|
|
3872
3872
|
const { S3Client, GetObjectCommand, PutObjectCommand } = require('@aws-sdk/client-s3');
|
|
3873
3873
|
const crypto = require('crypto');
|
|
3874
3874
|
|
|
@@ -4008,7 +4008,7 @@ catch {
|
|
|
4008
4008
|
ContentType: 'application/json',
|
|
4009
4009
|
}));
|
|
4010
4010
|
}
|
|
4011
|
-
`;static createThreadingLambda(e){return{[`${e.slug}EmailThreadingLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${e.slug}-email-threading`,Runtime:"nodejs20.x",Handler:"index.handler",Role:e.roleArn,Timeout:60,MemorySize:256,Code:{ZipFile:
|
|
4011
|
+
`;static createThreadingLambda(e){return{[`${e.slug}EmailThreadingLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${e.slug}-email-threading`,Runtime:"nodejs20.x",Handler:"index.handler",Role:e.roleArn,Timeout:60,MemorySize:256,Code:{ZipFile:Lt.ThreadingLambdaCode},Environment:{Variables:{EMAIL_BUCKET:e.emailBucket}}}}}}static async getThreads(e){let{s3Client:n,bucket:r,mailbox:i,limit:s=50,offset:a=0}=e,[c,u]=i.includes("@")?i.split("@"):[i,"default"],d=`mailboxes/${u}/${c}/threads.json`;try{let m=await n.send({Bucket:r,Key:d}),p=JSON.parse(m.Body),g=Object.values(p);return g.sort((y,f)=>new Date(f.lastMessageDate).getTime()-new Date(y.lastMessageDate).getTime()),g.slice(a,a+s)}catch{return[]}}static async getThread(e){let{s3Client:n,bucket:r,mailbox:i,threadId:s}=e,[a,c]=i.includes("@")?i.split("@"):[i,"default"],u=`mailboxes/${c}/${a}/threads.json`;try{let d=await n.send({Bucket:r,Key:u});return JSON.parse(d.Body)[s]||null}catch{return null}}}class $t{static SchedulerLambdaCode=`
|
|
4012
4012
|
const { S3Client, GetObjectCommand, PutObjectCommand, DeleteObjectCommand, ListObjectsV2Command } = require('@aws-sdk/client-s3');
|
|
4013
4013
|
const { SESClient, SendRawEmailCommand } = require('@aws-sdk/client-ses');
|
|
4014
4014
|
|
|
@@ -7236,7 +7236,7 @@ function unmarshallTest(item) {
|
|
|
7236
7236
|
|
|
7237
7237
|
return test;
|
|
7238
7238
|
}
|
|
7239
|
-
`;static createAbTestsTable(e){return{[`${e.slug}AbTestsTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${e.slug}-ab-tests`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}]}}}}static createAbTestManagerLambda(e){return{[`${e.slug}AbTestManagerLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${e.slug}-ab-test-manager`,Runtime:"nodejs20.x",Handler:"index.handler",Role:e.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:me.AbTestManagerCode},Environment:{Variables:{AB_TESTS_TABLE:e.abTestsTable}}}}}}static selectVariant(e,n){let i=me.hashString(n+e.id)%100,s=0;for(let a=0;a<e.variants.length;a++)if(s+=e.trafficSplit[a],i<s)return e.variants[a];return e.variants[e.variants.length-1]}static determineWinner(e){if(e.variants.length===0)return null;let n=e.winningCriteria,r=e.variants[0],i=me.getMetricValue(r,n);for(let s of e.variants.slice(1)){let a=me.getMetricValue(s,n);if(a>i)i=a,r=s}return r}static calculateSignificance(e,n,r){let i=e.stats.sent,s=n.stats.sent;if(i<30||s<30)return 0;let a=me.getMetricValue(e,r)/100,c=me.getMetricValue(n,r)/100,u=(a*i+c*s)/(i+s),d=Math.sqrt(u*(1-u)*(1/i+1/s));if(d===0)return 0;let m=Math.abs(a-c)/d;if(m>=2.576)return 99;if(m>=1.96)return 95;if(m>=1.645)return 90;if(m>=1.28)return 80;return Math.round(m*30)}static getMetricValue(e,n){switch(n){case"delivery_rate":return e.stats.deliveryRate;case"click_rate":return e.stats.clickRate;case"reply_rate":return e.stats.replyRate;case"conversion_rate":return e.stats.conversionRate;default:return e.stats.deliveryRate}}static hashString(e){let n=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);n=(n<<5)-n+i,n=n&n}return Math.abs(n)}}class ad{queues=new Map;messageGroups=new Map;deduplicationConfigs=new Map;messages=new Map;queueCounter=0;groupCounter=0;deduplicationCounter=0;messageCounter=0;sequenceCounter=0;createFIFOQueue(e){let n=`fifo-queue-${Date.now()}-${this.queueCounter++}`,r=e.name.endsWith(".fifo")?e.name:`${e.name}.fifo`,{name:i,...s}=e,a={id:n,name:r,queueUrl:`https://sqs.us-east-1.amazonaws.com/123456789012/${r}`,...s};return this.queues.set(n,a),this.createDeduplicationConfig({queueId:n,contentBasedDeduplication:e.contentBasedDeduplication,deduplicationInterval:300}),a}createHighThroughputFIFO(e){return this.createFIFOQueue({name:e.name,contentBasedDeduplication:e.contentBasedDeduplication??!0,deduplicationScope:"messageGroup",fifoThroughputLimit:"perMessageGroupId",messageRetentionPeriod:345600,visibilityTimeout:30,receiveMessageWaitTime:0})}createStandardFIFO(e){return this.createFIFOQueue({name:e.name,contentBasedDeduplication:e.contentBasedDeduplication??!1,deduplicationScope:"queue",fifoThroughputLimit:"perQueue",messageRetentionPeriod:345600,visibilityTimeout:30,receiveMessageWaitTime:0})}createDeduplicationConfig(e){let r={id:`dedup-${Date.now()}-${this.deduplicationCounter++}`,deduplicationHashes:new Map,...e};return this.deduplicationConfigs.set(e.queueId,r),r}sendMessage(e){let n=this.queues.get(e.queueId);if(!n)throw Error(`Queue not found: ${e.queueId}`);let r=this.deduplicationConfigs.get(e.queueId);if(r){let c=e.messageDeduplicationId||(n.contentBasedDeduplication?this.generateHash(e.messageBody):void 0);if(c&&this.isDuplicate(r,c))return null;if(c)r.deduplicationHashes.set(c,new Date)}let i=`msg-${Date.now()}-${this.messageCounter++}`,s=this.generateSequenceNumber(),a={id:i,messageId:i,messageGroupId:e.messageGroupId,messageDeduplicationId:e.messageDeduplicationId,body:e.messageBody,attributes:e.messageAttributes||{},sentTimestamp:new Date,sequenceNumber:s};return this.messages.set(i,a),this.updateMessageGroup(e.queueId,e.messageGroupId),a}isDuplicate(e,n){let r=e.deduplicationHashes.get(n);if(!r)return!1;if((Date.now()-r.getTime())/1000>e.deduplicationInterval)return e.deduplicationHashes.delete(n),!1;return!0}generateHash(e){let n=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);n=(n<<5)-n+i,n=n&n}return Math.abs(n).toString(36)}generateSequenceNumber(){return`${Date.now()}${this.sequenceCounter++}`.padStart(20,"0")}updateMessageGroup(e,n){let r=`${e}-${n}`,i=this.messageGroups.get(r);if(!i)i={id:`group-${Date.now()}-${this.groupCounter++}`,messageGroupId:n,queueId:e,messagesInFlight:0},this.messageGroups.set(r,i);i.messagesInFlight++,i.lastMessageTimestamp=new Date}getMessageGroups(e){return Array.from(this.messageGroups.values()).filter((n)=>n.queueId===e)}getQueue(e){return this.queues.get(e)}listQueues(){return Array.from(this.queues.values())}getMessages(e,n){let r=Array.from(this.messages.values());if(n)r=r.filter((i)=>i.messageGroupId===n);return r.sort((i,s)=>i.sequenceNumber.localeCompare(s.sequenceNumber))}generateFIFOQueueCF(e){return{Type:"AWS::SQS::Queue",Properties:{QueueName:e.name,FifoQueue:!0,ContentBasedDeduplication:e.contentBasedDeduplication,DeduplicationScope:e.deduplicationScope,FifoThroughputLimit:e.fifoThroughputLimit,MessageRetentionPeriod:e.messageRetentionPeriod,VisibilityTimeout:e.visibilityTimeout,ReceiveMessageWaitTimeSeconds:e.receiveMessageWaitTime,...e.deadLetterTargetArn&&{RedrivePolicy:{deadLetterTargetArn:e.deadLetterTargetArn,maxReceiveCount:e.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 ah=new ad;class cd{monitors=new Map;metrics=new Map;alerts=new Map;reprocessJobs=new Map;monitorCounter=0;metricsCounter=0;alertCounter=0;jobCounter=0;createDLQMonitor(e){let n=`dlq-monitor-${Date.now()}-${this.monitorCounter++}`,r={id:n,...e};return this.monitors.set(n,r),r}createAutomatedMonitor(e){return this.createDLQMonitor({name:e.name,queueUrl:e.queueUrl,sourceQueues:e.sourceQueues,maxReceiveCount:3,alarmThreshold:10,autoReprocess:!0,reprocessStrategy:"scheduled",notificationTopicArn:e.notificationTopicArn})}collectMetrics(e){let r={id:`metrics-${Date.now()}-${this.metricsCounter++}`,queueUrl:e,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)},i=this.metrics.get(e)||[];return i.push(r),this.metrics.set(e,i),this.checkForAlerts(e,r),r}checkForAlerts(e,n){let r=Array.from(this.monitors.values()).find((s)=>s.queueUrl===e);if(!r)return;if(n.approximateNumberOfMessages>=r.alarmThreshold)this.createAlert({monitorId:r.id,alertType:"threshold_exceeded",severity:"high",message:`DLQ ${r.name} has ${n.approximateNumberOfMessages} messages (threshold: ${r.alarmThreshold})`});let i=3600;if(n.approximateAgeOfOldestMessage>i)this.createAlert({monitorId:r.id,alertType:"old_message",severity:"medium",message:`DLQ ${r.name} has messages older than ${i} seconds`})}createAlert(e){let n=`alert-${Date.now()}-${this.alertCounter++}`,r={id:n,timestamp:new Date,acknowledged:!1,...e};return this.alerts.set(n,r),r}acknowledgeAlert(e){let n=this.alerts.get(e);if(!n)throw Error(`Alert not found: ${e}`);return n.acknowledged=!0,n}createReprocessJob(e){let n=`reprocess-${Date.now()}-${this.jobCounter++}`,r={id:n,queueUrl:e.queueUrl,messageId:e.messageId,attempts:0,status:"pending"};return this.reprocessJobs.set(n,r),r}async executeReprocessJob(e){let n=this.reprocessJobs.get(e);if(!n)throw Error(`Reprocess job not found: ${e}`);n.status="processing",n.startedAt=new Date,n.attempts++,await new Promise((i)=>setTimeout(i,100));let r=Math.random()>0.3;if(n.status=r?"success":"failed",n.completedAt=new Date,!r)n.error="Reprocessing failed - original error still present";return n}async batchReprocess(e){let n=[];for(let r=0;r<e.maxMessages;r++){let i=this.createReprocessJob({queueUrl:e.queueUrl,messageId:`msg-${r}`});await this.executeReprocessJob(i.id),n.push(i)}return n}getDLQStatistics(e,n=24){let r=new Date(Date.now()-n*60*60*1000),i=(this.metrics.get(e)||[]).filter((p)=>p.timestamp>=r);if(i.length===0)return{totalMessages:0,avgAge:0,messagesReceived:0,messagesDeleted:0,messagesReprocessed:0,successRate:0};let s=i[i.length-1],a=i.reduce((p,g)=>p+g.messagesReceived,0),c=i.reduce((p,g)=>p+g.messagesDeleted,0),u=i.reduce((p,g)=>p+g.messagesReprocessed,0),d=i.reduce((p,g)=>p+g.approximateAgeOfOldestMessage,0)/i.length,m=u>0?c/u*100:0;return{totalMessages:s.approximateNumberOfMessages,avgAge:d,messagesReceived:a,messagesDeleted:c,messagesReprocessed:u,successRate:m}}getMonitor(e){return this.monitors.get(e)}listMonitors(){return Array.from(this.monitors.values())}getAlerts(e,n){let r=Array.from(this.alerts.values());if(e)r=r.filter((i)=>i.monitorId===e);if(n!==void 0)r=r.filter((i)=>i.acknowledged===n);return r.sort((i,s)=>s.timestamp.getTime()-i.timestamp.getTime())}getReprocessJobs(e){let n=Array.from(this.reprocessJobs.values());if(e)n=n.filter((r)=>r.queueUrl===e);return n}generateDLQAlarmCF(e){return{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${e.name}-messages-alarm`,AlarmDescription:`Alert when DLQ ${e.name} exceeds threshold`,MetricName:"ApproximateNumberOfMessagesVisible",Namespace:"AWS/SQS",Statistic:"Average",Period:300,EvaluationPeriods:1,Threshold:e.alarmThreshold,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:e.queueUrl.split("/").pop()}],...e.notificationTopicArn&&{AlarmActions:[e.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 ch=new cd;class ld{configs=new Map;jobs=new Map;metrics=new Map;configCounter=0;jobCounter=0;metricsCounter=0;createBatchConfig(e){let n=`batch-config-${Date.now()}-${this.configCounter++}`,r={id:n,...e};return this.configs.set(n,r),r}createHighThroughputConfig(e){return this.createBatchConfig({queueUrl:e.queueUrl,batchSize:10,maxWaitTime:100,parallelProcessors:10,retryAttempts:3,visibilityTimeout:30})}createLowLatencyConfig(e){return this.createBatchConfig({queueUrl:e.queueUrl,batchSize:1,maxWaitTime:0,parallelProcessors:5,retryAttempts:2,visibilityTimeout:10})}createBatchJob(e){let n=`batch-job-${Date.now()}-${this.jobCounter++}`;if(!this.configs.get(e.configId))throw Error(`Batch config not found: ${e.configId}`);let i=[];for(let a=0;a<e.messageCount;a++)i.push({id:`msg-${n}-${a}`,messageId:`${n}-${a}`,body:`Message ${a}`,receiptHandle:`receipt-${n}-${a}`,attributes:{},status:"pending"});let s={id:n,configId:e.configId,messages:i,status:"pending",processedCount:0,failedCount:0};return this.jobs.set(n,s),s}async processBatchJob(e){let n=this.jobs.get(e);if(!n)throw Error(`Batch job not found: ${e}`);let r=this.configs.get(n.configId);if(!r)throw Error(`Batch config not found: ${n.configId}`);n.status="processing",n.startedAt=new Date;let i=this.chunkArray(n.messages,r.batchSize);for(let s of i)await this.processBatch(s,r);return n.processedCount=n.messages.filter((s)=>s.status==="success").length,n.failedCount=n.messages.filter((s)=>s.status==="failed").length,n.status=n.failedCount===0?"completed":"failed",n.completedAt=new Date,this.collectProcessorMetrics(r.id,n),n}async processBatch(e,n){let r=e.map((i)=>this.processMessage(i,n));await Promise.all(r)}async processMessage(e,n){e.status="processing";let r=Date.now();await new Promise((a)=>setTimeout(a,Math.random()*100));let i=Date.now()-r;if(e.processingTime=i,Math.random()>0.1)e.status="success";else e.status="failed",e.error="Processing error"}chunkArray(e,n){let r=[];for(let i=0;i<e.length;i+=n)r.push(e.slice(i,i+n));return r}collectProcessorMetrics(e,n){let r=`metrics-${Date.now()}-${this.metricsCounter++}`,s=n.messages.filter((g)=>g.status==="success").map((g)=>g.processingTime||0).filter((g)=>g>0),a=s.length>0?s.reduce((g,y)=>g+y,0)/s.length:0,c=n.completedAt&&n.startedAt?(n.completedAt.getTime()-n.startedAt.getTime())/1000:1,u=n.processedCount/c,d=n.messages.length>0?n.failedCount/n.messages.length*100:0,m={id:r,configId:e,timestamp:new Date,messagesProcessed:n.processedCount,averageProcessingTime:a,throughput:u,errorRate:d},p=this.metrics.get(e)||[];p.push(m),this.metrics.set(e,p)}getBatchStatistics(e){let n=this.metrics.get(e)||[];if(n.length===0)return{totalJobsProcessed:0,totalMessagesProcessed:0,averageThroughput:0,averageErrorRate:0,averageProcessingTime:0};let r=n.reduce((c,u)=>c+u.messagesProcessed,0),i=n.reduce((c,u)=>c+u.throughput,0)/n.length,s=n.reduce((c,u)=>c+u.errorRate,0)/n.length,a=n.reduce((c,u)=>c+u.averageProcessingTime,0)/n.length;return{totalJobsProcessed:n.length,totalMessagesProcessed:r,averageThroughput:i,averageErrorRate:s,averageProcessingTime:a}}optimizeBatchConfig(e){let n=this.configs.get(e);if(!n)throw Error(`Batch config not found: ${e}`);let r=this.getBatchStatistics(e);if(r.averageErrorRate<5&&n.batchSize<10)n.batchSize=Math.min(10,n.batchSize+1);if(r.averageErrorRate>20&&n.batchSize>1)n.batchSize=Math.max(1,n.batchSize-1);if(r.averageThroughput<5&&n.parallelProcessors<20)n.parallelProcessors++;return n}getConfig(e){return this.configs.get(e)}listConfigs(){return Array.from(this.configs.values())}getJob(e){return this.jobs.get(e)}listJobs(e){let n=Array.from(this.jobs.values());if(e)n=n.filter((r)=>r.configId===e);return n}generateBatchProcessorCF(e){return{Type:"AWS::Lambda::EventSourceMapping",Properties:{EventSourceArn:`arn:aws:sqs:us-east-1:123456789012:${e.queueUrl.split("/").pop()}`,FunctionName:"batch-processor-function",BatchSize:e.batchSize,MaximumBatchingWindowInSeconds:e.maxWaitTime/1000,FunctionResponseTypes:["ReportBatchItemFailures"]}}}clear(){this.configs.clear(),this.jobs.clear(),this.metrics.clear(),this.configCounter=0,this.jobCounter=0,this.metricsCounter=0}}var lh=new ld;class dd{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(e){let n=`queue-${Date.now()}-${this.queueCounter++}`,r={id:n,purgeInProgress:!1,...e};return this.queues.set(n,r),r}createStandardQueue(e){return this.createQueue({queueUrl:`https://sqs.us-east-1.amazonaws.com/123456789012/${e.queueName}`,queueName:e.queueName,messageRetentionPeriod:(e.messageRetentionDays||4)*24*60*60,delaySeconds:0,maximumMessageSize:262144,receiveMessageWaitTime:0})}createLongPollingQueue(e){return this.createQueue({queueUrl:`https://sqs.us-east-1.amazonaws.com/123456789012/${e.queueName}`,queueName:e.queueName,messageRetentionPeriod:345600,delaySeconds:0,maximumMessageSize:262144,receiveMessageWaitTime:e.waitTimeSeconds||20})}createRetentionPolicy(e){let n=`retention-${Date.now()}-${this.retentionCounter++}`,r={id:n,...e};this.retentionPolicies.set(n,r);let i=this.queues.get(e.queueId);if(i)i.messageRetentionPeriod=e.retentionPeriod;return r}createShortRetentionPolicy(e){return this.createRetentionPolicy({queueId:e.queueId,retentionPeriod:e.retentionHours*60*60,autoCleanup:!0,archiveExpiredMessages:!1})}createArchivalRetentionPolicy(e){return this.createRetentionPolicy({queueId:e.queueId,retentionPeriod:e.retentionDays*24*60*60,autoCleanup:!0,cleanupSchedule:"cron(0 0 * * ? *)",archiveExpiredMessages:!0,archiveS3Bucket:e.s3Bucket})}createDelayQueue(e){let n=`delay-${Date.now()}-${this.delayCounter++}`,r={id:n,...e};this.delayQueues.set(n,r);let i=Array.from(this.queues.values()).find((s)=>s.queueUrl===e.queueUrl);if(i)i.delaySeconds=e.defaultDelay;return r}createScheduledDelayQueue(e){return this.createDelayQueue({queueUrl:e.queueUrl,defaultDelay:e.delayMinutes*60,perMessageDelay:!1,maxDelay:900})}async purgeQueue(e){let n=this.queues.get(e);if(!n)throw Error(`Queue not found: ${e}`);if(n.purgeInProgress)throw Error("Purge already in progress for this queue");let r=`purge-${Date.now()}-${this.purgeCounter++}`,i={id:r,queueUrl:n.queueUrl,status:"in_progress",startedAt:new Date};return this.purgeOperations.set(r,i),n.purgeInProgress=!0,setTimeout(()=>{i.status="completed",i.completedAt=new Date,i.messagesPurged=Math.floor(Math.random()*1000),n.purgeInProgress=!1},100),i}collectQueueMetrics(e){let r={id:`metrics-${Date.now()}-${this.metricsCounter++}`,queueUrl:e,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)},i=this.metrics.get(e)||[];return i.push(r),this.metrics.set(e,i),r}getQueueHealth(e){let n=this.metrics.get(e)||[];if(n.length===0)return{status:"healthy",issues:[],recommendations:[]};let r=n[n.length-1],i=[],s=[],a="healthy";if(r.approximateNumberOfMessages>1e4)a="critical",i.push("Large message backlog detected"),s.push("Increase consumer capacity");else if(r.approximateNumberOfMessages>1000)a="warning",i.push("Growing message backlog"),s.push("Monitor consumer performance");if(r.oldestMessageAge&&r.oldestMessageAge>3600){if(a!=="critical")a="warning";i.push("Old messages in queue"),s.push("Review message processing")}if(r.approximateNumberOfMessagesDelayed>100){if(a!=="critical")a="warning";i.push("High number of delayed messages")}return{status:a,issues:i,recommendations:s}}getQueue(e){return this.queues.get(e)}listQueues(){return Array.from(this.queues.values())}getRetentionPolicy(e){return this.retentionPolicies.get(e)}listRetentionPolicies(){return Array.from(this.retentionPolicies.values())}getPurgeOperations(e){let n=Array.from(this.purgeOperations.values());if(e)n=n.filter((r)=>r.queueUrl===e);return n}generateQueueCF(e){return{Type:"AWS::SQS::Queue",Properties:{QueueName:e.queueName,MessageRetentionPeriod:e.messageRetentionPeriod,DelaySeconds:e.delaySeconds,MaximumMessageSize:e.maximumMessageSize,ReceiveMessageWaitTimeSeconds:e.receiveMessageWaitTime}}}generateCleanupRuleCF(e){return{Type:"AWS::Events::Rule",Properties:{Name:`${e.id}-cleanup`,Description:"Automated queue cleanup",ScheduleExpression:e.cleanupSchedule||"cron(0 0 * * ? *)",State:"ENABLED",Targets:[{Arn:"arn:aws:lambda:us-east-1:123456789012:function:queue-cleanup",Id:e.id,Input:JSON.stringify({queueId:e.queueId,archiveBucket:e.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 dh=new dd;import{deflateRawSync as ps}from"node:zlib";var gs=(()=>{let e=[];for(let n=0;n<256;n++){let r=n;for(let i=0;i<8;i++)r=r&1?3988292384^r>>>1:r>>>1;e[n]=r>>>0}return e})();function ys(e){let n=4294967295;for(let r=0;r<e.length;r++)n=gs[(n^e[r])&255]^n>>>8;return(n^4294967295)>>>0}function fs(e){if(typeof e==="string")return Buffer.from(e,"utf-8");if(Buffer.isBuffer(e))return e;return Buffer.from(e)}function hs(e){let n=Math.max(1980,e.getFullYear()),r=(e.getHours()<<11|e.getMinutes()<<5|e.getSeconds()>>1)&65535,i=(n-1980<<9|e.getMonth()+1<<5|e.getDate())&65535;return{time:r,date:i}}function xt(e){let n=[],r=[],i=0;for(let c of e){let u=fs(c.data),d=ps(u),m=ys(u),p=Buffer.from(c.name.replace(/\\/g,"/"),"utf-8"),{time:g,date:y}=hs(c.date??new Date(0)),f=c.mode??420,h=Buffer.alloc(30+p.length);h.writeUInt32LE(67324752,0),h.writeUInt16LE(20,4),h.writeUInt16LE(0,6),h.writeUInt16LE(8,8),h.writeUInt16LE(g,10),h.writeUInt16LE(y,12),h.writeUInt32LE(m,14),h.writeUInt32LE(d.length,18),h.writeUInt32LE(u.length,22),h.writeUInt16LE(p.length,26),h.writeUInt16LE(0,28),p.copy(h,30);let S=Buffer.alloc(46+p.length);S.writeUInt32LE(33639248,0),S.writeUInt16LE(798,4),S.writeUInt16LE(20,6),S.writeUInt16LE(0,8),S.writeUInt16LE(8,10),S.writeUInt16LE(g,12),S.writeUInt16LE(y,14),S.writeUInt32LE(m,16),S.writeUInt32LE(d.length,20),S.writeUInt32LE(u.length,24),S.writeUInt16LE(p.length,28),S.writeUInt16LE(0,30),S.writeUInt16LE(0,32),S.writeUInt16LE(0,34),S.writeUInt16LE(0,36),S.writeUInt32LE((f&65535)<<16,38),S.writeUInt32LE(i,42),p.copy(S,46),n.push(h,d),r.push(S),i+=h.length+d.length}let s=Buffer.concat(r),a=Buffer.alloc(22);return a.writeUInt32LE(101010256,0),a.writeUInt16LE(0,4),a.writeUInt16LE(0,6),a.writeUInt16LE(e.length,8),a.writeUInt16LE(e.length,10),a.writeUInt32LE(s.length,12),a.writeUInt32LE(i,16),a.writeUInt16LE(0,20),Buffer.concat([...n,s,a])}function ud(e){let n=e.adapterImport??"./adapter",r=e.entryImport.replace(/\\/g,"/");return`// Generated by ts-cloud — serverless app bootstrap. Do not edit.
|
|
7239
|
+
`;static createAbTestsTable(e){return{[`${e.slug}AbTestsTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${e.slug}-ab-tests`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}]}}}}static createAbTestManagerLambda(e){return{[`${e.slug}AbTestManagerLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${e.slug}-ab-test-manager`,Runtime:"nodejs20.x",Handler:"index.handler",Role:e.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:me.AbTestManagerCode},Environment:{Variables:{AB_TESTS_TABLE:e.abTestsTable}}}}}}static selectVariant(e,n){let i=me.hashString(n+e.id)%100,s=0;for(let a=0;a<e.variants.length;a++)if(s+=e.trafficSplit[a],i<s)return e.variants[a];return e.variants[e.variants.length-1]}static determineWinner(e){if(e.variants.length===0)return null;let n=e.winningCriteria,r=e.variants[0],i=me.getMetricValue(r,n);for(let s of e.variants.slice(1)){let a=me.getMetricValue(s,n);if(a>i)i=a,r=s}return r}static calculateSignificance(e,n,r){let i=e.stats.sent,s=n.stats.sent;if(i<30||s<30)return 0;let a=me.getMetricValue(e,r)/100,c=me.getMetricValue(n,r)/100,u=(a*i+c*s)/(i+s),d=Math.sqrt(u*(1-u)*(1/i+1/s));if(d===0)return 0;let m=Math.abs(a-c)/d;if(m>=2.576)return 99;if(m>=1.96)return 95;if(m>=1.645)return 90;if(m>=1.28)return 80;return Math.round(m*30)}static getMetricValue(e,n){switch(n){case"delivery_rate":return e.stats.deliveryRate;case"click_rate":return e.stats.clickRate;case"reply_rate":return e.stats.replyRate;case"conversion_rate":return e.stats.conversionRate;default:return e.stats.deliveryRate}}static hashString(e){let n=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);n=(n<<5)-n+i,n=n&n}return Math.abs(n)}}class ad{queues=new Map;messageGroups=new Map;deduplicationConfigs=new Map;messages=new Map;queueCounter=0;groupCounter=0;deduplicationCounter=0;messageCounter=0;sequenceCounter=0;createFIFOQueue(e){let n=`fifo-queue-${Date.now()}-${this.queueCounter++}`,r=e.name.endsWith(".fifo")?e.name:`${e.name}.fifo`,{name:i,...s}=e,a={id:n,name:r,queueUrl:`https://sqs.us-east-1.amazonaws.com/123456789012/${r}`,...s};return this.queues.set(n,a),this.createDeduplicationConfig({queueId:n,contentBasedDeduplication:e.contentBasedDeduplication,deduplicationInterval:300}),a}createHighThroughputFIFO(e){return this.createFIFOQueue({name:e.name,contentBasedDeduplication:e.contentBasedDeduplication??!0,deduplicationScope:"messageGroup",fifoThroughputLimit:"perMessageGroupId",messageRetentionPeriod:345600,visibilityTimeout:30,receiveMessageWaitTime:0})}createStandardFIFO(e){return this.createFIFOQueue({name:e.name,contentBasedDeduplication:e.contentBasedDeduplication??!1,deduplicationScope:"queue",fifoThroughputLimit:"perQueue",messageRetentionPeriod:345600,visibilityTimeout:30,receiveMessageWaitTime:0})}createDeduplicationConfig(e){let r={id:`dedup-${Date.now()}-${this.deduplicationCounter++}`,deduplicationHashes:new Map,...e};return this.deduplicationConfigs.set(e.queueId,r),r}sendMessage(e){let n=this.queues.get(e.queueId);if(!n)throw Error(`Queue not found: ${e.queueId}`);let r=this.deduplicationConfigs.get(e.queueId);if(r){let c=e.messageDeduplicationId||(n.contentBasedDeduplication?this.generateHash(e.messageBody):void 0);if(c&&this.isDuplicate(r,c))return null;if(c)r.deduplicationHashes.set(c,new Date)}let i=`msg-${Date.now()}-${this.messageCounter++}`,s=this.generateSequenceNumber(),a={id:i,messageId:i,messageGroupId:e.messageGroupId,messageDeduplicationId:e.messageDeduplicationId,body:e.messageBody,attributes:e.messageAttributes||{},sentTimestamp:new Date,sequenceNumber:s};return this.messages.set(i,a),this.updateMessageGroup(e.queueId,e.messageGroupId),a}isDuplicate(e,n){let r=e.deduplicationHashes.get(n);if(!r)return!1;if((Date.now()-r.getTime())/1000>e.deduplicationInterval)return e.deduplicationHashes.delete(n),!1;return!0}generateHash(e){let n=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);n=(n<<5)-n+i,n=n&n}return Math.abs(n).toString(36)}generateSequenceNumber(){return`${Date.now()}${this.sequenceCounter++}`.padStart(20,"0")}updateMessageGroup(e,n){let r=`${e}-${n}`,i=this.messageGroups.get(r);if(!i)i={id:`group-${Date.now()}-${this.groupCounter++}`,messageGroupId:n,queueId:e,messagesInFlight:0},this.messageGroups.set(r,i);i.messagesInFlight++,i.lastMessageTimestamp=new Date}getMessageGroups(e){return Array.from(this.messageGroups.values()).filter((n)=>n.queueId===e)}getQueue(e){return this.queues.get(e)}listQueues(){return Array.from(this.queues.values())}getMessages(e,n){let r=Array.from(this.messages.values());if(n)r=r.filter((i)=>i.messageGroupId===n);return r.sort((i,s)=>i.sequenceNumber.localeCompare(s.sequenceNumber))}generateFIFOQueueCF(e){return{Type:"AWS::SQS::Queue",Properties:{QueueName:e.name,FifoQueue:!0,ContentBasedDeduplication:e.contentBasedDeduplication,DeduplicationScope:e.deduplicationScope,FifoThroughputLimit:e.fifoThroughputLimit,MessageRetentionPeriod:e.messageRetentionPeriod,VisibilityTimeout:e.visibilityTimeout,ReceiveMessageWaitTimeSeconds:e.receiveMessageWaitTime,...e.deadLetterTargetArn&&{RedrivePolicy:{deadLetterTargetArn:e.deadLetterTargetArn,maxReceiveCount:e.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 ah=new ad;class cd{monitors=new Map;metrics=new Map;alerts=new Map;reprocessJobs=new Map;monitorCounter=0;metricsCounter=0;alertCounter=0;jobCounter=0;createDLQMonitor(e){let n=`dlq-monitor-${Date.now()}-${this.monitorCounter++}`,r={id:n,...e};return this.monitors.set(n,r),r}createAutomatedMonitor(e){return this.createDLQMonitor({name:e.name,queueUrl:e.queueUrl,sourceQueues:e.sourceQueues,maxReceiveCount:3,alarmThreshold:10,autoReprocess:!0,reprocessStrategy:"scheduled",notificationTopicArn:e.notificationTopicArn})}collectMetrics(e){let r={id:`metrics-${Date.now()}-${this.metricsCounter++}`,queueUrl:e,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)},i=this.metrics.get(e)||[];return i.push(r),this.metrics.set(e,i),this.checkForAlerts(e,r),r}checkForAlerts(e,n){let r=Array.from(this.monitors.values()).find((s)=>s.queueUrl===e);if(!r)return;if(n.approximateNumberOfMessages>=r.alarmThreshold)this.createAlert({monitorId:r.id,alertType:"threshold_exceeded",severity:"high",message:`DLQ ${r.name} has ${n.approximateNumberOfMessages} messages (threshold: ${r.alarmThreshold})`});let i=3600;if(n.approximateAgeOfOldestMessage>i)this.createAlert({monitorId:r.id,alertType:"old_message",severity:"medium",message:`DLQ ${r.name} has messages older than ${i} seconds`})}createAlert(e){let n=`alert-${Date.now()}-${this.alertCounter++}`,r={id:n,timestamp:new Date,acknowledged:!1,...e};return this.alerts.set(n,r),r}acknowledgeAlert(e){let n=this.alerts.get(e);if(!n)throw Error(`Alert not found: ${e}`);return n.acknowledged=!0,n}createReprocessJob(e){let n=`reprocess-${Date.now()}-${this.jobCounter++}`,r={id:n,queueUrl:e.queueUrl,messageId:e.messageId,attempts:0,status:"pending"};return this.reprocessJobs.set(n,r),r}async executeReprocessJob(e){let n=this.reprocessJobs.get(e);if(!n)throw Error(`Reprocess job not found: ${e}`);n.status="processing",n.startedAt=new Date,n.attempts++,await new Promise((i)=>setTimeout(i,100));let r=Math.random()>0.3;if(n.status=r?"success":"failed",n.completedAt=new Date,!r)n.error="Reprocessing failed - original error still present";return n}async batchReprocess(e){let n=[];for(let r=0;r<e.maxMessages;r++){let i=this.createReprocessJob({queueUrl:e.queueUrl,messageId:`msg-${r}`});await this.executeReprocessJob(i.id),n.push(i)}return n}getDLQStatistics(e,n=24){let r=new Date(Date.now()-n*60*60*1000),i=(this.metrics.get(e)||[]).filter((p)=>p.timestamp>=r);if(i.length===0)return{totalMessages:0,avgAge:0,messagesReceived:0,messagesDeleted:0,messagesReprocessed:0,successRate:0};let s=i[i.length-1],a=i.reduce((p,g)=>p+g.messagesReceived,0),c=i.reduce((p,g)=>p+g.messagesDeleted,0),u=i.reduce((p,g)=>p+g.messagesReprocessed,0),d=i.reduce((p,g)=>p+g.approximateAgeOfOldestMessage,0)/i.length,m=u>0?c/u*100:0;return{totalMessages:s.approximateNumberOfMessages,avgAge:d,messagesReceived:a,messagesDeleted:c,messagesReprocessed:u,successRate:m}}getMonitor(e){return this.monitors.get(e)}listMonitors(){return Array.from(this.monitors.values())}getAlerts(e,n){let r=Array.from(this.alerts.values());if(e)r=r.filter((i)=>i.monitorId===e);if(n!==void 0)r=r.filter((i)=>i.acknowledged===n);return r.sort((i,s)=>s.timestamp.getTime()-i.timestamp.getTime())}getReprocessJobs(e){let n=Array.from(this.reprocessJobs.values());if(e)n=n.filter((r)=>r.queueUrl===e);return n}generateDLQAlarmCF(e){return{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${e.name}-messages-alarm`,AlarmDescription:`Alert when DLQ ${e.name} exceeds threshold`,MetricName:"ApproximateNumberOfMessagesVisible",Namespace:"AWS/SQS",Statistic:"Average",Period:300,EvaluationPeriods:1,Threshold:e.alarmThreshold,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:e.queueUrl.split("/").pop()}],...e.notificationTopicArn&&{AlarmActions:[e.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 ch=new cd;class ld{configs=new Map;jobs=new Map;metrics=new Map;configCounter=0;jobCounter=0;metricsCounter=0;createBatchConfig(e){let n=`batch-config-${Date.now()}-${this.configCounter++}`,r={id:n,...e};return this.configs.set(n,r),r}createHighThroughputConfig(e){return this.createBatchConfig({queueUrl:e.queueUrl,batchSize:10,maxWaitTime:100,parallelProcessors:10,retryAttempts:3,visibilityTimeout:30})}createLowLatencyConfig(e){return this.createBatchConfig({queueUrl:e.queueUrl,batchSize:1,maxWaitTime:0,parallelProcessors:5,retryAttempts:2,visibilityTimeout:10})}createBatchJob(e){let n=`batch-job-${Date.now()}-${this.jobCounter++}`;if(!this.configs.get(e.configId))throw Error(`Batch config not found: ${e.configId}`);let i=[];for(let a=0;a<e.messageCount;a++)i.push({id:`msg-${n}-${a}`,messageId:`${n}-${a}`,body:`Message ${a}`,receiptHandle:`receipt-${n}-${a}`,attributes:{},status:"pending"});let s={id:n,configId:e.configId,messages:i,status:"pending",processedCount:0,failedCount:0};return this.jobs.set(n,s),s}async processBatchJob(e){let n=this.jobs.get(e);if(!n)throw Error(`Batch job not found: ${e}`);let r=this.configs.get(n.configId);if(!r)throw Error(`Batch config not found: ${n.configId}`);n.status="processing",n.startedAt=new Date;let i=this.chunkArray(n.messages,r.batchSize);for(let s of i)await this.processBatch(s,r);return n.processedCount=n.messages.filter((s)=>s.status==="success").length,n.failedCount=n.messages.filter((s)=>s.status==="failed").length,n.status=n.failedCount===0?"completed":"failed",n.completedAt=new Date,this.collectProcessorMetrics(r.id,n),n}async processBatch(e,n){let r=e.map((i)=>this.processMessage(i,n));await Promise.all(r)}async processMessage(e,n){e.status="processing";let r=Date.now();await new Promise((a)=>setTimeout(a,Math.random()*100));let i=Date.now()-r;if(e.processingTime=i,Math.random()>0.1)e.status="success";else e.status="failed",e.error="Processing error"}chunkArray(e,n){let r=[];for(let i=0;i<e.length;i+=n)r.push(e.slice(i,i+n));return r}collectProcessorMetrics(e,n){let r=`metrics-${Date.now()}-${this.metricsCounter++}`,s=n.messages.filter((g)=>g.status==="success").map((g)=>g.processingTime||0).filter((g)=>g>0),a=s.length>0?s.reduce((g,y)=>g+y,0)/s.length:0,c=n.completedAt&&n.startedAt?(n.completedAt.getTime()-n.startedAt.getTime())/1000:1,u=n.processedCount/c,d=n.messages.length>0?n.failedCount/n.messages.length*100:0,m={id:r,configId:e,timestamp:new Date,messagesProcessed:n.processedCount,averageProcessingTime:a,throughput:u,errorRate:d},p=this.metrics.get(e)||[];p.push(m),this.metrics.set(e,p)}getBatchStatistics(e){let n=this.metrics.get(e)||[];if(n.length===0)return{totalJobsProcessed:0,totalMessagesProcessed:0,averageThroughput:0,averageErrorRate:0,averageProcessingTime:0};let r=n.reduce((c,u)=>c+u.messagesProcessed,0),i=n.reduce((c,u)=>c+u.throughput,0)/n.length,s=n.reduce((c,u)=>c+u.errorRate,0)/n.length,a=n.reduce((c,u)=>c+u.averageProcessingTime,0)/n.length;return{totalJobsProcessed:n.length,totalMessagesProcessed:r,averageThroughput:i,averageErrorRate:s,averageProcessingTime:a}}optimizeBatchConfig(e){let n=this.configs.get(e);if(!n)throw Error(`Batch config not found: ${e}`);let r=this.getBatchStatistics(e);if(r.averageErrorRate<5&&n.batchSize<10)n.batchSize=Math.min(10,n.batchSize+1);if(r.averageErrorRate>20&&n.batchSize>1)n.batchSize=Math.max(1,n.batchSize-1);if(r.averageThroughput<5&&n.parallelProcessors<20)n.parallelProcessors++;return n}getConfig(e){return this.configs.get(e)}listConfigs(){return Array.from(this.configs.values())}getJob(e){return this.jobs.get(e)}listJobs(e){let n=Array.from(this.jobs.values());if(e)n=n.filter((r)=>r.configId===e);return n}generateBatchProcessorCF(e){return{Type:"AWS::Lambda::EventSourceMapping",Properties:{EventSourceArn:`arn:aws:sqs:us-east-1:123456789012:${e.queueUrl.split("/").pop()}`,FunctionName:"batch-processor-function",BatchSize:e.batchSize,MaximumBatchingWindowInSeconds:e.maxWaitTime/1000,FunctionResponseTypes:["ReportBatchItemFailures"]}}}clear(){this.configs.clear(),this.jobs.clear(),this.metrics.clear(),this.configCounter=0,this.jobCounter=0,this.metricsCounter=0}}var lh=new ld;class dd{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(e){let n=`queue-${Date.now()}-${this.queueCounter++}`,r={id:n,purgeInProgress:!1,...e};return this.queues.set(n,r),r}createStandardQueue(e){return this.createQueue({queueUrl:`https://sqs.us-east-1.amazonaws.com/123456789012/${e.queueName}`,queueName:e.queueName,messageRetentionPeriod:(e.messageRetentionDays||4)*24*60*60,delaySeconds:0,maximumMessageSize:262144,receiveMessageWaitTime:0})}createLongPollingQueue(e){return this.createQueue({queueUrl:`https://sqs.us-east-1.amazonaws.com/123456789012/${e.queueName}`,queueName:e.queueName,messageRetentionPeriod:345600,delaySeconds:0,maximumMessageSize:262144,receiveMessageWaitTime:e.waitTimeSeconds||20})}createRetentionPolicy(e){let n=`retention-${Date.now()}-${this.retentionCounter++}`,r={id:n,...e};this.retentionPolicies.set(n,r);let i=this.queues.get(e.queueId);if(i)i.messageRetentionPeriod=e.retentionPeriod;return r}createShortRetentionPolicy(e){return this.createRetentionPolicy({queueId:e.queueId,retentionPeriod:e.retentionHours*60*60,autoCleanup:!0,archiveExpiredMessages:!1})}createArchivalRetentionPolicy(e){return this.createRetentionPolicy({queueId:e.queueId,retentionPeriod:e.retentionDays*24*60*60,autoCleanup:!0,cleanupSchedule:"cron(0 0 * * ? *)",archiveExpiredMessages:!0,archiveS3Bucket:e.s3Bucket})}createDelayQueue(e){let n=`delay-${Date.now()}-${this.delayCounter++}`,r={id:n,...e};this.delayQueues.set(n,r);let i=Array.from(this.queues.values()).find((s)=>s.queueUrl===e.queueUrl);if(i)i.delaySeconds=e.defaultDelay;return r}createScheduledDelayQueue(e){return this.createDelayQueue({queueUrl:e.queueUrl,defaultDelay:e.delayMinutes*60,perMessageDelay:!1,maxDelay:900})}async purgeQueue(e){let n=this.queues.get(e);if(!n)throw Error(`Queue not found: ${e}`);if(n.purgeInProgress)throw Error("Purge already in progress for this queue");let r=`purge-${Date.now()}-${this.purgeCounter++}`,i={id:r,queueUrl:n.queueUrl,status:"in_progress",startedAt:new Date};return this.purgeOperations.set(r,i),n.purgeInProgress=!0,setTimeout(()=>{i.status="completed",i.completedAt=new Date,i.messagesPurged=Math.floor(Math.random()*1000),n.purgeInProgress=!1},100),i}collectQueueMetrics(e){let r={id:`metrics-${Date.now()}-${this.metricsCounter++}`,queueUrl:e,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)},i=this.metrics.get(e)||[];return i.push(r),this.metrics.set(e,i),r}getQueueHealth(e){let n=this.metrics.get(e)||[];if(n.length===0)return{status:"healthy",issues:[],recommendations:[]};let r=n[n.length-1],i=[],s=[],a="healthy";if(r.approximateNumberOfMessages>1e4)a="critical",i.push("Large message backlog detected"),s.push("Increase consumer capacity");else if(r.approximateNumberOfMessages>1000)a="warning",i.push("Growing message backlog"),s.push("Monitor consumer performance");if(r.oldestMessageAge&&r.oldestMessageAge>3600){if(a!=="critical")a="warning";i.push("Old messages in queue"),s.push("Review message processing")}if(r.approximateNumberOfMessagesDelayed>100){if(a!=="critical")a="warning";i.push("High number of delayed messages")}return{status:a,issues:i,recommendations:s}}getQueue(e){return this.queues.get(e)}listQueues(){return Array.from(this.queues.values())}getRetentionPolicy(e){return this.retentionPolicies.get(e)}listRetentionPolicies(){return Array.from(this.retentionPolicies.values())}getPurgeOperations(e){let n=Array.from(this.purgeOperations.values());if(e)n=n.filter((r)=>r.queueUrl===e);return n}generateQueueCF(e){return{Type:"AWS::SQS::Queue",Properties:{QueueName:e.queueName,MessageRetentionPeriod:e.messageRetentionPeriod,DelaySeconds:e.delaySeconds,MaximumMessageSize:e.maximumMessageSize,ReceiveMessageWaitTimeSeconds:e.receiveMessageWaitTime}}}generateCleanupRuleCF(e){return{Type:"AWS::Events::Rule",Properties:{Name:`${e.id}-cleanup`,Description:"Automated queue cleanup",ScheduleExpression:e.cleanupSchedule||"cron(0 0 * * ? *)",State:"ENABLED",Targets:[{Arn:"arn:aws:lambda:us-east-1:123456789012:function:queue-cleanup",Id:e.id,Input:JSON.stringify({queueId:e.queueId,archiveBucket:e.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 dh=new dd;import{deflateRawSync as ps}from"node:zlib";var gs=(()=>{let e=[];for(let n=0;n<256;n++){let r=n;for(let i=0;i<8;i++)r=r&1?3988292384^r>>>1:r>>>1;e[n]=r>>>0}return e})();function ys(e){let n=4294967295;for(let r=0;r<e.length;r++)n=gs[(n^e[r])&255]^n>>>8;return(n^4294967295)>>>0}function fs(e){if(typeof e==="string")return Buffer.from(e,"utf-8");if(Buffer.isBuffer(e))return e;return Buffer.from(e)}function hs(e){let n=Math.max(1980,e.getFullYear()),r=(e.getHours()<<11|e.getMinutes()<<5|e.getSeconds()>>1)&65535,i=(n-1980<<9|e.getMonth()+1<<5|e.getDate())&65535;return{time:r,date:i}}function _t(e){let n=[],r=[],i=0;for(let c of e){let u=fs(c.data),d=ps(u),m=ys(u),p=Buffer.from(c.name.replace(/\\/g,"/"),"utf-8"),{time:g,date:y}=hs(c.date??new Date(0)),f=c.mode??420,h=Buffer.alloc(30+p.length);h.writeUInt32LE(67324752,0),h.writeUInt16LE(20,4),h.writeUInt16LE(0,6),h.writeUInt16LE(8,8),h.writeUInt16LE(g,10),h.writeUInt16LE(y,12),h.writeUInt32LE(m,14),h.writeUInt32LE(d.length,18),h.writeUInt32LE(u.length,22),h.writeUInt16LE(p.length,26),h.writeUInt16LE(0,28),p.copy(h,30);let S=Buffer.alloc(46+p.length);S.writeUInt32LE(33639248,0),S.writeUInt16LE(798,4),S.writeUInt16LE(20,6),S.writeUInt16LE(0,8),S.writeUInt16LE(8,10),S.writeUInt16LE(g,12),S.writeUInt16LE(y,14),S.writeUInt32LE(m,16),S.writeUInt32LE(d.length,20),S.writeUInt32LE(u.length,24),S.writeUInt16LE(p.length,28),S.writeUInt16LE(0,30),S.writeUInt16LE(0,32),S.writeUInt16LE(0,34),S.writeUInt16LE(0,36),S.writeUInt32LE((f&65535)<<16,38),S.writeUInt32LE(i,42),p.copy(S,46),n.push(h,d),r.push(S),i+=h.length+d.length}let s=Buffer.concat(r),a=Buffer.alloc(22);return a.writeUInt32LE(101010256,0),a.writeUInt16LE(0,4),a.writeUInt16LE(0,6),a.writeUInt16LE(e.length,8),a.writeUInt16LE(e.length,10),a.writeUInt32LE(s.length,12),a.writeUInt32LE(i,16),a.writeUInt16LE(0,20),Buffer.concat([...n,s,a])}function ud(e){let n=e.adapterImport??"./adapter",r=e.entryImport.replace(/\\/g,"/");return`// Generated by ts-cloud — serverless app bootstrap. Do not edit.
|
|
7240
7240
|
import * as __userModule from ${JSON.stringify(r)}
|
|
7241
7241
|
import { resolveApp, createHandlers } from ${JSON.stringify(n)}
|
|
7242
7242
|
|
|
@@ -7246,9 +7246,9 @@ const __handlers = createHandlers(__app)
|
|
|
7246
7246
|
export const http = __handlers.http
|
|
7247
7247
|
export const queue = __handlers.queue
|
|
7248
7248
|
export const cli = __handlers.cli
|
|
7249
|
-
`}import{execSync as bs}from"node:child_process";import{createHash as Ss}from"node:crypto";import{cpSync as As,mkdtempSync as Cs,rmSync as vs,writeFileSync as Ts}from"node:fs";import{tmpdir as Rs}from"node:os";import{dirname as Ps,isAbsolute as Es,join as xe,resolve as ws}from"node:path";import{fileURLToPath as Is}from"node:url";var Ds=["adapter.ts","recursion.ts","auto-recursion.ts"];function Ns(){return xe(Ps(Is(import.meta.url)),"runtime")}function Sp(e,n,r){for(let i of e??[])r?.(`build: ${i}`),bs(i,{stdio:"inherit",cwd:n})}function is(e){return Ss("sha256").update(e).digest("hex")}function Xa(e,n,r){return`deployments/${e}/${n}/${r}.zip`}async function
|
|
7249
|
+
`}import{execSync as bs}from"node:child_process";import{createHash as Ss}from"node:crypto";import{cpSync as As,mkdtempSync as Cs,rmSync as vs,writeFileSync as Ts}from"node:fs";import{tmpdir as Rs}from"node:os";import{dirname as Ps,isAbsolute as Es,join as xe,resolve as ws}from"node:path";import{fileURLToPath as Is}from"node:url";var Ds=["adapter.ts","recursion.ts","auto-recursion.ts"];function Ns(){return xe(Ps(Is(import.meta.url)),"runtime")}function Sp(e,n,r){for(let i of e??[])r?.(`build: ${i}`),bs(i,{stdio:"inherit",cwd:n})}function is(e){return Ss("sha256").update(e).digest("hex")}function Xa(e,n,r){return`deployments/${e}/${n}/${r}.zip`}async function kn(e){let n=ws(e.projectRoot??process.cwd()),{app:r}=e;if(!e.skipBuild)Sp(r.build,n,e.onStep);let i=r.entry;if(!i)throw Error("serverless app: `entry` is required to package a Node/Bun application");let s=Es(i)?i:xe(n,i),a=Cs(xe(Rs(),"tscloud-pkg-"));try{for(let y of Ds)As(xe(Ns(),y),xe(a,y));let c=xe(a,"bootstrap.ts");Ts(c,ud({entryImport:s,adapterImport:"./adapter"})),e.onStep?.("bundling application");let u=await Bun.build({entrypoints:[c],target:r.kind==="bun"?"bun":"node",format:"esm",minify:!1,sourcemap:"none"});if(!u.success){let y=u.logs.map((f)=>String(f)).join(`
|
|
7250
7250
|
`);throw Error(`serverless app bundle failed:
|
|
7251
|
-
${y}`)}let d=u.outputs[0],m=Buffer.from(await d.arrayBuffer()),p="index",g=xt([{name:`${p}.mjs`,data:m}]);return{zip:g,bundle:m,sha256:is(g),handlerFile:p,handlers:{http:r.handlers?.http??`${p}.http`,queue:r.handlers?.queue??`${p}.queue`,cli:r.handlers?.cli??`${p}.cli`},bundleBytes:m.length}}finally{vs(a,{recursive:!0,force:!0})}}var vp=["18","20","22"];function xs(e){if(!e)return"22";let n=String(e).match(/(\d+)/);return n?n[1]:"22"}function Ki(e){let n=e.kind??"node";if(n==="php")return{lambdaRuntime:"provided.al2023",kind:"php",version:e.phpVersion??"8.3",usesLayer:!0,layerKind:"php",layerEnvVar:"TSCLOUD_PHP_LAYER_ARN"};if(n==="bun")return{lambdaRuntime:"provided.al2023",kind:"bun",version:e.runtimeVersion??"latest",usesLayer:!0,layerKind:"bun",layerEnvVar:"TSCLOUD_BUN_LAYER_ARN"};let r=xs(e.runtimeVersion);if(e.runtime!=="provided.al2023"&&vp.includes(r))return{lambdaRuntime:e.runtime&&e.runtime.startsWith("nodejs")?e.runtime:`nodejs${r}.x`,kind:"node",version:r,usesLayer:!1};return{lambdaRuntime:"provided.al2023",kind:"node",version:r,usesLayer:!0,layerKind:"node",layerEnvVar:"TSCLOUD_NODE_LAYER_ARN"}}function tr(e,n,r){if(e.queues===!1)return[];if(e.queues===void 0||e.queues===!0)return[{name:`${n}-${r}-default`}];return e.queues.map((i)=>{if(typeof i==="string")return{name:`${n}-${r}-${i}`};let[s,a]=Object.entries(i)[0];return{name:`${n}-${r}-${s}`,concurrency:a}})}function Qa(e,n,r){return tr(e,n,r).map((i)=>i.name)}function Ya(e){let{app:n,environment:r,handlers:i}=e,s=e.config.project.slug,a=Ki(n).lambdaRuntime,c=n.architecture??"x86_64",u=e.config.project.region,d={http:`${s}-${r}-http`,queue:`${s}-${r}-queue`,cli:`${s}-${r}-cli`};if(n.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 m=tr(n,s,r),p=m.map((k)=>k.name),g=p.length>0,y=n.logRetention??14,f=n.packaging==="image";if(f&&n.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 h=(n.scheduler??"on")!=="off",S=(n.cache?.driver??"dynamodb")==="dynamodb",C=Boolean(n.assets),P=Bi(s,r),E=n.tmpStorage??512,v={},w={},D=[{PolicyName:"tscloud-serverless-app",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["logs:CreateLogGroup","logs:CreateLogStream","logs:PutLogEvents"],Resource:t.sub("arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/*")},{Effect:"Allow",Action:["lambda:InvokeFunction"],Resource:t.sub(`arn:aws:lambda:\${AWS::Region}:\${AWS::AccountId}:function:${s}-${r}-*`)},{Effect:"Allow",Action:["secretsmanager:GetSecretValue","ssm:GetParameter","ssm:GetParameters","ssm:GetParametersByPath"],Resource:[t.sub(`arn:aws:secretsmanager:\${AWS::Region}:\${AWS::AccountId}:secret:${s}/${r}/*`),t.sub(`arn:aws:ssm:\${AWS::Region}:\${AWS::AccountId}:parameter/${s}/${r}/*`)]},{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:ListBucket"],Resource:[t.sub(`arn:aws:s3:::${P}`),t.sub(`arn:aws:s3:::${P}/*`),...n.storage?.bucket?[t.sub(`arn:aws:s3:::${n.storage.bucket}`),t.sub(`arn:aws:s3:::${n.storage.bucket}/*`)]:[]]}]}}];if(g)D[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["sqs:SendMessage","sqs:ReceiveMessage","sqs:DeleteMessage","sqs:GetQueueAttributes","sqs:GetQueueUrl"],Resource:t.sub(`arn:aws:sqs:\${AWS::Region}:\${AWS::AccountId}:${s}-${r}-*`)});if(S)D[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["dynamodb:GetItem","dynamodb:PutItem","dynamodb:UpdateItem","dynamodb:DeleteItem","dynamodb:Query","dynamodb:Scan","dynamodb:BatchGetItem","dynamodb:BatchWriteItem"],Resource:t.sub(`arn:aws:dynamodb:\${AWS::Region}:\${AWS::AccountId}:table/${s}-${r}-cache*`)});let x=["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"];if(n.vpc?.subnets?.length)x.push("arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole");if(n.lambdaInsights)x.push("arn:aws:iam::aws:policy/CloudWatchLambdaInsightsExecutionRolePolicy");v.AppRole={Type:"AWS::IAM::Role",Properties:{RoleName:`${s}-${r}-app-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:x,Policies:D}};let L=(k)=>({TSCLOUD_LAMBDA_MODE:k,TSCLOUD_ENV:r,...n.octane?{TSCLOUD_OCTANE:"1"}:{},...n.scheduler==="sub-minute"?{TSCLOUD_SCHEDULER:"sub-minute"}:{},...S?{TSCLOUD_CACHE_TABLE:`${s}-${r}-cache`}:{},...g?{TSCLOUD_QUEUE:p[0]}:{},...n.env??{}}),B=Boolean(n.efs),O=typeof n.efs==="object"?n.efs:{},F=O.mountPath??"/mnt/local",V=B&&!O.accessPointArn,ce=O.accessPointArn??(V?t.getAtt("EfsAccessPoint","Arn"):void 0),q=n.vpc?.subnets??[],J=q.length>0,K=n.cache?.driver==="elasticache"||n.database?.connection==="aurora-serverless"||Boolean(n.rdsProxy)||B;if(K&&!J)throw Error("serverless app: elasticache / aurora-serverless / rdsProxy / efs require app.vpc.subnets (private subnets) to be set.");let Q=J?{VpcConfig:{SubnetIds:q,SecurityGroupIds:[...n.vpc?.securityGroups??[],...K?[t.getAtt("DataSecurityGroup","GroupId")]:[]]}}:{},ge=V?q.map((k,G)=>`EfsMountTarget${G}`):[],Te=B?{FileSystemConfigs:[{Arn:ce,LocalMountPath:F}]}:{};if(B)D[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["elasticfilesystem:ClientMount","elasticfilesystem:ClientWrite","elasticfilesystem:ClientRootAccess","elasticfilesystem:DescribeMountTargets"],Resource:"*"});function te(k,G,W,_,ee,mt,Be,he=E){v[`${k}LogGroup`]={Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:`/aws/lambda/${G}`,RetentionInDays:y}};let Fe=[...e.runtimeLayers??[],...n.lambdaInsights?[n.lambdaInsights.layerArn]:[]],en=f?{PackageType:"Image",Code:{ImageUri:t.ref("ImageUri")},...n.kind==="php"?{}:{ImageConfig:{Command:[W]}}}:{Runtime:a,Handler:W,Code:{S3Bucket:t.ref("ArtifactBucket"),S3Key:t.ref("ArtifactKey")},...Fe.length?{Layers:[...new Set(Fe)]}:{}};v[k]={Type:"AWS::Lambda::Function",DependsOn:[`${k}LogGroup`,...ge],Properties:{FunctionName:G,Architectures:[c],MemorySize:ee,Timeout:mt,Role:t.getAtt("AppRole","Arn"),Environment:{Variables:L(_)},EphemeralStorage:{Size:he},...en,...Be!==void 0?{ReservedConcurrentExecutions:Be}:{},...Q,...Te}}}if(te("HttpFunction",d.http,i.http,"http",n.memory??1024,n.timeout??28,n.concurrency,E),te("CliFunction",d.cli,i.cli,"cli",n.cliMemory??1024,n.cliTimeout??900,void 0,n.cliTmpStorage??E),g)te("QueueFunction",d.queue,i.queue,"queue",n.queueMemory??1024,n.queueTimeout??120,void 0,n.queueTmpStorage??E);let Z=(n.provisionedConcurrency??0)>0?n.provisionedConcurrency:0,re=["HttpFunction","CliFunction",...g?["QueueFunction"]:[]];if(Z)for(let k of re)v[`${k}Version`]={Type:"AWS::Lambda::Version",DeletionPolicy:"Retain",Properties:{FunctionName:t.ref(k)}},v[`${k}Alias`]={Type:"AWS::Lambda::Alias",Properties:{FunctionName:t.ref(k),Name:"live",FunctionVersion:t.getAtt(`${k}Version`,"Version"),ProvisionedConcurrencyConfig:{ProvisionedConcurrentExecutions:Z}}};let fe=(k)=>Z?t.ref(`${k}Alias`):t.getAtt(k,"Arn"),se=(k)=>Z?t.ref(`${k}Alias`):t.ref(k);v.HttpApi={Type:"AWS::ApiGatewayV2::Api",Properties:{Name:`${s}-${r}`,ProtocolType:"HTTP"}},v.HttpIntegration={Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:t.ref("HttpApi"),IntegrationType:"AWS_PROXY",IntegrationUri:fe("HttpFunction"),PayloadFormatVersion:"2.0"}},v.HttpRoute={Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:t.ref("HttpApi"),RouteKey:"$default",Target:t.join("/",["integrations",t.ref("HttpIntegration")])}},v.HttpStage={Type:"AWS::ApiGatewayV2::Stage",Properties:{ApiId:t.ref("HttpApi"),StageName:"$default",AutoDeploy:!0}},v.HttpPermission={Type:"AWS::Lambda::Permission",Properties:{FunctionName:se("HttpFunction"),Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:t.sub("arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${HttpApi}/*/*")}},w.HttpApiEndpoint={Description:"HTTP API endpoint",Value:t.getAtt("HttpApi","ApiEndpoint")},w.HttpApiId={Description:"HTTP API id",Value:t.ref("HttpApi")};let ue=(Array.isArray(n.domain)?n.domain:n.domain?[n.domain]:[]).filter(Boolean);if(ue.length){if(!n.certificateArn&&!n.hostedZoneId)throw Error("serverless app: a custom `domain` needs either `certificateArn` (pre-issued, regional) or `hostedZoneId` (to auto-issue + validate an ACM cert).");let k=n.certificateArn;if(!k)v.HttpCertificate={Type:"AWS::CertificateManager::Certificate",Properties:{DomainName:ue[0],...ue.length>1?{SubjectAlternativeNames:ue.slice(1)}:{},ValidationMethod:"DNS",DomainValidationOptions:ue.map((G)=>({DomainName:G,HostedZoneId:n.hostedZoneId}))}},k=t.ref("HttpCertificate");ue.forEach((G,W)=>{let _=`HttpDomain${W}`;if(v[_]={Type:"AWS::ApiGatewayV2::DomainName",Properties:{DomainName:G,DomainNameConfigurations:[{CertificateArn:k,EndpointType:"REGIONAL"}]}},v[`HttpApiMapping${W}`]={Type:"AWS::ApiGatewayV2::ApiMapping",DependsOn:["HttpStage"],Properties:{ApiId:t.ref("HttpApi"),DomainName:t.ref(_),Stage:"$default"}},n.hostedZoneId)v[`HttpDomainRecord${W}`]={Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:n.hostedZoneId,Name:G,Type:"A",AliasTarget:{DNSName:t.getAtt(_,"RegionalDomainName"),HostedZoneId:t.getAtt(_,"RegionalHostedZoneId")}}};w[`CustomDomain${W}`]={Description:`Custom domain ${G}`,Value:G},w[`CustomDomainTarget${W}`]={Description:`Point ${G} (CNAME/alias) at this APIGW regional domain`,Value:t.getAtt(_,"RegionalDomainName")}})}if(g)v.AppQueueDlq={Type:"AWS::SQS::Queue",Properties:{QueueName:`${s}-${r}-dlq`,MessageRetentionPeriod:1209600}},m.forEach((k,G)=>{let W=`AppQueue${G}`,_=n.queueTimeout??120;v[W]={Type:"AWS::SQS::Queue",Properties:{QueueName:k.name,VisibilityTimeout:Math.min(43200,_*6),RedrivePolicy:{deadLetterTargetArn:t.getAtt("AppQueueDlq","Arn"),maxReceiveCount:n.queueTries??3}}};let ee=k.concurrency??n.queueConcurrency;v[`${W}Mapping`]={Type:"AWS::Lambda::EventSourceMapping",Properties:{EventSourceArn:t.getAtt(W,"Arn"),FunctionName:se("QueueFunction"),BatchSize:1,FunctionResponseTypes:["ReportBatchItemFailures"],...ee?{ScalingConfig:{MaximumConcurrency:Math.max(2,ee)}}:{}}},w[`QueueUrl${G}`]={Description:`Queue URL: ${k.name}`,Value:t.ref(W)}});if(h)v.SchedulerRule={Type:"AWS::Events::Rule",Properties:{Name:`${s}-${r}-scheduler`,ScheduleExpression:"rate(1 minute)",State:"ENABLED",Targets:[{Id:"cli",Arn:fe("CliFunction"),Input:JSON.stringify({command:"schedule:run"})}]}},v.SchedulerPermission={Type:"AWS::Lambda::Permission",Properties:{FunctionName:se("CliFunction"),Action:"lambda:InvokeFunction",Principal:"events.amazonaws.com",SourceArn:t.getAtt("SchedulerRule","Arn")}};if(n.warm&&n.warm>0){let G={http:"HttpFunction",queue:"QueueFunction",cli:"CliFunction"},W=(n.warmFunctions??["http"]).filter((_)=>_!=="queue"||g);for(let _ of W){let ee=_.charAt(0).toUpperCase()+_.slice(1),mt=Math.ceil(n.warm/5),Be=0;for(let he=0;he<mt;he++){let Fe=Math.min(5,n.warm-Be);v[`Warmer${ee}Rule${he}`]={Type:"AWS::Events::Rule",Properties:{Name:`${s}-${r}-warmer-${_}-${he}`,ScheduleExpression:"rate(5 minutes)",State:"ENABLED",Targets:Array.from({length:Fe},(en,lr)=>({Id:`warm-${_}-${he}-${lr}`,Arn:t.getAtt(G[_],"Arn"),Input:JSON.stringify({warmer:!0})}))}},Be+=Fe}v[`Warmer${ee}Permission`]={Type:"AWS::Lambda::Permission",Properties:{FunctionName:t.ref(G[_]),Action:"lambda:InvokeFunction",Principal:"events.amazonaws.com",SourceArn:t.sub(`arn:aws:events:\${AWS::Region}:\${AWS::AccountId}:rule/${s}-${r}-warmer-${_}-*`)}}}}if(S)v.CacheTable={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${s}-${r}-cache`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"key",AttributeType:"S"}],KeySchema:[{AttributeName:"key",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"expires_at",Enabled:!0}}},w.CacheTableName={Description:"DynamoDB cache table",Value:t.ref("CacheTable")};if(C){if(v.AssetsBucket={Type:"AWS::S3::Bucket",Properties:{BucketName:P,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0}}},v.AssetsOAC={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`${s}-${r}-assets-oac`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},v.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:t.getAtt("AssetsBucket","RegionalDomainName"),OriginAccessControlId:t.ref("AssetsOAC"),S3OriginConfig:{OriginAccessIdentity:""}}],...n.assetDomain?{Aliases:[n.assetDomain],ViewerCertificate:{AcmCertificateArn:n.assetCertificateArn??t.ref("AssetsCertificate"),SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}}:{}}}},n.assetDomain){if(!n.assetCertificateArn){if(!n.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(u!=="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 ${u}. Supply a pre-issued us-east-1 \`assetCertificateArn\` instead.`);v.AssetsCertificate={Type:"AWS::CertificateManager::Certificate",Properties:{DomainName:n.assetDomain,ValidationMethod:"DNS",DomainValidationOptions:[{DomainName:n.assetDomain,HostedZoneId:n.hostedZoneId}]}}}if(n.hostedZoneId)v.AssetsDomainRecord={Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:n.hostedZoneId,Name:n.assetDomain,Type:"A",AliasTarget:{DNSName:t.getAtt("AssetsDistribution","DomainName"),HostedZoneId:"Z2FDTNDATAQYW2"}}};w.AssetDomain={Description:"Custom asset CDN host",Value:n.assetDomain}}v.AssetsBucketPolicy={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:t.ref("AssetsBucket"),PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:t.sub(`arn:aws:s3:::${P}/*`),Condition:{StringEquals:{"AWS:SourceArn":t.sub("arn:aws:cloudfront::${AWS::AccountId}:distribution/${AssetsDistribution}")}}}]}}},w.AssetsBucketName={Description:"Assets bucket",Value:t.ref("AssetsBucket")},w.AssetsCdnDomain={Description:"Assets CloudFront domain",Value:t.getAtt("AssetsDistribution","DomainName")}}if(n.firewall?.enabled){let k=[],G=0;if(n.firewall.rateLimit)k.push({Name:"rate-limit",Priority:G++,Action:{Block:{}},Statement:{RateBasedStatement:{Limit:n.firewall.rateLimit,AggregateKeyType:"IP"}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${s}-${r}-rate`}});let W={sqlInjection:"AWSManagedRulesSQLiRuleSet",xss:"AWSManagedRulesCommonRuleSet",common:"AWSManagedRulesCommonRuleSet",botControl:"AWSManagedRulesBotControlRuleSet",ipReputation:"AWSManagedRulesAmazonIpReputationList"};for(let _ of n.firewall.rules??[]){let ee=W[_];if(!ee)continue;k.push({Name:`managed-${_}`,Priority:G++,OverrideAction:{None:{}},Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:ee}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${s}-${r}-${_}`}})}v.WebAcl={Type:"AWS::WAFv2::WebACL",Properties:{Name:`${s}-${r}-waf`,Scope:"REGIONAL",DefaultAction:{Allow:{}},Rules:k,VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${s}-${r}-waf`}}},w.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:t.getAtt("WebAcl","Arn")}}if(J&&K){if(!n.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.");v.DataSecurityGroup={Type:"AWS::EC2::SecurityGroup",Properties:{VpcId:n.vpc.id,GroupDescription:`${s}-${r} serverless data access`,SecurityGroupIngress:[{IpProtocol:"-1",CidrIp:"10.0.0.0/8"}]}}}if(V)v.EfsFileSystem={Type:"AWS::EFS::FileSystem",Properties:{Encrypted:!0,FileSystemTags:[{Key:"Name",Value:`${s}-${r}-efs`}]}},q.forEach((k,G)=>{v[`EfsMountTarget${G}`]={Type:"AWS::EFS::MountTarget",Properties:{FileSystemId:t.ref("EfsFileSystem"),SubnetId:k,SecurityGroups:[t.getAtt("DataSecurityGroup","GroupId")]}}}),v.EfsAccessPoint={Type:"AWS::EFS::AccessPoint",Properties:{FileSystemId:t.ref("EfsFileSystem"),PosixUser:{Uid:1001,Gid:1001},RootDirectory:{Path:"/lambda",CreationInfo:{OwnerUid:1001,OwnerGid:1001,Permissions:"0755"}}}},w.EfsFileSystemId={Description:"EFS file system id",Value:t.ref("EfsFileSystem")};if(n.cache?.driver==="elasticache")v.CacheSubnetGroup={Type:"AWS::ElastiCache::SubnetGroup",Properties:{Description:`${s}-${r} cache subnets`,SubnetIds:q}},v.CacheCluster={Type:"AWS::ElastiCache::ReplicationGroup",Properties:{ReplicationGroupId:`${s}-${r}-cache`,ReplicationGroupDescription:`${s}-${r} redis`,Engine:"redis",CacheNodeType:"cache.t4g.micro",NumCacheClusters:1,AutomaticFailoverEnabled:!1,CacheSubnetGroupName:t.ref("CacheSubnetGroup"),SecurityGroupIds:[t.getAtt("DataSecurityGroup","GroupId")],TransitEncryptionEnabled:!1}},w.CacheEndpoint={Description:"Redis primary endpoint",Value:t.getAtt("CacheCluster","PrimaryEndPoint.Address")};if(n.database?.connection==="aurora-serverless")v.DbSubnetGroup={Type:"AWS::RDS::DBSubnetGroup",Properties:{DBSubnetGroupDescription:`${s}-${r} db subnets`,SubnetIds:q}},v.DbSecret={Type:"AWS::SecretsManager::Secret",Properties:{Name:`${s}/${r}/db`,GenerateSecretString:{SecretStringTemplate:JSON.stringify({username:"app"}),GenerateStringKey:"password",PasswordLength:32,ExcludePunctuation:!0}}},v.DbCluster={Type:"AWS::RDS::DBCluster",Properties:{Engine:"aurora-mysql",EngineMode:"provisioned",DBClusterIdentifier:`${s}-${r}-db`,DatabaseName:"app",MasterUsername:t.sub("{{resolve:secretsmanager:${DbSecret}:SecretString:username}}"),MasterUserPassword:t.sub("{{resolve:secretsmanager:${DbSecret}:SecretString:password}}"),ServerlessV2ScalingConfiguration:{MinCapacity:n.database?.minCapacity??0.5,MaxCapacity:n.database?.maxCapacity??4},DBSubnetGroupName:t.ref("DbSubnetGroup"),VpcSecurityGroupIds:[t.getAtt("DataSecurityGroup","GroupId")]}},v.DbInstance={Type:"AWS::RDS::DBInstance",Properties:{Engine:"aurora-mysql",DBInstanceClass:"db.serverless",DBClusterIdentifier:t.ref("DbCluster")}},w.DbEndpoint={Description:"Aurora cluster endpoint",Value:t.getAtt("DbCluster","Endpoint.Address")};if(n.rdsProxy&&n.database?.connection==="aurora-serverless")v.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:t.ref("DbSecret")}]}}]}},v.DbProxy={Type:"AWS::RDS::DBProxy",Properties:{DBProxyName:typeof n.rdsProxy==="object"&&n.rdsProxy.name?n.rdsProxy.name:`${s}-${r}-proxy`,EngineFamily:"MYSQL",RoleArn:t.getAtt("DbProxyRole","Arn"),Auth:[{AuthScheme:"SECRETS",SecretArn:t.ref("DbSecret"),IAMAuth:"DISABLED"}],VpcSubnetIds:q,VpcSecurityGroupIds:[t.getAtt("DataSecurityGroup","GroupId")],RequireTLS:!1}},v.DbProxyTargetGroup={Type:"AWS::RDS::DBProxyTargetGroup",DependsOn:["DbInstance"],Properties:{DBProxyName:t.ref("DbProxy"),TargetGroupName:"default",DBClusterIdentifiers:[t.ref("DbCluster")]}},w.DbProxyEndpoint={Description:"RDS Proxy endpoint",Value:t.getAtt("DbProxy","Endpoint")};if(w.HttpFunctionName={Description:"HTTP function name",Value:t.ref("HttpFunction")},w.CliFunctionName={Description:"CLI function name",Value:t.ref("CliFunction")},g)w.QueueFunctionName={Description:"Queue function name",Value:t.ref("QueueFunction")};let Ee={AWSTemplateFormatVersion:"2010-09-09",Description:`Serverless application for ${e.config.project.name} (${s}-${r})`,Parameters:f?{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:v,Outputs:w},Oe={};for(let k of Object.values(v))Oe[k.Type]=(Oe[k.Type]??0)+1;return{template:Ee,functionNames:d,queueNames:p,resourceSummary:Oe}}var Cp=["cli","fpm","curl","mbstring","xml","pdo","mysqlnd","gd","bcmath","intl","opcache","sodium","process","pecl-redis6","pecl-apcu","pgsql"];function Tp(e){let n=`php${e.replace(".","")}`;return Cp.map((r)=>`${n}-php-${r}`)}function Za(e,n){let r=`php${e.replace(".","")}`,i=Tp(e).join(" \\\n "),s=`/opt/remi/${r}/root`,a=`/etc/opt/remi/${r}`;return`${n?`FROM almalinux:9 AS ${n}`:"FROM almalinux:9"}
|
|
7251
|
+
${y}`)}let d=u.outputs[0],m=Buffer.from(await d.arrayBuffer()),p="index",g=_t([{name:`${p}.mjs`,data:m}]);return{zip:g,bundle:m,sha256:is(g),handlerFile:p,handlers:{http:r.handlers?.http??`${p}.http`,queue:r.handlers?.queue??`${p}.queue`,cli:r.handlers?.cli??`${p}.cli`},bundleBytes:m.length}}finally{vs(a,{recursive:!0,force:!0})}}var vp=["18","20","22"];function xs(e){if(!e)return"22";let n=String(e).match(/(\d+)/);return n?n[1]:"22"}function Ki(e){let n=e.kind??"node";if(n==="php")return{lambdaRuntime:"provided.al2023",kind:"php",version:e.phpVersion??"8.3",usesLayer:!0,layerKind:"php",layerEnvVar:"TSCLOUD_PHP_LAYER_ARN"};if(n==="bun")return{lambdaRuntime:"provided.al2023",kind:"bun",version:e.runtimeVersion??"latest",usesLayer:!0,layerKind:"bun",layerEnvVar:"TSCLOUD_BUN_LAYER_ARN"};let r=xs(e.runtimeVersion);if(e.runtime!=="provided.al2023"&&vp.includes(r))return{lambdaRuntime:e.runtime&&e.runtime.startsWith("nodejs")?e.runtime:`nodejs${r}.x`,kind:"node",version:r,usesLayer:!1};return{lambdaRuntime:"provided.al2023",kind:"node",version:r,usesLayer:!0,layerKind:"node",layerEnvVar:"TSCLOUD_NODE_LAYER_ARN"}}function rr(e,n,r){if(e.queues===!1)return[];if(e.queues===void 0||e.queues===!0)return[{name:`${n}-${r}-default`}];return e.queues.map((i)=>{if(typeof i==="string")return{name:`${n}-${r}-${i}`};let[s,a]=Object.entries(i)[0];return{name:`${n}-${r}-${s}`,concurrency:a}})}function Qa(e,n,r){return rr(e,n,r).map((i)=>i.name)}function Ya(e){let{app:n,environment:r,handlers:i}=e,s=e.config.project.slug,a=Ki(n).lambdaRuntime,c=n.architecture??"x86_64",u=e.config.project.region,d={http:`${s}-${r}-http`,queue:`${s}-${r}-queue`,cli:`${s}-${r}-cli`};if(n.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 m=rr(n,s,r),p=m.map((k)=>k.name),g=p.length>0,y=n.logRetention??14,f=n.packaging==="image";if(f&&n.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 h=(n.scheduler??"on")!=="off",S=(n.cache?.driver??"dynamodb")==="dynamodb",C=Boolean(n.assets),P=Bi(s,r),E=n.tmpStorage??512,v={},w={},D=[{PolicyName:"tscloud-serverless-app",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["logs:CreateLogGroup","logs:CreateLogStream","logs:PutLogEvents"],Resource:t.sub("arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/*")},{Effect:"Allow",Action:["lambda:InvokeFunction"],Resource:t.sub(`arn:aws:lambda:\${AWS::Region}:\${AWS::AccountId}:function:${s}-${r}-*`)},{Effect:"Allow",Action:["secretsmanager:GetSecretValue","ssm:GetParameter","ssm:GetParameters","ssm:GetParametersByPath"],Resource:[t.sub(`arn:aws:secretsmanager:\${AWS::Region}:\${AWS::AccountId}:secret:${s}/${r}/*`),t.sub(`arn:aws:ssm:\${AWS::Region}:\${AWS::AccountId}:parameter/${s}/${r}/*`)]},{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:ListBucket"],Resource:[t.sub(`arn:aws:s3:::${P}`),t.sub(`arn:aws:s3:::${P}/*`),...n.storage?.bucket?[t.sub(`arn:aws:s3:::${n.storage.bucket}`),t.sub(`arn:aws:s3:::${n.storage.bucket}/*`)]:[]]}]}}];if(g)D[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["sqs:SendMessage","sqs:ReceiveMessage","sqs:DeleteMessage","sqs:GetQueueAttributes","sqs:GetQueueUrl"],Resource:t.sub(`arn:aws:sqs:\${AWS::Region}:\${AWS::AccountId}:${s}-${r}-*`)});if(S)D[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["dynamodb:GetItem","dynamodb:PutItem","dynamodb:UpdateItem","dynamodb:DeleteItem","dynamodb:Query","dynamodb:Scan","dynamodb:BatchGetItem","dynamodb:BatchWriteItem"],Resource:t.sub(`arn:aws:dynamodb:\${AWS::Region}:\${AWS::AccountId}:table/${s}-${r}-cache*`)});let x=["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"];if(n.vpc?.subnets?.length)x.push("arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole");if(n.lambdaInsights)x.push("arn:aws:iam::aws:policy/CloudWatchLambdaInsightsExecutionRolePolicy");v.AppRole={Type:"AWS::IAM::Role",Properties:{RoleName:`${s}-${r}-app-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:x,Policies:D}};let L=(k)=>({TSCLOUD_LAMBDA_MODE:k,TSCLOUD_ENV:r,...n.octane?{TSCLOUD_OCTANE:"1"}:{},...n.scheduler==="sub-minute"?{TSCLOUD_SCHEDULER:"sub-minute"}:{},...S?{TSCLOUD_CACHE_TABLE:`${s}-${r}-cache`}:{},...g?{TSCLOUD_QUEUE:p[0]}:{},...n.env??{}}),B=Boolean(n.efs),O=typeof n.efs==="object"?n.efs:{},F=O.mountPath??"/mnt/local",V=B&&!O.accessPointArn,ce=O.accessPointArn??(V?t.getAtt("EfsAccessPoint","Arn"):void 0),q=n.vpc?.subnets??[],J=q.length>0,K=n.cache?.driver==="elasticache"||n.database?.connection==="aurora-serverless"||Boolean(n.rdsProxy)||B;if(K&&!J)throw Error("serverless app: elasticache / aurora-serverless / rdsProxy / efs require app.vpc.subnets (private subnets) to be set.");let Q=J?{VpcConfig:{SubnetIds:q,SecurityGroupIds:[...n.vpc?.securityGroups??[],...K?[t.getAtt("DataSecurityGroup","GroupId")]:[]]}}:{},ge=V?q.map((k,G)=>`EfsMountTarget${G}`):[],Te=B?{FileSystemConfigs:[{Arn:ce,LocalMountPath:F}]}:{};if(B)D[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["elasticfilesystem:ClientMount","elasticfilesystem:ClientWrite","elasticfilesystem:ClientRootAccess","elasticfilesystem:DescribeMountTargets"],Resource:"*"});function te(k,G,W,_,ee,mt,Be,he=E){v[`${k}LogGroup`]={Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:`/aws/lambda/${G}`,RetentionInDays:y}};let Fe=[...e.runtimeLayers??[],...n.lambdaInsights?[n.lambdaInsights.layerArn]:[]],Xt=f?{PackageType:"Image",Code:{ImageUri:t.ref("ImageUri")},...n.kind==="php"?{}:{ImageConfig:{Command:[W]}}}:{Runtime:a,Handler:W,Code:{S3Bucket:t.ref("ArtifactBucket"),S3Key:t.ref("ArtifactKey")},...Fe.length?{Layers:[...new Set(Fe)]}:{}};v[k]={Type:"AWS::Lambda::Function",DependsOn:[`${k}LogGroup`,...ge],Properties:{FunctionName:G,Architectures:[c],MemorySize:ee,Timeout:mt,Role:t.getAtt("AppRole","Arn"),Environment:{Variables:L(_)},EphemeralStorage:{Size:he},...Xt,...Be!==void 0?{ReservedConcurrentExecutions:Be}:{},...Q,...Te}}}if(te("HttpFunction",d.http,i.http,"http",n.memory??1024,n.timeout??28,n.concurrency,E),te("CliFunction",d.cli,i.cli,"cli",n.cliMemory??1024,n.cliTimeout??900,void 0,n.cliTmpStorage??E),g)te("QueueFunction",d.queue,i.queue,"queue",n.queueMemory??1024,n.queueTimeout??120,void 0,n.queueTmpStorage??E);let Z=(n.provisionedConcurrency??0)>0?n.provisionedConcurrency:0,re=["HttpFunction","CliFunction",...g?["QueueFunction"]:[]];if(Z)for(let k of re)v[`${k}Version`]={Type:"AWS::Lambda::Version",DeletionPolicy:"Retain",Properties:{FunctionName:t.ref(k)}},v[`${k}Alias`]={Type:"AWS::Lambda::Alias",Properties:{FunctionName:t.ref(k),Name:"live",FunctionVersion:t.getAtt(`${k}Version`,"Version"),ProvisionedConcurrencyConfig:{ProvisionedConcurrentExecutions:Z}}};let fe=(k)=>Z?t.ref(`${k}Alias`):t.getAtt(k,"Arn"),se=(k)=>Z?t.ref(`${k}Alias`):t.ref(k);v.HttpApi={Type:"AWS::ApiGatewayV2::Api",Properties:{Name:`${s}-${r}`,ProtocolType:"HTTP"}},v.HttpIntegration={Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:t.ref("HttpApi"),IntegrationType:"AWS_PROXY",IntegrationUri:fe("HttpFunction"),PayloadFormatVersion:"2.0"}},v.HttpRoute={Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:t.ref("HttpApi"),RouteKey:"$default",Target:t.join("/",["integrations",t.ref("HttpIntegration")])}},v.HttpStage={Type:"AWS::ApiGatewayV2::Stage",Properties:{ApiId:t.ref("HttpApi"),StageName:"$default",AutoDeploy:!0}},v.HttpPermission={Type:"AWS::Lambda::Permission",Properties:{FunctionName:se("HttpFunction"),Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:t.sub("arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${HttpApi}/*/*")}},w.HttpApiEndpoint={Description:"HTTP API endpoint",Value:t.getAtt("HttpApi","ApiEndpoint")},w.HttpApiId={Description:"HTTP API id",Value:t.ref("HttpApi")};let ue=(Array.isArray(n.domain)?n.domain:n.domain?[n.domain]:[]).filter(Boolean);if(ue.length){if(!n.certificateArn&&!n.hostedZoneId)throw Error("serverless app: a custom `domain` needs either `certificateArn` (pre-issued, regional) or `hostedZoneId` (to auto-issue + validate an ACM cert).");let k=n.certificateArn;if(!k)v.HttpCertificate={Type:"AWS::CertificateManager::Certificate",Properties:{DomainName:ue[0],...ue.length>1?{SubjectAlternativeNames:ue.slice(1)}:{},ValidationMethod:"DNS",DomainValidationOptions:ue.map((G)=>({DomainName:G,HostedZoneId:n.hostedZoneId}))}},k=t.ref("HttpCertificate");ue.forEach((G,W)=>{let _=`HttpDomain${W}`;if(v[_]={Type:"AWS::ApiGatewayV2::DomainName",Properties:{DomainName:G,DomainNameConfigurations:[{CertificateArn:k,EndpointType:"REGIONAL"}]}},v[`HttpApiMapping${W}`]={Type:"AWS::ApiGatewayV2::ApiMapping",DependsOn:["HttpStage"],Properties:{ApiId:t.ref("HttpApi"),DomainName:t.ref(_),Stage:"$default"}},n.hostedZoneId)v[`HttpDomainRecord${W}`]={Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:n.hostedZoneId,Name:G,Type:"A",AliasTarget:{DNSName:t.getAtt(_,"RegionalDomainName"),HostedZoneId:t.getAtt(_,"RegionalHostedZoneId")}}};w[`CustomDomain${W}`]={Description:`Custom domain ${G}`,Value:G},w[`CustomDomainTarget${W}`]={Description:`Point ${G} (CNAME/alias) at this APIGW regional domain`,Value:t.getAtt(_,"RegionalDomainName")}})}if(g)v.AppQueueDlq={Type:"AWS::SQS::Queue",Properties:{QueueName:`${s}-${r}-dlq`,MessageRetentionPeriod:1209600}},m.forEach((k,G)=>{let W=`AppQueue${G}`,_=n.queueTimeout??120;v[W]={Type:"AWS::SQS::Queue",Properties:{QueueName:k.name,VisibilityTimeout:Math.min(43200,_*6),RedrivePolicy:{deadLetterTargetArn:t.getAtt("AppQueueDlq","Arn"),maxReceiveCount:n.queueTries??3}}};let ee=k.concurrency??n.queueConcurrency;v[`${W}Mapping`]={Type:"AWS::Lambda::EventSourceMapping",Properties:{EventSourceArn:t.getAtt(W,"Arn"),FunctionName:se("QueueFunction"),BatchSize:1,FunctionResponseTypes:["ReportBatchItemFailures"],...ee?{ScalingConfig:{MaximumConcurrency:Math.max(2,ee)}}:{}}},w[`QueueUrl${G}`]={Description:`Queue URL: ${k.name}`,Value:t.ref(W)}});if(h)v.SchedulerRule={Type:"AWS::Events::Rule",Properties:{Name:`${s}-${r}-scheduler`,ScheduleExpression:"rate(1 minute)",State:"ENABLED",Targets:[{Id:"cli",Arn:fe("CliFunction"),Input:JSON.stringify({command:"schedule:run"})}]}},v.SchedulerPermission={Type:"AWS::Lambda::Permission",Properties:{FunctionName:se("CliFunction"),Action:"lambda:InvokeFunction",Principal:"events.amazonaws.com",SourceArn:t.getAtt("SchedulerRule","Arn")}};if(n.warm&&n.warm>0){let G={http:"HttpFunction",queue:"QueueFunction",cli:"CliFunction"},W=(n.warmFunctions??["http"]).filter((_)=>_!=="queue"||g);for(let _ of W){let ee=_.charAt(0).toUpperCase()+_.slice(1),mt=Math.ceil(n.warm/5),Be=0;for(let he=0;he<mt;he++){let Fe=Math.min(5,n.warm-Be);v[`Warmer${ee}Rule${he}`]={Type:"AWS::Events::Rule",Properties:{Name:`${s}-${r}-warmer-${_}-${he}`,ScheduleExpression:"rate(5 minutes)",State:"ENABLED",Targets:Array.from({length:Fe},(Xt,lr)=>({Id:`warm-${_}-${he}-${lr}`,Arn:t.getAtt(G[_],"Arn"),Input:JSON.stringify({warmer:!0})}))}},Be+=Fe}v[`Warmer${ee}Permission`]={Type:"AWS::Lambda::Permission",Properties:{FunctionName:t.ref(G[_]),Action:"lambda:InvokeFunction",Principal:"events.amazonaws.com",SourceArn:t.sub(`arn:aws:events:\${AWS::Region}:\${AWS::AccountId}:rule/${s}-${r}-warmer-${_}-*`)}}}}if(S)v.CacheTable={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${s}-${r}-cache`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"key",AttributeType:"S"}],KeySchema:[{AttributeName:"key",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"expires_at",Enabled:!0}}},w.CacheTableName={Description:"DynamoDB cache table",Value:t.ref("CacheTable")};if(C){if(v.AssetsBucket={Type:"AWS::S3::Bucket",Properties:{BucketName:P,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0}}},v.AssetsOAC={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`${s}-${r}-assets-oac`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},v.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:t.getAtt("AssetsBucket","RegionalDomainName"),OriginAccessControlId:t.ref("AssetsOAC"),S3OriginConfig:{OriginAccessIdentity:""}}],...n.assetDomain?{Aliases:[n.assetDomain],ViewerCertificate:{AcmCertificateArn:n.assetCertificateArn??t.ref("AssetsCertificate"),SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}}:{}}}},n.assetDomain){if(!n.assetCertificateArn){if(!n.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(u!=="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 ${u}. Supply a pre-issued us-east-1 \`assetCertificateArn\` instead.`);v.AssetsCertificate={Type:"AWS::CertificateManager::Certificate",Properties:{DomainName:n.assetDomain,ValidationMethod:"DNS",DomainValidationOptions:[{DomainName:n.assetDomain,HostedZoneId:n.hostedZoneId}]}}}if(n.hostedZoneId)v.AssetsDomainRecord={Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:n.hostedZoneId,Name:n.assetDomain,Type:"A",AliasTarget:{DNSName:t.getAtt("AssetsDistribution","DomainName"),HostedZoneId:"Z2FDTNDATAQYW2"}}};w.AssetDomain={Description:"Custom asset CDN host",Value:n.assetDomain}}v.AssetsBucketPolicy={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:t.ref("AssetsBucket"),PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:t.sub(`arn:aws:s3:::${P}/*`),Condition:{StringEquals:{"AWS:SourceArn":t.sub("arn:aws:cloudfront::${AWS::AccountId}:distribution/${AssetsDistribution}")}}}]}}},w.AssetsBucketName={Description:"Assets bucket",Value:t.ref("AssetsBucket")},w.AssetsCdnDomain={Description:"Assets CloudFront domain",Value:t.getAtt("AssetsDistribution","DomainName")}}if(n.firewall?.enabled){let k=[],G=0;if(n.firewall.rateLimit)k.push({Name:"rate-limit",Priority:G++,Action:{Block:{}},Statement:{RateBasedStatement:{Limit:n.firewall.rateLimit,AggregateKeyType:"IP"}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${s}-${r}-rate`}});let W={sqlInjection:"AWSManagedRulesSQLiRuleSet",xss:"AWSManagedRulesCommonRuleSet",common:"AWSManagedRulesCommonRuleSet",botControl:"AWSManagedRulesBotControlRuleSet",ipReputation:"AWSManagedRulesAmazonIpReputationList"};for(let _ of n.firewall.rules??[]){let ee=W[_];if(!ee)continue;k.push({Name:`managed-${_}`,Priority:G++,OverrideAction:{None:{}},Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:ee}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${s}-${r}-${_}`}})}v.WebAcl={Type:"AWS::WAFv2::WebACL",Properties:{Name:`${s}-${r}-waf`,Scope:"REGIONAL",DefaultAction:{Allow:{}},Rules:k,VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${s}-${r}-waf`}}},w.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:t.getAtt("WebAcl","Arn")}}if(J&&K){if(!n.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.");v.DataSecurityGroup={Type:"AWS::EC2::SecurityGroup",Properties:{VpcId:n.vpc.id,GroupDescription:`${s}-${r} serverless data access`,SecurityGroupIngress:[{IpProtocol:"-1",CidrIp:"10.0.0.0/8"}]}}}if(V)v.EfsFileSystem={Type:"AWS::EFS::FileSystem",Properties:{Encrypted:!0,FileSystemTags:[{Key:"Name",Value:`${s}-${r}-efs`}]}},q.forEach((k,G)=>{v[`EfsMountTarget${G}`]={Type:"AWS::EFS::MountTarget",Properties:{FileSystemId:t.ref("EfsFileSystem"),SubnetId:k,SecurityGroups:[t.getAtt("DataSecurityGroup","GroupId")]}}}),v.EfsAccessPoint={Type:"AWS::EFS::AccessPoint",Properties:{FileSystemId:t.ref("EfsFileSystem"),PosixUser:{Uid:1001,Gid:1001},RootDirectory:{Path:"/lambda",CreationInfo:{OwnerUid:1001,OwnerGid:1001,Permissions:"0755"}}}},w.EfsFileSystemId={Description:"EFS file system id",Value:t.ref("EfsFileSystem")};if(n.cache?.driver==="elasticache")v.CacheSubnetGroup={Type:"AWS::ElastiCache::SubnetGroup",Properties:{Description:`${s}-${r} cache subnets`,SubnetIds:q}},v.CacheCluster={Type:"AWS::ElastiCache::ReplicationGroup",Properties:{ReplicationGroupId:`${s}-${r}-cache`,ReplicationGroupDescription:`${s}-${r} redis`,Engine:"redis",CacheNodeType:"cache.t4g.micro",NumCacheClusters:1,AutomaticFailoverEnabled:!1,CacheSubnetGroupName:t.ref("CacheSubnetGroup"),SecurityGroupIds:[t.getAtt("DataSecurityGroup","GroupId")],TransitEncryptionEnabled:!1}},w.CacheEndpoint={Description:"Redis primary endpoint",Value:t.getAtt("CacheCluster","PrimaryEndPoint.Address")};if(n.database?.connection==="aurora-serverless")v.DbSubnetGroup={Type:"AWS::RDS::DBSubnetGroup",Properties:{DBSubnetGroupDescription:`${s}-${r} db subnets`,SubnetIds:q}},v.DbSecret={Type:"AWS::SecretsManager::Secret",Properties:{Name:`${s}/${r}/db`,GenerateSecretString:{SecretStringTemplate:JSON.stringify({username:"app"}),GenerateStringKey:"password",PasswordLength:32,ExcludePunctuation:!0}}},v.DbCluster={Type:"AWS::RDS::DBCluster",Properties:{Engine:"aurora-mysql",EngineMode:"provisioned",DBClusterIdentifier:`${s}-${r}-db`,DatabaseName:"app",MasterUsername:t.sub("{{resolve:secretsmanager:${DbSecret}:SecretString:username}}"),MasterUserPassword:t.sub("{{resolve:secretsmanager:${DbSecret}:SecretString:password}}"),ServerlessV2ScalingConfiguration:{MinCapacity:n.database?.minCapacity??0.5,MaxCapacity:n.database?.maxCapacity??4},DBSubnetGroupName:t.ref("DbSubnetGroup"),VpcSecurityGroupIds:[t.getAtt("DataSecurityGroup","GroupId")]}},v.DbInstance={Type:"AWS::RDS::DBInstance",Properties:{Engine:"aurora-mysql",DBInstanceClass:"db.serverless",DBClusterIdentifier:t.ref("DbCluster")}},w.DbEndpoint={Description:"Aurora cluster endpoint",Value:t.getAtt("DbCluster","Endpoint.Address")};if(n.rdsProxy&&n.database?.connection==="aurora-serverless")v.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:t.ref("DbSecret")}]}}]}},v.DbProxy={Type:"AWS::RDS::DBProxy",Properties:{DBProxyName:typeof n.rdsProxy==="object"&&n.rdsProxy.name?n.rdsProxy.name:`${s}-${r}-proxy`,EngineFamily:"MYSQL",RoleArn:t.getAtt("DbProxyRole","Arn"),Auth:[{AuthScheme:"SECRETS",SecretArn:t.ref("DbSecret"),IAMAuth:"DISABLED"}],VpcSubnetIds:q,VpcSecurityGroupIds:[t.getAtt("DataSecurityGroup","GroupId")],RequireTLS:!1}},v.DbProxyTargetGroup={Type:"AWS::RDS::DBProxyTargetGroup",DependsOn:["DbInstance"],Properties:{DBProxyName:t.ref("DbProxy"),TargetGroupName:"default",DBClusterIdentifiers:[t.ref("DbCluster")]}},w.DbProxyEndpoint={Description:"RDS Proxy endpoint",Value:t.getAtt("DbProxy","Endpoint")};if(w.HttpFunctionName={Description:"HTTP function name",Value:t.ref("HttpFunction")},w.CliFunctionName={Description:"CLI function name",Value:t.ref("CliFunction")},g)w.QueueFunctionName={Description:"Queue function name",Value:t.ref("QueueFunction")};let Ee={AWSTemplateFormatVersion:"2010-09-09",Description:`Serverless application for ${e.config.project.name} (${s}-${r})`,Parameters:f?{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:v,Outputs:w},Oe={};for(let k of Object.values(v))Oe[k.Type]=(Oe[k.Type]??0)+1;return{template:Ee,functionNames:d,queueNames:p,resourceSummary:Oe}}var Cp=["cli","fpm","curl","mbstring","xml","pdo","mysqlnd","gd","bcmath","intl","opcache","sodium","process","pecl-redis6","pecl-apcu","pgsql"];function Tp(e){let n=`php${e.replace(".","")}`;return Cp.map((r)=>`${n}-php-${r}`)}function Za(e,n){let r=`php${e.replace(".","")}`,i=Tp(e).join(" \\\n "),s=`/opt/remi/${r}/root`,a=`/etc/opt/remi/${r}`;return`${n?`FROM almalinux:9 AS ${n}`:"FROM almalinux:9"}
|
|
7252
7252
|
|
|
7253
7253
|
# Build PHP on AlmaLinux 9 (where Remi's version-isolated SCL packages install
|
|
7254
7254
|
# cleanly — Remi's release RPM rejects Amazon Linux 2023). AlmaLinux 9 shares
|
|
@@ -7309,7 +7309,7 @@ COPY app/ \${LAMBDA_TASK_ROOT}/
|
|
|
7309
7309
|
|
|
7310
7310
|
# Per-function CMD (e.g. index.http) is supplied via ImageConfig.Command.
|
|
7311
7311
|
CMD [ "index.http" ]
|
|
7312
|
-
`}import{execFileSync as ot}from"node:child_process";import{mkdtempSync as Kn,readFileSync as lt,rmSync as qn}from"node:fs";import{tmpdir as zn}from"node:os";import{dirname as ks,join as pe}from"node:path";import{fileURLToPath as Ms}from"node:url";function Qn(){return ks(Ms(import.meta.url))}function md(){return lt(pe(Qn(),"runtime.mjs"),"utf-8")}function Jn(e){return lt(pe(Qn(),`${e}-bootstrap`),"utf-8")}function uh(e){let n=e.architecture??"x86_64",r=n==="arm64"?"arm64":"x64",i=e.version.replace(/^v/,""),s=e.onStep??(()=>{}),a=Kn(pe(zn(),"tscloud-node-layer-"));try{let c=i.includes(".")?i:Ls(i),u=`node-v${c}-linux-${r}`,d=`https://nodejs.org/dist/v${c}/${u}.tar.xz`;s(`downloading Node ${c} (${n})`);let m=pe(a,"node.tar.xz");Yn(d,m),s("extracting node binary"),ot("tar",["-xf",m,"-C",a,`${u}/bin/node`],{stdio:"inherit"});let p=lt(pe(a,u,"bin","node"));s("packaging layer");let g=[{name:"bootstrap",data:Jn("node"),mode:493},{name:"runtime.mjs",data:md(),mode:420},{name:"bin/node",data:p,mode:493}];return{zip:xt(g),architecture:n,version:c,fileCount:g.length}}finally{qn(a,{recursive:!0,force:!0})}}function ph(e){let n=e.architecture??"x86_64",r=n==="arm64"?"bun-linux-aarch64":"bun-linux-x64",i=e.version==="latest"?"":e.version.replace(/^v/,""),s=e.onStep??(()=>{}),a=Kn(pe(zn(),"tscloud-bun-layer-"));try{let c=i?`https://github.com/oven-sh/bun/releases/download/bun-v${i}/${r}.zip`:`https://github.com/oven-sh/bun/releases/latest/download/${r}.zip`;s(`downloading Bun ${i||"latest"} (${n})`);let u=pe(a,"bun.zip");Yn(c,u),s("extracting bun binary"),ot("unzip",["-o","-q",u,"-d",a],{stdio:"inherit"});let d=lt(pe(a,r,"bun"));s("packaging layer");let m=[{name:"bootstrap",data:Jn("bun"),mode:493},{name:"runtime.mjs",data:md(),mode:420},{name:"bin/bun",data:d,mode:493}];return{zip:xt(m),architecture:n,version:i||"latest",fileCount:m.length}}finally{qn(a,{recursive:!0,force:!0})}}function Yn(e,n){ot("curl",["-fsSL","-o",n,e],{stdio:["ignore","ignore","inherit"]})}function Ls(e){let n=ot("curl",["-fsSL","https://nodejs.org/dist/index.json"],{encoding:"utf-8"}),i=JSON.parse(n).find((s)=>s.version.startsWith(`v${e}.`));if(!i)throw Error(`No Node release found for major version ${e}`);return i.version.replace(/^v/,"")}import{AsyncLocalStorage as $s}from"node:async_hooks";import{createHash as Os}from"node:crypto";var tc="x-ts-cloud-invoke-depth",rc="x-ts-cloud-invoke-chain",nc="x-ts-cloud-trace-id";function gd(e){return Os("sha256").update(e).digest("hex").slice(0,8)}var Ji={maxDepth:10,maxRepeats:3,maxInvocationsPerTrace:100,traceWindowMs:60000,breakerThreshold:5,breakerCooldownMs:60000};function qt(e,n){if(typeof e.get==="function")return e.get(n)??void 0;let r=e;return r[n]??r[n.toLowerCase()]??r[n.toUpperCase()]}function fd(e,n=64){if(!e)return[];return e.split(".").map((r)=>r.trim()).filter((r)=>/^[0-9a-f]{8}$/.test(r)).slice(-n)}function hd(e,n=Ji){let r=gd(e.functionId),i=fd(qt(e.headers,rc)),s=e.traceId??qt(e.headers,nc)??crypto.randomUUID(),a=[...i,r],c=i.filter((g)=>g===r).length,u=i[i.length-1]===r,d=Number.parseInt(qt(e.headers,tc)??"",10),m=Math.max(a.length,Number.isFinite(d)?d+1:0),p="ok";if(m>n.maxDepth)p="depth_exceeded";else if(c>=n.maxRepeats)p="cycle_detected";else if(u&&n.maxRepeats<=1)p="self_invocation";return{reason:p,depth:m,chain:a,traceId:s,selfInvocation:u,repeats:c,propagate:{[tc]:String(m),[rc]:a.join("."),[nc]:s}}}var Zn={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 os{limits;clock;traces=new Map;breakers=new Map;constructor(e=Ji,n=()=>Date.now()){this.limits=e;this.clock=n}check(e){let n=this.clock();this.expireTraces(n);let r=hd(e,this.limits),i=this.breakers.get(e.functionId);if(i?.openUntil!=null&&i.openUntil>n)return this.deny(e.functionId,r,"breaker_open",n,!1);if(r.reason!=="ok")return this.deny(e.functionId,r,r.reason,n,!0);let s=this.traces.get(r.traceId)??{count:0,firstAt:n};if(s.count>=this.limits.maxInvocationsPerTrace)return this.traces.set(r.traceId,s),this.deny(e.functionId,r,"trace_budget_exceeded",n,!0);if(this.traces.set(r.traceId,{count:s.count+1,firstAt:s.firstAt}),i)this.breakers.set(e.functionId,{consecutiveBlocks:0});return{...r,allowed:!0,reason:"ok",propagate:r.propagate}}deny(e,n,r,i,s){if(s){let a=this.breakers.get(e)??{consecutiveBlocks:0},c=a.consecutiveBlocks+1;this.breakers.set(e,{consecutiveBlocks:c,openUntil:c>=this.limits.breakerThreshold?i+this.limits.breakerCooldownMs:a.openUntil})}return{...n,allowed:!1,reason:r,message:Zn[r]}}breakerOpen(e){let n=this.breakers.get(e);return n?.openUntil!=null&&n.openUntil>this.clock()}reset(e){if(e){this.breakers.delete(e);return}this.breakers.clear(),this.traces.clear()}expireTraces(e){if(this.traces.size===0)return;for(let[n,r]of this.traces)if(e-r.firstAt>this.limits.traceWindowMs)this.traces.delete(n)}get trackedTraces(){return this.traces.size}}function ic(e){return{...e.propagate}}function oc(e){return{status:508,headers:{"content-type":"application/json","x-ts-cloud-recursion-blocked":e.reason},body:{error:"recursion_blocked",reason:e.reason,message:e.message??Zn[e.reason],depth:e.depth,traceId:e.traceId}}}var yd=new $s;function Xn(e){let n=globalThis.process?.env?.[e];if(n==null||n==="")return;return n!=="0"&&n.toLowerCase()!=="false"}function Bs(){let e=globalThis.process?.env??{};return e.TS_CLOUD_FUNCTION_ID||e.AWS_LAMBDA_FUNCTION_NAME||e.FUNCTION_NAME||"function"}function Ep(e){let n=e===!1?{enabled:!1}:e??{},r=Xn("TS_CLOUD_RECURSION_PROTECTION"),i=Xn("TS_CLOUD_RECURSION_DETECTION_ONLY");return{enabled:r??n.enabled??!0,detectionOnly:i??n.detectionOnly??!1,limits:{...Ji,...n.limits},functionId:n.functionId??Bs()}}var ve,oe;function wp(){let e=globalThis.fetch;if(!e||ve===e)return()=>{};oe=e;let n=async(r,i)=>{let s=yd.getStore();if(!s)return oe(r,i);let a=new Headers(i?.headers??(r instanceof Request?r.headers:void 0));for(let[c,u]of Object.entries(ic(s)))a.set(c,u);if(r instanceof Request)return oe(new Request(r,{headers:a}),i);return oe(r,{...i,headers:a})};return Object.assign(n,e),globalThis.fetch=n,ve=n,()=>{if(globalThis.fetch===ve&&oe)globalThis.fetch=oe;ve=void 0}}var ut,zt;function Ap(e){if(!ut||JSON.stringify(zt)!==JSON.stringify(e))ut=new os(e),zt=e;return ut}function mh(){if(ut=void 0,zt=void 0,ve&&oe&&globalThis.fetch===ve)globalThis.fetch=oe;ve=void 0,oe=void 0}function bd(e,n){let r=Ep(n);if(!r.enabled)return;let i=Ap(r.limits),s={functionId:r.functionId,headers:e},a=i.check(s);return{verdict:a,blocked:!a.allowed&&!r.detectionOnly,observed:!a.allowed&&r.detectionOnly}}function Sd(e,n){return wp(),yd.run(e,n)}function gh(e){let n=e,r=n?.default??n;if(typeof r==="function")return{fetch:r};return{fetch:r?.fetch??n?.fetch,queue:r?.queue??n?.queue,cli:r?.cli??n?.cli}}var Fs=/^(?:text\/|application\/(?:json|xml|javascript|graphql|x-www-form-urlencoded|.*\+json|.*\+xml)|image\/svg)/i;function Gs(e){if(!e)return!0;return Fs.test(e)}function _s(e){if(e?.maintenance)return e.maintenance;let n=globalThis.process?.env??{};return{enabled:n.MAINTENANCE_MODE==="1"||n.MAINTENANCE_MODE==="true",bypassSecret:n.MAINTENANCE_BYPASS_SECRET}}function Rp(e){let n=e.requestContext?.domainName??"localhost",r=e.rawQueryString?`?${e.rawQueryString}`:"",i=`https://${n}${e.rawPath||"/"}${r}`,s=new Headers;for(let[u,d]of Object.entries(e.headers??{}))if(d!==void 0)s.set(u,d);if(e.cookies?.length)s.set("cookie",e.cookies.join("; "));let a=e.requestContext.http.method,c;if(e.body!==void 0&&a!=="GET"&&a!=="HEAD")c=e.isBase64Encoded?new Uint8Array(Buffer.from(e.body,"base64")):new TextEncoder().encode(e.body);return new Request(i,{method:a,headers:s,body:c})}async function vd(e){let n={},r=[],i=typeof e.headers.getSetCookie==="function"?e.headers.getSetCookie():[];for(let c of i)r.push(c);e.headers.forEach((c,u)=>{if(u.toLowerCase()==="set-cookie")return;n[u]=c});let s=Buffer.from(await e.arrayBuffer()),a=Gs(e.headers.get("content-type"));return{statusCode:e.status,headers:n,...r.length?{cookies:r}:{},body:a?s.toString("utf-8"):s.toString("base64"),isBase64Encoded:!a}}function Ip(e,n){return async(r)=>{if(r.warmer)return{statusCode:200,headers:{"content-type":"text/plain"},body:"warm",isBase64Encoded:!1};if(!e)return{statusCode:501,headers:{"content-type":"text/plain"},body:"No HTTP handler configured",isBase64Encoded:!1};let i=_s(n);if(i.enabled){let c=r.headers?.["x-maintenance-bypass"]??r.cookies?.find((u)=>u.startsWith("tscloud_bypass="))?.split("=")[1];if(!i.bypassSecret||c!==i.bypassSecret)return{statusCode:503,headers:{"content-type":"text/plain","retry-after":"120"},body:"Service temporarily unavailable (maintenance mode)",isBase64Encoded:!1}}let s=bd(r.headers??{},n?.recursionProtection);if(s?.blocked){let c=oc(s.verdict);return{statusCode:c.status,headers:{...c.headers,"retry-after":"60"},body:JSON.stringify(c.body),isBase64Encoded:!1}}let a=Rp(r);if(!s){let c=await e(a);return vd(c)}if(s.observed)console.warn(`[ts-cloud] recursion detected (${s.verdict.reason}) at depth ${s.verdict.depth}; detection-only mode let it run`);return Sd(s.verdict,async()=>vd(await e(a)))}}function Ws(e){try{return JSON.parse(e)}catch{return e}}function Pp(e){return async(n)=>{let r=[];if(n.warmer)return{batchItemFailures:r};if(!e)return{batchItemFailures:r};for(let i of n.Records??[])try{await e(Ws(i.body),i)}catch{r.push({itemIdentifier:i.messageId})}return{batchItemFailures:r}}}function Dp(e){return async(n)=>{if(n.warmer)return{statusCode:0,output:"warm"};if(!e)return{statusCode:501,output:"No CLI handler configured"};return e(n)}}function fh(e,n){return{http:Ip(e.fetch,n),queue:Pp(e.queue),cli:Dp(e.cli)}}function Cd(e={}){let n=e.socketPath??"/tmp/.tscloud-fpm.sock",r=e.maxChildren??1;return`; ts-cloud php-fpm configuration (generated) — AWS Lambda custom runtime.
|
|
7312
|
+
`}import{execFileSync as ot}from"node:child_process";import{mkdtempSync as jn,readFileSync as lt,rmSync as Kn}from"node:fs";import{tmpdir as qn}from"node:os";import{dirname as ks,join as pe}from"node:path";import{fileURLToPath as Ms}from"node:url";function zn(){return ks(Ms(import.meta.url))}function md(){return lt(pe(zn(),"runtime.mjs"),"utf-8")}function Qn(e){return lt(pe(zn(),`${e}-bootstrap`),"utf-8")}function uh(e){let n=e.architecture??"x86_64",r=n==="arm64"?"arm64":"x64",i=e.version.replace(/^v/,""),s=e.onStep??(()=>{}),a=jn(pe(qn(),"tscloud-node-layer-"));try{let c=i.includes(".")?i:Ls(i),u=`node-v${c}-linux-${r}`,d=`https://nodejs.org/dist/v${c}/${u}.tar.xz`;s(`downloading Node ${c} (${n})`);let m=pe(a,"node.tar.xz");Jn(d,m),s("extracting node binary"),ot("tar",["-xf",m,"-C",a,`${u}/bin/node`],{stdio:"inherit"});let p=lt(pe(a,u,"bin","node"));s("packaging layer");let g=[{name:"bootstrap",data:Qn("node"),mode:493},{name:"runtime.mjs",data:md(),mode:420},{name:"bin/node",data:p,mode:493}];return{zip:_t(g),architecture:n,version:c,fileCount:g.length}}finally{Kn(a,{recursive:!0,force:!0})}}function ph(e){let n=e.architecture??"x86_64",r=n==="arm64"?"bun-linux-aarch64":"bun-linux-x64",i=e.version==="latest"?"":e.version.replace(/^v/,""),s=e.onStep??(()=>{}),a=jn(pe(qn(),"tscloud-bun-layer-"));try{let c=i?`https://github.com/oven-sh/bun/releases/download/bun-v${i}/${r}.zip`:`https://github.com/oven-sh/bun/releases/latest/download/${r}.zip`;s(`downloading Bun ${i||"latest"} (${n})`);let u=pe(a,"bun.zip");Jn(c,u),s("extracting bun binary"),ot("unzip",["-o","-q",u,"-d",a],{stdio:"inherit"});let d=lt(pe(a,r,"bun"));s("packaging layer");let m=[{name:"bootstrap",data:Qn("bun"),mode:493},{name:"runtime.mjs",data:md(),mode:420},{name:"bin/bun",data:d,mode:493}];return{zip:_t(m),architecture:n,version:i||"latest",fileCount:m.length}}finally{Kn(a,{recursive:!0,force:!0})}}function Jn(e,n){ot("curl",["-fsSL","-o",n,e],{stdio:["ignore","ignore","inherit"]})}function Ls(e){let n=ot("curl",["-fsSL","https://nodejs.org/dist/index.json"],{encoding:"utf-8"}),i=JSON.parse(n).find((s)=>s.version.startsWith(`v${e}.`));if(!i)throw Error(`No Node release found for major version ${e}`);return i.version.replace(/^v/,"")}import{AsyncLocalStorage as $s}from"node:async_hooks";import{createHash as Os}from"node:crypto";var tc="x-ts-cloud-invoke-depth",rc="x-ts-cloud-invoke-chain",nc="x-ts-cloud-trace-id";function gd(e){return Os("sha256").update(e).digest("hex").slice(0,8)}var Ji={maxDepth:10,maxRepeats:3,maxInvocationsPerTrace:100,traceWindowMs:60000,breakerThreshold:5,breakerCooldownMs:60000};function qt(e,n){if(typeof e.get==="function")return e.get(n)??void 0;let r=e;return r[n]??r[n.toLowerCase()]??r[n.toUpperCase()]}function fd(e,n=64){if(!e)return[];return e.split(".").map((r)=>r.trim()).filter((r)=>/^[0-9a-f]{8}$/.test(r)).slice(-n)}function hd(e,n=Ji){let r=gd(e.functionId),i=fd(qt(e.headers,rc)),s=e.traceId??qt(e.headers,nc)??crypto.randomUUID(),a=[...i,r],c=i.filter((g)=>g===r).length,u=i[i.length-1]===r,d=Number.parseInt(qt(e.headers,tc)??"",10),m=Math.max(a.length,Number.isFinite(d)?d+1:0),p="ok";if(m>n.maxDepth)p="depth_exceeded";else if(c>=n.maxRepeats)p="cycle_detected";else if(u&&n.maxRepeats<=1)p="self_invocation";return{reason:p,depth:m,chain:a,traceId:s,selfInvocation:u,repeats:c,propagate:{[tc]:String(m),[rc]:a.join("."),[nc]:s}}}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 os{limits;clock;traces=new Map;breakers=new Map;constructor(e=Ji,n=()=>Date.now()){this.limits=e;this.clock=n}check(e){let n=this.clock();this.expireTraces(n);let r=hd(e,this.limits),i=this.breakers.get(e.functionId);if(i?.openUntil!=null&&i.openUntil>n)return this.deny(e.functionId,r,"breaker_open",n,!1);if(r.reason!=="ok")return this.deny(e.functionId,r,r.reason,n,!0);let s=this.traces.get(r.traceId)??{count:0,firstAt:n};if(s.count>=this.limits.maxInvocationsPerTrace)return this.traces.set(r.traceId,s),this.deny(e.functionId,r,"trace_budget_exceeded",n,!0);if(this.traces.set(r.traceId,{count:s.count+1,firstAt:s.firstAt}),i)this.breakers.set(e.functionId,{consecutiveBlocks:0});return{...r,allowed:!0,reason:"ok",propagate:r.propagate}}deny(e,n,r,i,s){if(s){let a=this.breakers.get(e)??{consecutiveBlocks:0},c=a.consecutiveBlocks+1;this.breakers.set(e,{consecutiveBlocks:c,openUntil:c>=this.limits.breakerThreshold?i+this.limits.breakerCooldownMs:a.openUntil})}return{...n,allowed:!1,reason:r,message:Yn[r]}}breakerOpen(e){let n=this.breakers.get(e);return n?.openUntil!=null&&n.openUntil>this.clock()}reset(e){if(e){this.breakers.delete(e);return}this.breakers.clear(),this.traces.clear()}expireTraces(e){if(this.traces.size===0)return;for(let[n,r]of this.traces)if(e-r.firstAt>this.limits.traceWindowMs)this.traces.delete(n)}get trackedTraces(){return this.traces.size}}function ic(e){return{...e.propagate}}function oc(e){return{status:508,headers:{"content-type":"application/json","x-ts-cloud-recursion-blocked":e.reason},body:{error:"recursion_blocked",reason:e.reason,message:e.message??Yn[e.reason],depth:e.depth,traceId:e.traceId}}}var yd=new $s;function Zn(e){let n=globalThis.process?.env?.[e];if(n==null||n==="")return;return n!=="0"&&n.toLowerCase()!=="false"}function Bs(){let e=globalThis.process?.env??{};return e.TS_CLOUD_FUNCTION_ID||e.AWS_LAMBDA_FUNCTION_NAME||e.FUNCTION_NAME||"function"}function Ep(e){let n=e===!1?{enabled:!1}:e??{},r=Zn("TS_CLOUD_RECURSION_PROTECTION"),i=Zn("TS_CLOUD_RECURSION_DETECTION_ONLY");return{enabled:r??n.enabled??!0,detectionOnly:i??n.detectionOnly??!1,limits:{...Ji,...n.limits},functionId:n.functionId??Bs()}}var ve,oe;function wp(){let e=globalThis.fetch;if(!e||ve===e)return()=>{};oe=e;let n=async(r,i)=>{let s=yd.getStore();if(!s)return oe(r,i);let a=new Headers(i?.headers??(r instanceof Request?r.headers:void 0));for(let[c,u]of Object.entries(ic(s)))a.set(c,u);if(r instanceof Request)return oe(new Request(r,{headers:a}),i);return oe(r,{...i,headers:a})};return Object.assign(n,e),globalThis.fetch=n,ve=n,()=>{if(globalThis.fetch===ve&&oe)globalThis.fetch=oe;ve=void 0}}var ut,zt;function Ap(e){if(!ut||JSON.stringify(zt)!==JSON.stringify(e))ut=new os(e),zt=e;return ut}function mh(){if(ut=void 0,zt=void 0,ve&&oe&&globalThis.fetch===ve)globalThis.fetch=oe;ve=void 0,oe=void 0}function bd(e,n){let r=Ep(n);if(!r.enabled)return;let i=Ap(r.limits),s={functionId:r.functionId,headers:e},a=i.check(s);return{verdict:a,blocked:!a.allowed&&!r.detectionOnly,observed:!a.allowed&&r.detectionOnly}}function Sd(e,n){return wp(),yd.run(e,n)}function gh(e){let n=e,r=n?.default??n;if(typeof r==="function")return{fetch:r};return{fetch:r?.fetch??n?.fetch,queue:r?.queue??n?.queue,cli:r?.cli??n?.cli}}var Fs=/^(?:text\/|application\/(?:json|xml|javascript|graphql|x-www-form-urlencoded|.*\+json|.*\+xml)|image\/svg)/i;function Gs(e){if(!e)return!0;return Fs.test(e)}function _s(e){if(e?.maintenance)return e.maintenance;let n=globalThis.process?.env??{};return{enabled:n.MAINTENANCE_MODE==="1"||n.MAINTENANCE_MODE==="true",bypassSecret:n.MAINTENANCE_BYPASS_SECRET}}function Rp(e){let n=e.requestContext?.domainName??"localhost",r=e.rawQueryString?`?${e.rawQueryString}`:"",i=`https://${n}${e.rawPath||"/"}${r}`,s=new Headers;for(let[u,d]of Object.entries(e.headers??{}))if(d!==void 0)s.set(u,d);if(e.cookies?.length)s.set("cookie",e.cookies.join("; "));let a=e.requestContext.http.method,c;if(e.body!==void 0&&a!=="GET"&&a!=="HEAD")c=e.isBase64Encoded?new Uint8Array(Buffer.from(e.body,"base64")):new TextEncoder().encode(e.body);return new Request(i,{method:a,headers:s,body:c})}async function vd(e){let n={},r=[],i=typeof e.headers.getSetCookie==="function"?e.headers.getSetCookie():[];for(let c of i)r.push(c);e.headers.forEach((c,u)=>{if(u.toLowerCase()==="set-cookie")return;n[u]=c});let s=Buffer.from(await e.arrayBuffer()),a=Gs(e.headers.get("content-type"));return{statusCode:e.status,headers:n,...r.length?{cookies:r}:{},body:a?s.toString("utf-8"):s.toString("base64"),isBase64Encoded:!a}}function Ip(e,n){return async(r)=>{if(r.warmer)return{statusCode:200,headers:{"content-type":"text/plain"},body:"warm",isBase64Encoded:!1};if(!e)return{statusCode:501,headers:{"content-type":"text/plain"},body:"No HTTP handler configured",isBase64Encoded:!1};let i=_s(n);if(i.enabled){let c=r.headers?.["x-maintenance-bypass"]??r.cookies?.find((u)=>u.startsWith("tscloud_bypass="))?.split("=")[1];if(!i.bypassSecret||c!==i.bypassSecret)return{statusCode:503,headers:{"content-type":"text/plain","retry-after":"120"},body:"Service temporarily unavailable (maintenance mode)",isBase64Encoded:!1}}let s=bd(r.headers??{},n?.recursionProtection);if(s?.blocked){let c=oc(s.verdict);return{statusCode:c.status,headers:{...c.headers,"retry-after":"60"},body:JSON.stringify(c.body),isBase64Encoded:!1}}let a=Rp(r);if(!s){let c=await e(a);return vd(c)}if(s.observed)console.warn(`[ts-cloud] recursion detected (${s.verdict.reason}) at depth ${s.verdict.depth}; detection-only mode let it run`);return Sd(s.verdict,async()=>vd(await e(a)))}}function Ws(e){try{return JSON.parse(e)}catch{return e}}function Pp(e){return async(n)=>{let r=[];if(n.warmer)return{batchItemFailures:r};if(!e)return{batchItemFailures:r};for(let i of n.Records??[])try{await e(Ws(i.body),i)}catch{r.push({itemIdentifier:i.messageId})}return{batchItemFailures:r}}}function Dp(e){return async(n)=>{if(n.warmer)return{statusCode:0,output:"warm"};if(!e)return{statusCode:501,output:"No CLI handler configured"};return e(n)}}function fh(e,n){return{http:Ip(e.fetch,n),queue:Pp(e.queue),cli:Dp(e.cli)}}function Cd(e={}){let n=e.socketPath??"/tmp/.tscloud-fpm.sock",r=e.maxChildren??1;return`; ts-cloud php-fpm configuration (generated) — AWS Lambda custom runtime.
|
|
7313
7313
|
[global]
|
|
7314
7314
|
daemonize = no
|
|
7315
7315
|
error_log = ${e.errorLog??"/tmp/storage/logs/php-fpm.log"}
|
|
@@ -7326,4 +7326,4 @@ decorate_workers_output = no
|
|
|
7326
7326
|
php_admin_value[error_log] = /dev/stderr
|
|
7327
7327
|
php_admin_flag[log_errors] = on
|
|
7328
7328
|
clear_env = no
|
|
7329
|
-
`}import{readFileSync as Vs}from"node:fs";import{dirname as Us,join as nr}from"node:path";import{fileURLToPath as Hs}from"node:url";function js(){return nr(Us(Hs(import.meta.url)),"runtime-assets")}function kn(){let e=js(),n=(r)=>Vs(nr(e,r),"utf-8");return[{path:"bootstrap",contents:n("bootstrap"),mode:493},{path:"tscloud/runtime.php",contents:n("runtime.php"),mode:420},{path:"tscloud/octane-runtime.php",contents:n("octane-runtime.php"),mode:420},{path:"tscloud/cli-runtime.php",contents:n("cli-runtime.php"),mode:420},{path:"tscloud/fastcgi-client.php",contents:n("fastcgi-client.php"),mode:420},{path:"tscloud/php-fpm.conf",contents:Cd(),mode:420}]}function sc(e={}){let n=e.cacheDriver??"dynamodb";return{APP_ENV:"production",LOG_CHANNEL:"stderr",CACHE_STORE:n,CACHE_DRIVER:n,SESSION_DRIVER:n,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 Td=["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 dt}from"node:child_process";import{existsSync as Ks,mkdirSync as qs,mkdtempSync as zs,readdirSync as Qs,readFileSync as Js,rmSync as Ys,statSync as ir,writeFileSync as Zs}from"node:fs";import{tmpdir as Xs}from"node:os";import{join as Me,relative as ea}from"node:path";function*sr(e){for(let n of Qs(e)){let r=Me(e,n);if(ir(r).isDirectory())yield*sr(r);else yield r}}function hh(e={}){let n=e.architecture??"x86_64",r=e.platform??(n==="arm64"?"linux/arm64":"linux/amd64"),i=e.onStep??(()=>{}),s=zs(Me(Xs(),"tscloud-php-layer-")),a="tscloud-php-layer:build";try{Zs(Me(s,"Dockerfile"),pd(e)),i("Building PHP runtime image (docker)"),dt("docker",["build","--platform",r,"-t","tscloud-php-layer:build",s],{stdio:"inherit"}),i("Extracting /opt/php from image");let c=dt("docker",["create","--platform",r,"tscloud-php-layer:build"],{encoding:"utf-8"}).trim(),u=Me(s,"opt");qs(u,{recursive:!0});try{dt("docker",["cp",`${c}:/opt/php`,Me(u,"php")],{stdio:"inherit"})}finally{dt("docker",["rm",c],{stdio:"ignore"})}if(!Ks(Me(u,"php","bin","php")))throw Error("layer build produced no /opt/php/bin/php");let d=[];for(let y of sr(u)){let f=ea(u,y).replace(/\\/g,"/"),h=ir(y).mode&73?493:420;d.push({name:f,data:Js(y),mode:h})}i("Injecting runtime assets");let m=new Set(kn().map((y)=>y.path)),p=d.filter((y)=>!m.has(y.name));for(let y of kn())p.push({name:y.path,data:y.contents,mode:y.mode});return i("Packaging layer ZIP"),{zip:xt(p),architecture:n,fileCount:p.length}}finally{Ys(s,{recursive:!0,force:!0})}}import{execSync as ta}from"node:child_process";import{createHash as na}from"node:crypto";import{readdirSync as ra,readFileSync as ia,statSync as ar}from"node:fs";import{join as sa,relative as or,resolve as Jt}from"node:path";var kp=[".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 aa(e,n){return n.some((r)=>e===r||e.startsWith(`${r}/`))}function*cr(e,n,r){for(let i of ra(e)){let s=sa(e,i),a=or(n,s).replace(/\\/g,"/");if(aa(a,r))continue;if(ar(s).isDirectory())yield*cr(s,n,r);else yield s}}function ss(e){if(e.skipBuild)return;let n=Jt(e.projectRoot??process.cwd()),r=e.app.build??Td;for(let i of r)e.onStep?.(`build: ${i}`),ta(i,{stdio:"inherit",cwd:n})}function as(e,n=[]){let r=Jt(e),i=[...kp,En(),...n],s=[];for(let a of cr(r,r,i)){let c=or(r,a).replace(/\\/g,"/"),u=(ar(a).mode&73)!==0;s.push({name:c,data:ia(a),mode:u?493:420})}return s}function ac(e){let n=Jt(e.projectRoot??process.cwd());ss(e),e.onStep?.("packaging application tree");let r=as(n,e.exclude);if(!r.length)throw Error(`No files to package under ${n}`);let i=xt(r),s=e.app.handlers?.http??"public/index.php";return{zip:i,sha256:na("sha256").update(i).digest("hex"),handlers:{http:s,queue:e.app.handlers?.queue??s,cli:e.app.handlers?.cli??s},fileCount:r.length}}class Ed{optimizations=new Map;imageConfigs=new Map;ssgConfigs=new Map;prerenderConfigs=new Map;counter=0;createAssetOptimization(e){let n=`asset-opt-${Date.now()}-${this.counter++}`,r={id:n,...e};return this.optimizations.set(n,r),r}createImageOptimization(e){let n=`image-opt-${Date.now()}-${this.counter++}`,r={id:n,...e};return this.imageConfigs.set(n,r),r}createSSGConfig(e){let n=`ssg-${Date.now()}-${this.counter++}`,r={id:n,...e};return this.ssgConfigs.set(n,r),r}createPrerenderConfig(e){let n=`prerender-${Date.now()}-${this.counter++}`,r={id:n,...e};return this.prerenderConfigs.set(n,r),r}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 yh=new Ed;class cc{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(e,n){let r=`lifecycle-${Date.now()}-${this.counter++}`,i={id:r,transitions:e,expiration:n};return this.policies.set(r,i),i}enableVersioning(e=!1){let n=`versioning-${Date.now()}-${this.counter++}`,r={id:n,enabled:!0,mfaDelete:e};return this.versioningConfigs.set(n,r),r}createReplicationRule(e,n,r){let i=`replication-${Date.now()}-${this.counter++}`,s={id:i,sourceRegion:e,destRegion:n,destBucket:r};return this.replicationRules.set(i,s),s}createIntelligentTiering(e,n){let r=`tiering-${Date.now()}-${this.counter++}`,i={id:r,archiveDays:e,deepArchiveDays:n};return this.tieringConfigs.set(r,i),i}enableObjectLock(e){let n=`object-lock-${Date.now()}-${this.counter++}`,r={id:n,bucketName:e.bucketName,mode:e.mode||"COMPLIANCE",retentionDays:e.retentionDays,retentionYears:e.retentionYears,legalHoldEnabled:e.legalHoldEnabled||!1};return this.objectLocks.set(n,r),r}enableTransferAcceleration(e){let n=`transfer-accel-${Date.now()}-${this.counter++}`,r={id:n,bucketName:e,enabled:!0,endpoint:`${e}.s3-accelerate.amazonaws.com`};return this.transferAcceleration.set(n,r),r}createAccessPoint(e){let n=`access-point-${Date.now()}-${this.counter++}`,r={id:n,name:e.name,bucketName:e.bucketName,vpcId:e.vpcId,publicAccessBlock:e.publicAccessBlock!==!1,policy:e.policy};return this.accessPoints.set(n,r),r}createGlacierArchive(e){let n=`glacier-${Date.now()}-${this.counter++}`,r={id:n,bucketName:e.bucketName,archiveType:e.archiveType,transitionDays:e.transitionDays,restoreConfig:e.restoreTier?{tier:e.restoreTier,days:e.restoreDays||7}:void 0};return this.glacierConfigs.set(n,r),r}createInventory(e){let n=`inventory-${Date.now()}-${this.counter++}`,r={id:n,sourceBucket:e.sourceBucket,destinationBucket:e.destinationBucket,schedule:e.schedule||"Daily",format:e.format||"CSV",includedFields:e.includedFields||["Size","LastModifiedDate","StorageClass","ETag"],prefix:e.prefix};return this.inventories.set(n,r),r}createBatchOperation(e){let n=`batch-op-${Date.now()}-${this.counter++}`,r={id:n,operation:e.operation,manifestBucket:e.manifestBucket,manifestKey:e.manifestKey,priority:e.priority||10,status:"pending"};return this.batchOps.set(n,r),r}executeBatchOperation(e){let n=this.batchOps.get(e);if(!n)throw Error(`Batch operation not found: ${e}`);return n.status="in_progress",n.totalObjects=1000,n.processedObjects=0,n}getBatchOperationStatus(e){return this.batchOps.get(e)}createLambdaNotification(e){let n=`event-${Date.now()}-${this.counter++}`,r={id:n,bucketName:e.bucketName,events:e.events,destination:{type:"Lambda",arn:e.lambdaArn},filter:e.prefix||e.suffix?{prefix:e.prefix,suffix:e.suffix}:void 0};return this.eventNotifications.set(n,r),r}createSQSNotification(e){let n=`event-${Date.now()}-${this.counter++}`,r={id:n,bucketName:e.bucketName,events:e.events,destination:{type:"SQS",arn:e.queueArn},filter:e.prefix||e.suffix?{prefix:e.prefix,suffix:e.suffix}:void 0};return this.eventNotifications.set(n,r),r}createSNSNotification(e){let n=`event-${Date.now()}-${this.counter++}`,r={id:n,bucketName:e.bucketName,events:e.events,destination:{type:"SNS",arn:e.topicArn},filter:e.prefix||e.suffix?{prefix:e.prefix,suffix:e.suffix}:void 0};return this.eventNotifications.set(n,r),r}generateObjectLockCF(e){let n={ObjectLockEnabled:"Enabled",ObjectLockConfiguration:{ObjectLockEnabled:"Enabled",Rule:{DefaultRetention:{Mode:e.mode}}}};if(e.retentionDays)n.ObjectLockConfiguration.Rule.DefaultRetention.Days=e.retentionDays;if(e.retentionYears)n.ObjectLockConfiguration.Rule.DefaultRetention.Years=e.retentionYears;return n}generateTransferAccelerationCF(e){return{AccelerateConfiguration:{AccelerationStatus:e.enabled?"Enabled":"Suspended"}}}generateAccessPointCF(e){return{Type:"AWS::S3::AccessPoint",Properties:{Name:e.name,Bucket:e.bucketName,...e.vpcId&&{VpcConfiguration:{VpcId:e.vpcId}},PublicAccessBlockConfiguration:e.publicAccessBlock?{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0}:void 0,...e.policy&&{Policy:e.policy}}}}generateInventoryCF(e){return{Type:"AWS::S3::Bucket",Properties:{InventoryConfigurations:[{Id:e.id,Destination:{BucketArn:`arn:aws:s3:::${e.destinationBucket}`,Format:e.format},Enabled:!0,IncludedObjectVersions:"Current",OptionalFields:e.includedFields,ScheduleFrequency:e.schedule,...e.prefix&&{Prefix:e.prefix}}]}}}generateEventNotificationCF(e){let n=e.destination.type==="Lambda"?"LambdaConfigurations":e.destination.type==="SQS"?"QueueConfigurations":"TopicConfigurations",r=e.destination.type==="Lambda"?"Function":e.destination.type==="SQS"?"Queue":"Topic",i={Event:e.events[0],[r]:e.destination.arn};if(e.filter)i.Filter={S3Key:{Rules:[...e.filter.prefix?[{Name:"prefix",Value:e.filter.prefix}]:[],...e.filter.suffix?[{Name:"suffix",Value:e.filter.suffix}]:[]]}};return{NotificationConfiguration:{[n]:[i]}}}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 Np=new cc;class wd{checks=new Map;synthetics=new Map;uptimeTrackers=new Map;counter=0;createHealthCheck(e,n=30,r=10){let i=`health-${Date.now()}-${this.counter++}`,s={id:i,url:e,interval:n,timeout:r,status:"healthy"};return this.checks.set(i,s),s}createSyntheticMonitor(e,n,r,i){let s=`synthetic-${Date.now()}-${this.counter++}`,a={id:s,name:e,script:n,frequency:r,locations:i};return this.synthetics.set(s,a),a}trackUptime(e,n,r){let i=`uptime-${Date.now()}-${this.counter++}`,s=n/(n+r)*100,a={id:i,resource:e,uptime:n,downtime:r,availability:s};return this.uptimeTrackers.set(i,a),a}clear(){this.checks.clear(),this.synthetics.clear(),this.uptimeTrackers.clear()}}var bh=new wd;class Ad{wafRules=new Map;shieldProtections=new Map;securityGroups=new Map;nacls=new Map;counter=0;createWAFRule(e,n,r,i){let s=`waf-${Date.now()}-${this.counter++}`,a={id:s,name:e,priority:n,action:r,conditions:i};return this.wafRules.set(s,a),a}enableShield(e,n="standard"){let r=`shield-${Date.now()}-${this.counter++}`,i={id:r,resourceArn:e,protectionType:n};return this.shieldProtections.set(r,i),i}createSecurityGroup(e,n,r){let i=`sg-${Date.now()}-${this.counter++}`,s={id:i,name:e,vpcId:n,rules:r};return this.securityGroups.set(i,s),s}createNACL(e,n){let r=`nacl-${Date.now()}-${this.counter++}`,i={id:r,vpcId:e,rules:n};return this.nacls.set(r,i),i}clear(){this.wafRules.clear(),this.shieldProtections.clear(),this.securityGroups.clear(),this.nacls.clear()}}var Sh=new Ad;class Rd{strategies=new Map;allocations=new Map;groups=new Map;counter=0;createTaggingStrategy(e,n){let r=`tagging-${Date.now()}-${this.counter++}`,i={id:r,tags:e,resources:n};return this.strategies.set(r,i),i}createCostAllocation(e,n){let r=`cost-${Date.now()}-${this.counter++}`,i={id:r,tagKey:e,allocations:n};return this.allocations.set(r,i),i}createResourceGroup(e,n,r){let i=`group-${Date.now()}-${this.counter++}`,s={id:i,name:e,query:{resourceTypeFilters:n,tagFilters:r}};return this.groups.set(i,s),s}clear(){this.strategies.clear(),this.allocations.clear(),this.groups.clear()}}var vh=new Rd;export{Tm,Em,da,il,ua,pa,En,ze,I,ma,ol,H,Fr,A,ou,ne,jr,ga,Jo,le,U,Xo,su,au,cu,lu,l,o,wm,Am,T,fa,ha,ya,Rm,Im,$e,ba,Bi,du,Pm,Dm,He,Pt,Sa,sl,al,km,cl,ll,dl,Qo,va,st,Yo,wn,Fi,An,Ge,uu,Zo,es,Ca,Ta,Ea,wa,Aa,Ra,Ae,j,pu,mu,ul,b,M,at,N,pl,Dt,ye,Xt,Nm,ml,Re,ts,qe,Qt,ji,Ie,rs,Le,gu,Vi,Pe,De,ie,zi,X,Yt,kt,ke,t,Rn,xm,gl,Ia,_m,Om,$m,Lm,Pa,Mm,Um,Bm,Fm,jm,Vm,zm,Hm,Gm,qm,Wm,Km,fu,hu,yu,bu,Su,vu,Cu,Zt,fl,hl,Vr,Hi,Jm,yl,Xm,Qm,In,Ym,Zm,eg,tg,rg,ng,Tu,Eu,wu,Au,Ru,Gi,ig,Pn,Iu,bl,Pu,Da,be,Du,ku,Nt,ns,er,Nu,Sl,xu,_u,Ou,vl,Se,og,sg,ag,cg,$u,lg,Ne,dg,ug,pg,ka,Na,Lu,Cl,Tl,mg,gg,fg,hg,yg,Mu,xa,bg,Sg,vg,Cg,Tg,Uu,Bu,Eg,wg,Ag,Rg,Ig,Pg,Dg,Fu,kg,El,_a,Ng,xg,_g,Og,wl,Al,Rl,$g,Oa,ju,Vu,zu,Hu,$a,Gu,Lg,Mg,Ug,Bg,Fg,jg,Vg,qu,Wu,Ku,Ju,Il,zg,Hg,Gg,qg,Wg,Kg,Jg,Xg,Qg,Xu,Qu,Yu,Zu,Yg,Zg,Pl,ef,Dl,kl,Nl,xl,tf,rf,nf,of,ct,qi,sf,af,cf,lf,df,uf,pf,mf,ep,gf,ff,_l,Ol,hf,yf,tp,bf,Sf,vf,Cf,Tf,Ef,wf,Af,Rf,If,Pf,Df,kf,Nf,xf,_f,Of,$f,Lf,Mf,Uf,La,rp,Ma,np,Ua,ip,Ba,op,Fa,sp,zr,ap,ja,cp,Wi,lp,Va,dp,za,up,$l,Bf,Ll,Ff,Ha,pp,Hr,mp,Ml,jf,Ga,gp,Ul,Vf,Bl,zf,Fl,Hf,qa,fp,jl,Gf,Vl,qf,zl,Wf,Hl,Kf,Wa,hp,Ka,yp,Gl,Jf,ql,Xf,Wl,Qf,Kl,Yf,Jl,Zf,Xl,eh,Ja,bp,Ql,th,Yl,rh,Zl,nh,ed,ih,td,oh,rd,sh,nd,id,od,sd,ad,ah,cd,ch,ld,lh,dd,dh,xt,ud,Sp,is,Xa,Dn,vp,Ki,tr,Qa,Ya,Cp,Tp,Za,pd,ec,md,uh,ph,tc,rc,nc,gd,Ji,fd,hd,os,ic,oc,yd,Ep,wp,Ap,mh,bd,Sd,gh,Rp,vd,Ip,Pp,Dp,fh,Cd,kn,sc,Td,hh,kp,ss,as,ac,Ed,yh,cc,Np,wd,bh,Ad,Sh,Rd,vh};
|
|
7329
|
+
`}import{readFileSync as Vs}from"node:fs";import{dirname as Us,join as Xn}from"node:path";import{fileURLToPath as Hs}from"node:url";function js(){return Xn(Us(Hs(import.meta.url)),"runtime-assets")}function Nn(){let e=js(),n=(r)=>Vs(Xn(e,r),"utf-8");return[{path:"bootstrap",contents:n("bootstrap"),mode:493},{path:"tscloud/runtime.php",contents:n("runtime.php"),mode:420},{path:"tscloud/octane-runtime.php",contents:n("octane-runtime.php"),mode:420},{path:"tscloud/cli-runtime.php",contents:n("cli-runtime.php"),mode:420},{path:"tscloud/fastcgi-client.php",contents:n("fastcgi-client.php"),mode:420},{path:"tscloud/php-fpm.conf",contents:Cd(),mode:420}]}function sc(e={}){let n=e.cacheDriver??"dynamodb";return{APP_ENV:"production",LOG_CHANNEL:"stderr",CACHE_STORE:n,CACHE_DRIVER:n,SESSION_DRIVER:n,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 Td=["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 dt}from"node:child_process";import{existsSync as Ks,mkdirSync as qs,mkdtempSync as zs,readdirSync as Qs,readFileSync as Js,rmSync as Ys,statSync as ir,writeFileSync as Zs}from"node:fs";import{tmpdir as Xs}from"node:os";import{join as Me,relative as ea}from"node:path";function*sr(e){for(let n of Qs(e)){let r=Me(e,n);if(ir(r).isDirectory())yield*sr(r);else yield r}}function hh(e={}){let n=e.architecture??"x86_64",r=e.platform??(n==="arm64"?"linux/arm64":"linux/amd64"),i=e.onStep??(()=>{}),s=zs(Me(Xs(),"tscloud-php-layer-")),a="tscloud-php-layer:build";try{Zs(Me(s,"Dockerfile"),pd(e)),i("Building PHP runtime image (docker)"),dt("docker",["build","--platform",r,"-t","tscloud-php-layer:build",s],{stdio:"inherit"}),i("Extracting /opt/php from image");let c=dt("docker",["create","--platform",r,"tscloud-php-layer:build"],{encoding:"utf-8"}).trim(),u=Me(s,"opt");qs(u,{recursive:!0});try{dt("docker",["cp",`${c}:/opt/php`,Me(u,"php")],{stdio:"inherit"})}finally{dt("docker",["rm",c],{stdio:"ignore"})}if(!Ks(Me(u,"php","bin","php")))throw Error("layer build produced no /opt/php/bin/php");let d=[];for(let y of sr(u)){let f=ea(u,y).replace(/\\/g,"/"),h=ir(y).mode&73?493:420;d.push({name:f,data:Js(y),mode:h})}i("Injecting runtime assets");let m=new Set(Nn().map((y)=>y.path)),p=d.filter((y)=>!m.has(y.name));for(let y of Nn())p.push({name:y.path,data:y.contents,mode:y.mode});return i("Packaging layer ZIP"),{zip:_t(p),architecture:n,fileCount:p.length}}finally{Ys(s,{recursive:!0,force:!0})}}import{execSync as ta}from"node:child_process";import{createHash as na}from"node:crypto";import{readdirSync as ra,readFileSync as ia,statSync as ar}from"node:fs";import{join as sa,relative as or,resolve as Jt}from"node:path";var kp=[".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 aa(e,n){return n.some((r)=>e===r||e.startsWith(`${r}/`))}function*cr(e,n,r){for(let i of ra(e)){let s=sa(e,i),a=or(n,s).replace(/\\/g,"/");if(aa(a,r))continue;if(ar(s).isDirectory())yield*cr(s,n,r);else yield s}}function ss(e){if(e.skipBuild)return;let n=Jt(e.projectRoot??process.cwd()),r=e.app.build??Td;for(let i of r)e.onStep?.(`build: ${i}`),ta(i,{stdio:"inherit",cwd:n})}function as(e,n=[]){let r=Jt(e),i=[...kp,wn(),...n],s=[];for(let a of cr(r,r,i)){let c=or(r,a).replace(/\\/g,"/"),u=(ar(a).mode&73)!==0;s.push({name:c,data:ia(a),mode:u?493:420})}return s}function ac(e){let n=Jt(e.projectRoot??process.cwd());ss(e),e.onStep?.("packaging application tree");let r=as(n,e.exclude);if(!r.length)throw Error(`No files to package under ${n}`);let i=_t(r),s=e.app.handlers?.http??"public/index.php";return{zip:i,sha256:na("sha256").update(i).digest("hex"),handlers:{http:s,queue:e.app.handlers?.queue??s,cli:e.app.handlers?.cli??s},fileCount:r.length}}class Ed{optimizations=new Map;imageConfigs=new Map;ssgConfigs=new Map;prerenderConfigs=new Map;counter=0;createAssetOptimization(e){let n=`asset-opt-${Date.now()}-${this.counter++}`,r={id:n,...e};return this.optimizations.set(n,r),r}createImageOptimization(e){let n=`image-opt-${Date.now()}-${this.counter++}`,r={id:n,...e};return this.imageConfigs.set(n,r),r}createSSGConfig(e){let n=`ssg-${Date.now()}-${this.counter++}`,r={id:n,...e};return this.ssgConfigs.set(n,r),r}createPrerenderConfig(e){let n=`prerender-${Date.now()}-${this.counter++}`,r={id:n,...e};return this.prerenderConfigs.set(n,r),r}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 yh=new Ed;class cc{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(e,n){let r=`lifecycle-${Date.now()}-${this.counter++}`,i={id:r,transitions:e,expiration:n};return this.policies.set(r,i),i}enableVersioning(e=!1){let n=`versioning-${Date.now()}-${this.counter++}`,r={id:n,enabled:!0,mfaDelete:e};return this.versioningConfigs.set(n,r),r}createReplicationRule(e,n,r){let i=`replication-${Date.now()}-${this.counter++}`,s={id:i,sourceRegion:e,destRegion:n,destBucket:r};return this.replicationRules.set(i,s),s}createIntelligentTiering(e,n){let r=`tiering-${Date.now()}-${this.counter++}`,i={id:r,archiveDays:e,deepArchiveDays:n};return this.tieringConfigs.set(r,i),i}enableObjectLock(e){let n=`object-lock-${Date.now()}-${this.counter++}`,r={id:n,bucketName:e.bucketName,mode:e.mode||"COMPLIANCE",retentionDays:e.retentionDays,retentionYears:e.retentionYears,legalHoldEnabled:e.legalHoldEnabled||!1};return this.objectLocks.set(n,r),r}enableTransferAcceleration(e){let n=`transfer-accel-${Date.now()}-${this.counter++}`,r={id:n,bucketName:e,enabled:!0,endpoint:`${e}.s3-accelerate.amazonaws.com`};return this.transferAcceleration.set(n,r),r}createAccessPoint(e){let n=`access-point-${Date.now()}-${this.counter++}`,r={id:n,name:e.name,bucketName:e.bucketName,vpcId:e.vpcId,publicAccessBlock:e.publicAccessBlock!==!1,policy:e.policy};return this.accessPoints.set(n,r),r}createGlacierArchive(e){let n=`glacier-${Date.now()}-${this.counter++}`,r={id:n,bucketName:e.bucketName,archiveType:e.archiveType,transitionDays:e.transitionDays,restoreConfig:e.restoreTier?{tier:e.restoreTier,days:e.restoreDays||7}:void 0};return this.glacierConfigs.set(n,r),r}createInventory(e){let n=`inventory-${Date.now()}-${this.counter++}`,r={id:n,sourceBucket:e.sourceBucket,destinationBucket:e.destinationBucket,schedule:e.schedule||"Daily",format:e.format||"CSV",includedFields:e.includedFields||["Size","LastModifiedDate","StorageClass","ETag"],prefix:e.prefix};return this.inventories.set(n,r),r}createBatchOperation(e){let n=`batch-op-${Date.now()}-${this.counter++}`,r={id:n,operation:e.operation,manifestBucket:e.manifestBucket,manifestKey:e.manifestKey,priority:e.priority||10,status:"pending"};return this.batchOps.set(n,r),r}executeBatchOperation(e){let n=this.batchOps.get(e);if(!n)throw Error(`Batch operation not found: ${e}`);return n.status="in_progress",n.totalObjects=1000,n.processedObjects=0,n}getBatchOperationStatus(e){return this.batchOps.get(e)}createLambdaNotification(e){let n=`event-${Date.now()}-${this.counter++}`,r={id:n,bucketName:e.bucketName,events:e.events,destination:{type:"Lambda",arn:e.lambdaArn},filter:e.prefix||e.suffix?{prefix:e.prefix,suffix:e.suffix}:void 0};return this.eventNotifications.set(n,r),r}createSQSNotification(e){let n=`event-${Date.now()}-${this.counter++}`,r={id:n,bucketName:e.bucketName,events:e.events,destination:{type:"SQS",arn:e.queueArn},filter:e.prefix||e.suffix?{prefix:e.prefix,suffix:e.suffix}:void 0};return this.eventNotifications.set(n,r),r}createSNSNotification(e){let n=`event-${Date.now()}-${this.counter++}`,r={id:n,bucketName:e.bucketName,events:e.events,destination:{type:"SNS",arn:e.topicArn},filter:e.prefix||e.suffix?{prefix:e.prefix,suffix:e.suffix}:void 0};return this.eventNotifications.set(n,r),r}generateObjectLockCF(e){let n={ObjectLockEnabled:"Enabled",ObjectLockConfiguration:{ObjectLockEnabled:"Enabled",Rule:{DefaultRetention:{Mode:e.mode}}}};if(e.retentionDays)n.ObjectLockConfiguration.Rule.DefaultRetention.Days=e.retentionDays;if(e.retentionYears)n.ObjectLockConfiguration.Rule.DefaultRetention.Years=e.retentionYears;return n}generateTransferAccelerationCF(e){return{AccelerateConfiguration:{AccelerationStatus:e.enabled?"Enabled":"Suspended"}}}generateAccessPointCF(e){return{Type:"AWS::S3::AccessPoint",Properties:{Name:e.name,Bucket:e.bucketName,...e.vpcId&&{VpcConfiguration:{VpcId:e.vpcId}},PublicAccessBlockConfiguration:e.publicAccessBlock?{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0}:void 0,...e.policy&&{Policy:e.policy}}}}generateInventoryCF(e){return{Type:"AWS::S3::Bucket",Properties:{InventoryConfigurations:[{Id:e.id,Destination:{BucketArn:`arn:aws:s3:::${e.destinationBucket}`,Format:e.format},Enabled:!0,IncludedObjectVersions:"Current",OptionalFields:e.includedFields,ScheduleFrequency:e.schedule,...e.prefix&&{Prefix:e.prefix}}]}}}generateEventNotificationCF(e){let n=e.destination.type==="Lambda"?"LambdaConfigurations":e.destination.type==="SQS"?"QueueConfigurations":"TopicConfigurations",r=e.destination.type==="Lambda"?"Function":e.destination.type==="SQS"?"Queue":"Topic",i={Event:e.events[0],[r]:e.destination.arn};if(e.filter)i.Filter={S3Key:{Rules:[...e.filter.prefix?[{Name:"prefix",Value:e.filter.prefix}]:[],...e.filter.suffix?[{Name:"suffix",Value:e.filter.suffix}]:[]]}};return{NotificationConfiguration:{[n]:[i]}}}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 Np=new cc;class wd{checks=new Map;synthetics=new Map;uptimeTrackers=new Map;counter=0;createHealthCheck(e,n=30,r=10){let i=`health-${Date.now()}-${this.counter++}`,s={id:i,url:e,interval:n,timeout:r,status:"healthy"};return this.checks.set(i,s),s}createSyntheticMonitor(e,n,r,i){let s=`synthetic-${Date.now()}-${this.counter++}`,a={id:s,name:e,script:n,frequency:r,locations:i};return this.synthetics.set(s,a),a}trackUptime(e,n,r){let i=`uptime-${Date.now()}-${this.counter++}`,s=n/(n+r)*100,a={id:i,resource:e,uptime:n,downtime:r,availability:s};return this.uptimeTrackers.set(i,a),a}clear(){this.checks.clear(),this.synthetics.clear(),this.uptimeTrackers.clear()}}var bh=new wd;class Ad{wafRules=new Map;shieldProtections=new Map;securityGroups=new Map;nacls=new Map;counter=0;createWAFRule(e,n,r,i){let s=`waf-${Date.now()}-${this.counter++}`,a={id:s,name:e,priority:n,action:r,conditions:i};return this.wafRules.set(s,a),a}enableShield(e,n="standard"){let r=`shield-${Date.now()}-${this.counter++}`,i={id:r,resourceArn:e,protectionType:n};return this.shieldProtections.set(r,i),i}createSecurityGroup(e,n,r){let i=`sg-${Date.now()}-${this.counter++}`,s={id:i,name:e,vpcId:n,rules:r};return this.securityGroups.set(i,s),s}createNACL(e,n){let r=`nacl-${Date.now()}-${this.counter++}`,i={id:r,vpcId:e,rules:n};return this.nacls.set(r,i),i}clear(){this.wafRules.clear(),this.shieldProtections.clear(),this.securityGroups.clear(),this.nacls.clear()}}var Sh=new Ad;class Rd{strategies=new Map;allocations=new Map;groups=new Map;counter=0;createTaggingStrategy(e,n){let r=`tagging-${Date.now()}-${this.counter++}`,i={id:r,tags:e,resources:n};return this.strategies.set(r,i),i}createCostAllocation(e,n){let r=`cost-${Date.now()}-${this.counter++}`,i={id:r,tagKey:e,allocations:n};return this.allocations.set(r,i),i}createResourceGroup(e,n,r){let i=`group-${Date.now()}-${this.counter++}`,s={id:i,name:e,query:{resourceTypeFilters:n,tagFilters:r}};return this.groups.set(i,s),s}clear(){this.strategies.clear(),this.allocations.clear(),this.groups.clear()}}var vh=new Rd;export{Tm,Em,da,il,ua,pa,wn,ze,I,ma,ol,H,Fr,A,ou,ne,jr,ga,Jo,le,U,Xo,su,au,cu,lu,l,o,wm,Am,T,fa,ha,ya,Rm,Im,$e,ba,Bi,du,Pm,Dm,He,Dt,Sa,sl,al,km,cl,ll,dl,Qo,va,st,Yo,An,Fi,Rn,Ge,uu,Zo,es,Ca,Ta,Ea,wa,Aa,Ra,Ae,j,pu,mu,ul,b,M,at,N,pl,kt,ye,Qt,Nm,ml,Re,ts,qe,Yt,ji,Ie,rs,Le,gu,Vi,Pe,De,ie,zi,X,Zt,Nt,ke,t,In,xm,gl,Ia,_m,Om,$m,Lm,Pa,Mm,Um,Bm,Fm,jm,Vm,zm,Hm,Gm,qm,Wm,Km,fu,hu,yu,bu,Su,vu,Cu,er,fl,hl,Vr,Hi,Jm,yl,Xm,Qm,Pn,Ym,Zm,eg,tg,rg,ng,Tu,Eu,wu,Au,Ru,Gi,ig,Dn,Iu,bl,Pu,Da,be,Du,ku,xt,ns,tr,Nu,Sl,xu,_u,Ou,vl,Se,og,sg,ag,cg,$u,lg,Ne,dg,ug,pg,ka,Na,Lu,Cl,Tl,mg,gg,fg,hg,yg,Mu,xa,bg,Sg,vg,Cg,Tg,Uu,Bu,Eg,wg,Ag,Rg,Ig,Pg,Dg,Fu,kg,El,_a,Ng,xg,_g,Og,wl,Al,Rl,$g,Oa,ju,Vu,zu,Hu,$a,Gu,Lg,Mg,Ug,Bg,Fg,jg,Vg,qu,Wu,Ku,Ju,Il,zg,Hg,Gg,qg,Wg,Kg,Jg,Xg,Qg,Xu,Qu,Yu,Zu,Yg,Zg,Pl,ef,Dl,kl,Nl,xl,tf,rf,nf,of,ct,qi,sf,af,cf,lf,df,uf,pf,mf,ep,gf,ff,_l,Ol,hf,yf,tp,bf,Sf,vf,Cf,Tf,Ef,wf,Af,Rf,If,Pf,Df,kf,Nf,xf,_f,Of,$f,Lf,Mf,Uf,La,rp,Ma,np,Ua,ip,Ba,op,Fa,sp,zr,ap,ja,cp,Wi,lp,Va,dp,za,up,$l,Bf,Ll,Ff,Ha,pp,Hr,mp,Ml,jf,Ga,gp,Ul,Vf,Bl,zf,Fl,Hf,qa,fp,jl,Gf,Vl,qf,zl,Wf,Hl,Kf,Wa,hp,Ka,yp,Gl,Jf,ql,Xf,Wl,Qf,Kl,Yf,Jl,Zf,Xl,eh,Ja,bp,Ql,th,Yl,rh,Zl,nh,ed,ih,td,oh,rd,sh,nd,id,od,sd,ad,ah,cd,ch,ld,lh,dd,dh,_t,ud,Sp,is,Xa,kn,vp,Ki,rr,Qa,Ya,Cp,Tp,Za,pd,ec,md,uh,ph,tc,rc,nc,gd,Ji,fd,hd,os,ic,oc,yd,Ep,wp,Ap,mh,bd,Sd,gh,Rp,vd,Ip,Pp,Dp,fh,Cd,Nn,sc,Td,hh,kp,ss,as,ac,Ed,yh,cc,Np,wd,bh,Ad,Sh,Rd,vh};
|