@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.
Files changed (180) hide show
  1. package/dist/aws/index.js +1 -1
  2. package/dist/bin/chunk-00j7xxxg.js +1 -0
  3. package/dist/bin/{chunk-10z6s9nj.js → chunk-06hwds44.js} +2 -2
  4. package/dist/bin/{chunk-xhe84hg1.js → chunk-0e7y7q0t.js} +1 -1
  5. package/dist/bin/{chunk-cs2a075v.js → chunk-0r8k7qth.js} +2 -2
  6. package/dist/bin/{chunk-jh4ajbt1.js → chunk-0v5q5sh0.js} +3 -3
  7. package/dist/bin/{chunk-fwcd0ef4.js → chunk-0zydd9s4.js} +3 -3
  8. package/dist/bin/chunk-1xfn93bc.js +1 -0
  9. package/dist/bin/{chunk-11xdxrp3.js → chunk-26vbw2m6.js} +70 -70
  10. package/dist/bin/{chunk-7v68hpgc.js → chunk-2h1q758c.js} +2 -2
  11. package/dist/bin/{chunk-bgjvxdds.js → chunk-33shhgye.js} +2 -2
  12. package/dist/bin/chunk-413nb697.js +1 -0
  13. package/dist/bin/{chunk-c99xvba1.js → chunk-4m2k5mvd.js} +4 -4
  14. package/dist/bin/{chunk-rg6r03q3.js → chunk-4vtyjj7c.js} +1 -1
  15. package/dist/bin/{chunk-9cj1fm00.js → chunk-540wkkhs.js} +3 -3
  16. package/dist/bin/{chunk-6wvgwn9q.js → chunk-6xx24qev.js} +1 -1
  17. package/dist/bin/chunk-72kpcqps.js +1 -0
  18. package/dist/bin/chunk-8esaawk6.js +1 -0
  19. package/dist/bin/chunk-8zc4kx6k.js +1 -0
  20. package/dist/bin/{chunk-whryzwb7.js → chunk-9ktyfegk.js} +1 -1
  21. package/dist/bin/chunk-9t6wztvn.js +1 -0
  22. package/dist/bin/{chunk-613m8vf9.js → chunk-b77qsk6r.js} +1 -1
  23. package/dist/bin/{chunk-ae9epvrr.js → chunk-by7dtwtj.js} +1 -1
  24. package/dist/bin/{chunk-6gspchrt.js → chunk-c1znyyca.js} +1 -1
  25. package/dist/bin/{chunk-9xs1fh7q.js → chunk-d73xkm0k.js} +1 -1
  26. package/dist/bin/{chunk-yjmydj1w.js → chunk-dmj5xv74.js} +1 -1
  27. package/dist/bin/chunk-dnswjyen.js +1 -0
  28. package/dist/bin/{chunk-bj94s3a7.js → chunk-e12679p1.js} +1 -1
  29. package/dist/bin/{chunk-zcq82zv1.js → chunk-eyzdhtp4.js} +3 -3
  30. package/dist/bin/{chunk-69j7md80.js → chunk-fhqjr3ba.js} +4 -4
  31. package/dist/bin/{chunk-eevqxagd.js → chunk-gndp57b6.js} +44 -44
  32. package/dist/bin/{chunk-648xb030.js → chunk-gq4htm3f.js} +2 -2
  33. package/dist/bin/{chunk-zph18vv6.js → chunk-gqstb8zn.js} +3 -3
  34. package/dist/bin/{chunk-7xd2tnjb.js → chunk-hhbmtgkq.js} +2 -2
  35. package/dist/bin/{chunk-8fspkmer.js → chunk-jcehsvnm.js} +10 -10
  36. package/dist/bin/chunk-k1bdndgj.js +1 -0
  37. package/dist/bin/{chunk-r5cpsqqk.js → chunk-k3cyh23p.js} +3 -3
  38. package/dist/bin/chunk-kkrp8100.js +1 -0
  39. package/dist/bin/{chunk-tvd5w8xq.js → chunk-kq526rgc.js} +1 -1
  40. package/dist/bin/{chunk-1g3gvxy2.js → chunk-ma0d990n.js} +2 -2
  41. package/dist/bin/{chunk-1n1s649d.js → chunk-nbffypj8.js} +1 -1
  42. package/dist/bin/chunk-nwcpck34.js +1 -0
  43. package/dist/bin/chunk-nzky7rgv.js +1 -0
  44. package/dist/bin/{chunk-qw5ch629.js → chunk-p35e4j11.js} +1 -1
  45. package/dist/bin/chunk-p96975b7.js +1 -0
  46. package/dist/bin/{chunk-sfv47z62.js → chunk-ps0pzqm0.js} +7 -7
  47. package/dist/bin/chunk-rgwwr6x2.js +1 -0
  48. package/dist/bin/{chunk-ekr2rzf6.js → chunk-s076q9sj.js} +2 -2
  49. package/dist/bin/chunk-sky689gw.js +1 -0
  50. package/dist/bin/{chunk-a8fqqd62.js → chunk-tf5tf414.js} +1 -1
  51. package/dist/bin/{chunk-47yznk07.js → chunk-th05q1gs.js} +1 -1
  52. package/dist/bin/chunk-tx56y5qk.js +1 -0
  53. package/dist/bin/{chunk-28a6yey5.js → chunk-v0fkhtgq.js} +1 -1
  54. package/dist/bin/chunk-v7dk21w9.js +1 -0
  55. package/dist/bin/{chunk-w244mfsx.js → chunk-vgcscxh1.js} +2 -2
  56. package/dist/bin/{chunk-gghy8mb4.js → chunk-wayhpmn7.js} +38 -38
  57. package/dist/bin/chunk-ww4r3r7x.js +1 -0
  58. package/dist/bin/{chunk-swbb39hj.js → chunk-y5gx3dq2.js} +1 -1
  59. package/dist/bin/chunk-y5hsmt17.js +1 -0
  60. package/dist/bin/{chunk-t6njpv8j.js → chunk-zfy6f6ph.js} +1 -1
  61. package/dist/bin/cli.js +82 -82
  62. package/dist/bin/dashboard-server.js +1 -1
  63. package/dist/{chunk-fd6gsz34.js → chunk-0cgrk9g3.js} +2 -2
  64. package/dist/{chunk-zthcwfbg.js → chunk-4ccv5c4m.js} +1 -1
  65. package/dist/{chunk-207hnnpp.js → chunk-84z2a1xn.js} +3 -3
  66. package/dist/chunk-86qwnp25.js +1 -0
  67. package/dist/{chunk-1ktv8jxf.js → chunk-8k44kaz0.js} +2 -2
  68. package/dist/{chunk-tdhm38cg.js → chunk-9pwvnh3f.js} +2 -2
  69. package/dist/{chunk-mqr6s8wa.js → chunk-b6wsc7jp.js} +22 -22
  70. package/dist/{chunk-49rt1jbe.js → chunk-c8kf2268.js} +3 -3
  71. package/dist/chunk-crpbs450.js +1 -0
  72. package/dist/{chunk-dq9g7cg9.js → chunk-dvma06m5.js} +3 -3
  73. package/dist/{chunk-qcs3qkdf.js → chunk-etv0rcjd.js} +3 -3
  74. package/dist/chunk-f4fggc5f.js +1 -0
  75. package/dist/{chunk-ebb7j388.js → chunk-fdf181e6.js} +1 -1
  76. package/dist/chunk-fmhqz3eg.js +1 -0
  77. package/dist/{chunk-yqzc3a9m.js → chunk-fnc88v79.js} +89 -89
  78. package/dist/{chunk-c2hvf1h5.js → chunk-hg93a2g9.js} +1 -1
  79. package/dist/{chunk-k05g8vy5.js → chunk-jx1zz1pw.js} +1 -1
  80. package/dist/{chunk-z90dv6jx.js → chunk-m9szynnf.js} +3 -3
  81. package/dist/{chunk-s7gv665w.js → chunk-ne8btf6v.js} +86 -86
  82. package/dist/{chunk-ssywr12y.js → chunk-nftqsker.js} +1 -1
  83. package/dist/{chunk-2r334egt.js → chunk-nxj8pwa7.js} +2 -2
  84. package/dist/chunk-pev4cpbd.js +1 -0
  85. package/dist/{chunk-277enqjc.js → chunk-t7qgvz8z.js} +27 -27
  86. package/dist/{chunk-7qhcfnqf.js → chunk-tmp2ym80.js} +1 -1
  87. package/dist/{chunk-65fwpzeg.js → chunk-tp37gyhc.js} +5 -5
  88. package/dist/{chunk-8ynkxbj6.js → chunk-v6s9k1mp.js} +3 -3
  89. package/dist/{chunk-cfyn21gd.js → chunk-vq8bejep.js} +2 -2
  90. package/dist/{chunk-49raybtd.js → chunk-w8sctn7m.js} +7 -7
  91. package/dist/{chunk-ggqxjcbe.js → chunk-z56sccfh.js} +1 -1
  92. package/dist/{chunk-f4qv0c6w.js → chunk-z5c5amm1.js} +5 -5
  93. package/dist/deploy/index.js +1 -1
  94. package/dist/dns/index.js +1 -1
  95. package/dist/drivers/index.js +1 -1
  96. package/dist/drivers/shared/db-provision.d.ts +3 -3
  97. package/dist/index.js +10 -10
  98. package/dist/mail/index.js +2 -2
  99. package/dist/operations/index.js +1 -1
  100. package/dist/protection/index.js +1 -1
  101. package/dist/spend/index.js +1 -1
  102. package/dist/ui/404.html +1 -1
  103. package/dist/ui/accept-invitation.html +1 -1
  104. package/dist/ui/access-denied.html +1 -1
  105. package/dist/ui/account/automation.html +6 -6
  106. package/dist/ui/account/security.html +2 -2
  107. package/dist/ui/applications/compose.html +6 -6
  108. package/dist/ui/applications/new.html +2 -2
  109. package/dist/ui/data/backups.html +6 -6
  110. package/dist/ui/data/services.html +6 -6
  111. package/dist/ui/data/volumes.html +6 -6
  112. package/dist/ui/index.html +5 -5
  113. package/dist/ui/infrastructure/topology.html +6 -6
  114. package/dist/ui/integrations.html +2 -2
  115. package/dist/ui/operations/alerts.html +6 -6
  116. package/dist/ui/operations/configuration.html +6 -6
  117. package/dist/ui/operations/jobs.html +6 -6
  118. package/dist/ui/operations/maintenance.html +5 -5
  119. package/dist/ui/operations/observability.html +6 -6
  120. package/dist/ui/operations/previews.html +6 -6
  121. package/dist/ui/operations/queue.html +6 -6
  122. package/dist/ui/operations/regions.html +5 -5
  123. package/dist/ui/operations/releases.html +6 -6
  124. package/dist/ui/operations/spend.html +6 -6
  125. package/dist/ui/operations/workloads.html +6 -6
  126. package/dist/ui/security.html +2 -2
  127. package/dist/ui/server/actions.html +6 -6
  128. package/dist/ui/server/activity.html +1 -1
  129. package/dist/ui/server/capacity.html +6 -6
  130. package/dist/ui/server/database.html +5 -5
  131. package/dist/ui/server/deployments.html +6 -6
  132. package/dist/ui/server/diagnostics.html +2 -2
  133. package/dist/ui/server/firewall.html +5 -5
  134. package/dist/ui/server/fleet.html +6 -6
  135. package/dist/ui/server/logs.html +6 -6
  136. package/dist/ui/server/metrics.html +6 -6
  137. package/dist/ui/server/security.html +1 -1
  138. package/dist/ui/server/services.html +1 -1
  139. package/dist/ui/server/sites.html +5 -5
  140. package/dist/ui/server/ssh-keys.html +5 -5
  141. package/dist/ui/server/team.html +5 -5
  142. package/dist/ui/server/terminal.html +2 -2
  143. package/dist/ui/serverless/alarms.html +5 -5
  144. package/dist/ui/serverless/assets.html +2 -2
  145. package/dist/ui/serverless/cost.html +2 -2
  146. package/dist/ui/serverless/data.html +5 -5
  147. package/dist/ui/serverless/deployments.html +1 -1
  148. package/dist/ui/serverless/firewall.html +1 -1
  149. package/dist/ui/serverless/functions.html +5 -5
  150. package/dist/ui/serverless/logs.html +6 -6
  151. package/dist/ui/serverless/metrics.html +2 -2
  152. package/dist/ui/serverless/queues.html +6 -6
  153. package/dist/ui/serverless/secrets.html +6 -6
  154. package/dist/ui/serverless/traces.html +6 -6
  155. package/dist/ui/serverless.html +5 -5
  156. package/package.json +3 -3
  157. package/dist/bin/chunk-0pptjpck.js +0 -1
  158. package/dist/bin/chunk-0sswdcvq.js +0 -1
  159. package/dist/bin/chunk-1pj60edk.js +0 -1
  160. package/dist/bin/chunk-1qcztara.js +0 -1
  161. package/dist/bin/chunk-6bnxvtvy.js +0 -1
  162. package/dist/bin/chunk-7x4vs33k.js +0 -1
  163. package/dist/bin/chunk-8bs3m2x7.js +0 -1
  164. package/dist/bin/chunk-8cxdvpzy.js +0 -1
  165. package/dist/bin/chunk-9twr514q.js +0 -1
  166. package/dist/bin/chunk-9zbfadg4.js +0 -1
  167. package/dist/bin/chunk-bgm9p3x6.js +0 -1
  168. package/dist/bin/chunk-cmraxfxd.js +0 -1
  169. package/dist/bin/chunk-cvet8kjp.js +0 -1
  170. package/dist/bin/chunk-d5n4d3pj.js +0 -1
  171. package/dist/bin/chunk-e6kfkaxc.js +0 -1
  172. package/dist/bin/chunk-f80asgbh.js +0 -1
  173. package/dist/bin/chunk-wkwcskhg.js +0 -1
  174. package/dist/bin/chunk-yqqx644v.js +0 -1
  175. package/dist/bin/chunk-ywpkvdfg.js +0 -1
  176. package/dist/chunk-c5pq3x7x.js +0 -1
  177. package/dist/chunk-fvad4wm8.js +0 -1
  178. package/dist/chunk-gc8r2gvd.js +0 -1
  179. package/dist/chunk-k0scshn2.js +0 -1
  180. package/dist/chunk-sacbxd79.js +0 -1
@@ -1,4 +1,4 @@
1
- import{k,na}from"./chunk-928z0h9b.js";import{hn,it}from"./chunk-tdhm38cg.js";var Nm={};hn(Nm,{default:()=>Rr,handler:()=>At});var Bm={};hn(Bm,{default:()=>Pr,handler:()=>Ct});var Ef={};hn(Ef,{EmailAnalyticsModule:()=>Xe,EmailRules:()=>Ut,EmailScheduling:()=>Wt,EmailSearch:()=>Gt,EmailTemplates:()=>ke,EmailThreading:()=>_t,SharedMailboxes:()=>Vt});var vf={};hn(vf,{default:()=>ki,handler:()=>xi});var Tf={};hn(Tf,{CallAnalytics:()=>jt,CallRecording:()=>Ht,Callbacks:()=>mt,IVRBuilder:()=>Be});var wf={};hn(wf,{AbTesting:()=>Ee,LinkTracking:()=>Jt,MmsSupport:()=>zt,SmsAnalytics:()=>qt,SmsCampaigns:()=>Kt,SmsChatbot:()=>Qt});var $I={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}},MI={serverless:{development:{enabled:!0,mode:"serverless",channels:{public:!0,private:!0,presence:!0},storage:{type:"dynamodb",dynamodb:{billingMode:"PAY_PER_REQUEST"}},scaling:{maxConnections:1000,handlerMemory:128}},production:{enabled:!0,mode:"serverless",channels:{public:!0,private:!0,presence:{enabled:!0,maxMembers:100,heartbeatInterval:30,inactivityTimeout:60}},storage:{type:"dynamodb",dynamodb:{billingMode:"PAY_PER_REQUEST",pointInTimeRecovery:!0,connectionTTL:86400}},scaling:{maxConnections:50000,messagesPerSecond:5000,handlerMemory:256,handlerTimeout:30},monitoring:{enabled:!0,connectionThreshold:40000,errorThreshold:100,latencyThreshold:500},keepAlive:!0,keepAliveInterval:30,idleTimeout:600},notifications:{enabled:!0,mode:"serverless",channels:{public:!1,private:!0,presence:!1},storage:{type:"dynamodb",dynamodb:{billingMode:"PAY_PER_REQUEST"}},scaling:{maxConnections:50000,messagesPerSecond:2000,handlerMemory:128},keepAlive:!0,keepAliveInterval:60,idleTimeout:1800}},server:{development:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"ws",driver:"bun",idleTimeout:120,perMessageDeflate:!1,metrics:!1}},production:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:120,maxPayloadLength:16777216,backpressureLimit:1048576,sendPings:!0,perMessageDeflate:!0,instances:2,redis:{enabled:!0,keyPrefix:"broadcasting:"},rateLimit:{enabled:!0,max:100,window:60000,perChannel:!0,perUser:!0},loadManagement:{enabled:!0,maxConnections:1e4,maxSubscriptionsPerConnection:100,shedLoadThreshold:0.8},metrics:!0,autoScaling:{min:2,max:10,targetCPU:70}},monitoring:{enabled:!0,connectionThreshold:8000,errorThreshold:100}},highPerformance:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:60,maxPayloadLength:8388608,backpressureLimit:2097152,closeOnBackpressureLimit:!0,sendPings:!0,perMessageDeflate:!0,instances:4,redis:{enabled:!0,useElastiCache:!0,keyPrefix:"rt:"},rateLimit:{enabled:!0,max:200,window:60000,perChannel:!0},loadManagement:{enabled:!0,maxConnections:25000,maxSubscriptionsPerConnection:50,shedLoadThreshold:0.7},metrics:{enabled:!0,path:"/metrics"},autoScaling:{min:4,max:20,targetCPU:60,targetConnections:20000}},monitoring:{enabled:!0,connectionThreshold:80000,errorThreshold:50,latencyThreshold:50}},chat:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:{enabled:!0,maxMembers:200,heartbeatInterval:20,inactivityTimeout:60}},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:300,maxPayloadLength:1048576,sendPings:!0,perMessageDeflate:!0,instances:2,redis:{enabled:!0,keyPrefix:"chat:"},rateLimit:{enabled:!0,max:60,window:60000,perChannel:!0},loadManagement:{enabled:!0,maxConnections:15000,maxSubscriptionsPerConnection:20},metrics:!0},keepAlive:!0,keepAliveInterval:25,idleTimeout:900},gaming:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:{enabled:!0,maxMembers:100,heartbeatInterval:10,inactivityTimeout:30}},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:30,maxPayloadLength:65536,backpressureLimit:524288,closeOnBackpressureLimit:!0,sendPings:!0,perMessageDeflate:!1,instances:4,redis:{enabled:!0,useElastiCache:!0},rateLimit:{enabled:!0,max:120,window:60000},loadManagement:{enabled:!0,maxConnections:5000,maxSubscriptionsPerConnection:10,shedLoadThreshold:0.6},metrics:!0,autoScaling:{min:4,max:16,targetCPU:50}},keepAlive:!0,keepAliveInterval:10,idleTimeout:60},single:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:120,sendPings:!0,perMessageDeflate:!0,instances:1,rateLimit:{enabled:!0,max:100,window:60000},loadManagement:{enabled:!0,maxConnections:1e4},metrics:!0}}}};import{isAbsolute as bt,join as st,relative as ar}from"node:path";var rl=".ts-cloud",Sm="TS_CLOUD_STATE_DIR",St=null;function nl(n){St=n?.trim()||null}function il(){return Boolean(process.env[Sm]?.trim()||St)}function cn(){return process.env[Sm]?.trim()||St||rl}function Q(...n){return st(cn(),...n)}function l(n,...i){let s=cn();return bt(s)?st(s,...i):st(n,s,...i)}function sl(n,i=process.cwd()){let s=(c,u)=>{let d=ar(c,u);return d===""||!d.startsWith("..")&&!bt(d)},o=bt(n)?n:st(i,n);return s(l(i),o)}function Im(n){let i=n.infrastructure?.compute!=null,s=Object.values(n.environments??{}).some((o)=>o?.app!=null);return{server:i,serverless:s}}function K(n){if(n.mode==="server"||n.mode==="serverless")return n.mode;let{serverless:i}=Im(n);return i?"serverless":"server"}function ol(n){let{server:i,serverless:s}=Im(n);if(i&&s)return"A project cannot be both a server and a serverless deployment. Found `infrastructure.compute` (server) AND `environments.<env>.app` (serverless Lambda). Keep one: remove `infrastructure.compute` for a serverless app, or remove `environments.<env>.app` for a server.";if(n.mode==="server"&&s&&!i)return"Config sets `mode: 'server'` but declares a serverless app (`environments.<env>.app`). Remove the app or change the mode.";if(n.mode==="serverless"&&i&&!s)return"Config sets `mode: 'serverless'` but declares a server (`infrastructure.compute`). Remove the compute block or change the mode.";return null}function p(n){return n.infrastructure?.appDatabase??n.infrastructure?.compute?.database}function or(n){return typeof n==="object"&&n!==null?n:{}}function ry(n){return n===!0||typeof n==="object"&&n!==null}function cr(n,i){let s=i?n.environments?.[i]:void 0;if(s?.domain)return s.domain;let o=Object.values(n.sites??{}),c=n.sites?.main?.domain??o.find((u)=>u.domain)?.domain;if(c)return c;return`${n.project?.slug??"app"}.local`}function dr(n){let i=n.indexOf(".");return i>0?n.slice(i+1):void 0}function C(n,i={}){let s=n.infrastructure?.compute?.managedServices?.mail,o=or(s),c=i.environmentType??(i.environment?n.environments?.[i.environment]?.type:void 0),u=o.mode??(c==="production"?"server":"catcher"),d=u==="server",g=cr(n,i.environment),y=o.hostname??(d?`mail.${g}`:"localhost"),h=o.ports??{},b=d?{smtp:h.smtp??25,submission:h.submission??587,submissions:h.submissions??465,imap:h.imap??143,imaps:h.imaps??993,webmail:h.webmail??8080,managesieve:h.managesieve}:{smtp:h.smtp??1025,submission:h.submission,submissions:h.submissions,imap:h.imap,imaps:h.imaps,webmail:h.webmail??8025,managesieve:h.managesieve},v=o.tls??{},A=v.enabled??d,T=!!(v.certPath&&v.keyPath),R=(o.accounts??[]).map((pe)=>({address:pe.address,password:pe.password,passwordPolicy:pe.passwordPolicy??"initial"})),P=typeof o.dkim==="object"&&o.dkim!==null?o.dkim:{},I=o.dkim===!1?!1:o.dkim===!0||d,M=typeof o.webmail==="object"&&o.webmail!==null?o.webmail:{},L=o.webmail===!1?!1:M.enabled??!0,N=y.includes(".")&&!y.endsWith(".local")&&!/^\d+\.\d+\.\d+\.\d+$/.test(y),O=M.domain===!1?void 0:M.domain??(d&&N?y:void 0),B=M.tls??(O?!1:A),F=[...new Set(M.aliases??[])].filter((pe)=>pe!==O),U=o.spam??{},j=o.delivery??(d?"direct":"none"),H=o.expose??d,z=dr(y),se=[...new Set([y,...z?[z]:[],...o.domains??[]])],Te=M.attachments?.maxFileBytes??20971520,oe=M.attachments?.maxTotalBytes??20971520,ge=M.attachments?.maxCount??20,ae=M.undoSendSeconds??10;for(let[pe,Ie,Le]of[["maxFileBytes",Te,104857600],["maxTotalBytes",oe,104857600],["maxCount",ge,100],["undoSendSeconds",ae,30]])if(!Number.isInteger(Ie)||Ie<0||Ie>Le)throw Error(`Mail webmail ${pe} must be an integer from 0 to ${Le}`);return{enabled:ry(s),mode:u,version:o.version,hostname:y,domains:se,ports:b,tls:{enabled:A,acme:A&&!T&&(v.acme??!0),certPath:v.certPath,keyPath:v.keyPath,requireForAuth:v.requireForAuth??(A&&d),acmeEmail:v.acmeEmail??R[0]?.address},dkim:{enabled:I,selector:P.selector??"default",rotate:P.rotate??!1,rotateIntervalDays:P.rotateIntervalDays??90},webmail:{enabled:L,port:M.port??b.webmail,domain:O,aliases:F,tls:B,secureCookies:M.secureCookies??(!!O||B),attachmentMaxFileBytes:Te,attachmentMaxTotalBytes:oe,attachmentMaxCount:ge,undoSendSeconds:ae},delivery:j,sesRegion:o.sesRegion??"us-east-1",accounts:R,storagePath:o.storagePath??"/var/lib/mail",maxMessageSize:o.maxMessageSize??26214400,spam:{enabled:U.enabled??d,enforce:U.enforce??!1,junkScore:U.junkScore??5,rejectScore:U.rejectScore??12,dnsbl:U.dnsbl??d,dnsblReject:U.dnsblReject??!1,greylist:U.greylist??!1},webhookUrl:o.webhookUrl,expose:H,bindAddress:H?"0.0.0.0":"127.0.0.1"}}function Ye(n){if(!n.enabled||!n.expose)return[];let i=[n.ports.smtp,n.ports.submission,n.ports.submissions,n.ports.imap,n.ports.imaps,n.ports.managesieve].filter((s)=>typeof s==="number");if(n.webmail.enabled&&!n.webmail.domain)i.push(n.webmail.port);return[...new Set(i)].sort((s,o)=>s-o)}function Ji(n){if(!n.enabled)return{};let i=n.ports.submission??n.ports.smtp,s={MAIL_MAILER:"smtp",MAIL_HOST:"127.0.0.1",MAIL_PORT:String(i)};if(n.mode==="server"){s.MAIL_ENCRYPTION=n.tls.enabled?"tls":"null";let o=n.accounts[0];if(o)s.MAIL_USERNAME=o.address,s.MAIL_PASSWORD=o.password}else s.MAIL_ENCRYPTION="null",s.MAIL_USERNAME="null",s.MAIL_PASSWORD="null";return s}function dn(n){if(!n.enabled||!n.webmail.enabled||!n.webmail.domain)return{};let i=[n.webmail.domain,...n.webmail.aliases];if(!Number.isInteger(n.webmail.port)||n.webmail.port<1||n.webmail.port>65535)throw Error("Mail webmail port must be between 1 and 65535");return Object.fromEntries(i.map((s,o)=>{if(!/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(s))throw Error(`Invalid mail webmail hostname: ${s}`);return[`__mail_webmail_${o}`,{domain:s,proxyTo:`localhost:${n.webmail.port}`}]}))}function w(n,i={}){let s=n.infrastructure?.compute?.proxy,o=C(n,i);if(!o.enabled||!o.webmail.enabled||!o.webmail.domain)return s;return{engine:"rpx",onDemandTls:!0,onDemandTlsEmail:o.tls.acmeEmail??`webmaster@${o.webmail.domain}`,...s}}function ce(n){if(n.cloud?.provider)return n.cloud.provider;if(n.ssh?.hosts?.length)return"ssh";if(n.hetzner?.apiToken)return"hetzner";return"aws"}class al{template;constructor(n){this.template={AWSTemplateFormatVersion:"2010-09-09",Description:n,Resources:{}}}addResource(n,i){return this.template.Resources[n]=i,this}addResources(n){return Object.assign(this.template.Resources,n),this}addParameter(n,i){if(!this.template.Parameters)this.template.Parameters={};return this.template.Parameters[n]=i,this}addOutput(n,i){if(!this.template.Outputs)this.template.Outputs={};return this.template.Outputs[n]=i,this}addMetadata(n,i){if(!this.template.Metadata)this.template.Metadata={};return this.template.Metadata[n]=i,this}hasResource(n){return n in this.template.Resources}getResources(){return this.template.Resources}build(){return this.template}toJSON(n=!0){return JSON.stringify(this.template,null,n?2:0)}toYAML(){return this.convertToYAML(this.template)}convertToYAML(n,i=0){let s=" ".repeat(i),o="";for(let[c,u]of Object.entries(n)){if(u===null||u===void 0)continue;if(typeof u==="object"&&!Array.isArray(u))o+=`${s}${c}:
1
+ import{k,na}from"./chunk-928z0h9b.js";import{An,st}from"./chunk-9pwvnh3f.js";var Nm={};An(Nm,{default:()=>Rr,handler:()=>At});var Bm={};An(Bm,{default:()=>Pr,handler:()=>Ct});var Ef={};An(Ef,{EmailAnalyticsModule:()=>Ye,EmailRules:()=>Ut,EmailScheduling:()=>Wt,EmailSearch:()=>Gt,EmailTemplates:()=>ke,EmailThreading:()=>_t,SharedMailboxes:()=>Vt});var vf={};An(vf,{default:()=>ki,handler:()=>xi});var Tf={};An(Tf,{CallAnalytics:()=>jt,CallRecording:()=>Ht,Callbacks:()=>mt,IVRBuilder:()=>Be});var wf={};An(wf,{AbTesting:()=>Ee,LinkTracking:()=>Jt,MmsSupport:()=>zt,SmsAnalytics:()=>qt,SmsCampaigns:()=>Kt,SmsChatbot:()=>Qt});var $I={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}},MI={serverless:{development:{enabled:!0,mode:"serverless",channels:{public:!0,private:!0,presence:!0},storage:{type:"dynamodb",dynamodb:{billingMode:"PAY_PER_REQUEST"}},scaling:{maxConnections:1000,handlerMemory:128}},production:{enabled:!0,mode:"serverless",channels:{public:!0,private:!0,presence:{enabled:!0,maxMembers:100,heartbeatInterval:30,inactivityTimeout:60}},storage:{type:"dynamodb",dynamodb:{billingMode:"PAY_PER_REQUEST",pointInTimeRecovery:!0,connectionTTL:86400}},scaling:{maxConnections:50000,messagesPerSecond:5000,handlerMemory:256,handlerTimeout:30},monitoring:{enabled:!0,connectionThreshold:40000,errorThreshold:100,latencyThreshold:500},keepAlive:!0,keepAliveInterval:30,idleTimeout:600},notifications:{enabled:!0,mode:"serverless",channels:{public:!1,private:!0,presence:!1},storage:{type:"dynamodb",dynamodb:{billingMode:"PAY_PER_REQUEST"}},scaling:{maxConnections:50000,messagesPerSecond:2000,handlerMemory:128},keepAlive:!0,keepAliveInterval:60,idleTimeout:1800}},server:{development:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"ws",driver:"bun",idleTimeout:120,perMessageDeflate:!1,metrics:!1}},production:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:120,maxPayloadLength:16777216,backpressureLimit:1048576,sendPings:!0,perMessageDeflate:!0,instances:2,redis:{enabled:!0,keyPrefix:"broadcasting:"},rateLimit:{enabled:!0,max:100,window:60000,perChannel:!0,perUser:!0},loadManagement:{enabled:!0,maxConnections:1e4,maxSubscriptionsPerConnection:100,shedLoadThreshold:0.8},metrics:!0,autoScaling:{min:2,max:10,targetCPU:70}},monitoring:{enabled:!0,connectionThreshold:8000,errorThreshold:100}},highPerformance:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:60,maxPayloadLength:8388608,backpressureLimit:2097152,closeOnBackpressureLimit:!0,sendPings:!0,perMessageDeflate:!0,instances:4,redis:{enabled:!0,useElastiCache:!0,keyPrefix:"rt:"},rateLimit:{enabled:!0,max:200,window:60000,perChannel:!0},loadManagement:{enabled:!0,maxConnections:25000,maxSubscriptionsPerConnection:50,shedLoadThreshold:0.7},metrics:{enabled:!0,path:"/metrics"},autoScaling:{min:4,max:20,targetCPU:60,targetConnections:20000}},monitoring:{enabled:!0,connectionThreshold:80000,errorThreshold:50,latencyThreshold:50}},chat:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:{enabled:!0,maxMembers:200,heartbeatInterval:20,inactivityTimeout:60}},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:300,maxPayloadLength:1048576,sendPings:!0,perMessageDeflate:!0,instances:2,redis:{enabled:!0,keyPrefix:"chat:"},rateLimit:{enabled:!0,max:60,window:60000,perChannel:!0},loadManagement:{enabled:!0,maxConnections:15000,maxSubscriptionsPerConnection:20},metrics:!0},keepAlive:!0,keepAliveInterval:25,idleTimeout:900},gaming:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:{enabled:!0,maxMembers:100,heartbeatInterval:10,inactivityTimeout:30}},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:30,maxPayloadLength:65536,backpressureLimit:524288,closeOnBackpressureLimit:!0,sendPings:!0,perMessageDeflate:!1,instances:4,redis:{enabled:!0,useElastiCache:!0},rateLimit:{enabled:!0,max:120,window:60000},loadManagement:{enabled:!0,maxConnections:5000,maxSubscriptionsPerConnection:10,shedLoadThreshold:0.6},metrics:!0,autoScaling:{min:4,max:16,targetCPU:50}},keepAlive:!0,keepAliveInterval:10,idleTimeout:60},single:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:120,sendPings:!0,perMessageDeflate:!0,instances:1,rateLimit:{enabled:!0,max:100,window:60000},loadManagement:{enabled:!0,maxConnections:1e4},metrics:!0}}}};import{isAbsolute as bt,join as Xe,relative as ar}from"node:path";var rl=".ts-cloud",Sm="TS_CLOUD_STATE_DIR",St=null;function nl(n){St=n?.trim()||null}function il(){return Boolean(process.env[Sm]?.trim()||St)}function dn(){return process.env[Sm]?.trim()||St||rl}function Q(...n){return Xe(dn(),...n)}function l(n,...i){let s=dn();return bt(s)?Xe(s,...i):Xe(n,s,...i)}function sl(n,i=process.cwd()){let s=(c,u)=>{let d=ar(c,u);return d===""||!d.startsWith("..")&&!bt(d)},o=bt(n)?n:Xe(i,n);return s(l(i),o)}function Im(n){let i=n.infrastructure?.compute!=null,s=Object.values(n.environments??{}).some((o)=>o?.app!=null);return{server:i,serverless:s}}function K(n){if(n.mode==="server"||n.mode==="serverless")return n.mode;let{serverless:i}=Im(n);return i?"serverless":"server"}function ol(n){let{server:i,serverless:s}=Im(n);if(i&&s)return"A project cannot be both a server and a serverless deployment. Found `infrastructure.compute` (server) AND `environments.<env>.app` (serverless Lambda). Keep one: remove `infrastructure.compute` for a serverless app, or remove `environments.<env>.app` for a server.";if(n.mode==="server"&&s&&!i)return"Config sets `mode: 'server'` but declares a serverless app (`environments.<env>.app`). Remove the app or change the mode.";if(n.mode==="serverless"&&i&&!s)return"Config sets `mode: 'serverless'` but declares a server (`infrastructure.compute`). Remove the compute block or change the mode.";return null}function p(n){return n.infrastructure?.appDatabase??n.infrastructure?.compute?.database}function or(n){return typeof n==="object"&&n!==null?n:{}}function ry(n){return n===!0||typeof n==="object"&&n!==null}function cr(n,i){let s=i?n.environments?.[i]:void 0;if(s?.domain)return s.domain;let o=Object.values(n.sites??{}),c=n.sites?.main?.domain??o.find((u)=>u.domain)?.domain;if(c)return c;return`${n.project?.slug??"app"}.local`}function dr(n){let i=n.indexOf(".");return i>0?n.slice(i+1):void 0}function C(n,i={}){let s=n.infrastructure?.compute?.managedServices?.mail,o=or(s),c=i.environmentType??(i.environment?n.environments?.[i.environment]?.type:void 0),u=o.mode??(c==="production"?"server":"catcher"),d=u==="server",g=cr(n,i.environment),y=o.hostname??(d?`mail.${g}`:"localhost"),h=o.ports??{},b=d?{smtp:h.smtp??25,submission:h.submission??587,submissions:h.submissions??465,imap:h.imap??143,imaps:h.imaps??993,webmail:h.webmail??8080,managesieve:h.managesieve}:{smtp:h.smtp??1025,submission:h.submission,submissions:h.submissions,imap:h.imap,imaps:h.imaps,webmail:h.webmail??8025,managesieve:h.managesieve},v=o.tls??{},A=v.enabled??d,T=!!(v.certPath&&v.keyPath),R=(o.accounts??[]).map((pe)=>({address:pe.address,password:pe.password,passwordPolicy:pe.passwordPolicy??"initial"})),P=typeof o.dkim==="object"&&o.dkim!==null?o.dkim:{},I=o.dkim===!1?!1:o.dkim===!0||d,M=typeof o.webmail==="object"&&o.webmail!==null?o.webmail:{},L=o.webmail===!1?!1:M.enabled??!0,N=y.includes(".")&&!y.endsWith(".local")&&!/^\d+\.\d+\.\d+\.\d+$/.test(y),O=M.domain===!1?void 0:M.domain??(d&&N?y:void 0),B=M.tls??(O?!1:A),F=[...new Set(M.aliases??[])].filter((pe)=>pe!==O),U=o.spam??{},j=o.delivery??(d?"direct":"none"),H=o.expose??d,z=dr(y),se=[...new Set([y,...z?[z]:[],...o.domains??[]])],Te=M.attachments?.maxFileBytes??20971520,oe=M.attachments?.maxTotalBytes??20971520,ge=M.attachments?.maxCount??20,ae=M.undoSendSeconds??10;for(let[pe,Ie,Le]of[["maxFileBytes",Te,104857600],["maxTotalBytes",oe,104857600],["maxCount",ge,100],["undoSendSeconds",ae,30]])if(!Number.isInteger(Ie)||Ie<0||Ie>Le)throw Error(`Mail webmail ${pe} must be an integer from 0 to ${Le}`);return{enabled:ry(s),mode:u,version:o.version,hostname:y,domains:se,ports:b,tls:{enabled:A,acme:A&&!T&&(v.acme??!0),certPath:v.certPath,keyPath:v.keyPath,requireForAuth:v.requireForAuth??(A&&d),acmeEmail:v.acmeEmail??R[0]?.address},dkim:{enabled:I,selector:P.selector??"default",rotate:P.rotate??!1,rotateIntervalDays:P.rotateIntervalDays??90},webmail:{enabled:L,port:M.port??b.webmail,domain:O,aliases:F,tls:B,secureCookies:M.secureCookies??(!!O||B),attachmentMaxFileBytes:Te,attachmentMaxTotalBytes:oe,attachmentMaxCount:ge,undoSendSeconds:ae},delivery:j,sesRegion:o.sesRegion??"us-east-1",accounts:R,storagePath:o.storagePath??"/var/lib/mail",maxMessageSize:o.maxMessageSize??26214400,spam:{enabled:U.enabled??d,enforce:U.enforce??!1,junkScore:U.junkScore??5,rejectScore:U.rejectScore??12,dnsbl:U.dnsbl??d,dnsblReject:U.dnsblReject??!1,greylist:U.greylist??!1},webhookUrl:o.webhookUrl,expose:H,bindAddress:H?"0.0.0.0":"127.0.0.1"}}function Ze(n){if(!n.enabled||!n.expose)return[];let i=[n.ports.smtp,n.ports.submission,n.ports.submissions,n.ports.imap,n.ports.imaps,n.ports.managesieve].filter((s)=>typeof s==="number");if(n.webmail.enabled&&!n.webmail.domain)i.push(n.webmail.port);return[...new Set(i)].sort((s,o)=>s-o)}function Ji(n){if(!n.enabled)return{};let i=n.ports.submission??n.ports.smtp,s={MAIL_MAILER:"smtp",MAIL_HOST:"127.0.0.1",MAIL_PORT:String(i)};if(n.mode==="server"){s.MAIL_ENCRYPTION=n.tls.enabled?"tls":"null";let o=n.accounts[0];if(o)s.MAIL_USERNAME=o.address,s.MAIL_PASSWORD=o.password}else s.MAIL_ENCRYPTION="null",s.MAIL_USERNAME="null",s.MAIL_PASSWORD="null";return s}function ln(n){if(!n.enabled||!n.webmail.enabled||!n.webmail.domain)return{};let i=[n.webmail.domain,...n.webmail.aliases];if(!Number.isInteger(n.webmail.port)||n.webmail.port<1||n.webmail.port>65535)throw Error("Mail webmail port must be between 1 and 65535");return Object.fromEntries(i.map((s,o)=>{if(!/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(s))throw Error(`Invalid mail webmail hostname: ${s}`);return[`__mail_webmail_${o}`,{domain:s,proxyTo:`localhost:${n.webmail.port}`}]}))}function w(n,i={}){let s=n.infrastructure?.compute?.proxy,o=C(n,i);if(!o.enabled||!o.webmail.enabled||!o.webmail.domain)return s;return{engine:"rpx",onDemandTls:!0,onDemandTlsEmail:o.tls.acmeEmail??`webmaster@${o.webmail.domain}`,...s}}function ce(n){if(n.cloud?.provider)return n.cloud.provider;if(n.ssh?.hosts?.length)return"ssh";if(n.hetzner?.apiToken)return"hetzner";return"aws"}class al{template;constructor(n){this.template={AWSTemplateFormatVersion:"2010-09-09",Description:n,Resources:{}}}addResource(n,i){return this.template.Resources[n]=i,this}addResources(n){return Object.assign(this.template.Resources,n),this}addParameter(n,i){if(!this.template.Parameters)this.template.Parameters={};return this.template.Parameters[n]=i,this}addOutput(n,i){if(!this.template.Outputs)this.template.Outputs={};return this.template.Outputs[n]=i,this}addMetadata(n,i){if(!this.template.Metadata)this.template.Metadata={};return this.template.Metadata[n]=i,this}hasResource(n){return n in this.template.Resources}getResources(){return this.template.Resources}build(){return this.template}toJSON(n=!0){return JSON.stringify(this.template,null,n?2:0)}toYAML(){return this.convertToYAML(this.template)}convertToYAML(n,i=0){let s=" ".repeat(i),o="";for(let[c,u]of Object.entries(n)){if(u===null||u===void 0)continue;if(typeof u==="object"&&!Array.isArray(u))o+=`${s}${c}:
2
2
  ${this.convertToYAML(u,i+1)}`;else if(Array.isArray(u)){o+=`${s}${c}:
3
3
  `;for(let d of u)if(typeof d==="object")o+=`${s} -
4
4
  ${this.convertToYAML(d,i+2)}`;else o+=`${s} - ${d}
@@ -8,7 +8,7 @@ ${this.convertToYAML(d,i+2)}`;else o+=`${s} - ${d}
8
8
  `),i.join(`
9
9
  `);if(i.push(`Total changes: ${n.summary.totalChanges}`),i.push(`Requires replacement: ${n.summary.requiresReplacement?"Yes":"No"}
10
10
  `),n.summary.dangerousChanges.length>0){i.push("⚠️ DANGEROUS CHANGES DETECTED:");for(let s of n.summary.dangerousChanges)i.push(` • ${s}`);i.push("")}if(n.added.length>0){i.push(`✅ Resources to Add (${n.added.length}):`);for(let s of n.added)i.push(` + ${s.logicalId} (${s.resourceType})`);i.push("")}if(n.removed.length>0){i.push(`❌ Resources to Remove (${n.removed.length}):`);for(let s of n.removed)i.push(` - ${s.logicalId} (${s.resourceType})`);i.push("")}if(n.replaced.length>0){i.push(`\uD83D\uDD04 Resources to Replace (${n.replaced.length}):`);for(let s of n.replaced){if(i.push(` ~ ${s.logicalId} (${s.resourceType})`),s.reason)i.push(` Reason: ${s.reason}`);if(s.changes){for(let o of s.changes.slice(0,3))i.push(` • ${o.path}: ${JSON.stringify(o.oldValue)} → ${JSON.stringify(o.newValue)}`);if(s.changes.length>3)i.push(` ... and ${s.changes.length-3} more changes`)}}i.push("")}if(n.updated.length>0){i.push(`\uD83D\uDCDD Resources to Update (${n.updated.length}):`);for(let s of n.updated)if(i.push(` ~ ${s.logicalId} (${s.resourceType})`),s.changes){for(let o of s.changes.slice(0,3))i.push(` • ${o.path}: ${JSON.stringify(o.oldValue)} → ${JSON.stringify(o.newValue)}`);if(s.changes.length>3)i.push(` ... and ${s.changes.length-3} more changes`)}i.push("")}if(n.unchanged.length>0)i.push(`⚪ Unchanged Resources (${n.unchanged.length})`);return i.join(`
11
- `)}import{existsSync as He,readdirSync as Sr}from"node:fs";import{join as Pe}from"node:path";class xe{static createBucket(n){let{name:i,bucketName:s,slug:o,environment:c,public:u=!1,versioning:d=!1,website:g=!1,encryption:y=!0,intelligentTiering:h=!1,cors:b,lifecycleRules:v}=n,A=s??r({slug:o,environment:c,resourceType:"s3",suffix:i}),T=t(A),R={Type:"AWS::S3::Bucket",Properties:{BucketName:A}};if(y)R.Properties.BucketEncryption={ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]};if(d)R.Properties.VersioningConfiguration={Status:"Enabled"};if(g)R.Properties.WebsiteConfiguration={IndexDocument:"index.html",ErrorDocument:"error.html"};if(!u)R.Properties.PublicAccessBlockConfiguration={BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0};if(b&&b.length>0)R.Properties.CorsConfiguration={CorsRules:b.map((I)=>({AllowedOrigins:I.allowedOrigins,AllowedMethods:I.allowedMethods,AllowedHeaders:I.allowedHeaders,MaxAge:I.maxAge}))};if(v&&v.length>0)R.Properties.LifecycleConfiguration={Rules:v.map((I)=>({Id:I.id,Status:I.enabled?"Enabled":"Disabled",ExpirationInDays:I.expirationDays,Transitions:I.transitions?.map((M)=>({TransitionInDays:M.days,StorageClass:M.storageClass}))}))};if(h&&v){let I={id:"IntelligentTieringRule",enabled:!0,transitions:[{days:0,storageClass:"INTELLIGENT_TIERING"}]};if(!R.Properties.LifecycleConfiguration)R.Properties.LifecycleConfiguration={Rules:[]};R.Properties.LifecycleConfiguration.Rules.push({Id:I.id,Status:"Enabled",Transitions:I.transitions?.map((M)=>({TransitionInDays:M.days,StorageClass:M.storageClass}))})}let P;if(u)P={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:x.Ref(T),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadGetObject",Effect:"Allow",Principal:"*",Action:["s3:GetObject"],Resource:[x.Join("",[x.GetAtt(T,"Arn"),"/*"])]}]}}};return{bucket:R,bucketPolicy:P,logicalId:T}}static enableVersioning(n){if(!n.Properties)n.Properties={};return n.Properties.VersioningConfiguration={Status:"Enabled"},n}static enableWebsiteHosting(n,i="index.html",s="error.html"){if(!n.Properties)n.Properties={};return n.Properties.WebsiteConfiguration={IndexDocument:i,ErrorDocument:s},n}static setLifecycleRules(n,i){if(!n.Properties)n.Properties={};return n.Properties.LifecycleConfiguration={Rules:i.map((s)=>({Id:s.id,Status:s.enabled?"Enabled":"Disabled",ExpirationInDays:s.expirationDays,Transitions:s.transitions?.map((o)=>({TransitionInDays:o.days,StorageClass:o.storageClass}))}))},n}static enableIntelligentTiering(n){if(!n.Properties)n.Properties={};if(!n.Properties.LifecycleConfiguration)n.Properties.LifecycleConfiguration={Rules:[]};return n.Properties.LifecycleConfiguration.Rules.push({Id:"IntelligentTieringRule",Status:"Enabled",Transitions:[{TransitionInDays:0,StorageClass:"INTELLIGENT_TIERING"}]}),n}static addLambdaNotification(n,i){if(!n.Properties)n.Properties={};if(!n.Properties.NotificationConfiguration)n.Properties.NotificationConfiguration={};if(!n.Properties.NotificationConfiguration.LambdaConfigurations)n.Properties.NotificationConfiguration.LambdaConfigurations=[];let s={Event:i.events[0],Function:i.functionArn};if(i.filter)s.Filter={S3Key:{Rules:[...i.filter.prefix?[{Name:"prefix",Value:i.filter.prefix}]:[],...i.filter.suffix?[{Name:"suffix",Value:i.filter.suffix}]:[]]}};for(let o of i.events){let c={...s,Event:o};n.Properties.NotificationConfiguration.LambdaConfigurations.push(c)}return n}static Notifications={onObjectCreated:(n)=>({functionArn:n,events:["s3:ObjectCreated:*"]}),onObjectRemoved:(n)=>({functionArn:n,events:["s3:ObjectRemoved:*"]}),onImageUpload:(n,i)=>({functionArn:n,events:["s3:ObjectCreated:*"],filter:{prefix:i,suffix:".jpg"}}),onFileType:(n,i,s)=>({functionArn:n,events:["s3:ObjectCreated:*"],filter:{prefix:s,suffix:i}}),onFolderUpload:(n,i)=>({functionArn:n,events:["s3:ObjectCreated:*"],filter:{prefix:i.endsWith("/")?i:`${i}/`}})};static createBackupPlan(n){let{name:i,slug:s,environment:o,bucketLogicalIds:c,retentionDays:u,schedule:d="cron(0 5 * * ? *)",vaultName:g,enableContinuousBackup:y=!1,moveToColdStorageAfterDays:h}=n,b=g||r({slug:s,environment:o,resourceType:"backup-vault",suffix:i}),v=t(b),A={Type:"AWS::Backup::BackupVault",Properties:{BackupVaultName:b}},T=r({slug:s,environment:o,resourceType:"backup-role",suffix:i}),R=t(T),P={Type:"AWS::IAM::Role",Properties:{RoleName:T,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"backup.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSBackupServiceRolePolicyForBackup","arn:aws:iam::aws:policy/service-role/AWSBackupServiceRolePolicyForRestores"]}},I=r({slug:s,environment:o,resourceType:"backup-plan",suffix:i}),M=t(I),L={DeleteAfterDays:u};if(h&&h<u)L.MoveToColdStorageAfterDays=h;let N={Type:"AWS::Backup::BackupPlan",Properties:{BackupPlan:{BackupPlanName:I,BackupPlanRule:[{RuleName:`${i}-daily-backup`,TargetBackupVault:x.Ref(v),ScheduleExpression:d,StartWindowMinutes:60,CompletionWindowMinutes:120,Lifecycle:L,EnableContinuousBackup:y}]}}},O=r({slug:s,environment:o,resourceType:"backup-selection",suffix:i}),B=t(O),F=c.map((j)=>x.GetAtt(j,"Arn")),U={Type:"AWS::Backup::BackupSelection",Properties:{BackupPlanId:x.Ref(M),BackupSelection:{SelectionName:O,IamRoleArn:x.GetAtt(R,"Arn"),Resources:F}}};return{vault:A,plan:N,selection:U,role:P,vaultLogicalId:v,planLogicalId:M,selectionLogicalId:B,roleLogicalId:R}}static BackupSchedules={HOURLY:"cron(0 * * * ? *)",DAILY_5AM:"cron(0 5 * * ? *)",DAILY_MIDNIGHT:"cron(0 0 * * ? *)",WEEKLY_SUNDAY:"cron(0 5 ? * SUN *)",WEEKLY_SATURDAY:"cron(0 5 ? * SAT *)",MONTHLY_FIRST:"cron(0 5 1 * ? *)",EVERY_12_HOURS:"cron(0 */12 * * ? *)",EVERY_6_HOURS:"cron(0 */6 * * ? *)"};static BackupRetention={ONE_DAY:1,ONE_WEEK:7,TWO_WEEKS:14,ONE_MONTH:30,THREE_MONTHS:90,SIX_MONTHS:180,ONE_YEAR:365,TWO_YEARS:730,FIVE_YEARS:1825,SEVEN_YEARS:2555};static createWwwRedirectBucket(n){let{slug:i,environment:s,sourceDomain:o,targetDomain:c,protocol:u="https"}=n,d=r({slug:i,environment:s,resourceType:"s3",suffix:"www-redirect"}),g=t(d),y={Type:"AWS::S3::Bucket",Properties:{BucketName:o,WebsiteConfiguration:{RedirectAllRequestsTo:{HostName:c,Protocol:u}},PublicAccessBlockConfiguration:{BlockPublicAcls:!1,BlockPublicPolicy:!1,IgnorePublicAcls:!1,RestrictPublicBuckets:!1}}},h={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:x.Ref(g),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadForRedirect",Effect:"Allow",Principal:"*",Action:["s3:GetObject"],Resource:[x.Join("",[x.GetAtt(g,"Arn"),"/*"])]}]}}};return{bucket:y,bucketPolicy:h,logicalId:g}}static createDocsBucket(n){let{slug:i,environment:s,domain:o}=n,c=o||r({slug:i,environment:s,resourceType:"s3",suffix:"docs"}),u=t(c);return{bucket:{Type:"AWS::S3::Bucket",Properties:{BucketName:c,BucketEncryption:{ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]},PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},Tags:[{Key:"backup",Value:"weekly"}]}},logicalId:u}}static createEmailBucket(n){let{slug:i,environment:s}=n,o=r({slug:i,environment:s,resourceType:"s3",suffix:"email"}),c=t(o),u={Type:"AWS::S3::Bucket",Properties:{BucketName:o,BucketEncryption:{ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]},PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},LifecycleConfiguration:{Rules:[{Id:"EmailRetention",Status:"Enabled",ExpirationInDays:90,Transitions:[{TransitionInDays:30,StorageClass:"STANDARD_IA"}]}]}}},d={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:x.Ref(c),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowSESPuts",Effect:"Allow",Principal:{Service:"ses.amazonaws.com"},Action:"s3:PutObject",Resource:x.Join("",[x.GetAtt(c,"Arn"),"/*"]),Condition:{StringEquals:{"AWS:SourceAccount":x.Ref("AWS::AccountId")}}}]}}};return{bucket:u,bucketPolicy:d,logicalId:c}}static docsExist(n={}){let{projectRoot:i=process.cwd(),docsPaths:s=["docs","documentation","doc"]}=n;for(let o of s){let c=Pe(i,o);if(He(c)){let u=["dist","build",".bunpress/dist","_site","out","public"];for(let d of u){let g=Pe(c,d);if(He(g))try{if(Sr(g).length>0)return{exists:!0,path:c,hasDistFolder:!0,distPath:g}}catch{}}return{exists:!0,path:c,hasDistFolder:!1,distPath:null}}}return{exists:!1,path:null,hasDistFolder:!1,distPath:null}}static createDocsBucketIfExists(n){let i=xe.docsExist({projectRoot:n.projectRoot,docsPaths:n.docsPaths});if(!i.exists)return{bucket:null,logicalId:null,docsInfo:i};let s=xe.createDocsBucket({slug:n.slug,environment:n.environment,domain:n.domain});return{bucket:s.bucket,bucketPolicy:s.bucketPolicy,logicalId:s.logicalId,docsInfo:i}}static createPrivateBucket(n){let{slug:i,environment:s,enableVersioning:o=!0,retentionDays:c,encryptionKeyArn:u}=n,d=r({slug:i,environment:s,resourceType:"s3",suffix:"private"}),g=t(d);return{bucket:{Type:"AWS::S3::Bucket",Properties:{BucketName:d,BucketEncryption:{ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:u?{SSEAlgorithm:"aws:kms",KMSMasterKeyID:u}:{SSEAlgorithm:"AES256"}}]},PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},VersioningConfiguration:o?{Status:"Enabled"}:void 0,LifecycleConfiguration:c?{Rules:[{Id:"RetentionPolicy",Status:"Enabled",ExpirationInDays:c}]}:void 0,Tags:[{Key:"backup",Value:"daily"}]}},logicalId:g}}static checkSourcePaths(n={}){let{projectRoot:i=process.cwd(),paths:s={}}=n,o=s.web||"views/web/dist",c=s.docs||"docs/dist",u=s.private||"private";return{web:{exists:He(Pe(i,o)),path:Pe(i,o)},docs:{exists:He(Pe(i,c)),path:Pe(i,c)},private:{exists:He(Pe(i,u)),path:Pe(i,u)}}}static createDeploymentBuckets(n){let{slug:i,environment:s,domain:o,projectRoot:c,paths:u}=n,d=xe.checkSourcePaths({projectRoot:c,paths:u}),g={},y={web:!1,docs:!1,private:!1},h=xe.createBucket({name:"web",slug:i,environment:s,public:!1,versioning:!1,encryption:!0});if(g[h.logicalId]=h.bucket,y.web=!0,d.docs.exists){let b=xe.createDocsBucket({slug:i,environment:s,domain:o?`docs.${o}`:void 0});if(g[b.logicalId]=b.bucket,b.bucketPolicy)g[`${b.logicalId}Policy`]=b.bucketPolicy;y.docs=!0}if(d.private.exists){let b=xe.createPrivateBucket({slug:i,environment:s,enableVersioning:!0});g[b.logicalId]=b.bucket,y.private=!0}return{resources:g,created:y,sourcePaths:d}}}class Ze{static createRepository(n){let{name:i,slug:s,environment:o,scanOnPush:c=!0,imageMutability:u="MUTABLE",encryption:d="AES256",kmsKey:g,lifecyclePolicy:y,tags:h}=n,b=r({slug:s,environment:o,resourceType:"ecr",suffix:i}),v=t(b),A={Type:"AWS::ECR::Repository",Properties:{RepositoryName:b,ImageTagMutability:u,ImageScanningConfiguration:{ScanOnPush:c},EncryptionConfiguration:{EncryptionType:d,...g&&d==="KMS"?{KmsKey:g}:{}}}};if(y)A.Properties.LifecyclePolicy={LifecyclePolicyText:JSON.stringify(Ze.generateLifecyclePolicy(y))};if(h)A.Properties.Tags=Object.entries(h).map(([T,R])=>({Key:T,Value:R}));return{repository:A,logicalId:v}}static generateLifecyclePolicy(n){let i=[];if(n.untaggedImageExpireDays!==void 0)i.push({rulePriority:1,description:"Delete untagged images",selection:{tagStatus:"untagged",countType:"sinceImagePushed",countNumber:n.untaggedImageExpireDays,countUnit:"days"},action:{type:"expire"}});if(n.maxImageCount!==void 0)i.push({rulePriority:i.length+1,description:"Keep only most recent images",selection:{tagStatus:"any",countType:"imageCountMoreThan",countNumber:n.maxImageCount},action:{type:"expire"}});if(n.maxImageAgeDays!==void 0)i.push({rulePriority:i.length+1,description:"Delete images older than specified days",selection:{tagStatus:"any",countType:"sinceImagePushed",countNumber:n.maxImageAgeDays,countUnit:"days"},action:{type:"expire"}});return{rules:i}}static LifecyclePolicies={production:{maxImageCount:10,untaggedImageExpireDays:7},development:{maxImageCount:5,untaggedImageExpireDays:3},minimal:{maxImageCount:3,untaggedImageExpireDays:1},archive:{maxImageCount:50,untaggedImageExpireDays:30}};static enableImmutableTags(n){if(!n.Properties)n.Properties={};return n.Properties.ImageTagMutability="IMMUTABLE",n}static enableScanOnPush(n){if(!n.Properties)n.Properties={};return n.Properties.ImageScanningConfiguration={ScanOnPush:!0},n}static setLifecyclePolicy(n,i){if(!n.Properties)n.Properties={};return n.Properties.LifecyclePolicy={LifecyclePolicyText:JSON.stringify(Ze.generateLifecyclePolicy(i))},n}static addCrossAccountAccess(n,i){if(!n.Properties)n.Properties={};return n.Properties.RepositoryPolicyText={Version:"2012-10-17",Statement:[{Sid:"CrossAccountPull",Effect:"Allow",Principal:{AWS:i.map((s)=>`arn:aws:iam::${s}:root`)},Action:["ecr:GetDownloadUrlForLayer","ecr:BatchGetImage","ecr:BatchCheckLayerAvailability"]}]},n}static addLambdaAccess(n){if(!n.Properties)n.Properties={};return n.Properties.RepositoryPolicyText={Version:"2012-10-17",Statement:[{Sid:"LambdaECRImageRetrievalPolicy",Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:["ecr:GetDownloadUrlForLayer","ecr:BatchGetImage"]}]},n}static generateBunDockerfile(n){let{baseImage:i="oven/bun:1-debian",serverPath:s,port:o=3000,additionalDirs:c=[],healthCheckEndpoint:u="/health",nodeCompatible:d=!1,envVars:g={},buildCommands:y=[],runCommand:h}=n,b=["app","config",...c],v=h||`bun run ${s}`,A=`# Multi-stage build for Bun application
11
+ `)}import{existsSync as He,readdirSync as Sr}from"node:fs";import{join as Pe}from"node:path";class xe{static createBucket(n){let{name:i,bucketName:s,slug:o,environment:c,public:u=!1,versioning:d=!1,website:g=!1,encryption:y=!0,intelligentTiering:h=!1,cors:b,lifecycleRules:v}=n,A=s??r({slug:o,environment:c,resourceType:"s3",suffix:i}),T=t(A),R={Type:"AWS::S3::Bucket",Properties:{BucketName:A}};if(y)R.Properties.BucketEncryption={ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]};if(d)R.Properties.VersioningConfiguration={Status:"Enabled"};if(g)R.Properties.WebsiteConfiguration={IndexDocument:"index.html",ErrorDocument:"error.html"};if(!u)R.Properties.PublicAccessBlockConfiguration={BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0};if(b&&b.length>0)R.Properties.CorsConfiguration={CorsRules:b.map((I)=>({AllowedOrigins:I.allowedOrigins,AllowedMethods:I.allowedMethods,AllowedHeaders:I.allowedHeaders,MaxAge:I.maxAge}))};if(v&&v.length>0)R.Properties.LifecycleConfiguration={Rules:v.map((I)=>({Id:I.id,Status:I.enabled?"Enabled":"Disabled",ExpirationInDays:I.expirationDays,Transitions:I.transitions?.map((M)=>({TransitionInDays:M.days,StorageClass:M.storageClass}))}))};if(h&&v){let I={id:"IntelligentTieringRule",enabled:!0,transitions:[{days:0,storageClass:"INTELLIGENT_TIERING"}]};if(!R.Properties.LifecycleConfiguration)R.Properties.LifecycleConfiguration={Rules:[]};R.Properties.LifecycleConfiguration.Rules.push({Id:I.id,Status:"Enabled",Transitions:I.transitions?.map((M)=>({TransitionInDays:M.days,StorageClass:M.storageClass}))})}let P;if(u)P={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:x.Ref(T),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadGetObject",Effect:"Allow",Principal:"*",Action:["s3:GetObject"],Resource:[x.Join("",[x.GetAtt(T,"Arn"),"/*"])]}]}}};return{bucket:R,bucketPolicy:P,logicalId:T}}static enableVersioning(n){if(!n.Properties)n.Properties={};return n.Properties.VersioningConfiguration={Status:"Enabled"},n}static enableWebsiteHosting(n,i="index.html",s="error.html"){if(!n.Properties)n.Properties={};return n.Properties.WebsiteConfiguration={IndexDocument:i,ErrorDocument:s},n}static setLifecycleRules(n,i){if(!n.Properties)n.Properties={};return n.Properties.LifecycleConfiguration={Rules:i.map((s)=>({Id:s.id,Status:s.enabled?"Enabled":"Disabled",ExpirationInDays:s.expirationDays,Transitions:s.transitions?.map((o)=>({TransitionInDays:o.days,StorageClass:o.storageClass}))}))},n}static enableIntelligentTiering(n){if(!n.Properties)n.Properties={};if(!n.Properties.LifecycleConfiguration)n.Properties.LifecycleConfiguration={Rules:[]};return n.Properties.LifecycleConfiguration.Rules.push({Id:"IntelligentTieringRule",Status:"Enabled",Transitions:[{TransitionInDays:0,StorageClass:"INTELLIGENT_TIERING"}]}),n}static addLambdaNotification(n,i){if(!n.Properties)n.Properties={};if(!n.Properties.NotificationConfiguration)n.Properties.NotificationConfiguration={};if(!n.Properties.NotificationConfiguration.LambdaConfigurations)n.Properties.NotificationConfiguration.LambdaConfigurations=[];let s={Event:i.events[0],Function:i.functionArn};if(i.filter)s.Filter={S3Key:{Rules:[...i.filter.prefix?[{Name:"prefix",Value:i.filter.prefix}]:[],...i.filter.suffix?[{Name:"suffix",Value:i.filter.suffix}]:[]]}};for(let o of i.events){let c={...s,Event:o};n.Properties.NotificationConfiguration.LambdaConfigurations.push(c)}return n}static Notifications={onObjectCreated:(n)=>({functionArn:n,events:["s3:ObjectCreated:*"]}),onObjectRemoved:(n)=>({functionArn:n,events:["s3:ObjectRemoved:*"]}),onImageUpload:(n,i)=>({functionArn:n,events:["s3:ObjectCreated:*"],filter:{prefix:i,suffix:".jpg"}}),onFileType:(n,i,s)=>({functionArn:n,events:["s3:ObjectCreated:*"],filter:{prefix:s,suffix:i}}),onFolderUpload:(n,i)=>({functionArn:n,events:["s3:ObjectCreated:*"],filter:{prefix:i.endsWith("/")?i:`${i}/`}})};static createBackupPlan(n){let{name:i,slug:s,environment:o,bucketLogicalIds:c,retentionDays:u,schedule:d="cron(0 5 * * ? *)",vaultName:g,enableContinuousBackup:y=!1,moveToColdStorageAfterDays:h}=n,b=g||r({slug:s,environment:o,resourceType:"backup-vault",suffix:i}),v=t(b),A={Type:"AWS::Backup::BackupVault",Properties:{BackupVaultName:b}},T=r({slug:s,environment:o,resourceType:"backup-role",suffix:i}),R=t(T),P={Type:"AWS::IAM::Role",Properties:{RoleName:T,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"backup.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSBackupServiceRolePolicyForBackup","arn:aws:iam::aws:policy/service-role/AWSBackupServiceRolePolicyForRestores"]}},I=r({slug:s,environment:o,resourceType:"backup-plan",suffix:i}),M=t(I),L={DeleteAfterDays:u};if(h&&h<u)L.MoveToColdStorageAfterDays=h;let N={Type:"AWS::Backup::BackupPlan",Properties:{BackupPlan:{BackupPlanName:I,BackupPlanRule:[{RuleName:`${i}-daily-backup`,TargetBackupVault:x.Ref(v),ScheduleExpression:d,StartWindowMinutes:60,CompletionWindowMinutes:120,Lifecycle:L,EnableContinuousBackup:y}]}}},O=r({slug:s,environment:o,resourceType:"backup-selection",suffix:i}),B=t(O),F=c.map((j)=>x.GetAtt(j,"Arn")),U={Type:"AWS::Backup::BackupSelection",Properties:{BackupPlanId:x.Ref(M),BackupSelection:{SelectionName:O,IamRoleArn:x.GetAtt(R,"Arn"),Resources:F}}};return{vault:A,plan:N,selection:U,role:P,vaultLogicalId:v,planLogicalId:M,selectionLogicalId:B,roleLogicalId:R}}static BackupSchedules={HOURLY:"cron(0 * * * ? *)",DAILY_5AM:"cron(0 5 * * ? *)",DAILY_MIDNIGHT:"cron(0 0 * * ? *)",WEEKLY_SUNDAY:"cron(0 5 ? * SUN *)",WEEKLY_SATURDAY:"cron(0 5 ? * SAT *)",MONTHLY_FIRST:"cron(0 5 1 * ? *)",EVERY_12_HOURS:"cron(0 */12 * * ? *)",EVERY_6_HOURS:"cron(0 */6 * * ? *)"};static BackupRetention={ONE_DAY:1,ONE_WEEK:7,TWO_WEEKS:14,ONE_MONTH:30,THREE_MONTHS:90,SIX_MONTHS:180,ONE_YEAR:365,TWO_YEARS:730,FIVE_YEARS:1825,SEVEN_YEARS:2555};static createWwwRedirectBucket(n){let{slug:i,environment:s,sourceDomain:o,targetDomain:c,protocol:u="https"}=n,d=r({slug:i,environment:s,resourceType:"s3",suffix:"www-redirect"}),g=t(d),y={Type:"AWS::S3::Bucket",Properties:{BucketName:o,WebsiteConfiguration:{RedirectAllRequestsTo:{HostName:c,Protocol:u}},PublicAccessBlockConfiguration:{BlockPublicAcls:!1,BlockPublicPolicy:!1,IgnorePublicAcls:!1,RestrictPublicBuckets:!1}}},h={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:x.Ref(g),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadForRedirect",Effect:"Allow",Principal:"*",Action:["s3:GetObject"],Resource:[x.Join("",[x.GetAtt(g,"Arn"),"/*"])]}]}}};return{bucket:y,bucketPolicy:h,logicalId:g}}static createDocsBucket(n){let{slug:i,environment:s,domain:o}=n,c=o||r({slug:i,environment:s,resourceType:"s3",suffix:"docs"}),u=t(c);return{bucket:{Type:"AWS::S3::Bucket",Properties:{BucketName:c,BucketEncryption:{ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]},PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},Tags:[{Key:"backup",Value:"weekly"}]}},logicalId:u}}static createEmailBucket(n){let{slug:i,environment:s}=n,o=r({slug:i,environment:s,resourceType:"s3",suffix:"email"}),c=t(o),u={Type:"AWS::S3::Bucket",Properties:{BucketName:o,BucketEncryption:{ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]},PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},LifecycleConfiguration:{Rules:[{Id:"EmailRetention",Status:"Enabled",ExpirationInDays:90,Transitions:[{TransitionInDays:30,StorageClass:"STANDARD_IA"}]}]}}},d={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:x.Ref(c),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowSESPuts",Effect:"Allow",Principal:{Service:"ses.amazonaws.com"},Action:"s3:PutObject",Resource:x.Join("",[x.GetAtt(c,"Arn"),"/*"]),Condition:{StringEquals:{"AWS:SourceAccount":x.Ref("AWS::AccountId")}}}]}}};return{bucket:u,bucketPolicy:d,logicalId:c}}static docsExist(n={}){let{projectRoot:i=process.cwd(),docsPaths:s=["docs","documentation","doc"]}=n;for(let o of s){let c=Pe(i,o);if(He(c)){let u=["dist","build",".bunpress/dist","_site","out","public"];for(let d of u){let g=Pe(c,d);if(He(g))try{if(Sr(g).length>0)return{exists:!0,path:c,hasDistFolder:!0,distPath:g}}catch{}}return{exists:!0,path:c,hasDistFolder:!1,distPath:null}}}return{exists:!1,path:null,hasDistFolder:!1,distPath:null}}static createDocsBucketIfExists(n){let i=xe.docsExist({projectRoot:n.projectRoot,docsPaths:n.docsPaths});if(!i.exists)return{bucket:null,logicalId:null,docsInfo:i};let s=xe.createDocsBucket({slug:n.slug,environment:n.environment,domain:n.domain});return{bucket:s.bucket,bucketPolicy:s.bucketPolicy,logicalId:s.logicalId,docsInfo:i}}static createPrivateBucket(n){let{slug:i,environment:s,enableVersioning:o=!0,retentionDays:c,encryptionKeyArn:u}=n,d=r({slug:i,environment:s,resourceType:"s3",suffix:"private"}),g=t(d);return{bucket:{Type:"AWS::S3::Bucket",Properties:{BucketName:d,BucketEncryption:{ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:u?{SSEAlgorithm:"aws:kms",KMSMasterKeyID:u}:{SSEAlgorithm:"AES256"}}]},PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},VersioningConfiguration:o?{Status:"Enabled"}:void 0,LifecycleConfiguration:c?{Rules:[{Id:"RetentionPolicy",Status:"Enabled",ExpirationInDays:c}]}:void 0,Tags:[{Key:"backup",Value:"daily"}]}},logicalId:g}}static checkSourcePaths(n={}){let{projectRoot:i=process.cwd(),paths:s={}}=n,o=s.web||"views/web/dist",c=s.docs||"docs/dist",u=s.private||"private";return{web:{exists:He(Pe(i,o)),path:Pe(i,o)},docs:{exists:He(Pe(i,c)),path:Pe(i,c)},private:{exists:He(Pe(i,u)),path:Pe(i,u)}}}static createDeploymentBuckets(n){let{slug:i,environment:s,domain:o,projectRoot:c,paths:u}=n,d=xe.checkSourcePaths({projectRoot:c,paths:u}),g={},y={web:!1,docs:!1,private:!1},h=xe.createBucket({name:"web",slug:i,environment:s,public:!1,versioning:!1,encryption:!0});if(g[h.logicalId]=h.bucket,y.web=!0,d.docs.exists){let b=xe.createDocsBucket({slug:i,environment:s,domain:o?`docs.${o}`:void 0});if(g[b.logicalId]=b.bucket,b.bucketPolicy)g[`${b.logicalId}Policy`]=b.bucketPolicy;y.docs=!0}if(d.private.exists){let b=xe.createPrivateBucket({slug:i,environment:s,enableVersioning:!0});g[b.logicalId]=b.bucket,y.private=!0}return{resources:g,created:y,sourcePaths:d}}}class et{static createRepository(n){let{name:i,slug:s,environment:o,scanOnPush:c=!0,imageMutability:u="MUTABLE",encryption:d="AES256",kmsKey:g,lifecyclePolicy:y,tags:h}=n,b=r({slug:s,environment:o,resourceType:"ecr",suffix:i}),v=t(b),A={Type:"AWS::ECR::Repository",Properties:{RepositoryName:b,ImageTagMutability:u,ImageScanningConfiguration:{ScanOnPush:c},EncryptionConfiguration:{EncryptionType:d,...g&&d==="KMS"?{KmsKey:g}:{}}}};if(y)A.Properties.LifecyclePolicy={LifecyclePolicyText:JSON.stringify(et.generateLifecyclePolicy(y))};if(h)A.Properties.Tags=Object.entries(h).map(([T,R])=>({Key:T,Value:R}));return{repository:A,logicalId:v}}static generateLifecyclePolicy(n){let i=[];if(n.untaggedImageExpireDays!==void 0)i.push({rulePriority:1,description:"Delete untagged images",selection:{tagStatus:"untagged",countType:"sinceImagePushed",countNumber:n.untaggedImageExpireDays,countUnit:"days"},action:{type:"expire"}});if(n.maxImageCount!==void 0)i.push({rulePriority:i.length+1,description:"Keep only most recent images",selection:{tagStatus:"any",countType:"imageCountMoreThan",countNumber:n.maxImageCount},action:{type:"expire"}});if(n.maxImageAgeDays!==void 0)i.push({rulePriority:i.length+1,description:"Delete images older than specified days",selection:{tagStatus:"any",countType:"sinceImagePushed",countNumber:n.maxImageAgeDays,countUnit:"days"},action:{type:"expire"}});return{rules:i}}static LifecyclePolicies={production:{maxImageCount:10,untaggedImageExpireDays:7},development:{maxImageCount:5,untaggedImageExpireDays:3},minimal:{maxImageCount:3,untaggedImageExpireDays:1},archive:{maxImageCount:50,untaggedImageExpireDays:30}};static enableImmutableTags(n){if(!n.Properties)n.Properties={};return n.Properties.ImageTagMutability="IMMUTABLE",n}static enableScanOnPush(n){if(!n.Properties)n.Properties={};return n.Properties.ImageScanningConfiguration={ScanOnPush:!0},n}static setLifecyclePolicy(n,i){if(!n.Properties)n.Properties={};return n.Properties.LifecyclePolicy={LifecyclePolicyText:JSON.stringify(et.generateLifecyclePolicy(i))},n}static addCrossAccountAccess(n,i){if(!n.Properties)n.Properties={};return n.Properties.RepositoryPolicyText={Version:"2012-10-17",Statement:[{Sid:"CrossAccountPull",Effect:"Allow",Principal:{AWS:i.map((s)=>`arn:aws:iam::${s}:root`)},Action:["ecr:GetDownloadUrlForLayer","ecr:BatchGetImage","ecr:BatchCheckLayerAvailability"]}]},n}static addLambdaAccess(n){if(!n.Properties)n.Properties={};return n.Properties.RepositoryPolicyText={Version:"2012-10-17",Statement:[{Sid:"LambdaECRImageRetrievalPolicy",Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:["ecr:GetDownloadUrlForLayer","ecr:BatchGetImage"]}]},n}static generateBunDockerfile(n){let{baseImage:i="oven/bun:1-debian",serverPath:s,port:o=3000,additionalDirs:c=[],healthCheckEndpoint:u="/health",nodeCompatible:d=!1,envVars:g={},buildCommands:y=[],runCommand:h}=n,b=["app","config",...c],v=h||`bun run ${s}`,A=`# 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", "${s}"]
65
- `,A}static generateDockerBuildCommands(n){let{repositoryUri:i,tag:s="latest",dockerfilePath:o="Dockerfile",context:c=".",additionalTags:u=[],buildArgs:d={},platform:g="linux/amd64",noCache:y=!1}=n,h=`${i}:${s}`,b=[s,...u],v=`docker build -f ${o} -t ${h}`;if(g)v+=` --platform ${g}`;if(y)v+=" --no-cache";for(let[R,P]of Object.entries(d))v+=` --build-arg ${R}=${P}`;v+=` ${c}`;let A=b.slice(1).map((R)=>`docker tag ${h} ${i}:${R}`),T=b.map((R)=>`docker push ${i}:${R}`);return{build:v,tag:A,push:T,all:[v,...A,...T]}}static generateEcrLoginCommand(n,i){return`aws ecr get-login-password --region ${n} | docker login --username AWS --password-stdin ${i}.dkr.ecr.${n}.amazonaws.com`}static buildRepositoryUri(n){return`${n.accountId}.dkr.ecr.${n.region}.amazonaws.com/${n.repositoryName}`}static generateImageTags(n){let i=["latest"];if(n.version){i.push(n.version);let s=n.version.split(".");if(s.length>=2)i.push(`${s[0]}.${s[1]}`);if(s.length>=1)i.push(s[0])}if(n.gitSha)i.push(n.gitSha.substring(0,7)),i.push(n.gitSha);if(n.gitBranch){let s=n.gitBranch.replace(/[^a-zA-Z0-9.-]/g,"-").replace(/^-+|-+$/g,"");i.push(s)}if(n.environment)i.push(n.environment);if(n.timestamp){let s=new Date().toISOString().replace(/[:.]/g,"-").substring(0,19);i.push(s)}return[...new Set(i)]}static DeploymentWorkflow={generateDeployScript:(n)=>{let i=Ze.buildRepositoryUri({accountId:n.accountId,region:n.region,repositoryName:n.repositoryName}),s=n.tags||["latest"],o=s[0];return`#!/bin/bash
65
+ `,A}static generateDockerBuildCommands(n){let{repositoryUri:i,tag:s="latest",dockerfilePath:o="Dockerfile",context:c=".",additionalTags:u=[],buildArgs:d={},platform:g="linux/amd64",noCache:y=!1}=n,h=`${i}:${s}`,b=[s,...u],v=`docker build -f ${o} -t ${h}`;if(g)v+=` --platform ${g}`;if(y)v+=" --no-cache";for(let[R,P]of Object.entries(d))v+=` --build-arg ${R}=${P}`;v+=` ${c}`;let A=b.slice(1).map((R)=>`docker tag ${h} ${i}:${R}`),T=b.map((R)=>`docker push ${i}:${R}`);return{build:v,tag:A,push:T,all:[v,...A,...T]}}static generateEcrLoginCommand(n,i){return`aws ecr get-login-password --region ${n} | docker login --username AWS --password-stdin ${i}.dkr.ecr.${n}.amazonaws.com`}static buildRepositoryUri(n){return`${n.accountId}.dkr.ecr.${n.region}.amazonaws.com/${n.repositoryName}`}static generateImageTags(n){let i=["latest"];if(n.version){i.push(n.version);let s=n.version.split(".");if(s.length>=2)i.push(`${s[0]}.${s[1]}`);if(s.length>=1)i.push(s[0])}if(n.gitSha)i.push(n.gitSha.substring(0,7)),i.push(n.gitSha);if(n.gitBranch){let s=n.gitBranch.replace(/[^a-zA-Z0-9.-]/g,"-").replace(/^-+|-+$/g,"");i.push(s)}if(n.environment)i.push(n.environment);if(n.timestamp){let s=new Date().toISOString().replace(/[:.]/g,"-").substring(0,19);i.push(s)}return[...new Set(i)]}static DeploymentWorkflow={generateDeployScript:(n)=>{let i=et.buildRepositoryUri({accountId:n.accountId,region:n.region,repositoryName:n.repositoryName}),s=n.tags||["latest"],o=s[0];return`#!/bin/bash
66
66
  set -e
67
67
 
68
68
  # Configuration
@@ -73,7 +73,7 @@ IMAGE_URI="${i}"
73
73
  DOCKERFILE="${n.dockerfilePath||"Dockerfile"}"
74
74
 
75
75
  echo "=== ECR Login ==="
76
- ${Ze.generateEcrLoginCommand(n.region,n.accountId)}
76
+ ${et.generateEcrLoginCommand(n.region,n.accountId)}
77
77
 
78
78
  echo "=== Building Image ==="
79
79
  docker build -f $DOCKERFILE -t $IMAGE_URI:${o} --platform linux/amd64 .
@@ -91,7 +91,7 @@ echo "Image: $IMAGE_URI:${o}"
91
91
  docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG
92
92
  docker push $ECR_REGISTRY/$ECR_REPOSITORY:latest`},...n.ecsCluster&&n.ecsService?[{name:"Deploy to ECS",run:`aws ecs update-service --cluster ${n.ecsCluster} --service ${n.ecsService} --force-new-deployment`}]:[]]}}};return`# Generated by ts-cloud
93
93
  ${JSON.stringify(i,null,2).replace(/"/g,"").replace(/,\n/g,`
94
- `)}`}};static DockerfileTemplates={bunServer:(n,i=3000)=>Ze.generateBunDockerfile({serverPath:n,port:i}),bunWithBuild:(n,i,s=3000)=>Ze.generateBunDockerfile({serverPath:n,port:s,buildCommands:[i]}),bunFullStack:(n,i=3000)=>Ze.generateBunDockerfile({serverPath:n,port:i,additionalDirs:["public","views","dist"],buildCommands:["bun run build"]}),bunApi:(n,i=3000)=>Ze.generateBunDockerfile({serverPath:n,port:i,healthCheckEndpoint:"/api/health"})}}var dl=[400,403,404,416,429,500,502,503,504],bm=[500,502,503,504],Cm=["GET","HEAD","OPTIONS"],KI="-failover-group",Em=["default","media-quality-based"],vm={min:1,max:3},Tm={min:1,max:10};function Ho(n){if(n===void 0)return[...bm];if(n.length===0)throw Error(`CloudFront origin failover: statusCodes must list at least one code (allowed: ${dl.join(", ")}). Omit it to use the default ${bm.join(", ")}.`);let i=n.filter((s)=>!dl.includes(s));if(i.length>0)throw Error(`CloudFront origin failover: ${i.join(", ")} ${i.length===1?"is not a status code":"are not status codes"} CloudFront can fail over on. Allowed: ${dl.join(", ")}.`);return[...new Set(n)].sort((s,o)=>s-o)}function ll(n){let{primaryOriginId:i,secondaryOriginId:s}=n;if(!i||!s)throw Error("CloudFront origin failover: both a primary and a secondary origin id are required");if(i===s)throw Error(`CloudFront origin failover: the secondary origin must differ from the primary (both are "${i}")`);let o=Ho(n.statusCodes);return nn(n.selectionCriteria),{Id:n.groupId??`${i}-failover-group`,FailoverCriteria:{StatusCodes:{Quantity:o.length,Items:o}},Members:{Quantity:2,Items:[{OriginId:i},{OriginId:s}]},...n.selectionCriteria?{SelectionCriteria:n.selectionCriteria}:{}}}function nn(n,i="the origin group"){if(n===void 0)return;if(!Em.includes(n))throw Error(`CloudFront origin failover: ${i} has selection criteria ${JSON.stringify(n)}. Allowed: ${Em.join(", ")}.`)}function at(n,i,s){if(typeof n!=="number"||!Number.isInteger(n)||n<i.min||n>i.max)throw Error(`CloudFront origin: ${s} must be a whole number from ${i.min} to ${i.max}, got ${JSON.stringify(n)}.`)}function de(n,i="the origin"){let s={};if(n?.connectionAttempts!==void 0)at(n.connectionAttempts,vm,`${i} connectionAttempts`),s.ConnectionAttempts=n.connectionAttempts;if(n?.connectionTimeout!==void 0)at(n.connectionTimeout,Tm,`${i} connectionTimeout (seconds)`),s.ConnectionTimeout=n.connectionTimeout;return s}function ln(n){return{Quantity:1,Items:[ll(n)]}}function Pt(n,i="the cache behavior"){let o=(Array.isArray(n)?n:n?.Items??[]).filter((c)=>!Cm.includes(c.toUpperCase()));if(o.length>0)throw Error(`CloudFront origin failover: ${i} allows ${o.join(", ")}, but a cache behavior that targets an origin group may only allow ${Cm.join(", ")}. CloudFront never fails over a write, so point the write paths at a single origin in their own cache behavior.`)}function Go(n){return/\.s3[.-](?:[a-z0-9-]+\.)?amazonaws\.com(?:\.cn)?$/i.test(n)&&!/s3-website/i.test(n)}function je(n){if(!n)return[];if(Array.isArray(n))return n;return n.Items??[]}function Ae(n){return typeof n==="string"?n:void 0}var Cr=/\.mediapackagev2\.[a-z0-9-]+\.amazonaws\.com$/i;function kt(n,i="the distribution"){let s=je(n.Origins),o=new Set(s.map((b)=>Ae(b.Id)).filter((b)=>!!b)),c=new Map(s.map((b)=>[Ae(b.Id)??"",b.DomainName])),u=s.some((b)=>Ae(b.Id)===void 0);for(let b of s){let v=Ae(b.Id)??"(unnamed origin)";if(b.ConnectionAttempts!==void 0)at(b.ConnectionAttempts,vm,`${i} origin "${v}" ConnectionAttempts`);if(b.ConnectionTimeout!==void 0)at(b.ConnectionTimeout,Tm,`${i} origin "${v}" ConnectionTimeout (seconds)`)}let d=n.OriginGroups,g=je(d);if(d&&!Array.isArray(d)&&d.Quantity!==void 0&&d.Quantity!==g.length)throw Error(`CloudFront origin failover: ${i} OriginGroups.Quantity is ${d.Quantity} but it lists ${g.length} group(s).`);let y=new Set;for(let b of g){let v=Ae(b.Id);if(b.Id===void 0||b.Id==="")throw Error(`CloudFront origin failover: ${i} has an origin group without an Id.`);let A=`${i} origin group "${v??"(intrinsic id)"}"`;if(v){if(y.has(v))throw Error(`CloudFront origin failover: ${i} declares origin group "${v}" twice.`);if(o.has(v))throw Error(`CloudFront origin failover: ${A} has the same id as an origin. Cache behaviors target groups and origins by id, so the two must differ.`);y.add(v)}let T=b.Members,R=je(T);if(R.length!==2||T?.Quantity!==void 0&&T.Quantity!==R.length)throw Error(`CloudFront origin failover: ${A} must have exactly 2 members (a primary and a secondary), it has ${R.length}${T?.Quantity!==void 0&&T.Quantity!==R.length?` with Quantity ${T.Quantity}`:""}.`);let P=R.map((L)=>Ae(L.OriginId));for(let L of P)if(L&&!o.has(L)&&!u)throw Error(`CloudFront origin failover: ${A} lists member "${L}", which is not an origin of this distribution. Origins: ${[...o].join(", ")||"(none)"}.`);if(P[0]&&P[0]===P[1])throw Error(`CloudFront origin failover: ${A} lists "${P[0]}" as both primary and secondary.`);let I=b.FailoverCriteria?.StatusCodes,M=je(I);if(Ho(M),I?.Quantity!==void 0&&I.Quantity!==M.length)throw Error(`CloudFront origin failover: ${A} FailoverCriteria.StatusCodes.Quantity is ${I.Quantity} but it lists ${M.length} code(s).`);if(nn(b.SelectionCriteria,A),b.SelectionCriteria==="media-quality-based")for(let L of P){let N=L?Ae(c.get(L)):void 0;if(N&&!Cr.test(N))throw Error(`CloudFront origin failover: ${A} uses media-quality-based selection, which only works between AWS Elemental MediaPackage v2 origins, but member "${L}" is ${N}. Use 'default'.`)}}let h=[];if(n.DefaultCacheBehavior)h.push({behavior:n.DefaultCacheBehavior,name:"the default cache behavior"});for(let b of je(n.CacheBehaviors))h.push({behavior:b,name:`the cache behavior for ${JSON.stringify(b.PathPattern)}`});for(let{behavior:b,name:v}of h){let A=Ae(b.TargetOriginId);if(!A)continue;if(y.has(A))Pt(b.AllowedMethods??["GET","HEAD"],`${v} of ${i} (origin group "${A}")`);else if(!o.has(A)&&!u&&g.every((T)=>Ae(T.Id)!==void 0))throw Error(`CloudFront: ${v} of ${i} targets "${A}", which is neither an origin nor an origin group of this distribution.`)}}class Ce{static createDistribution(n){let{slug:i,environment:s,origin:o,customDomain:c,certificateArn:u,errorPages:d,cachePolicy:g,edgeFunctions:y,http3:h=!1,comment:b,failoverOrigin:v}=n,A=r({slug:i,environment:s,resourceType:"cdn"}),T=t(A),R={Id:"DefaultOrigin",DomainName:o.domainName,OriginPath:o.originPath||"",...de(o,"the CDN origin")},P;if(o.type==="s3"){let M=`${T}OAC`;P={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`${A}-oac`,Description:`Origin Access Control for ${A}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},R.OriginAccessControlId=x.Ref(M)}else if(o.type==="alb"||o.type==="custom")R.CustomOriginConfig={HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only"};let I={Type:"AWS::CloudFront::Distribution",Properties:{DistributionConfig:{Enabled:!0,Comment:b||`CDN for ${A}`,DefaultRootObject:"index.html",Origins:[R],DefaultCacheBehavior:{TargetOriginId:"DefaultOrigin",ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0},PriceClass:"PriceClass_100",HttpVersion:h?"http2and3":"http2"}}};if(c&&u)I.Properties.DistributionConfig.Aliases=[c],I.Properties.DistributionConfig.ViewerCertificate={AcmCertificateArn:u,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};if(d&&d.length>0)I.Properties.DistributionConfig.CustomErrorResponses=d.map((M)=>({ErrorCode:M.errorCode,ResponseCode:M.responseCode,ResponsePagePath:M.responsePagePath}));if(y&&y.length>0)I.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations=y.map((M)=>({EventType:M.event,LambdaFunctionARN:M.functionArn}));if(v)Ce.addOriginFailover(I,v);return{distribution:I,originAccessControl:P,logicalId:T}}static addOriginFailover(n,i){let s=n.Properties.DistributionConfig,o=s.DefaultCacheBehavior,c=o.TargetOriginId,u=i.id??"FailoverOrigin";if(s.OriginGroups&&s.OriginGroups.Quantity>0)throw Error("CloudFront origin failover: this distribution already has an origin group");if(Pt(o.AllowedMethods??["GET","HEAD"],"the default cache behavior"),s.Origins.some((b)=>b.Id===u))throw Error(`CloudFront origin failover: an origin with id "${u}" already exists`);let d=ll({primaryOriginId:c,secondaryOriginId:u,statusCodes:i.statusCodes,selectionCriteria:i.selectionCriteria}),g=i.type??(Go(i.domainName)?"s3":"custom"),y={Id:u,DomainName:i.domainName,OriginPath:i.originPath||"",...de(i,"the failover origin")},h=de(i.primary,"the primary origin");if(Object.keys(h).length>0){let b=s.Origins.find((v)=>v.Id===c);if(b)Object.assign(b,h)}if(g==="s3"){let b=s.Origins.find((v)=>v.Id===c);if(y.S3OriginConfig={OriginAccessIdentity:""},b?.OriginAccessControlId)y.OriginAccessControlId=b.OriginAccessControlId}else y.CustomOriginConfig={HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only"};return s.Origins.push(y),s.OriginGroups={Quantity:1,Items:[d]},o.TargetOriginId=d.Id,kt(s),n}static setCustomDomain(n,i,s){return n.Properties.DistributionConfig.Aliases=[i],n.Properties.DistributionConfig.ViewerCertificate={AcmCertificateArn:s,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"},n}static setErrorPages(n,i){return n.Properties.DistributionConfig.CustomErrorResponses=i.map((s)=>({ErrorCode:s.errorCode,ResponseCode:s.responseCode,ResponsePagePath:s.responsePagePath})),n}static enableHttp3(n){return n.Properties.DistributionConfig.HttpVersion="http2and3",n}static addEdgeFunction(n,i,s){if(!n.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations)n.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations=[];return n.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations.push({EventType:i,LambdaFunctionARN:s}),n}static setCachePolicy(n,i){return n.Properties.DistributionConfig.Comment=`${n.Properties.DistributionConfig.Comment||""} (TTL: ${i.default||86400}s)`,n}static createSpaDistribution(n){return Ce.createDistribution({...n,errorPages:[{errorCode:404,responseCode:200,responsePagePath:"/index.html"},{errorCode:403,responseCode:200,responsePagePath:"/index.html"}]})}static createDocsOriginRequestFunction(n){let{slug:i,environment:s}=n,o=r({slug:i,environment:s,resourceType:"edge-docs"}),c=t(o),u=t(`${o}-role`),d=t(`${o}-version`),g={Type:"AWS::IAM::Role",Properties:{RoleName:`${o}-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:["lambda.amazonaws.com","edgelambda.amazonaws.com"]},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"]}},y=`
94
+ `)}`}};static DockerfileTemplates={bunServer:(n,i=3000)=>et.generateBunDockerfile({serverPath:n,port:i}),bunWithBuild:(n,i,s=3000)=>et.generateBunDockerfile({serverPath:n,port:s,buildCommands:[i]}),bunFullStack:(n,i=3000)=>et.generateBunDockerfile({serverPath:n,port:i,additionalDirs:["public","views","dist"],buildCommands:["bun run build"]}),bunApi:(n,i=3000)=>et.generateBunDockerfile({serverPath:n,port:i,healthCheckEndpoint:"/api/health"})}}var dl=[400,403,404,416,429,500,502,503,504],bm=[500,502,503,504],Cm=["GET","HEAD","OPTIONS"],KI="-failover-group",Em=["default","media-quality-based"],vm={min:1,max:3},Tm={min:1,max:10};function Ho(n){if(n===void 0)return[...bm];if(n.length===0)throw Error(`CloudFront origin failover: statusCodes must list at least one code (allowed: ${dl.join(", ")}). Omit it to use the default ${bm.join(", ")}.`);let i=n.filter((s)=>!dl.includes(s));if(i.length>0)throw Error(`CloudFront origin failover: ${i.join(", ")} ${i.length===1?"is not a status code":"are not status codes"} CloudFront can fail over on. Allowed: ${dl.join(", ")}.`);return[...new Set(n)].sort((s,o)=>s-o)}function ll(n){let{primaryOriginId:i,secondaryOriginId:s}=n;if(!i||!s)throw Error("CloudFront origin failover: both a primary and a secondary origin id are required");if(i===s)throw Error(`CloudFront origin failover: the secondary origin must differ from the primary (both are "${i}")`);let o=Ho(n.statusCodes);return nn(n.selectionCriteria),{Id:n.groupId??`${i}-failover-group`,FailoverCriteria:{StatusCodes:{Quantity:o.length,Items:o}},Members:{Quantity:2,Items:[{OriginId:i},{OriginId:s}]},...n.selectionCriteria?{SelectionCriteria:n.selectionCriteria}:{}}}function nn(n,i="the origin group"){if(n===void 0)return;if(!Em.includes(n))throw Error(`CloudFront origin failover: ${i} has selection criteria ${JSON.stringify(n)}. Allowed: ${Em.join(", ")}.`)}function at(n,i,s){if(typeof n!=="number"||!Number.isInteger(n)||n<i.min||n>i.max)throw Error(`CloudFront origin: ${s} must be a whole number from ${i.min} to ${i.max}, got ${JSON.stringify(n)}.`)}function de(n,i="the origin"){let s={};if(n?.connectionAttempts!==void 0)at(n.connectionAttempts,vm,`${i} connectionAttempts`),s.ConnectionAttempts=n.connectionAttempts;if(n?.connectionTimeout!==void 0)at(n.connectionTimeout,Tm,`${i} connectionTimeout (seconds)`),s.ConnectionTimeout=n.connectionTimeout;return s}function un(n){return{Quantity:1,Items:[ll(n)]}}function kt(n,i="the cache behavior"){let o=(Array.isArray(n)?n:n?.Items??[]).filter((c)=>!Cm.includes(c.toUpperCase()));if(o.length>0)throw Error(`CloudFront origin failover: ${i} allows ${o.join(", ")}, but a cache behavior that targets an origin group may only allow ${Cm.join(", ")}. CloudFront never fails over a write, so point the write paths at a single origin in their own cache behavior.`)}function Go(n){return/\.s3[.-](?:[a-z0-9-]+\.)?amazonaws\.com(?:\.cn)?$/i.test(n)&&!/s3-website/i.test(n)}function je(n){if(!n)return[];if(Array.isArray(n))return n;return n.Items??[]}function Ae(n){return typeof n==="string"?n:void 0}var Cr=/\.mediapackagev2\.[a-z0-9-]+\.amazonaws\.com$/i;function Nt(n,i="the distribution"){let s=je(n.Origins),o=new Set(s.map((b)=>Ae(b.Id)).filter((b)=>!!b)),c=new Map(s.map((b)=>[Ae(b.Id)??"",b.DomainName])),u=s.some((b)=>Ae(b.Id)===void 0);for(let b of s){let v=Ae(b.Id)??"(unnamed origin)";if(b.ConnectionAttempts!==void 0)at(b.ConnectionAttempts,vm,`${i} origin "${v}" ConnectionAttempts`);if(b.ConnectionTimeout!==void 0)at(b.ConnectionTimeout,Tm,`${i} origin "${v}" ConnectionTimeout (seconds)`)}let d=n.OriginGroups,g=je(d);if(d&&!Array.isArray(d)&&d.Quantity!==void 0&&d.Quantity!==g.length)throw Error(`CloudFront origin failover: ${i} OriginGroups.Quantity is ${d.Quantity} but it lists ${g.length} group(s).`);let y=new Set;for(let b of g){let v=Ae(b.Id);if(b.Id===void 0||b.Id==="")throw Error(`CloudFront origin failover: ${i} has an origin group without an Id.`);let A=`${i} origin group "${v??"(intrinsic id)"}"`;if(v){if(y.has(v))throw Error(`CloudFront origin failover: ${i} declares origin group "${v}" twice.`);if(o.has(v))throw Error(`CloudFront origin failover: ${A} has the same id as an origin. Cache behaviors target groups and origins by id, so the two must differ.`);y.add(v)}let T=b.Members,R=je(T);if(R.length!==2||T?.Quantity!==void 0&&T.Quantity!==R.length)throw Error(`CloudFront origin failover: ${A} must have exactly 2 members (a primary and a secondary), it has ${R.length}${T?.Quantity!==void 0&&T.Quantity!==R.length?` with Quantity ${T.Quantity}`:""}.`);let P=R.map((L)=>Ae(L.OriginId));for(let L of P)if(L&&!o.has(L)&&!u)throw Error(`CloudFront origin failover: ${A} lists member "${L}", which is not an origin of this distribution. Origins: ${[...o].join(", ")||"(none)"}.`);if(P[0]&&P[0]===P[1])throw Error(`CloudFront origin failover: ${A} lists "${P[0]}" as both primary and secondary.`);let I=b.FailoverCriteria?.StatusCodes,M=je(I);if(Ho(M),I?.Quantity!==void 0&&I.Quantity!==M.length)throw Error(`CloudFront origin failover: ${A} FailoverCriteria.StatusCodes.Quantity is ${I.Quantity} but it lists ${M.length} code(s).`);if(nn(b.SelectionCriteria,A),b.SelectionCriteria==="media-quality-based")for(let L of P){let N=L?Ae(c.get(L)):void 0;if(N&&!Cr.test(N))throw Error(`CloudFront origin failover: ${A} uses media-quality-based selection, which only works between AWS Elemental MediaPackage v2 origins, but member "${L}" is ${N}. Use 'default'.`)}}let h=[];if(n.DefaultCacheBehavior)h.push({behavior:n.DefaultCacheBehavior,name:"the default cache behavior"});for(let b of je(n.CacheBehaviors))h.push({behavior:b,name:`the cache behavior for ${JSON.stringify(b.PathPattern)}`});for(let{behavior:b,name:v}of h){let A=Ae(b.TargetOriginId);if(!A)continue;if(y.has(A))kt(b.AllowedMethods??["GET","HEAD"],`${v} of ${i} (origin group "${A}")`);else if(!o.has(A)&&!u&&g.every((T)=>Ae(T.Id)!==void 0))throw Error(`CloudFront: ${v} of ${i} targets "${A}", which is neither an origin nor an origin group of this distribution.`)}}class Ce{static createDistribution(n){let{slug:i,environment:s,origin:o,customDomain:c,certificateArn:u,errorPages:d,cachePolicy:g,edgeFunctions:y,http3:h=!1,comment:b,failoverOrigin:v}=n,A=r({slug:i,environment:s,resourceType:"cdn"}),T=t(A),R={Id:"DefaultOrigin",DomainName:o.domainName,OriginPath:o.originPath||"",...de(o,"the CDN origin")},P;if(o.type==="s3"){let M=`${T}OAC`;P={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`${A}-oac`,Description:`Origin Access Control for ${A}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},R.OriginAccessControlId=x.Ref(M)}else if(o.type==="alb"||o.type==="custom")R.CustomOriginConfig={HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only"};let I={Type:"AWS::CloudFront::Distribution",Properties:{DistributionConfig:{Enabled:!0,Comment:b||`CDN for ${A}`,DefaultRootObject:"index.html",Origins:[R],DefaultCacheBehavior:{TargetOriginId:"DefaultOrigin",ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0},PriceClass:"PriceClass_100",HttpVersion:h?"http2and3":"http2"}}};if(c&&u)I.Properties.DistributionConfig.Aliases=[c],I.Properties.DistributionConfig.ViewerCertificate={AcmCertificateArn:u,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};if(d&&d.length>0)I.Properties.DistributionConfig.CustomErrorResponses=d.map((M)=>({ErrorCode:M.errorCode,ResponseCode:M.responseCode,ResponsePagePath:M.responsePagePath}));if(y&&y.length>0)I.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations=y.map((M)=>({EventType:M.event,LambdaFunctionARN:M.functionArn}));if(v)Ce.addOriginFailover(I,v);return{distribution:I,originAccessControl:P,logicalId:T}}static addOriginFailover(n,i){let s=n.Properties.DistributionConfig,o=s.DefaultCacheBehavior,c=o.TargetOriginId,u=i.id??"FailoverOrigin";if(s.OriginGroups&&s.OriginGroups.Quantity>0)throw Error("CloudFront origin failover: this distribution already has an origin group");if(kt(o.AllowedMethods??["GET","HEAD"],"the default cache behavior"),s.Origins.some((b)=>b.Id===u))throw Error(`CloudFront origin failover: an origin with id "${u}" already exists`);let d=ll({primaryOriginId:c,secondaryOriginId:u,statusCodes:i.statusCodes,selectionCriteria:i.selectionCriteria}),g=i.type??(Go(i.domainName)?"s3":"custom"),y={Id:u,DomainName:i.domainName,OriginPath:i.originPath||"",...de(i,"the failover origin")},h=de(i.primary,"the primary origin");if(Object.keys(h).length>0){let b=s.Origins.find((v)=>v.Id===c);if(b)Object.assign(b,h)}if(g==="s3"){let b=s.Origins.find((v)=>v.Id===c);if(y.S3OriginConfig={OriginAccessIdentity:""},b?.OriginAccessControlId)y.OriginAccessControlId=b.OriginAccessControlId}else y.CustomOriginConfig={HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only"};return s.Origins.push(y),s.OriginGroups={Quantity:1,Items:[d]},o.TargetOriginId=d.Id,Nt(s),n}static setCustomDomain(n,i,s){return n.Properties.DistributionConfig.Aliases=[i],n.Properties.DistributionConfig.ViewerCertificate={AcmCertificateArn:s,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"},n}static setErrorPages(n,i){return n.Properties.DistributionConfig.CustomErrorResponses=i.map((s)=>({ErrorCode:s.errorCode,ResponseCode:s.responseCode,ResponsePagePath:s.responsePagePath})),n}static enableHttp3(n){return n.Properties.DistributionConfig.HttpVersion="http2and3",n}static addEdgeFunction(n,i,s){if(!n.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations)n.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations=[];return n.Properties.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations.push({EventType:i,LambdaFunctionARN:s}),n}static setCachePolicy(n,i){return n.Properties.DistributionConfig.Comment=`${n.Properties.DistributionConfig.Comment||""} (TTL: ${i.default||86400}s)`,n}static createSpaDistribution(n){return Ce.createDistribution({...n,errorPages:[{errorCode:404,responseCode:200,responsePagePath:"/index.html"},{errorCode:403,responseCode:200,responsePagePath:"/index.html"}]})}static createDocsOriginRequestFunction(n){let{slug:i,environment:s}=n,o=r({slug:i,environment:s,resourceType:"edge-docs"}),c=t(o),u=t(`${o}-role`),d=t(`${o}-version`),g={Type:"AWS::IAM::Role",Properties:{RoleName:`${o}-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:["lambda.amazonaws.com","edgelambda.amazonaws.com"]},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"]}},y=`
95
95
  'use strict';
96
96
 
97
97
  exports.handler = async (event) => {
@@ -585,7 +585,7 @@ echo "Redis server setup complete!"
585
585
  - Using a single NAT Gateway (singleNatGateway: true)
586
586
  - Using NAT Instances instead (cheaper but requires management)
587
587
  - Disabling NAT entirely for isolated private subnets
588
- `}class et{static createFileSystem(n){let{slug:i,environment:s,encrypted:o=!0,kmsKeyId:c,performanceMode:u="generalPurpose",throughputMode:d="bursting",provisionedThroughput:g,enableBackup:y=!0}=n,h=r({slug:i,environment:s,resourceType:"efs"}),b=t(h),v={Type:"AWS::EFS::FileSystem",Properties:{Encrypted:o,PerformanceMode:u,ThroughputMode:d,FileSystemTags:[{Key:"Name",Value:h},{Key:"Environment",Value:s}]}};if(c)v.Properties.KmsKeyId=c;if(d==="provisioned"&&g)v.Properties.ProvisionedThroughputInMibps=g;if(y)v.Properties.BackupPolicy={Status:"ENABLED"};return{fileSystem:v,logicalId:b}}static createMountTarget(n,i){let{slug:s,environment:o,subnetId:c,securityGroups:u,ipAddress:d}=i,g=r({slug:s,environment:o,resourceType:"efs-mt"}),y=t(`${g}-${c}`),h={Type:"AWS::EFS::MountTarget",Properties:{FileSystemId:x.Ref(n),SubnetId:c,SecurityGroups:u}};if(d)h.Properties.IpAddress=d;return{mountTarget:h,logicalId:y}}static createAccessPoint(n,i){let{slug:s,environment:o,path:c="/",uid:u="1000",gid:d="1000",permissions:g="755"}=i,y=r({slug:s,environment:o,resourceType:"efs-ap"}),h=t(`${y}-${c.replace(/\//g,"-")}`);return{accessPoint:{Type:"AWS::EFS::AccessPoint",Properties:{FileSystemId:x.Ref(n),PosixUser:{Uid:u,Gid:d},RootDirectory:{Path:c,CreationInfo:{OwnerUid:u,OwnerGid:d,Permissions:g}},AccessPointTags:[{Key:"Name",Value:`${y}-${c}`},{Key:"Environment",Value:o}]}},logicalId:h}}static setLifecyclePolicy(n,i){let{transitionToIA:s,transitionToPrimary:o=!1}=i;if(!n.Properties)n.Properties={};if(n.Properties.LifecyclePolicies=[],s){let c=`AFTER_${s}_DAYS`;n.Properties.LifecyclePolicies.push({TransitionToIA:c})}if(o)n.Properties.LifecyclePolicies.push({TransitionToPrimaryStorageClass:"AFTER_1_ACCESS"});return n}static enableBackup(n){if(!n.Properties)n.Properties={};return n.Properties.BackupPolicy={Status:"ENABLED"},n}static disableBackup(n){if(!n.Properties)n.Properties={};return n.Properties.BackupPolicy={Status:"DISABLED"},n}static setProvisionedThroughput(n,i){if(!n.Properties)n.Properties={};return n.Properties.ThroughputMode="provisioned",n.Properties.ProvisionedThroughputInMibps=i,n}static setElasticThroughput(n){if(!n.Properties)n.Properties={};return n.Properties.ThroughputMode="elastic",n}static enableMaxIO(n){if(!n.Properties)n.Properties={};return n.Properties.PerformanceMode="maxIO",n}static createEfsSecurityGroup(n){let{slug:i,environment:s,vpcId:o,sourceSecurityGroupIds:c=[],sourceCidrBlocks:u=[],description:d}=n,g=r({slug:i,environment:s,resourceType:"efs-sg"}),y=t(g),h=[];for(let v of c)h.push({IpProtocol:"tcp",FromPort:2049,ToPort:2049,SourceSecurityGroupId:v,Description:"NFS from security group"});for(let v of u)h.push({IpProtocol:"tcp",FromPort:2049,ToPort:2049,CidrIp:v,Description:"NFS from CIDR block"});return{securityGroup:{Type:"AWS::EC2::SecurityGroup",Properties:{GroupName:g,GroupDescription:d||`Security group for EFS mount targets - ${i} ${s}`,VpcId:o,SecurityGroupIngress:h,Tags:[{Key:"Name",Value:g},{Key:"Environment",Value:s}]}},logicalId:y}}static createMultiAzMountTargets(n,i){let{slug:s,environment:o,subnetIds:c,securityGroupId:u}=i,d=[],g=[];for(let y=0;y<c.length;y++){let h=c[y],b=r({slug:s,environment:o,resourceType:"efs-mt"}),v=t(`${b}-az${y+1}`),A={Type:"AWS::EFS::MountTarget",Properties:{FileSystemId:x.Ref(n),SubnetId:h,SecurityGroups:[u]}};d.push(A),g.push(v)}return{mountTargets:d,logicalIds:g}}static createCompleteFileSystem(n){let{slug:i,environment:s,vpcId:o,subnetIds:c,sourceSecurityGroupIds:u=[],encrypted:d=!0,performanceMode:g="generalPurpose",throughputMode:y="elastic",enableBackup:h=!0,transitionToIA:b}=n,v={},{fileSystem:A,logicalId:T}=et.createFileSystem({slug:i,environment:s,encrypted:d,performanceMode:g,throughputMode:y,enableBackup:h});if(b)et.setLifecyclePolicy(A,{transitionToIA:b,transitionToPrimary:!0});v[T]=A;let{securityGroup:R,logicalId:P}=et.createEfsSecurityGroup({slug:i,environment:s,vpcId:o,sourceSecurityGroupIds:u});v[P]=R;let{mountTargets:I,logicalIds:M}=et.createMultiAzMountTargets(T,{slug:i,environment:s,subnetIds:c,securityGroupId:x.Ref(P)});for(let L=0;L<I.length;L++)v[M[L]]=I[L];return{resources:v,outputs:{fileSystemId:T,securityGroupId:P,mountTargetIds:M}}}}class f{static verifyDomain(n){let{domain:i,slug:s,environment:o,enableDkim:c=!0,dkimKeyLength:u="RSA_2048_BIT"}=n,d=r({slug:s,environment:o,resourceType:"ses-identity"}),g=t(`${d}-${i.replace(/\./g,"")}`),y={Type:"AWS::SES::EmailIdentity",Properties:{EmailIdentity:i,FeedbackAttributes:{EmailForwardingEnabled:!0}}};if(c)y.Properties.DkimSigningAttributes={NextSigningKeyLength:u};return{emailIdentity:y,logicalId:g}}static createDkimRecords(n,i,s){let o=[];for(let c=0;c<i.length;c++){let u=i[c],d=t(`dkim-${n.replace(/\./g,"")}-${c+1}`),g={Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:s,Name:`${u}._domainkey.${n}`,Type:"CNAME",TTL:1800,ResourceRecords:[`${u}.dkim.amazonses.com`]}};o.push({record:g,logicalId:d})}return o}static createConfigurationSet(n){let{slug:i,environment:s,name:o,reputationMetrics:c=!0,sendingEnabled:u=!0,suppressBounces:d=!0,suppressComplaints:g=!0}=n,y=o||r({slug:i,environment:s,resourceType:"ses-config"}),h=t(y),b=[];if(d)b.push("BOUNCE");if(g)b.push("COMPLAINT");return{configurationSet:{Type:"AWS::SES::ConfigurationSet",Properties:{Name:y,ReputationOptions:{ReputationMetricsEnabled:c},SendingOptions:{SendingEnabled:u},SuppressionOptions:{SuppressedReasons:b}}},logicalId:h}}static createReceiptRuleSet(n){let{slug:i,environment:s,name:o}=n,c=o||r({slug:i,environment:s,resourceType:"ses-ruleset"}),u=t(c);return{ruleSet:{Type:"AWS::SES::ReceiptRuleSet",Properties:{RuleSetName:c}},logicalId:u}}static createReceiptRule(n,i){let{slug:s,environment:o,ruleSetName:c,recipients:u,enabled:d=!0,scanEnabled:g=!0,tlsPolicy:y="Require",s3Action:h,lambdaAction:b,snsAction:v}=i,A=r({slug:s,environment:o,resourceType:"ses-rule"}),T=t(A),R=[];if(h)R.push({S3Action:{BucketName:h.bucketName,ObjectKeyPrefix:h.prefix,KmsKeyArn:h.kmsKeyArn}});if(b)R.push({LambdaAction:{FunctionArn:b.functionArn,InvocationType:b.invocationType||"Event"}});if(v)R.push({SNSAction:{TopicArn:v.topicArn,Encoding:v.encoding||"UTF-8"}});return{receiptRule:{Type:"AWS::SES::ReceiptRule",Properties:{RuleSetName:c,Rule:{Name:A,Enabled:d,ScanEnabled:g,TlsPolicy:y,Recipients:u,Actions:R.length>0?R:void 0}}},logicalId:T}}static createMxRecord(n,i,s){let o=t(`mx-${n.replace(/\./g,"")}`);return{record:{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:i,Name:n,Type:"MX",TTL:300,ResourceRecords:[`10 inbound-smtp.${s}.amazonaws.com`]}},logicalId:o}}static createVerificationRecord(n,i,s){let o=t(`verification-${n.replace(/\./g,"")}`);return{record:{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:s,Name:`_amazonses.${n}`,Type:"TXT",TTL:1800,ResourceRecords:[`"${i}"`]}},logicalId:o}}static getSmtpEndpoint(n){return`email-smtp.${n}.amazonaws.com`}static SmtpPorts={TLS:587,SSL:465,Unencrypted:25};static createSpfRecord(n,i,s){let{includeDomains:o=[],softFail:c=!1}=s||{},u=t(`spf-${n.replace(/\./g,"")}`),d="v=spf1 include:amazonses.com";for(let y of o)d+=` include:${y}`;return d+=c?" ~all":" -all",{record:{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:i,Name:n,Type:"TXT",TTL:300,ResourceRecords:[`"${d}"`]}},logicalId:u}}static createDmarcRecord(n,i,s){let{policy:o="none",subdomainPolicy:c,percentage:u=100,reportingEmail:d,forensicEmail:g}=s||{},y=t(`dmarc-${n.replace(/\./g,"")}`),h=`v=DMARC1; p=${o}; pct=${u}`;if(c)h+=`; sp=${c}`;if(d)h+=`; rua=mailto:${d}`;if(g)h+=`; ruf=mailto:${g}`;return{record:{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:i,Name:`_dmarc.${n}`,Type:"TXT",TTL:300,ResourceRecords:[`"${h}"`]}},logicalId:y}}static createInboundEmailSetup(n){let{slug:i,environment:s,domain:o,s3BucketName:c,s3KeyPrefix:u="inbound/",region:d,hostedZoneId:g,lambdaFunctionArn:y,snsTopicArn:h}=n,b={},{ruleSet:v,logicalId:A}=f.createReceiptRuleSet({slug:i,environment:s});b[A]=v;let{receiptRule:T,logicalId:R}=f.createReceiptRule(A,{slug:i,environment:s,ruleSetName:v.Properties.RuleSetName||`${i}-${s}-receipt-rule-set`,recipients:[o],s3Action:{bucketName:c,prefix:u},lambdaAction:y?{functionArn:y,invocationType:"Event"}:void 0,snsAction:h?{topicArn:h}:void 0});b[R]=T;let{record:P,logicalId:I}=f.createMxRecord(o,g,d);return b[I]=P,{resources:b,outputs:{ruleSetLogicalId:A,ruleLogicalId:R,mxRecordLogicalId:I}}}static createCompleteDomainSetup(n){let{slug:i,environment:s,domain:o,hostedZoneId:c,region:u,enableInbound:d=!1,inboundS3Bucket:g,dmarcReportingEmail:y}=n,h={},{emailIdentity:b,logicalId:v}=f.verifyDomain({domain:o,slug:i,environment:s});h[v]=b;let{configurationSet:A,logicalId:T}=f.createConfigurationSet({slug:i,environment:s});h[T]=A;let{record:R,logicalId:P}=f.createSpfRecord(o,c);h[P]=R;let{record:I,logicalId:M}=f.createDmarcRecord(o,c,{policy:"none",reportingEmail:y||`dmarc-reports@${o}`});if(h[M]=I,d&&g){let L=f.createInboundEmailSetup({slug:i,environment:s,domain:o,s3BucketName:g,region:u,hostedZoneId:c});Object.assign(h,L.resources)}return{resources:h,outputs:{identityLogicalId:v,configSetLogicalId:T}}}static InboundSmtpEndpoints={"us-east-1":"inbound-smtp.us-east-1.amazonaws.com","us-west-2":"inbound-smtp.us-west-2.amazonaws.com","eu-west-1":"inbound-smtp.eu-west-1.amazonaws.com"};static supportsInboundEmail(n){return n in f.InboundSmtpEndpoints}static createEmailLambdaRole(n){let{slug:i,environment:s,s3BucketArn:o,sesIdentityArn:c}=n,u=r({slug:i,environment:s,resourceType:"email-lambda-role"}),d=t(u),g=t(`${u}-policy`),y={Type:"AWS::IAM::Role",Properties:{RoleName:u,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"],Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:s}]}},h=[{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:ListBucket"],Resource:[o,`${o}/*`]}];if(c)h.push({Effect:"Allow",Action:["ses:SendEmail","ses:SendRawEmail"],Resource:c});let b={Type:"AWS::IAM::Policy",Properties:{PolicyName:`${u}-policy`,PolicyDocument:{Version:"2012-10-17",Statement:h},Roles:[x.Ref(d)]}};return{role:y,policy:b,roleLogicalId:d,policyLogicalId:g}}static createOutboundEmailLambda(n){let{slug:i,environment:s,roleArn:o,domain:c,configurationSetName:u,timeout:d=30,memorySize:g=256}=n,y=r({slug:i,environment:s,resourceType:"outbound-email"}),h=t(y);return{function:{Type:"AWS::Lambda::Function",Properties:{FunctionName:y,Runtime:"nodejs20.x",Handler:"index.handler",Role:o,Timeout:d,MemorySize:g,Environment:{Variables:{DOMAIN:c,CONFIGURATION_SET:u||""}},Code:{ZipFile:f.LambdaCode.outboundEmail},Tags:[{Key:"Name",Value:y},{Key:"Environment",Value:s},{Key:"Purpose",Value:"OutboundEmail"}]}},logicalId:h}}static createInboundEmailLambda(n){let{slug:i,environment:s,roleArn:o,s3BucketName:c,organizedPrefix:u="organized/",timeout:d=60,memorySize:g=512}=n,y=r({slug:i,environment:s,resourceType:"inbound-email"}),h=t(y),b=t(`${y}-permission`),v={Type:"AWS::Lambda::Function",Properties:{FunctionName:y,Runtime:"nodejs20.x",Handler:"index.handler",Role:o,Timeout:d,MemorySize:g,Environment:{Variables:{S3_BUCKET:c,ORGANIZED_PREFIX:u}},Code:{ZipFile:f.LambdaCode.inboundEmail},Tags:[{Key:"Name",Value:y},{Key:"Environment",Value:s},{Key:"Purpose",Value:"InboundEmail"}]}},A={Type:"AWS::Lambda::Permission",Properties:{FunctionName:x.Ref(h),Action:"lambda:InvokeFunction",Principal:"ses.amazonaws.com",SourceAccount:x.Ref("AWS::AccountId")}};return{function:v,permission:A,logicalId:h,permissionLogicalId:b}}static createEmailConversionLambda(n){let{slug:i,environment:s,roleArn:o,s3BucketName:c,convertedPrefix:u="converted/",timeout:d=60,memorySize:g=512}=n,y=r({slug:i,environment:s,resourceType:"email-conversion"}),h=t(y);return{function:{Type:"AWS::Lambda::Function",Properties:{FunctionName:y,Runtime:"nodejs20.x",Handler:"index.handler",Role:o,Timeout:d,MemorySize:g,Environment:{Variables:{S3_BUCKET:c,CONVERTED_PREFIX:u}},Code:{ZipFile:f.LambdaCode.emailConversion},Tags:[{Key:"Name",Value:y},{Key:"Environment",Value:s},{Key:"Purpose",Value:"EmailConversion"}]}},logicalId:h}}static createEmailBucketNotification(n){let{lambdaArn:i,prefix:s="inbound/",suffix:o,events:c}=n,u=c??["s3:ObjectCreated:*"],d={};if(s||o){if(d.S3Key={Rules:[]},s)d.S3Key.Rules.push({Name:"prefix",Value:s});if(o)d.S3Key.Rules.push({Name:"suffix",Value:o})}return{notificationConfiguration:{LambdaConfigurations:[{Event:u[0],Function:i,Filter:Object.keys(d).length>0?d:void 0}]}}}static createS3LambdaPermission(n){let{slug:i,environment:s,lambdaLogicalId:o,s3BucketArn:c}=n,u=r({slug:i,environment:s,resourceType:"s3-lambda-permission"}),d=t(u);return{permission:{Type:"AWS::Lambda::Permission",Properties:{FunctionName:x.Ref(o),Action:"lambda:InvokeFunction",Principal:"s3.amazonaws.com",SourceArn:c}},logicalId:d}}static createEmailProcessingStack(n){let{slug:i,environment:s,domain:o,s3BucketName:c,s3BucketArn:u,configurationSetName:d,enableInbound:g=!0,enableConversion:y=!0}=n,h={},{role:b,policy:v,roleLogicalId:A,policyLogicalId:T}=f.createEmailLambdaRole({slug:i,environment:s,s3BucketArn:u,sesIdentityArn:`arn:aws:ses:*:*:identity/${o}`});h[A]=b,h[T]=v;let{function:R,logicalId:P}=f.createOutboundEmailLambda({slug:i,environment:s,roleArn:x.GetAtt(A,"Arn"),domain:o,configurationSetName:d});h[P]=R;let I={roleLogicalId:A,outboundLambdaLogicalId:P};if(g){let{function:M,permission:L,logicalId:N,permissionLogicalId:O}=f.createInboundEmailLambda({slug:i,environment:s,roleArn:x.GetAtt(A,"Arn"),s3BucketName:c});h[N]=M,h[O]=L;let{permission:B,logicalId:F}=f.createS3LambdaPermission({slug:i,environment:s,lambdaLogicalId:N,s3BucketArn:u});h[F]=B,I.inboundLambdaLogicalId=N}if(y){let{function:M,logicalId:L}=f.createEmailConversionLambda({slug:i,environment:s,roleArn:x.GetAtt(A,"Arn"),s3BucketName:c});h[L]=M,I.conversionLambdaLogicalId=L}return{resources:h,outputs:I}}static LambdaCode={outboundEmail:`
588
+ `}class tt{static createFileSystem(n){let{slug:i,environment:s,encrypted:o=!0,kmsKeyId:c,performanceMode:u="generalPurpose",throughputMode:d="bursting",provisionedThroughput:g,enableBackup:y=!0}=n,h=r({slug:i,environment:s,resourceType:"efs"}),b=t(h),v={Type:"AWS::EFS::FileSystem",Properties:{Encrypted:o,PerformanceMode:u,ThroughputMode:d,FileSystemTags:[{Key:"Name",Value:h},{Key:"Environment",Value:s}]}};if(c)v.Properties.KmsKeyId=c;if(d==="provisioned"&&g)v.Properties.ProvisionedThroughputInMibps=g;if(y)v.Properties.BackupPolicy={Status:"ENABLED"};return{fileSystem:v,logicalId:b}}static createMountTarget(n,i){let{slug:s,environment:o,subnetId:c,securityGroups:u,ipAddress:d}=i,g=r({slug:s,environment:o,resourceType:"efs-mt"}),y=t(`${g}-${c}`),h={Type:"AWS::EFS::MountTarget",Properties:{FileSystemId:x.Ref(n),SubnetId:c,SecurityGroups:u}};if(d)h.Properties.IpAddress=d;return{mountTarget:h,logicalId:y}}static createAccessPoint(n,i){let{slug:s,environment:o,path:c="/",uid:u="1000",gid:d="1000",permissions:g="755"}=i,y=r({slug:s,environment:o,resourceType:"efs-ap"}),h=t(`${y}-${c.replace(/\//g,"-")}`);return{accessPoint:{Type:"AWS::EFS::AccessPoint",Properties:{FileSystemId:x.Ref(n),PosixUser:{Uid:u,Gid:d},RootDirectory:{Path:c,CreationInfo:{OwnerUid:u,OwnerGid:d,Permissions:g}},AccessPointTags:[{Key:"Name",Value:`${y}-${c}`},{Key:"Environment",Value:o}]}},logicalId:h}}static setLifecyclePolicy(n,i){let{transitionToIA:s,transitionToPrimary:o=!1}=i;if(!n.Properties)n.Properties={};if(n.Properties.LifecyclePolicies=[],s){let c=`AFTER_${s}_DAYS`;n.Properties.LifecyclePolicies.push({TransitionToIA:c})}if(o)n.Properties.LifecyclePolicies.push({TransitionToPrimaryStorageClass:"AFTER_1_ACCESS"});return n}static enableBackup(n){if(!n.Properties)n.Properties={};return n.Properties.BackupPolicy={Status:"ENABLED"},n}static disableBackup(n){if(!n.Properties)n.Properties={};return n.Properties.BackupPolicy={Status:"DISABLED"},n}static setProvisionedThroughput(n,i){if(!n.Properties)n.Properties={};return n.Properties.ThroughputMode="provisioned",n.Properties.ProvisionedThroughputInMibps=i,n}static setElasticThroughput(n){if(!n.Properties)n.Properties={};return n.Properties.ThroughputMode="elastic",n}static enableMaxIO(n){if(!n.Properties)n.Properties={};return n.Properties.PerformanceMode="maxIO",n}static createEfsSecurityGroup(n){let{slug:i,environment:s,vpcId:o,sourceSecurityGroupIds:c=[],sourceCidrBlocks:u=[],description:d}=n,g=r({slug:i,environment:s,resourceType:"efs-sg"}),y=t(g),h=[];for(let v of c)h.push({IpProtocol:"tcp",FromPort:2049,ToPort:2049,SourceSecurityGroupId:v,Description:"NFS from security group"});for(let v of u)h.push({IpProtocol:"tcp",FromPort:2049,ToPort:2049,CidrIp:v,Description:"NFS from CIDR block"});return{securityGroup:{Type:"AWS::EC2::SecurityGroup",Properties:{GroupName:g,GroupDescription:d||`Security group for EFS mount targets - ${i} ${s}`,VpcId:o,SecurityGroupIngress:h,Tags:[{Key:"Name",Value:g},{Key:"Environment",Value:s}]}},logicalId:y}}static createMultiAzMountTargets(n,i){let{slug:s,environment:o,subnetIds:c,securityGroupId:u}=i,d=[],g=[];for(let y=0;y<c.length;y++){let h=c[y],b=r({slug:s,environment:o,resourceType:"efs-mt"}),v=t(`${b}-az${y+1}`),A={Type:"AWS::EFS::MountTarget",Properties:{FileSystemId:x.Ref(n),SubnetId:h,SecurityGroups:[u]}};d.push(A),g.push(v)}return{mountTargets:d,logicalIds:g}}static createCompleteFileSystem(n){let{slug:i,environment:s,vpcId:o,subnetIds:c,sourceSecurityGroupIds:u=[],encrypted:d=!0,performanceMode:g="generalPurpose",throughputMode:y="elastic",enableBackup:h=!0,transitionToIA:b}=n,v={},{fileSystem:A,logicalId:T}=tt.createFileSystem({slug:i,environment:s,encrypted:d,performanceMode:g,throughputMode:y,enableBackup:h});if(b)tt.setLifecyclePolicy(A,{transitionToIA:b,transitionToPrimary:!0});v[T]=A;let{securityGroup:R,logicalId:P}=tt.createEfsSecurityGroup({slug:i,environment:s,vpcId:o,sourceSecurityGroupIds:u});v[P]=R;let{mountTargets:I,logicalIds:M}=tt.createMultiAzMountTargets(T,{slug:i,environment:s,subnetIds:c,securityGroupId:x.Ref(P)});for(let L=0;L<I.length;L++)v[M[L]]=I[L];return{resources:v,outputs:{fileSystemId:T,securityGroupId:P,mountTargetIds:M}}}}class f{static verifyDomain(n){let{domain:i,slug:s,environment:o,enableDkim:c=!0,dkimKeyLength:u="RSA_2048_BIT"}=n,d=r({slug:s,environment:o,resourceType:"ses-identity"}),g=t(`${d}-${i.replace(/\./g,"")}`),y={Type:"AWS::SES::EmailIdentity",Properties:{EmailIdentity:i,FeedbackAttributes:{EmailForwardingEnabled:!0}}};if(c)y.Properties.DkimSigningAttributes={NextSigningKeyLength:u};return{emailIdentity:y,logicalId:g}}static createDkimRecords(n,i,s){let o=[];for(let c=0;c<i.length;c++){let u=i[c],d=t(`dkim-${n.replace(/\./g,"")}-${c+1}`),g={Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:s,Name:`${u}._domainkey.${n}`,Type:"CNAME",TTL:1800,ResourceRecords:[`${u}.dkim.amazonses.com`]}};o.push({record:g,logicalId:d})}return o}static createConfigurationSet(n){let{slug:i,environment:s,name:o,reputationMetrics:c=!0,sendingEnabled:u=!0,suppressBounces:d=!0,suppressComplaints:g=!0}=n,y=o||r({slug:i,environment:s,resourceType:"ses-config"}),h=t(y),b=[];if(d)b.push("BOUNCE");if(g)b.push("COMPLAINT");return{configurationSet:{Type:"AWS::SES::ConfigurationSet",Properties:{Name:y,ReputationOptions:{ReputationMetricsEnabled:c},SendingOptions:{SendingEnabled:u},SuppressionOptions:{SuppressedReasons:b}}},logicalId:h}}static createReceiptRuleSet(n){let{slug:i,environment:s,name:o}=n,c=o||r({slug:i,environment:s,resourceType:"ses-ruleset"}),u=t(c);return{ruleSet:{Type:"AWS::SES::ReceiptRuleSet",Properties:{RuleSetName:c}},logicalId:u}}static createReceiptRule(n,i){let{slug:s,environment:o,ruleSetName:c,recipients:u,enabled:d=!0,scanEnabled:g=!0,tlsPolicy:y="Require",s3Action:h,lambdaAction:b,snsAction:v}=i,A=r({slug:s,environment:o,resourceType:"ses-rule"}),T=t(A),R=[];if(h)R.push({S3Action:{BucketName:h.bucketName,ObjectKeyPrefix:h.prefix,KmsKeyArn:h.kmsKeyArn}});if(b)R.push({LambdaAction:{FunctionArn:b.functionArn,InvocationType:b.invocationType||"Event"}});if(v)R.push({SNSAction:{TopicArn:v.topicArn,Encoding:v.encoding||"UTF-8"}});return{receiptRule:{Type:"AWS::SES::ReceiptRule",Properties:{RuleSetName:c,Rule:{Name:A,Enabled:d,ScanEnabled:g,TlsPolicy:y,Recipients:u,Actions:R.length>0?R:void 0}}},logicalId:T}}static createMxRecord(n,i,s){let o=t(`mx-${n.replace(/\./g,"")}`);return{record:{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:i,Name:n,Type:"MX",TTL:300,ResourceRecords:[`10 inbound-smtp.${s}.amazonaws.com`]}},logicalId:o}}static createVerificationRecord(n,i,s){let o=t(`verification-${n.replace(/\./g,"")}`);return{record:{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:s,Name:`_amazonses.${n}`,Type:"TXT",TTL:1800,ResourceRecords:[`"${i}"`]}},logicalId:o}}static getSmtpEndpoint(n){return`email-smtp.${n}.amazonaws.com`}static SmtpPorts={TLS:587,SSL:465,Unencrypted:25};static createSpfRecord(n,i,s){let{includeDomains:o=[],softFail:c=!1}=s||{},u=t(`spf-${n.replace(/\./g,"")}`),d="v=spf1 include:amazonses.com";for(let y of o)d+=` include:${y}`;return d+=c?" ~all":" -all",{record:{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:i,Name:n,Type:"TXT",TTL:300,ResourceRecords:[`"${d}"`]}},logicalId:u}}static createDmarcRecord(n,i,s){let{policy:o="none",subdomainPolicy:c,percentage:u=100,reportingEmail:d,forensicEmail:g}=s||{},y=t(`dmarc-${n.replace(/\./g,"")}`),h=`v=DMARC1; p=${o}; pct=${u}`;if(c)h+=`; sp=${c}`;if(d)h+=`; rua=mailto:${d}`;if(g)h+=`; ruf=mailto:${g}`;return{record:{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:i,Name:`_dmarc.${n}`,Type:"TXT",TTL:300,ResourceRecords:[`"${h}"`]}},logicalId:y}}static createInboundEmailSetup(n){let{slug:i,environment:s,domain:o,s3BucketName:c,s3KeyPrefix:u="inbound/",region:d,hostedZoneId:g,lambdaFunctionArn:y,snsTopicArn:h}=n,b={},{ruleSet:v,logicalId:A}=f.createReceiptRuleSet({slug:i,environment:s});b[A]=v;let{receiptRule:T,logicalId:R}=f.createReceiptRule(A,{slug:i,environment:s,ruleSetName:v.Properties.RuleSetName||`${i}-${s}-receipt-rule-set`,recipients:[o],s3Action:{bucketName:c,prefix:u},lambdaAction:y?{functionArn:y,invocationType:"Event"}:void 0,snsAction:h?{topicArn:h}:void 0});b[R]=T;let{record:P,logicalId:I}=f.createMxRecord(o,g,d);return b[I]=P,{resources:b,outputs:{ruleSetLogicalId:A,ruleLogicalId:R,mxRecordLogicalId:I}}}static createCompleteDomainSetup(n){let{slug:i,environment:s,domain:o,hostedZoneId:c,region:u,enableInbound:d=!1,inboundS3Bucket:g,dmarcReportingEmail:y}=n,h={},{emailIdentity:b,logicalId:v}=f.verifyDomain({domain:o,slug:i,environment:s});h[v]=b;let{configurationSet:A,logicalId:T}=f.createConfigurationSet({slug:i,environment:s});h[T]=A;let{record:R,logicalId:P}=f.createSpfRecord(o,c);h[P]=R;let{record:I,logicalId:M}=f.createDmarcRecord(o,c,{policy:"none",reportingEmail:y||`dmarc-reports@${o}`});if(h[M]=I,d&&g){let L=f.createInboundEmailSetup({slug:i,environment:s,domain:o,s3BucketName:g,region:u,hostedZoneId:c});Object.assign(h,L.resources)}return{resources:h,outputs:{identityLogicalId:v,configSetLogicalId:T}}}static InboundSmtpEndpoints={"us-east-1":"inbound-smtp.us-east-1.amazonaws.com","us-west-2":"inbound-smtp.us-west-2.amazonaws.com","eu-west-1":"inbound-smtp.eu-west-1.amazonaws.com"};static supportsInboundEmail(n){return n in f.InboundSmtpEndpoints}static createEmailLambdaRole(n){let{slug:i,environment:s,s3BucketArn:o,sesIdentityArn:c}=n,u=r({slug:i,environment:s,resourceType:"email-lambda-role"}),d=t(u),g=t(`${u}-policy`),y={Type:"AWS::IAM::Role",Properties:{RoleName:u,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"],Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:s}]}},h=[{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:ListBucket"],Resource:[o,`${o}/*`]}];if(c)h.push({Effect:"Allow",Action:["ses:SendEmail","ses:SendRawEmail"],Resource:c});let b={Type:"AWS::IAM::Policy",Properties:{PolicyName:`${u}-policy`,PolicyDocument:{Version:"2012-10-17",Statement:h},Roles:[x.Ref(d)]}};return{role:y,policy:b,roleLogicalId:d,policyLogicalId:g}}static createOutboundEmailLambda(n){let{slug:i,environment:s,roleArn:o,domain:c,configurationSetName:u,timeout:d=30,memorySize:g=256}=n,y=r({slug:i,environment:s,resourceType:"outbound-email"}),h=t(y);return{function:{Type:"AWS::Lambda::Function",Properties:{FunctionName:y,Runtime:"nodejs20.x",Handler:"index.handler",Role:o,Timeout:d,MemorySize:g,Environment:{Variables:{DOMAIN:c,CONFIGURATION_SET:u||""}},Code:{ZipFile:f.LambdaCode.outboundEmail},Tags:[{Key:"Name",Value:y},{Key:"Environment",Value:s},{Key:"Purpose",Value:"OutboundEmail"}]}},logicalId:h}}static createInboundEmailLambda(n){let{slug:i,environment:s,roleArn:o,s3BucketName:c,organizedPrefix:u="organized/",timeout:d=60,memorySize:g=512}=n,y=r({slug:i,environment:s,resourceType:"inbound-email"}),h=t(y),b=t(`${y}-permission`),v={Type:"AWS::Lambda::Function",Properties:{FunctionName:y,Runtime:"nodejs20.x",Handler:"index.handler",Role:o,Timeout:d,MemorySize:g,Environment:{Variables:{S3_BUCKET:c,ORGANIZED_PREFIX:u}},Code:{ZipFile:f.LambdaCode.inboundEmail},Tags:[{Key:"Name",Value:y},{Key:"Environment",Value:s},{Key:"Purpose",Value:"InboundEmail"}]}},A={Type:"AWS::Lambda::Permission",Properties:{FunctionName:x.Ref(h),Action:"lambda:InvokeFunction",Principal:"ses.amazonaws.com",SourceAccount:x.Ref("AWS::AccountId")}};return{function:v,permission:A,logicalId:h,permissionLogicalId:b}}static createEmailConversionLambda(n){let{slug:i,environment:s,roleArn:o,s3BucketName:c,convertedPrefix:u="converted/",timeout:d=60,memorySize:g=512}=n,y=r({slug:i,environment:s,resourceType:"email-conversion"}),h=t(y);return{function:{Type:"AWS::Lambda::Function",Properties:{FunctionName:y,Runtime:"nodejs20.x",Handler:"index.handler",Role:o,Timeout:d,MemorySize:g,Environment:{Variables:{S3_BUCKET:c,CONVERTED_PREFIX:u}},Code:{ZipFile:f.LambdaCode.emailConversion},Tags:[{Key:"Name",Value:y},{Key:"Environment",Value:s},{Key:"Purpose",Value:"EmailConversion"}]}},logicalId:h}}static createEmailBucketNotification(n){let{lambdaArn:i,prefix:s="inbound/",suffix:o,events:c}=n,u=c??["s3:ObjectCreated:*"],d={};if(s||o){if(d.S3Key={Rules:[]},s)d.S3Key.Rules.push({Name:"prefix",Value:s});if(o)d.S3Key.Rules.push({Name:"suffix",Value:o})}return{notificationConfiguration:{LambdaConfigurations:[{Event:u[0],Function:i,Filter:Object.keys(d).length>0?d:void 0}]}}}static createS3LambdaPermission(n){let{slug:i,environment:s,lambdaLogicalId:o,s3BucketArn:c}=n,u=r({slug:i,environment:s,resourceType:"s3-lambda-permission"}),d=t(u);return{permission:{Type:"AWS::Lambda::Permission",Properties:{FunctionName:x.Ref(o),Action:"lambda:InvokeFunction",Principal:"s3.amazonaws.com",SourceArn:c}},logicalId:d}}static createEmailProcessingStack(n){let{slug:i,environment:s,domain:o,s3BucketName:c,s3BucketArn:u,configurationSetName:d,enableInbound:g=!0,enableConversion:y=!0}=n,h={},{role:b,policy:v,roleLogicalId:A,policyLogicalId:T}=f.createEmailLambdaRole({slug:i,environment:s,s3BucketArn:u,sesIdentityArn:`arn:aws:ses:*:*:identity/${o}`});h[A]=b,h[T]=v;let{function:R,logicalId:P}=f.createOutboundEmailLambda({slug:i,environment:s,roleArn:x.GetAtt(A,"Arn"),domain:o,configurationSetName:d});h[P]=R;let I={roleLogicalId:A,outboundLambdaLogicalId:P};if(g){let{function:M,permission:L,logicalId:N,permissionLogicalId:O}=f.createInboundEmailLambda({slug:i,environment:s,roleArn:x.GetAtt(A,"Arn"),s3BucketName:c});h[N]=M,h[O]=L;let{permission:B,logicalId:F}=f.createS3LambdaPermission({slug:i,environment:s,lambdaLogicalId:N,s3BucketArn:u});h[F]=B,I.inboundLambdaLogicalId=N}if(y){let{function:M,logicalId:L}=f.createEmailConversionLambda({slug:i,environment:s,roleArn:x.GetAtt(A,"Arn"),s3BucketName:c});h[L]=M,I.conversionLambdaLogicalId=L}return{resources:h,outputs:I}}static LambdaCode={outboundEmail:`
589
589
  const { SESClient, SendRawEmailCommand } = require('@aws-sdk/client-ses');
590
590
  const ses = new SESClient({});
591
591
 
@@ -1623,7 +1623,7 @@ catch (error) {
1623
1623
 
1624
1624
  return { statusCode: 200, body: 'OK' };
1625
1625
  };
1626
- `;class tt{static LambdaCode={incomingCall:At,voicemail:sn,missedCall:rn};static createConnectInstance(n){let{slug:i,environment:s,instanceAlias:o,inboundCallsEnabled:c=!0,outboundCallsEnabled:u=!0}=n;return{[`${i}ConnectInstance`]:{Type:"AWS::Connect::Instance",Properties:{InstanceAlias:o,IdentityManagementType:"CONNECT_MANAGED",Attributes:{InboundCalls:c,OutboundCalls:u,ContactflowLogs:!0,ContactLens:!0,AutoResolveBestVoices:!0,UseCustomTTSVoices:!1,EarlyMedia:!0}}}}}static createHoursOfOperation(n){return{[`${n.slug}HoursOfOperation`]:{Type:"AWS::Connect::HoursOfOperation",Properties:{InstanceArn:n.instanceArn,Name:n.name,TimeZone:n.timezone,Config:n.schedule.map((i)=>({Day:i.day,StartTime:{Hours:i.startHour,Minutes:i.startMinute},EndTime:{Hours:i.endHour,Minutes:i.endMinute}}))}}}}static createQueue(n){return{[`${n.slug}Queue`]:{Type:"AWS::Connect::Queue",Properties:{InstanceArn:n.instanceArn,Name:n.name,HoursOfOperationArn:n.hoursOfOperationArn,MaxContacts:n.maxContacts||10}}}}static createContactFlow(n){return{[`${n.slug}ContactFlow`]:{Type:"AWS::Connect::ContactFlow",Properties:{InstanceArn:n.instanceArn,Name:n.name,Type:n.type,Content:n.content}}}}static createBasicIvrFlow(n){let i={Version:"2019-10-30",StartAction:"greeting",Actions:[{Identifier:"greeting",Type:"MessageParticipant",Parameters:{Text:n.greeting},Transitions:{NextAction:"transfer_to_queue",Errors:[{NextAction:"disconnect"}]}},{Identifier:"transfer_to_queue",Type:"TransferToQueue",Parameters:{QueueId:n.queueArn},Transitions:{NextAction:n.voicemailLambdaArn?"voicemail":"disconnect",Errors:[{NextAction:"disconnect"}]}},...n.voicemailLambdaArn?[{Identifier:"voicemail",Type:"InvokeLambdaFunction",Parameters:{LambdaFunctionARN:n.voicemailLambdaArn},Transitions:{NextAction:"disconnect",Errors:[{NextAction:"disconnect"}]}}]:[],{Identifier:"disconnect",Type:"DisconnectParticipant",Parameters:{},Transitions:{}}]};return JSON.stringify(i)}static createPhoneLambdaRole(n){return{[`${n.slug}PhoneLambdaRole`]:{Type:"AWS::IAM::Role",Properties:{RoleName:`${n.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(n){return{[`${n.slug}IncomingCallLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${n.slug}-incoming-call`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:tt.LambdaCode.incomingCall},Environment:{Variables:{NOTIFICATION_TOPIC_ARN:n.notificationTopicArn||"",CALL_LOG_TABLE:n.callLogTable||"",WEBHOOK_URL:n.webhookUrl||""}}}}}}static createVoicemailLambda(n){return{[`${n.slug}VoicemailLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${n.slug}-voicemail`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n.roleArn,Timeout:300,MemorySize:512,Code:{ZipFile:tt.LambdaCode.voicemail},Environment:{Variables:{VOICEMAIL_BUCKET:n.voicemailBucket,NOTIFICATION_TOPIC_ARN:n.notificationTopicArn||"",CALL_LOG_TABLE:n.callLogTable||"",TRANSCRIPTION_ENABLED:n.transcriptionEnabled?"true":"false"}}}}}}static createMissedCallLambda(n){return{[`${n.slug}MissedCallLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${n.slug}-missed-call`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:tt.LambdaCode.missedCall},Environment:{Variables:{NOTIFICATION_TOPIC_ARN:n.notificationTopicArn||"",CALL_LOG_TABLE:n.callLogTable||"",WEBHOOK_URL:n.webhookUrl||""}}}}}}static createCallLogTable(n){return{[`${n.slug}CallLogTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${n.slug}-call-log`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"contactId",AttributeType:"S"}],KeySchema:[{AttributeName:"contactId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createCompleteSetup(n){let i={},s={};Object.assign(i,tt.createPhoneLambdaRole({slug:n.slug})),Object.assign(i,tt.createCallLogTable({slug:n.slug})),i[`${n.slug}PhoneNotificationTopic`]={Type:"AWS::SNS::Topic",Properties:{TopicName:`${n.slug}-phone-notifications`}},i[`${n.slug}VoicemailBucket`]={Type:"AWS::S3::Bucket",Properties:{BucketName:`${n.slug}-voicemails`,LifecycleConfiguration:{Rules:[{Id:"DeleteOldVoicemails",Status:"Enabled",ExpirationInDays:90}]}}};let o={"Fn::GetAtt":[`${n.slug}PhoneLambdaRole`,"Arn"]},c={Ref:`${n.slug}PhoneNotificationTopic`},u={Ref:`${n.slug}CallLogTable`},d={Ref:`${n.slug}VoicemailBucket`};if(Object.assign(i,tt.createIncomingCallLambda({slug:n.slug,roleArn:o,notificationTopicArn:c,callLogTable:u,webhookUrl:n.webhookUrl})),n.voicemailEnabled!==!1)Object.assign(i,tt.createVoicemailLambda({slug:n.slug,roleArn:o,voicemailBucket:d,notificationTopicArn:c,callLogTable:u,transcriptionEnabled:n.transcriptionEnabled}));return Object.assign(i,tt.createMissedCallLambda({slug:n.slug,roleArn:o,notificationTopicArn:c,callLogTable:u,webhookUrl:n.webhookUrl})),s[`${n.slug}PhoneNotificationTopicArn`]={Description:"Phone notification topic ARN",Value:{Ref:`${n.slug}PhoneNotificationTopic`}},s[`${n.slug}CallLogTableName`]={Description:"Call log table name",Value:{Ref:`${n.slug}CallLogTable`}},s[`${n.slug}VoicemailBucketName`]={Description:"Voicemail bucket name",Value:{Ref:`${n.slug}VoicemailBucket`}},{resources:i,outputs:s}}}class J{static createQueue(n){let{slug:i,environment:s,name:o,delaySeconds:c=0,visibilityTimeout:u=30,messageRetentionPeriod:d=345600,maxMessageSize:g=262144,receiveMessageWaitTime:y=0,fifo:h=!1,contentBasedDeduplication:b=!1,encrypted:v=!0,kmsKeyId:A}=n,T=o||r({slug:i,environment:s,resourceType:"queue"}),R=h?`${T}.fifo`:T,P=t(T),I={Type:"AWS::SQS::Queue",Properties:{QueueName:R,DelaySeconds:c,MaximumMessageSize:g,MessageRetentionPeriod:d,ReceiveMessageWaitTimeSeconds:y,VisibilityTimeout:u,Tags:[{Key:"Name",Value:R},{Key:"Environment",Value:s}]}};if(h)I.Properties.FifoQueue=!0,I.Properties.ContentBasedDeduplication=b;if(v)if(A)I.Properties.KmsMasterKeyId=A;else I.Properties.SqsManagedSseEnabled=!0;return{queue:I,logicalId:P}}static createDeadLetterQueue(n,i){let{slug:s,environment:o,maxReceiveCount:c=3}=i,u=r({slug:s,environment:o,resourceType:"dlq"}),d=t(u),g={Type:"AWS::SQS::Queue",Properties:{QueueName:u,MessageRetentionPeriod:1209600,Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:o},{Key:"Type",Value:"DeadLetterQueue"}]}},y={Type:"AWS::SQS::Queue",Properties:{RedrivePolicy:{deadLetterTargetArn:x.GetAtt(d,"Arn"),maxReceiveCount:c}}};return{deadLetterQueue:g,updatedSourceQueue:y,deadLetterLogicalId:d}}static createSchedule(n,i){let{slug:s,environment:o,name:c,description:u,enabled:d=!0}=i,g=c||r({slug:s,environment:o,resourceType:"schedule"}),y=t(g);return{rule:{Type:"AWS::Events::Rule",Properties:{Name:g,Description:u,ScheduleExpression:n,State:d?"ENABLED":"DISABLED",Targets:[]}},logicalId:y}}static scheduleEcsTask(n,i,s){let{slug:o,environment:c,name:u,description:d,enabled:g=!0,taskDefinitionArn:y,clusterArn:h,subnets:b,securityGroups:v=[],assignPublicIp:A=!1,taskCount:T=1,containerOverrides:R}=s,P=u||r({slug:o,environment:c,resourceType:"ecs-schedule"}),I=t(P),L={Id:"1",Arn:h,RoleArn:i,EcsParameters:{TaskDefinitionArn:y,TaskCount:T,LaunchType:"FARGATE",NetworkConfiguration:{awsvpcConfiguration:{Subnets:b,SecurityGroups:v,AssignPublicIp:A?"ENABLED":"DISABLED"}},PlatformVersion:"LATEST"}};if(R&&R.length>0)L.Input=JSON.stringify({containerOverrides:R});return{rule:{Type:"AWS::Events::Rule",Properties:{Name:P,Description:d||`Scheduled ECS task: ${y}`,ScheduleExpression:n,State:g?"ENABLED":"DISABLED",Targets:[L]}},logicalId:I}}static scheduleLambda(n,i){let{slug:s,environment:o,name:c,description:u,enabled:d=!0,functionArn:g,input:y}=i,h=c||r({slug:s,environment:o,resourceType:"lambda-schedule"}),b=t(h),v={Id:"1",Arn:g};if(y)v.Input=JSON.stringify(y);return{rule:{Type:"AWS::Events::Rule",Properties:{Name:h,Description:u||`Scheduled Lambda: ${g}`,ScheduleExpression:n,State:d?"ENABLED":"DISABLED",Targets:[v]}},logicalId:b}}static scheduleSqsMessage(n,i){let{slug:s,environment:o,name:c,description:u,enabled:d=!0,queueArn:g,messageGroupId:y}=i,h=c||r({slug:s,environment:o,resourceType:"sqs-schedule"}),b=t(h),v={Id:"1",Arn:g};if(y)v.SqsParameters={MessageGroupId:y};return{rule:{Type:"AWS::Events::Rule",Properties:{Name:h,Description:u||`Scheduled SQS message: ${g}`,ScheduleExpression:n,State:d?"ENABLED":"DISABLED",Targets:[v]}},logicalId:b}}static addTarget(n,i){if(!n.Properties.Targets)n.Properties.Targets=[];let s={Id:i.id,Arn:i.arn};if(i.roleArn)s.RoleArn=i.roleArn;if(i.input)s.Input=JSON.stringify(i.input);return n.Properties.Targets.push(s),n}static toCronExpression(n){if(n.startsWith("cron(")||n.startsWith("rate("))return n;return`cron(${n})`}static rateExpression(n,i){return`rate(${n} ${i})`}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(n){let i=n.toLowerCase().trim(),s=i.match(/^every\s+(\d+)\s+(minute|minutes|hour|hours|day|days)$/i);if(s){let h=parseInt(s[1],10),b=s[2].toLowerCase(),v=b.endsWith("s")&&h===1?b.slice(0,-1):b,A=!b.endsWith("s")&&h>1?`${b}s`:b;return`rate(${h} ${h===1?v:A})`}let o=i.match(/^every\s+(minute|hour|day)$/i);if(o)return`rate(1 ${o[1]})`;let c={"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(c[i])return c[i];let u=i.match(/^daily\s+at\s+(\d{1,2})\s*(am|pm)?$/i);if(u){let h=parseInt(u[1],10),b=u[2]?.toLowerCase();if(b==="pm"&&h!==12)h+=12;else if(b==="am"&&h===12)h=0;return`cron(0 ${h} * * ? *)`}let d=i.match(/^at\s+(\d{1,2}):(\d{2})$/i);if(d){let h=parseInt(d[1],10);return`cron(${parseInt(d[2],10)} ${h} * * ? *)`}let g={monday:"MON",tuesday:"TUE",wednesday:"WED",thursday:"THU",friday:"FRI",saturday:"SAT",sunday:"SUN"},y=i.match(/^every\s+(monday|tuesday|wednesday|thursday|friday|saturday|sunday)$/i);if(y)return`cron(0 0 ? * ${g[y[1].toLowerCase()]} *)`;return J.toCronExpression(n)}static JobConfig={create:(n)=>{let{name:i,handler:s,retries:o=3,backoff:c="exponential",backoffDelay:u=1000,maxDelay:d=30000,timeout:g=60000,jitter:y=!0}=n;return{name:i,handler:s,retries:o,backoff:c,backoffDelay:u,maxDelay:d,timeout:g,jitter:y}},calculateDelay:(n,i)=>{let{backoff:s,backoffDelay:o,maxDelay:c,jitter:u}=i,d;switch(s){case"linear":d=o*n;break;case"exponential":d=o*2**(n-1);break;case"fixed":default:d=o}if(d=Math.min(d,c||Number.MAX_SAFE_INTEGER),u){let g=d*0.25*Math.random();d+=g}return Math.floor(d)},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(n){let{containerName:i,jobClass:s,jobData:o,environment:c={}}=n,u=[{name:"JOB_CLASS",value:s}];if(o)u.push({name:"JOB_DATA",value:JSON.stringify(o)});for(let[d,g]of Object.entries(c))u.push({name:d,value:g});return{name:i,command:["bun","run","app/Jobs/runner.ts"],environment:u}}static createScheduledJob(n){let{slug:i,environment:s,schedule:o,jobClass:c,jobData:u,taskDefinitionArn:d,clusterArn:g,subnets:y,securityGroups:h=[],roleArn:b,containerName:v="app"}=n,A=J.rateStringToExpression(o),T=J.createJobContainerOverride({containerName:v,jobClass:c,jobData:u});return J.scheduleEcsTask(A,b,{slug:i,environment:s,name:`${i}-${c.toLowerCase().replace(/[^a-z0-9]/g,"-")}`,description:`Scheduled job: ${c}`,taskDefinitionArn:d,clusterArn:g,subnets:y,securityGroups:h,containerOverrides:[T]})}static QueuePresets={highThroughput:(n,i)=>J.createQueue({slug:n,environment:i,visibilityTimeout:30,receiveMessageWaitTime:0,delaySeconds:0}),longRunning:(n,i)=>J.createQueue({slug:n,environment:i,visibilityTimeout:300,messageRetentionPeriod:1209600}),fifo:(n,i)=>J.createQueue({slug:n,environment:i,fifo:!0,contentBasedDeduplication:!0}),delayed:(n,i,s=60)=>J.createQueue({slug:n,environment:i,delaySeconds:s})}}class Nt{static async discoverJobs(n){let{projectRoot:i,jobsPath:s="app/Jobs"}=n,o=`${i}/${s}`,c=[];try{let u=await import("node:fs"),d=await import("node:path");if(!u.existsSync(o))return[];let g=u.readdirSync(o).filter((y)=>y.endsWith(".ts")&&!y.startsWith("_")&&y!=="runner.ts");for(let y of g){let h=d.join(o,y),b=y.replace(".ts",""),v=u.readFileSync(h,"utf-8"),A=Nt.parseJobMetadata(v,b,h);if(A)c.push(A)}}catch{return[]}return c}static parseJobMetadata(n,i,s){let o=n.match(/export\s + const\s + schedule\s*=\s*['"`]([^'"`]+)['"`]/)||n.match(/schedule:\s*['"`]([^'"`]+)['"`]/),c=n.match(/export\s+const\s+enabled\s*=\s*(true|false)/)||n.match(/enabled:\s*(true|false)/),u=n.match(/export\s+const\s+retries\s*=\s*(\d+)/)||n.match(/retries:\s*(\d+)/),d=n.match(/export\s+const\s+timeout\s*=\s*(\d+)/)||n.match(/timeout:\s*(\d+)/),g=n.match(/export\s+const\s+backoff\s*=\s*['"`](linear|exponential|fixed)['"`]/)||n.match(/backoff:\s*['"`](linear|exponential|fixed)['"`]/),y=n.match(/export\s + const\s + description\s*=\s*['"`]([^'"`]+)['"`]/)||n.match(/description:\s*['"`]([^'"`]+)['"`]/);if(!(n.includes("export async function handle")||n.includes("export function handle")||n.includes("export default")))return null;return{name:i,path:s,schedule:o?.[1],handler:`${i}.handle`,enabled:c?.[1]!=="false",retries:u?parseInt(u[1],10):void 0,backoff:g?.[1],timeout:d?parseInt(d[1],10):void 0,description:y?.[1]}}static async discoverActions(n){let{projectRoot:i,actionsPath:s="app/Actions"}=n,o=`${i}/${s}`,c=[];try{let u=await import("node:fs"),d=await import("node:path");if(!u.existsSync(o))return[];let g=u.readdirSync(o).filter((y)=>y.endsWith(".ts")&&!y.startsWith("_"));for(let y of g){let h=d.join(o,y),b=y.replace(".ts",""),v=u.readFileSync(h,"utf-8"),A=Nt.parseActionMetadata(v,b,h);if(A)c.push(A)}}catch{return[]}return c}static parseActionMetadata(n,i,s){if(!(n.includes("export async function handle")||n.includes("export function handle")||n.includes("export default")))return null;let c=n.match(/export\s + const\s + description\s*=\s*['"`]([^'"`]+)['"`]/)||n.match(/description:\s*['"`]([^'"`]+)['"`]/);return{name:i,path:s,handler:`${i}.handle`,description:c?.[1]}}static generateScheduledJobResources(n){let{slug:i,environment:s,jobs:o,taskDefinitionArn:c,clusterArn:u,subnets:d,securityGroups:g=[],roleArn:y,containerName:h="app"}=n,b={},v=0;for(let A of o){if(!A.schedule||!A.enabled)continue;let{rule:T,logicalId:R}=J.createScheduledJob({slug:i,environment:s,schedule:A.schedule,jobClass:A.name,taskDefinitionArn:c,clusterArn:u,subnets:d,securityGroups:g,roleArn:y,containerName:h});b[R]=T,v++}return{rules:b,count:v}}static generateJobRunnerScript(){return`#!/usr/bin/env bun
1626
+ `;class rt{static LambdaCode={incomingCall:At,voicemail:sn,missedCall:rn};static createConnectInstance(n){let{slug:i,environment:s,instanceAlias:o,inboundCallsEnabled:c=!0,outboundCallsEnabled:u=!0}=n;return{[`${i}ConnectInstance`]:{Type:"AWS::Connect::Instance",Properties:{InstanceAlias:o,IdentityManagementType:"CONNECT_MANAGED",Attributes:{InboundCalls:c,OutboundCalls:u,ContactflowLogs:!0,ContactLens:!0,AutoResolveBestVoices:!0,UseCustomTTSVoices:!1,EarlyMedia:!0}}}}}static createHoursOfOperation(n){return{[`${n.slug}HoursOfOperation`]:{Type:"AWS::Connect::HoursOfOperation",Properties:{InstanceArn:n.instanceArn,Name:n.name,TimeZone:n.timezone,Config:n.schedule.map((i)=>({Day:i.day,StartTime:{Hours:i.startHour,Minutes:i.startMinute},EndTime:{Hours:i.endHour,Minutes:i.endMinute}}))}}}}static createQueue(n){return{[`${n.slug}Queue`]:{Type:"AWS::Connect::Queue",Properties:{InstanceArn:n.instanceArn,Name:n.name,HoursOfOperationArn:n.hoursOfOperationArn,MaxContacts:n.maxContacts||10}}}}static createContactFlow(n){return{[`${n.slug}ContactFlow`]:{Type:"AWS::Connect::ContactFlow",Properties:{InstanceArn:n.instanceArn,Name:n.name,Type:n.type,Content:n.content}}}}static createBasicIvrFlow(n){let i={Version:"2019-10-30",StartAction:"greeting",Actions:[{Identifier:"greeting",Type:"MessageParticipant",Parameters:{Text:n.greeting},Transitions:{NextAction:"transfer_to_queue",Errors:[{NextAction:"disconnect"}]}},{Identifier:"transfer_to_queue",Type:"TransferToQueue",Parameters:{QueueId:n.queueArn},Transitions:{NextAction:n.voicemailLambdaArn?"voicemail":"disconnect",Errors:[{NextAction:"disconnect"}]}},...n.voicemailLambdaArn?[{Identifier:"voicemail",Type:"InvokeLambdaFunction",Parameters:{LambdaFunctionARN:n.voicemailLambdaArn},Transitions:{NextAction:"disconnect",Errors:[{NextAction:"disconnect"}]}}]:[],{Identifier:"disconnect",Type:"DisconnectParticipant",Parameters:{},Transitions:{}}]};return JSON.stringify(i)}static createPhoneLambdaRole(n){return{[`${n.slug}PhoneLambdaRole`]:{Type:"AWS::IAM::Role",Properties:{RoleName:`${n.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(n){return{[`${n.slug}IncomingCallLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${n.slug}-incoming-call`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:rt.LambdaCode.incomingCall},Environment:{Variables:{NOTIFICATION_TOPIC_ARN:n.notificationTopicArn||"",CALL_LOG_TABLE:n.callLogTable||"",WEBHOOK_URL:n.webhookUrl||""}}}}}}static createVoicemailLambda(n){return{[`${n.slug}VoicemailLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${n.slug}-voicemail`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n.roleArn,Timeout:300,MemorySize:512,Code:{ZipFile:rt.LambdaCode.voicemail},Environment:{Variables:{VOICEMAIL_BUCKET:n.voicemailBucket,NOTIFICATION_TOPIC_ARN:n.notificationTopicArn||"",CALL_LOG_TABLE:n.callLogTable||"",TRANSCRIPTION_ENABLED:n.transcriptionEnabled?"true":"false"}}}}}}static createMissedCallLambda(n){return{[`${n.slug}MissedCallLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${n.slug}-missed-call`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:rt.LambdaCode.missedCall},Environment:{Variables:{NOTIFICATION_TOPIC_ARN:n.notificationTopicArn||"",CALL_LOG_TABLE:n.callLogTable||"",WEBHOOK_URL:n.webhookUrl||""}}}}}}static createCallLogTable(n){return{[`${n.slug}CallLogTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${n.slug}-call-log`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"contactId",AttributeType:"S"}],KeySchema:[{AttributeName:"contactId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createCompleteSetup(n){let i={},s={};Object.assign(i,rt.createPhoneLambdaRole({slug:n.slug})),Object.assign(i,rt.createCallLogTable({slug:n.slug})),i[`${n.slug}PhoneNotificationTopic`]={Type:"AWS::SNS::Topic",Properties:{TopicName:`${n.slug}-phone-notifications`}},i[`${n.slug}VoicemailBucket`]={Type:"AWS::S3::Bucket",Properties:{BucketName:`${n.slug}-voicemails`,LifecycleConfiguration:{Rules:[{Id:"DeleteOldVoicemails",Status:"Enabled",ExpirationInDays:90}]}}};let o={"Fn::GetAtt":[`${n.slug}PhoneLambdaRole`,"Arn"]},c={Ref:`${n.slug}PhoneNotificationTopic`},u={Ref:`${n.slug}CallLogTable`},d={Ref:`${n.slug}VoicemailBucket`};if(Object.assign(i,rt.createIncomingCallLambda({slug:n.slug,roleArn:o,notificationTopicArn:c,callLogTable:u,webhookUrl:n.webhookUrl})),n.voicemailEnabled!==!1)Object.assign(i,rt.createVoicemailLambda({slug:n.slug,roleArn:o,voicemailBucket:d,notificationTopicArn:c,callLogTable:u,transcriptionEnabled:n.transcriptionEnabled}));return Object.assign(i,rt.createMissedCallLambda({slug:n.slug,roleArn:o,notificationTopicArn:c,callLogTable:u,webhookUrl:n.webhookUrl})),s[`${n.slug}PhoneNotificationTopicArn`]={Description:"Phone notification topic ARN",Value:{Ref:`${n.slug}PhoneNotificationTopic`}},s[`${n.slug}CallLogTableName`]={Description:"Call log table name",Value:{Ref:`${n.slug}CallLogTable`}},s[`${n.slug}VoicemailBucketName`]={Description:"Voicemail bucket name",Value:{Ref:`${n.slug}VoicemailBucket`}},{resources:i,outputs:s}}}class J{static createQueue(n){let{slug:i,environment:s,name:o,delaySeconds:c=0,visibilityTimeout:u=30,messageRetentionPeriod:d=345600,maxMessageSize:g=262144,receiveMessageWaitTime:y=0,fifo:h=!1,contentBasedDeduplication:b=!1,encrypted:v=!0,kmsKeyId:A}=n,T=o||r({slug:i,environment:s,resourceType:"queue"}),R=h?`${T}.fifo`:T,P=t(T),I={Type:"AWS::SQS::Queue",Properties:{QueueName:R,DelaySeconds:c,MaximumMessageSize:g,MessageRetentionPeriod:d,ReceiveMessageWaitTimeSeconds:y,VisibilityTimeout:u,Tags:[{Key:"Name",Value:R},{Key:"Environment",Value:s}]}};if(h)I.Properties.FifoQueue=!0,I.Properties.ContentBasedDeduplication=b;if(v)if(A)I.Properties.KmsMasterKeyId=A;else I.Properties.SqsManagedSseEnabled=!0;return{queue:I,logicalId:P}}static createDeadLetterQueue(n,i){let{slug:s,environment:o,maxReceiveCount:c=3}=i,u=r({slug:s,environment:o,resourceType:"dlq"}),d=t(u),g={Type:"AWS::SQS::Queue",Properties:{QueueName:u,MessageRetentionPeriod:1209600,Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:o},{Key:"Type",Value:"DeadLetterQueue"}]}},y={Type:"AWS::SQS::Queue",Properties:{RedrivePolicy:{deadLetterTargetArn:x.GetAtt(d,"Arn"),maxReceiveCount:c}}};return{deadLetterQueue:g,updatedSourceQueue:y,deadLetterLogicalId:d}}static createSchedule(n,i){let{slug:s,environment:o,name:c,description:u,enabled:d=!0}=i,g=c||r({slug:s,environment:o,resourceType:"schedule"}),y=t(g);return{rule:{Type:"AWS::Events::Rule",Properties:{Name:g,Description:u,ScheduleExpression:n,State:d?"ENABLED":"DISABLED",Targets:[]}},logicalId:y}}static scheduleEcsTask(n,i,s){let{slug:o,environment:c,name:u,description:d,enabled:g=!0,taskDefinitionArn:y,clusterArn:h,subnets:b,securityGroups:v=[],assignPublicIp:A=!1,taskCount:T=1,containerOverrides:R}=s,P=u||r({slug:o,environment:c,resourceType:"ecs-schedule"}),I=t(P),L={Id:"1",Arn:h,RoleArn:i,EcsParameters:{TaskDefinitionArn:y,TaskCount:T,LaunchType:"FARGATE",NetworkConfiguration:{awsvpcConfiguration:{Subnets:b,SecurityGroups:v,AssignPublicIp:A?"ENABLED":"DISABLED"}},PlatformVersion:"LATEST"}};if(R&&R.length>0)L.Input=JSON.stringify({containerOverrides:R});return{rule:{Type:"AWS::Events::Rule",Properties:{Name:P,Description:d||`Scheduled ECS task: ${y}`,ScheduleExpression:n,State:g?"ENABLED":"DISABLED",Targets:[L]}},logicalId:I}}static scheduleLambda(n,i){let{slug:s,environment:o,name:c,description:u,enabled:d=!0,functionArn:g,input:y}=i,h=c||r({slug:s,environment:o,resourceType:"lambda-schedule"}),b=t(h),v={Id:"1",Arn:g};if(y)v.Input=JSON.stringify(y);return{rule:{Type:"AWS::Events::Rule",Properties:{Name:h,Description:u||`Scheduled Lambda: ${g}`,ScheduleExpression:n,State:d?"ENABLED":"DISABLED",Targets:[v]}},logicalId:b}}static scheduleSqsMessage(n,i){let{slug:s,environment:o,name:c,description:u,enabled:d=!0,queueArn:g,messageGroupId:y}=i,h=c||r({slug:s,environment:o,resourceType:"sqs-schedule"}),b=t(h),v={Id:"1",Arn:g};if(y)v.SqsParameters={MessageGroupId:y};return{rule:{Type:"AWS::Events::Rule",Properties:{Name:h,Description:u||`Scheduled SQS message: ${g}`,ScheduleExpression:n,State:d?"ENABLED":"DISABLED",Targets:[v]}},logicalId:b}}static addTarget(n,i){if(!n.Properties.Targets)n.Properties.Targets=[];let s={Id:i.id,Arn:i.arn};if(i.roleArn)s.RoleArn=i.roleArn;if(i.input)s.Input=JSON.stringify(i.input);return n.Properties.Targets.push(s),n}static toCronExpression(n){if(n.startsWith("cron(")||n.startsWith("rate("))return n;return`cron(${n})`}static rateExpression(n,i){return`rate(${n} ${i})`}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(n){let i=n.toLowerCase().trim(),s=i.match(/^every\s+(\d+)\s+(minute|minutes|hour|hours|day|days)$/i);if(s){let h=parseInt(s[1],10),b=s[2].toLowerCase(),v=b.endsWith("s")&&h===1?b.slice(0,-1):b,A=!b.endsWith("s")&&h>1?`${b}s`:b;return`rate(${h} ${h===1?v:A})`}let o=i.match(/^every\s+(minute|hour|day)$/i);if(o)return`rate(1 ${o[1]})`;let c={"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(c[i])return c[i];let u=i.match(/^daily\s+at\s+(\d{1,2})\s*(am|pm)?$/i);if(u){let h=parseInt(u[1],10),b=u[2]?.toLowerCase();if(b==="pm"&&h!==12)h+=12;else if(b==="am"&&h===12)h=0;return`cron(0 ${h} * * ? *)`}let d=i.match(/^at\s+(\d{1,2}):(\d{2})$/i);if(d){let h=parseInt(d[1],10);return`cron(${parseInt(d[2],10)} ${h} * * ? *)`}let g={monday:"MON",tuesday:"TUE",wednesday:"WED",thursday:"THU",friday:"FRI",saturday:"SAT",sunday:"SUN"},y=i.match(/^every\s+(monday|tuesday|wednesday|thursday|friday|saturday|sunday)$/i);if(y)return`cron(0 0 ? * ${g[y[1].toLowerCase()]} *)`;return J.toCronExpression(n)}static JobConfig={create:(n)=>{let{name:i,handler:s,retries:o=3,backoff:c="exponential",backoffDelay:u=1000,maxDelay:d=30000,timeout:g=60000,jitter:y=!0}=n;return{name:i,handler:s,retries:o,backoff:c,backoffDelay:u,maxDelay:d,timeout:g,jitter:y}},calculateDelay:(n,i)=>{let{backoff:s,backoffDelay:o,maxDelay:c,jitter:u}=i,d;switch(s){case"linear":d=o*n;break;case"exponential":d=o*2**(n-1);break;case"fixed":default:d=o}if(d=Math.min(d,c||Number.MAX_SAFE_INTEGER),u){let g=d*0.25*Math.random();d+=g}return Math.floor(d)},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(n){let{containerName:i,jobClass:s,jobData:o,environment:c={}}=n,u=[{name:"JOB_CLASS",value:s}];if(o)u.push({name:"JOB_DATA",value:JSON.stringify(o)});for(let[d,g]of Object.entries(c))u.push({name:d,value:g});return{name:i,command:["bun","run","app/Jobs/runner.ts"],environment:u}}static createScheduledJob(n){let{slug:i,environment:s,schedule:o,jobClass:c,jobData:u,taskDefinitionArn:d,clusterArn:g,subnets:y,securityGroups:h=[],roleArn:b,containerName:v="app"}=n,A=J.rateStringToExpression(o),T=J.createJobContainerOverride({containerName:v,jobClass:c,jobData:u});return J.scheduleEcsTask(A,b,{slug:i,environment:s,name:`${i}-${c.toLowerCase().replace(/[^a-z0-9]/g,"-")}`,description:`Scheduled job: ${c}`,taskDefinitionArn:d,clusterArn:g,subnets:y,securityGroups:h,containerOverrides:[T]})}static QueuePresets={highThroughput:(n,i)=>J.createQueue({slug:n,environment:i,visibilityTimeout:30,receiveMessageWaitTime:0,delaySeconds:0}),longRunning:(n,i)=>J.createQueue({slug:n,environment:i,visibilityTimeout:300,messageRetentionPeriod:1209600}),fifo:(n,i)=>J.createQueue({slug:n,environment:i,fifo:!0,contentBasedDeduplication:!0}),delayed:(n,i,s=60)=>J.createQueue({slug:n,environment:i,delaySeconds:s})}}class Bt{static async discoverJobs(n){let{projectRoot:i,jobsPath:s="app/Jobs"}=n,o=`${i}/${s}`,c=[];try{let u=await import("node:fs"),d=await import("node:path");if(!u.existsSync(o))return[];let g=u.readdirSync(o).filter((y)=>y.endsWith(".ts")&&!y.startsWith("_")&&y!=="runner.ts");for(let y of g){let h=d.join(o,y),b=y.replace(".ts",""),v=u.readFileSync(h,"utf-8"),A=Bt.parseJobMetadata(v,b,h);if(A)c.push(A)}}catch{return[]}return c}static parseJobMetadata(n,i,s){let o=n.match(/export\s + const\s + schedule\s*=\s*['"`]([^'"`]+)['"`]/)||n.match(/schedule:\s*['"`]([^'"`]+)['"`]/),c=n.match(/export\s+const\s+enabled\s*=\s*(true|false)/)||n.match(/enabled:\s*(true|false)/),u=n.match(/export\s+const\s+retries\s*=\s*(\d+)/)||n.match(/retries:\s*(\d+)/),d=n.match(/export\s+const\s+timeout\s*=\s*(\d+)/)||n.match(/timeout:\s*(\d+)/),g=n.match(/export\s+const\s+backoff\s*=\s*['"`](linear|exponential|fixed)['"`]/)||n.match(/backoff:\s*['"`](linear|exponential|fixed)['"`]/),y=n.match(/export\s + const\s + description\s*=\s*['"`]([^'"`]+)['"`]/)||n.match(/description:\s*['"`]([^'"`]+)['"`]/);if(!(n.includes("export async function handle")||n.includes("export function handle")||n.includes("export default")))return null;return{name:i,path:s,schedule:o?.[1],handler:`${i}.handle`,enabled:c?.[1]!=="false",retries:u?parseInt(u[1],10):void 0,backoff:g?.[1],timeout:d?parseInt(d[1],10):void 0,description:y?.[1]}}static async discoverActions(n){let{projectRoot:i,actionsPath:s="app/Actions"}=n,o=`${i}/${s}`,c=[];try{let u=await import("node:fs"),d=await import("node:path");if(!u.existsSync(o))return[];let g=u.readdirSync(o).filter((y)=>y.endsWith(".ts")&&!y.startsWith("_"));for(let y of g){let h=d.join(o,y),b=y.replace(".ts",""),v=u.readFileSync(h,"utf-8"),A=Bt.parseActionMetadata(v,b,h);if(A)c.push(A)}}catch{return[]}return c}static parseActionMetadata(n,i,s){if(!(n.includes("export async function handle")||n.includes("export function handle")||n.includes("export default")))return null;let c=n.match(/export\s + const\s + description\s*=\s*['"`]([^'"`]+)['"`]/)||n.match(/description:\s*['"`]([^'"`]+)['"`]/);return{name:i,path:s,handler:`${i}.handle`,description:c?.[1]}}static generateScheduledJobResources(n){let{slug:i,environment:s,jobs:o,taskDefinitionArn:c,clusterArn:u,subnets:d,securityGroups:g=[],roleArn:y,containerName:h="app"}=n,b={},v=0;for(let A of o){if(!A.schedule||!A.enabled)continue;let{rule:T,logicalId:R}=J.createScheduledJob({slug:i,environment:s,schedule:A.schedule,jobClass:A.name,taskDefinitionArn:c,clusterArn:u,subnets:d,securityGroups:g,roleArn:y,containerName:h});b[R]=T,v++}return{rules:b,count:v}}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(n){let i=await Nt.discoverJobs(n),s=i.filter((o)=>o.schedule&&o.enabled);return{jobs:i,scheduledCount:s.length,totalCount:i.length}}}var JI={loadJobs:Nt.discoverJobs,loadActions:Nt.discoverActions,generateScheduledJobs:Nt.generateScheduledJobResources,generateRunner:Nt.generateJobRunnerScript,paths:{jobs:"app/Jobs",actions:"app/Actions",runner:"app/Jobs/runner.ts"}};var an=`
1671
+ `}static async generateJobManifest(n){let i=await Bt.discoverJobs(n),s=i.filter((o)=>o.schedule&&o.enabled);return{jobs:i,scheduledCount:s.length,totalCount:i.length}}}var JI={loadJobs:Bt.discoverJobs,loadActions:Bt.discoverActions,generateScheduledJobs:Bt.generateScheduledJobResources,generateRunner:Bt.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
 
@@ -2278,7 +2278,7 @@ function resolveTemplate(template, data) {
2278
2278
  | fields @timestamp, @message
2279
2279
  | filter @message like /ERROR|WARN|Exception/
2280
2280
  | sort @timestamp desc
2281
- | limit 50`,region:o,title:"Recent Errors and Warnings"}}),d+=6;return jo.createDashboard({slug:i,environment:s,widgets:u})}static DashboardTemplates={staticWebsite:(n)=>({slug:n.slug,environment:n.environment,widgets:[{type:"text",x:0,y:0,width:24,height:1,properties:{markdown:`# ${n.slug.toUpperCase()} Static Website Dashboard`}},{type:"metric",x:0,y:1,width:8,height:6,properties:{title:"CloudFront Requests",region:"us-east-1",metrics:[["AWS/CloudFront","Requests","DistributionId",n.cloudFrontDistributionId,"Region","Global"]],period:300,stat:"Sum"}},{type:"metric",x:8,y:1,width:8,height:6,properties:{title:"Error Rate",region:"us-east-1",metrics:[["AWS/CloudFront","4xxErrorRate","DistributionId",n.cloudFrontDistributionId,"Region","Global",{label:"4XX"}],["AWS/CloudFront","5xxErrorRate","DistributionId",n.cloudFrontDistributionId,"Region","Global",{label:"5XX"}]],period:300,stat:"Average"}},{type:"metric",x:16,y:1,width:8,height:6,properties:{title:"Bytes Downloaded",region:"us-east-1",metrics:[["AWS/CloudFront","BytesDownloaded","DistributionId",n.cloudFrontDistributionId,"Region","Global"]],period:300,stat:"Sum"}},{type:"metric",x:0,y:7,width:12,height:6,properties:{title:"S3 Bucket Size",region:n.region||"us-east-1",metrics:[["AWS/S3","BucketSizeBytes","BucketName",n.s3BucketName,"StorageType","StandardStorage"]],period:86400,stat:"Average"}},{type:"metric",x:12,y:7,width:12,height:6,properties:{title:"S3 Number of Objects",region:n.region||"us-east-1",metrics:[["AWS/S3","NumberOfObjects","BucketName",n.s3BucketName,"StorageType","AllStorageTypes"]],period:86400,stat:"Average"}}]}),serverlessApi:(n)=>({slug:n.slug,environment:n.environment,widgets:[{type:"text",x:0,y:0,width:24,height:1,properties:{markdown:`# ${n.slug.toUpperCase()} Serverless API Dashboard`}},{type:"metric",x:0,y:1,width:8,height:6,properties:{title:"API Requests",region:n.region||"us-east-1",metrics:[["AWS/ApiGateway","Count","ApiName",n.apiGatewayName]],period:60,stat:"Sum"}},{type:"metric",x:8,y:1,width:8,height:6,properties:{title:"API Latency",region:n.region||"us-east-1",metrics:[["AWS/ApiGateway","Latency","ApiName",n.apiGatewayName]],period:60,stat:"Average"}},{type:"metric",x:16,y:1,width:8,height:6,properties:{title:"API Errors",region:n.region||"us-east-1",metrics:[["AWS/ApiGateway","4XXError","ApiName",n.apiGatewayName,{label:"4XX"}],["AWS/ApiGateway","5XXError","ApiName",n.apiGatewayName,{label:"5XX"}]],period:60,stat:"Sum"}},...n.lambdaFunctionNames.map((i,s)=>({type:"metric",x:s%3*8,y:7+Math.floor(s/3)*6,width:8,height:6,properties:{title:`${i} Metrics`,region:n.region||"us-east-1",metrics:[["AWS/Lambda","Invocations","FunctionName",i],["AWS/Lambda","Duration","FunctionName",i],["AWS/Lambda","Errors","FunctionName",i]],period:300,stat:"Sum"}}))]}),containerService:(n)=>({slug:n.slug,environment:n.environment,widgets:[{type:"text",x:0,y:0,width:24,height:1,properties:{markdown:`# ${n.slug.toUpperCase()} Container Service Dashboard`}},{type:"metric",x:0,y:1,width:8,height:6,properties:{title:"ECS CPU",region:n.region||"us-east-1",metrics:[["AWS/ECS","CPUUtilization","ClusterName",n.ecsClusterName,"ServiceName",n.ecsServiceName]],period:60,stat:"Average"}},{type:"metric",x:8,y:1,width:8,height:6,properties:{title:"ECS Memory",region:n.region||"us-east-1",metrics:[["AWS/ECS","MemoryUtilization","ClusterName",n.ecsClusterName,"ServiceName",n.ecsServiceName]],period:60,stat:"Average"}},{type:"metric",x:16,y:1,width:8,height:6,properties:{title:"Running Tasks",region:n.region||"us-east-1",metrics:[["ECS/ContainerInsights","RunningTaskCount","ClusterName",n.ecsClusterName,"ServiceName",n.ecsServiceName]],period:60,stat:"Average"}},{type:"metric",x:0,y:7,width:8,height:6,properties:{title:"ALB Requests",region:n.region||"us-east-1",metrics:[["AWS/ApplicationELB","RequestCount","LoadBalancer",n.albName]],period:60,stat:"Sum"}},{type:"metric",x:8,y:7,width:8,height:6,properties:{title:"Response Time",region:n.region||"us-east-1",metrics:[["AWS/ApplicationELB","TargetResponseTime","LoadBalancer",n.albName]],period:60,stat:"Average"}},{type:"metric",x:16,y:7,width:8,height:6,properties:{title:"Healthy Hosts",region:n.region||"us-east-1",metrics:[["AWS/ApplicationELB","HealthyHostCount","LoadBalancer",n.albName]],period:60,stat:"Average"}},...n.rdsInstanceId?[{type:"metric",x:0,y:13,width:12,height:6,properties:{title:"RDS CPU",region:n.region||"us-east-1",metrics:[["AWS/RDS","CPUUtilization","DBInstanceIdentifier",n.rdsInstanceId]],period:300,stat:"Average"}},{type:"metric",x:12,y:13,width:12,height:6,properties:{title:"RDS Connections",region:n.region||"us-east-1",metrics:[["AWS/RDS","DatabaseConnections","DBInstanceIdentifier",n.rdsInstanceId]],period:60,stat:"Sum"}}]:[]]})};static Config={createAlarmConfig:(n)=>{let{metricName:i,namespace:s,threshold:o,comparisonOperator:c="GreaterThanThreshold",evaluationPeriods:u=1,period:d=300,statistic:g="Average",treatMissingData:y="missing"}=n;return{MetricName:i,Namespace:s,Threshold:o,ComparisonOperator:c,EvaluationPeriods:u,Period:d,Statistic:g,TreatMissingData:y}},namespaces:{ec2:"AWS/EC2",ecs:"AWS/ECS",lambda:"AWS/Lambda",rds:"AWS/RDS",sqs:"AWS/SQS",sns:"AWS/SNS",s3:"AWS/S3",cloudfront:"AWS/CloudFront",alb:"AWS/ApplicationELB",nlb:"AWS/NetworkELB",apiGateway:"AWS/ApiGateway",dynamodb:"AWS/DynamoDB",elasticache:"AWS/ElastiCache"},comparisonOperators:{greaterThan:"GreaterThanThreshold",greaterOrEqual:"GreaterThanOrEqualToThreshold",lessThan:"LessThanThreshold",lessOrEqual:"LessThanOrEqualToThreshold"},metrics:{ec2:{cpu:{metricName:"CPUUtilization",namespace:"AWS/EC2"},networkIn:{metricName:"NetworkIn",namespace:"AWS/EC2"},networkOut:{metricName:"NetworkOut",namespace:"AWS/EC2"},statusCheck:{metricName:"StatusCheckFailed",namespace:"AWS/EC2"}},ecs:{cpu:{metricName:"CPUUtilization",namespace:"AWS/ECS"},memory:{metricName:"MemoryUtilization",namespace:"AWS/ECS"}},lambda:{invocations:{metricName:"Invocations",namespace:"AWS/Lambda"},errors:{metricName:"Errors",namespace:"AWS/Lambda"},duration:{metricName:"Duration",namespace:"AWS/Lambda"},throttles:{metricName:"Throttles",namespace:"AWS/Lambda"},concurrentExecutions:{metricName:"ConcurrentExecutions",namespace:"AWS/Lambda"}},rds:{cpu:{metricName:"CPUUtilization",namespace:"AWS/RDS"},connections:{metricName:"DatabaseConnections",namespace:"AWS/RDS"},freeStorage:{metricName:"FreeStorageSpace",namespace:"AWS/RDS"},readLatency:{metricName:"ReadLatency",namespace:"AWS/RDS"},writeLatency:{metricName:"WriteLatency",namespace:"AWS/RDS"}},alb:{requestCount:{metricName:"RequestCount",namespace:"AWS/ApplicationELB"},responseTime:{metricName:"TargetResponseTime",namespace:"AWS/ApplicationELB"},httpCode4xx:{metricName:"HTTPCode_Target_4XX_Count",namespace:"AWS/ApplicationELB"},httpCode5xx:{metricName:"HTTPCode_Target_5XX_Count",namespace:"AWS/ApplicationELB"},healthyHosts:{metricName:"HealthyHostCount",namespace:"AWS/ApplicationELB"}},sqs:{messagesVisible:{metricName:"ApproximateNumberOfMessagesVisible",namespace:"AWS/SQS"},messagesDelayed:{metricName:"ApproximateNumberOfMessagesDelayed",namespace:"AWS/SQS"},messageAge:{metricName:"ApproximateAgeOfOldestMessage",namespace:"AWS/SQS"}}},presets:{highCpu:(n=80)=>({metricName:"CPUUtilization",threshold:n,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),highMemory:(n=80)=>({metricName:"MemoryUtilization",threshold:n,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),highErrors:(n=10)=>({metricName:"Errors",threshold:n,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:1,period:60,statistic:"Sum"}),highLatency:(n=5000)=>({metricName:"Duration",threshold:n,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),lowHealthyHosts:(n=1)=>({metricName:"HealthyHostCount",namespace:"AWS/ApplicationELB",threshold:n,comparisonOperator:"LessThanThreshold",evaluationPeriods:2,period:60,statistic:"Minimum"}),queueDepth:(n=1000)=>({metricName:"ApproximateNumberOfMessagesVisible",namespace:"AWS/SQS",threshold:n,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),lowStorage:(n=10737418240)=>({metricName:"FreeStorageSpace",namespace:"AWS/RDS",threshold:n,comparisonOperator:"LessThanThreshold",evaluationPeriods:1,period:300,statistic:"Average"})}}}class Y{static createUserPool(n){let{slug:i,environment:s,userPoolName:o,aliasAttributes:c,autoVerifiedAttributes:u,passwordPolicy:d,mfaConfiguration:g,emailConfiguration:y,smsConfiguration:h,lambdaTriggers:b,userPoolAddOns:v,accountRecoverySetting:A}=n,T=o||r({slug:i,environment:s,resourceType:"user-pool"}),R=t(T),P={Type:"AWS::Cognito::UserPool",Properties:{UserPoolName:T,Policies:d?{PasswordPolicy:{MinimumLength:d.minimumLength,RequireLowercase:d.requireLowercase,RequireUppercase:d.requireUppercase,RequireNumbers:d.requireNumbers,RequireSymbols:d.requireSymbols,TemporaryPasswordValidityDays:d.temporaryPasswordValidityDays}}:void 0,MfaConfiguration:g,Schema:[{Name:"email",AttributeDataType:"String",Required:!0,Mutable:!1}]}};if(c&&c.length>0)P.Properties.UsernameAttributes=c;if(u&&u.length>0)P.Properties.AutoVerifiedAttributes=u;if(y)P.Properties.EmailConfiguration={EmailSendingAccount:y.emailSendingAccount,From:y.from,ReplyToEmailAddress:y.replyToEmailAddress,SourceArn:y.sourceArn,ConfigurationSet:y.configurationSet};if(h)P.Properties.SmsConfiguration={ExternalId:h.externalId,SnsCallerArn:h.snsCallerArn};if(b)P.Properties.LambdaConfig={PreSignUp:b.preSignUp,PostConfirmation:b.postConfirmation,PreAuthentication:b.preAuthentication,PostAuthentication:b.postAuthentication,CustomMessage:b.customMessage,DefineAuthChallenge:b.defineAuthChallenge,CreateAuthChallenge:b.createAuthChallenge,VerifyAuthChallengeResponse:b.verifyAuthChallengeResponse,PreTokenGeneration:b.preTokenGeneration,UserMigration:b.userMigration};if(v)P.Properties.UserPoolAddOns={AdvancedSecurityMode:v.advancedSecurityMode};if(A)P.Properties.AccountRecoverySetting={RecoveryMechanisms:A.recoveryMechanisms};return{userPool:P,logicalId:R}}static createUserPoolClient(n,i){let{slug:s,environment:o,clientName:c,generateSecret:u=!1,refreshTokenValidity:d,accessTokenValidity:g,idTokenValidity:y,tokenValidityUnits:h,readAttributes:b,writeAttributes:v,explicitAuthFlows:A,preventUserExistenceErrors:T,enableTokenRevocation:R,callbackURLs:P,logoutURLs:I,allowedOAuthFlows:M,allowedOAuthScopes:L,allowedOAuthFlowsUserPoolClient:N,supportedIdentityProviders:O}=i,B=c||r({slug:s,environment:o,resourceType:"user-pool-client"}),F=t(B);return{client:{Type:"AWS::Cognito::UserPoolClient",Properties:{ClientName:B,UserPoolId:x.Ref(n),GenerateSecret:u,RefreshTokenValidity:d,AccessTokenValidity:g,IdTokenValidity:y,TokenValidityUnits:h,ReadAttributes:b,WriteAttributes:v,ExplicitAuthFlows:A,PreventUserExistenceErrors:T,EnableTokenRevocation:R,CallbackURLs:P,LogoutURLs:I,AllowedOAuthFlows:M,AllowedOAuthScopes:L,AllowedOAuthFlowsUserPoolClient:N,SupportedIdentityProviders:O}},logicalId:F}}static createUserPoolDomain(n,i){let{slug:s,environment:o,domain:c,customDomainConfig:u}=i,d=r({slug:s,environment:o,resourceType:"user-pool-domain"}),g=t(d);return{domain:{Type:"AWS::Cognito::UserPoolDomain",Properties:{Domain:c,UserPoolId:x.Ref(n),CustomDomainConfig:u}},logicalId:g}}static createIdentityPool(n){let{slug:i,environment:s,identityPoolName:o,allowUnauthenticatedIdentities:c=!1,cognitoIdentityProviders:u,supportedLoginProviders:d,samlProviderARNs:g,openIdConnectProviderARNs:y}=n,h=o||r({slug:i,environment:s,resourceType:"identity-pool"}),b=t(h);return{identityPool:{Type:"AWS::Cognito::IdentityPool",Properties:{IdentityPoolName:h,AllowUnauthenticatedIdentities:c,CognitoIdentityProviders:u,SupportedLoginProviders:d,SamlProviderARNs:g,OpenIdConnectProviderARNs:y}},logicalId:b}}static createIdentityPoolRoleAttachment(n,i){let{slug:s,environment:o,authenticatedRole:c,unauthenticatedRole:u,roleMappings:d}=i,g=r({slug:s,environment:o,resourceType:"identity-pool-role-attachment"}),y=t(g),h={authenticated:c};if(u)h.unauthenticated=u;return{attachment:{Type:"AWS::Cognito::IdentityPoolRoleAttachment",Properties:{IdentityPoolId:x.Ref(n),Roles:h,RoleMappings:d}},logicalId:y}}static createAuthenticatedRole(n){let{slug:i,environment:s,identityPoolLogicalId:o}=n,c=r({slug:i,environment:s,resourceType:"cognito-authenticated-role"}),u=t(c);return{role:{Type:"AWS::IAM::Role",Properties:{RoleName:c,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Federated:"cognito-identity.amazonaws.com"},Action:"sts:AssumeRoleWithWebIdentity",Condition:{StringEquals:{"cognito-identity.amazonaws.com:aud":x.Ref(o)},"ForAnyValue:StringLike":{"cognito-identity.amazonaws.com:amr":"authenticated"}}}]},Policies:[{PolicyName:"CognitoAuthenticatedPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["cognito-sync:*","cognito-identity:*"],Resource:"*"}]}}],Tags:[{Key:"Name",Value:c},{Key:"Environment",Value:s}]}},logicalId:u}}static createUnauthenticatedRole(n){let{slug:i,environment:s,identityPoolLogicalId:o}=n,c=r({slug:i,environment:s,resourceType:"cognito-unauthenticated-role"}),u=t(c);return{role:{Type:"AWS::IAM::Role",Properties:{RoleName:c,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Federated:"cognito-identity.amazonaws.com"},Action:"sts:AssumeRoleWithWebIdentity",Condition:{StringEquals:{"cognito-identity.amazonaws.com:aud":x.Ref(o)},"ForAnyValue:StringLike":{"cognito-identity.amazonaws.com:amr":"unauthenticated"}}}]},Policies:[{PolicyName:"CognitoUnauthenticatedPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["cognito-sync:*"],Resource:"*"}]}}],Tags:[{Key:"Name",Value:c},{Key:"Environment",Value:s}]}},logicalId:u}}static PasswordPolicies={relaxed:()=>({minimumLength:8,requireLowercase:!1,requireUppercase:!1,requireNumbers:!1,requireSymbols:!1,temporaryPasswordValidityDays:7}),standard:()=>({minimumLength:8,requireLowercase:!0,requireUppercase:!0,requireNumbers:!0,requireSymbols:!1,temporaryPasswordValidityDays:3}),strict:()=>({minimumLength:12,requireLowercase:!0,requireUppercase:!0,requireNumbers:!0,requireSymbols:!0,temporaryPasswordValidityDays:1})};static AuthFlows={standard:["ALLOW_USER_SRP_AUTH","ALLOW_REFRESH_TOKEN_AUTH"],admin:["ALLOW_ADMIN_USER_PASSWORD_AUTH","ALLOW_REFRESH_TOKEN_AUTH"],custom:["ALLOW_CUSTOM_AUTH","ALLOW_REFRESH_TOKEN_AUTH"],all:["ALLOW_USER_SRP_AUTH","ALLOW_USER_PASSWORD_AUTH","ALLOW_ADMIN_USER_PASSWORD_AUTH","ALLOW_CUSTOM_AUTH","ALLOW_REFRESH_TOKEN_AUTH"]};static OAuthScopes={basic:["openid","email","profile"],all:["openid","email","profile","phone","aws.cognito.signin.user.admin"]};static UseCases={webApp:(n,i,s)=>{let{userPool:o,logicalId:c}=Y.createUserPool({slug:n,environment:i,aliasAttributes:["email"],autoVerifiedAttributes:["email"],passwordPolicy:Y.PasswordPolicies.standard(),mfaConfiguration:"OPTIONAL"}),{client:u,logicalId:d}=Y.createUserPoolClient(c,{slug:n,environment:i,explicitAuthFlows:[...Y.AuthFlows.standard],callbackURLs:[s],allowedOAuthFlows:["code"],allowedOAuthScopes:[...Y.OAuthScopes.basic],allowedOAuthFlowsUserPoolClient:!0});return{userPool:o,poolId:c,client:u,clientId:d}},mobileApp:(n,i)=>{let{userPool:s,logicalId:o}=Y.createUserPool({slug:n,environment:i,aliasAttributes:["email"],autoVerifiedAttributes:["email"],passwordPolicy:Y.PasswordPolicies.standard(),mfaConfiguration:"OPTIONAL"}),{client:c,logicalId:u}=Y.createUserPoolClient(o,{slug:n,environment:i,explicitAuthFlows:[...Y.AuthFlows.standard]}),{identityPool:d,logicalId:g}=Y.createIdentityPool({slug:n,environment:i,allowUnauthenticatedIdentities:!1,cognitoIdentityProviders:[{ClientId:x.Ref(u),ProviderName:x.GetAtt(o,"ProviderName")}]}),{role:y,logicalId:h}=Y.createAuthenticatedRole({slug:n,environment:i,identityPoolLogicalId:g}),{attachment:b,logicalId:v}=Y.createIdentityPoolRoleAttachment(g,{slug:n,environment:i,authenticatedRole:x.GetAtt(h,"Arn")});return{userPool:s,poolId:o,client:c,clientId:u,identityPool:d,identityPoolId:g,authRole:y,authRoleId:h,attachment:b,attachmentId:v}}}}import{createHash as xr}from"node:crypto";import{copyFileSync as kr,existsSync as Tt,readdirSync as Mr,readFileSync as ot,statSync as Lr,writeFileSync as ct}from"node:fs";import{basename as Or,dirname as yn,extname as bn,join as Ke}from"node:path";class Z{static createApplication(n){let{slug:i,environment:s,applicationName:o,computePlatform:c}=n,u=o||r({slug:i,environment:s,resourceType:"deploy-app"}),d=t(u);return{application:{Type:"AWS::CodeDeploy::Application",Properties:{ApplicationName:u,ComputePlatform:c,Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:s}]}},logicalId:d}}static createDeploymentGroup(n,i){let{slug:s,environment:o,deploymentGroupName:c,serviceRoleArn:u,autoScalingGroups:d,ec2TagFilters:g,deploymentConfigName:y,autoRollbackConfiguration:h,alarmConfiguration:b,loadBalancerInfo:v,blueGreenDeploymentConfiguration:A}=i,T=c||r({slug:s,environment:o,resourceType:"deploy-group"}),R=t(T);return{deploymentGroup:{Type:"AWS::CodeDeploy::DeploymentGroup",Properties:{ApplicationName:x.Ref(n),DeploymentGroupName:T,ServiceRoleArn:u,AutoScalingGroups:d,Ec2TagFilters:g?.map((I)=>({Key:I.key,Value:I.value,Type:I.type})),DeploymentConfigName:y,AutoRollbackConfiguration:h?{Enabled:h.enabled,Events:h.events}:void 0,AlarmConfiguration:b?{Enabled:b.enabled,Alarms:b.alarms?.map((I)=>({Name:I.name})),IgnorePollAlarmFailure:b.ignorePollAlarmFailure}:void 0,LoadBalancerInfo:v?{TargetGroupInfoList:v.targetGroupInfoList?.map((I)=>({Name:I.name})),ElbInfoList:v.elbInfoList?.map((I)=>({Name:I.name}))}:void 0,BlueGreenDeploymentConfiguration:A?{TerminateBlueInstancesOnDeploymentSuccess:A.terminateBlueInstancesOnDeploymentSuccess?{Action:A.terminateBlueInstancesOnDeploymentSuccess.action,TerminationWaitTimeInMinutes:A.terminateBlueInstancesOnDeploymentSuccess.terminationWaitTimeInMinutes}:void 0,DeploymentReadyOption:A.deploymentReadyOption?{ActionOnTimeout:A.deploymentReadyOption.actionOnTimeout,WaitTimeInMinutes:A.deploymentReadyOption.waitTimeInMinutes}:void 0,GreenFleetProvisioningOption:A.greenFleetProvisioningOption?{Action:A.greenFleetProvisioningOption.action}:void 0}:void 0,Tags:[{Key:"Name",Value:T},{Key:"Environment",Value:o}]}},logicalId:R}}static createDeploymentConfig(n){let{slug:i,environment:s,deploymentConfigName:o,minimumHealthyHosts:c,trafficRoutingConfig:u}=n,d=o||r({slug:i,environment:s,resourceType:"deploy-config"}),g=t(d);return{deploymentConfig:{Type:"AWS::CodeDeploy::DeploymentConfig",Properties:{DeploymentConfigName:d,MinimumHealthyHosts:c?{Type:c.type,Value:c.value}:void 0,TrafficRoutingConfig:u?{Type:u.type,TimeBasedCanary:u.timeBasedCanary?{CanaryPercentage:u.timeBasedCanary.canaryPercentage,CanaryInterval:u.timeBasedCanary.canaryInterval}:void 0,TimeBasedLinear:u.timeBasedLinear?{LinearPercentage:u.timeBasedLinear.linearPercentage,LinearInterval:u.timeBasedLinear.linearInterval}:void 0}:void 0}},logicalId:g}}static DeploymentConfigs={allAtOnce:()=>({type:"FLEET_PERCENT",value:0}),halfAtATime:()=>({type:"FLEET_PERCENT",value:50}),oneAtATime:()=>({type:"HOST_COUNT",value:1}),custom:(n,i)=>({type:n,value:i})};static TrafficRouting={allAtOnce:()=>({type:"AllAtOnce"}),canary:(n,i)=>({type:"TimeBasedCanary",timeBasedCanary:{canaryPercentage:n,canaryInterval:i}}),linear:(n,i)=>({type:"TimeBasedLinear",timeBasedLinear:{linearPercentage:n,linearInterval:i}})};static RollbackConfigs={onFailure:()=>({enabled:!0,events:["DEPLOYMENT_FAILURE"]}),onAlarmOrFailure:()=>({enabled:!0,events:["DEPLOYMENT_FAILURE","DEPLOYMENT_STOP_ON_ALARM"]}),onAllEvents:()=>({enabled:!0,events:["DEPLOYMENT_FAILURE","DEPLOYMENT_STOP_ON_ALARM","DEPLOYMENT_STOP_ON_REQUEST"]}),disabled:()=>({enabled:!1})};static BlueGreenConfigs={standard:()=>({terminateBlueInstancesOnDeploymentSuccess:{action:"TERMINATE",terminationWaitTimeInMinutes:5},deploymentReadyOption:{actionOnTimeout:"CONTINUE_DEPLOYMENT",waitTimeInMinutes:0},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}}),withDelay:(n)=>({terminateBlueInstancesOnDeploymentSuccess:{action:"TERMINATE",terminationWaitTimeInMinutes:n},deploymentReadyOption:{actionOnTimeout:"CONTINUE_DEPLOYMENT",waitTimeInMinutes:0},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}}),withManualApproval:(n)=>({terminateBlueInstancesOnDeploymentSuccess:{action:"TERMINATE",terminationWaitTimeInMinutes:5},deploymentReadyOption:{actionOnTimeout:"STOP_DEPLOYMENT",waitTimeInMinutes:n},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}}),keepBlue:()=>({terminateBlueInstancesOnDeploymentSuccess:{action:"KEEP_ALIVE"},deploymentReadyOption:{actionOnTimeout:"CONTINUE_DEPLOYMENT",waitTimeInMinutes:0},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}})};static UseCases={ec2Deployment:(n,i,s,o)=>{let{application:c,logicalId:u}=Z.createApplication({slug:n,environment:i,computePlatform:"Server"}),{deploymentGroup:d,logicalId:g}=Z.createDeploymentGroup(u,{slug:n,environment:i,serviceRoleArn:s,autoScalingGroups:o,deploymentConfigName:"CodeDeployDefault.OneAtATime",autoRollbackConfiguration:Z.RollbackConfigs.onFailure()});return{application:c,appId:u,deploymentGroup:d,groupId:g}},lambdaCanaryDeployment:(n,i,s,o=10,c=5)=>{let{application:u,logicalId:d}=Z.createApplication({slug:n,environment:i,computePlatform:"Lambda"}),{deploymentConfig:g,logicalId:y}=Z.createDeploymentConfig({slug:n,environment:i,trafficRoutingConfig:Z.TrafficRouting.canary(o,c)}),{deploymentGroup:h,logicalId:b}=Z.createDeploymentGroup(d,{slug:n,environment:i,serviceRoleArn:s,deploymentConfigName:x.Ref(y),autoRollbackConfiguration:Z.RollbackConfigs.onAlarmOrFailure()});return{application:u,appId:d,deploymentConfig:g,configId:y,deploymentGroup:h,groupId:b}},ecsBlueGreenDeployment:(n,i,s,o)=>{let{application:c,logicalId:u}=Z.createApplication({slug:n,environment:i,computePlatform:"ECS"}),{deploymentGroup:d,logicalId:g}=Z.createDeploymentGroup(u,{slug:n,environment:i,serviceRoleArn:s,loadBalancerInfo:{targetGroupInfoList:[{name:o}]},blueGreenDeploymentConfiguration:Z.BlueGreenConfigs.standard(),autoRollbackConfiguration:Z.RollbackConfigs.onFailure()});return{application:c,appId:u,deploymentGroup:d,groupId:g}}};static Strategies={rolling:(n=25)=>({type:"rolling",batchPercentage:n}),blueGreen:()=>({type:"blue-green"}),canary:(n=10,i=5)=>({type:"canary",canaryPercentage:n,canaryInterval:i}),allAtOnce:()=>({type:"all-at-once"})}}class _{static ContentTypes={".html":"text/html",".htm":"text/html",".css":"text/css",".js":"application/javascript",".mjs":"application/javascript",".json":"application/json",".xml":"application/xml",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject",".pdf":"application/pdf",".txt":"text/plain",".md":"text/markdown",".map":"application/json"};static NoHashPatterns=[/^index\.html$/,/^favicon\.ico$/,/^robots\.txt$/,/^sitemap\.xml$/,/^manifest\.json$/,/^\.well-known\//,/^_redirects$/,/^_headers$/];static computeFileHash(n,i="md5"){let s=ot(n);return xr(i).update(s).digest("hex")}static computeShortHash(n){return _.computeFileHash(n).slice(0,8)}static getContentType(n){let i=bn(n).toLowerCase();return _.ContentTypes[i]||"application/octet-stream"}static shouldHashFile(n,i){return![..._.NoHashPatterns,...i||[]].some((o)=>o.test(n))}static generateHashedFilename(n,i){let s=bn(n),o=Or(n,s),c=yn(n);if(c===".")return`${o}.${i}${s}`;return Ke(c,`${o}.${i}${s}`)}static collectFiles(n,i){let s=[],o=i||n;if(!Tt(n))return s;let c=Mr(n,{withFileTypes:!0});for(let u of c){let d=Ke(n,u.name);if(u.isDirectory())s.push(..._.collectFiles(d,o));else if(u.isFile())s.push(d)}return s}static hashDirectory(n){let{sourceDir:i,outputDir:s,excludePatterns:o=[],hashAlgorithm:c="md5",copyUnhashed:u=!0}=n,d=_.collectFiles(i),g=[],y={};for(let b of d){let v=b.replace(i,"").replace(/^[/\\]/,""),A=_.shouldHashFile(v,o),T=Lr(b),R=A?_.computeFileHash(b,c).slice(0,8):"",P=A?_.generateHashedFilename(v,R):v,I={originalPath:v,hashedPath:P,hash:R,size:T.size,contentType:_.getContentType(b)};if(g.push(I),y[v]=P,s){let M=Ke(s,P),L=yn(M);if(!Tt(L)){let{mkdirSync:N}=it("node:fs");N(L,{recursive:!0})}if(A||u)kr(b,M)}}let h={version:"1.0",timestamp:new Date().toISOString(),assets:g,hashMap:y};if(s){let b=Ke(s,"asset-manifest.json");ct(b,JSON.stringify(h,null,2))}return h}static getInvalidationPaths(n,i){let s=[];if(!n)return["/*"];let o=n.hashMap,c=i.hashMap;for(let[u,d]of Object.entries(c)){let g=o[u];if(!g||g!==d){if(s.push(`/${u}`),g&&g!==d)s.push(`/${g}`)}}for(let[u,d]of Object.entries(o))if(!c[u])s.push(`/${u}`),s.push(`/${d}`);if(s.length>100)return["/*"];return[...new Set(s)]}static updateHtmlReferences(n){let{htmlDir:i,manifest:s,basePath:o=""}=n,c=_.collectFiles(i).filter((u)=>u.endsWith(".html")||u.endsWith(".htm"));for(let u of c){let d=ot(u,"utf-8");for(let[g,y]of Object.entries(s.hashMap)){if(g===y)continue;let h=[new RegExp(`(src|href)=["']${o}/?${_.escapeRegExp(g)}["']`,"g"),new RegExp(`url\\(["']?${o}/?${_.escapeRegExp(g)}["']?\\)`,"g")];for(let b of h)d=d.replace(b,(v)=>v.replace(g,y))}ct(u,d)}}static updateCssReferences(n){let{cssDir:i,manifest:s,basePath:o=""}=n,c=_.collectFiles(i).filter((u)=>u.endsWith(".css"));for(let u of c){let d=ot(u,"utf-8");for(let[g,y]of Object.entries(s.hashMap)){if(g===y)continue;let h=new RegExp(`url\\(["']?${o}/?${_.escapeRegExp(g)}["']?\\)`,"g");d=d.replace(h,`url(${o}/${y})`)}ct(u,d)}}static escapeRegExp(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}static generateS3DeploymentManifest(n){let{sourceDir:i,keyPrefix:s="",excludePatterns:o=[],cacheControl:c={hashed:"public, max-age=31536000, immutable",unhashed:"public, max-age=3600",html:"public, max-age=0, must-revalidate"}}=n;return _.hashDirectory({sourceDir:i,excludePatterns:o}).assets.map((d)=>{let g=d.hash!=="",y=d.contentType==="text/html",h=c.unhashed||"public, max-age=3600";if(y)h=c.html||"public, max-age=0, must-revalidate";else if(g)h=c.hashed||"public, max-age=31536000, immutable";return{localPath:Ke(i,d.originalPath),s3Key:s?`${s}/${d.hashedPath}`:d.hashedPath,contentType:d.contentType,cacheControl:h,hash:d.hash}})}static compareManifests(n,i){let s={added:[],removed:[],changed:[],unchanged:[]},o=new Set(Object.keys(n.hashMap)),c=new Set(Object.keys(i.hashMap));for(let u of c)if(!o.has(u))s.added.push(u);for(let u of o)if(!c.has(u))s.removed.push(u);for(let u of c)if(o.has(u))if(n.hashMap[u]!==i.hashMap[u])s.changed.push(u);else s.unchanged.push(u);return s}static loadManifest(n){if(!Tt(n))return null;try{let i=ot(n,"utf-8");return JSON.parse(i)}catch{return null}}static saveManifest(n,i){ct(i,JSON.stringify(n,null,2))}}class Yi{static createSecret(n){let{slug:i,environment:s,secretName:o,description:c,secretString:u,kmsKeyId:d,tags:g}=n,y=o||r({slug:i,environment:s,resourceType:"secret"}),h=t(y),b={Type:"AWS::SecretsManager::Secret",Properties:{Name:y,Description:c,SecretString:u,Tags:[{Key:"Name",Value:y},{Key:"Environment",Value:s},...g?Object.entries(g).map(([v,A])=>({Key:v,Value:A})):[]]}};if(d)b.Properties.KmsKeyId=d;return{secret:b,logicalId:h}}static createGeneratedSecret(n){let{slug:i,environment:s,secretName:o,description:c,excludeCharacters:u,excludeLowercase:d,excludeNumbers:g,excludePunctuation:y,excludeUppercase:h,passwordLength:b,requireEachIncludedType:v,kmsKeyId:A,tags:T}=n,R=o||r({slug:i,environment:s,resourceType:"secret"}),P=t(R),I={Type:"AWS::SecretsManager::Secret",Properties:{Name:R,Description:c,GenerateSecretString:{ExcludeCharacters:u,ExcludeLowercase:d,ExcludeNumbers:g,ExcludePunctuation:y,ExcludeUppercase:h,PasswordLength:b||32,RequireEachIncludedType:v!==!1},Tags:[{Key:"Name",Value:R},{Key:"Environment",Value:s},...T?Object.entries(T).map(([M,L])=>({Key:M,Value:L})):[]]}};if(A)I.Properties.KmsKeyId=A;return{secret:I,logicalId:P}}static createDatabaseSecret(n){let{slug:i,environment:s,secretName:o,username:c,dbname:u,engine:d,host:g,port:y,kmsKeyId:h}=n,b=o||r({slug:i,environment:s,resourceType:"db-secret"}),v=t(b),A={username:c};if(u)A.dbname=u;if(d)A.engine=d;if(g)A.host=g;if(y)A.port=y;let T={Type:"AWS::SecretsManager::Secret",Properties:{Name:b,Description:`Database credentials for ${c}`,GenerateSecretString:{SecretStringTemplate:JSON.stringify(A),GenerateStringKey:"password",PasswordLength:32,ExcludeCharacters:'"@/\\',RequireEachIncludedType:!0},Tags:[{Key:"Name",Value:b},{Key:"Environment",Value:s},{Key:"Type",Value:"database"}]}};if(h)T.Properties.KmsKeyId=h;return{secret:T,logicalId:v}}static attachToDatabase(n){let{slug:i,environment:s,secretId:o,targetId:c,targetType:u}=n,d=r({slug:i,environment:s,resourceType:"secret-attachment"}),g=t(d);return{attachment:{Type:"AWS::SecretsManager::SecretTargetAttachment",Properties:{SecretId:o,TargetId:c,TargetType:u}},logicalId:g}}static enableRotation(n){let{slug:i,environment:s,secretId:o,rotationLambdaArn:c,automaticallyAfterDays:u,rotationType:d,kmsKeyArn:g,vpcSecurityGroupIds:y,vpcSubnetIds:h}=n,b=r({slug:i,environment:s,resourceType:"secret-rotation"}),v=t(b),A={Type:"AWS::SecretsManager::RotationSchedule",Properties:{SecretId:o,RotationRules:{AutomaticallyAfterDays:u||30}}};if(c)A.Properties.RotationLambdaARN=c;else if(d)A.Properties.HostedRotationLambda={RotationType:d,KmsKeyArn:g,VpcSecurityGroupIds:y,VpcSubnetIds:h};return{rotation:A,logicalId:v}}static SecretTypes={apiKey:(n,i,s)=>Yi.createGeneratedSecret({slug:n,environment:i,secretName:`${n}-${i}-${s}-api-key`,description:`API key for ${s}`,passwordLength:32,excludePunctuation:!0,excludeLowercase:!1,excludeUppercase:!1,excludeNumbers:!1}),oauthClientSecret:(n,i,s)=>Yi.createGeneratedSecret({slug:n,environment:i,secretName:`${n}-${i}-${s}-oauth-secret`,description:`OAuth client secret for ${s}`,passwordLength:64,excludeCharacters:"\"'`\\/@",requireEachIncludedType:!0}),jwtSecret:(n,i)=>Yi.createGeneratedSecret({slug:n,environment:i,secretName:`${n}-${i}-jwt-secret`,description:"JWT signing secret",passwordLength:64,excludePunctuation:!0}),encryptionKey:(n,i)=>Yi.createGeneratedSecret({slug:n,environment:i,secretName:`${n}-${i}-encryption-key`,description:"Data encryption key",passwordLength:64,excludeCharacters:"+/=",excludePunctuation:!0})};static RotationTypes={MySQLSingleUser:"MySQLSingleUser",MySQLMultiUser:"MySQLMultiUser",PostgreSQLSingleUser:"PostgreSQLSingleUser",PostgreSQLMultiUser:"PostgreSQLMultiUser",OracleSingleUser:"OracleSingleUser",OracleMultiUser:"OracleMultiUser",MariaDBSingleUser:"MariaDBSingleUser",MariaDBMultiUser:"MariaDBMultiUser",SQLServerSingleUser:"SQLServerSingleUser",SQLServerMultiUser:"SQLServerMultiUser",RedshiftSingleUser:"RedshiftSingleUser",RedshiftMultiUser:"RedshiftMultiUser",MongoDBSingleUser:"MongoDBSingleUser",MongoDBMultiUser:"MongoDBMultiUser"}}class D{static createParameter(n){let{slug:i,environment:s,parameterName:o,value:c,type:u="String",description:d,tier:g="Standard",tags:y}=n,h=o||r({slug:i,environment:s,resourceType:"parameter"}),b=t(h);return{parameter:{Type:"AWS::SSM::Parameter",Properties:{Name:`/${i}/${s}/${h}`,Type:u,Value:c,Description:d,Tier:g,Tags:{Name:h,Environment:s,...y}}},logicalId:b}}static createString(n,i,s,o,c){return D.createParameter({slug:n,environment:i,parameterName:s,value:o,type:"String",description:c})}static createSecureString(n,i,s,o,c){return D.createParameter({slug:n,environment:i,parameterName:s,value:o,type:"SecureString",description:c})}static createStringList(n,i,s,o,c){return D.createParameter({slug:n,environment:i,parameterName:s,value:o.join(","),type:"StringList",description:c})}static Parameters={databaseUrl:(n,i,s)=>D.createSecureString(n,i,"database-url",s,"Database connection URL"),apiEndpoint:(n,i,s)=>D.createString(n,i,"api-endpoint",s,"API endpoint URL"),appVersion:(n,i,s)=>D.createString(n,i,"app-version",s,"Application version"),featureFlags:(n,i,s)=>D.createStringList(n,i,"feature-flags",s,"Enabled feature flags"),apiKey:(n,i,s,o)=>D.createSecureString(n,i,`${s}-api-key`,o,`API key for ${s}`),oauthCredentials:(n,i,s,o)=>{let c=D.createString(n,i,"oauth-client-id",s,"OAuth client ID"),u=D.createSecureString(n,i,"oauth-client-secret",o,"OAuth client secret");return{clientId:c,clientSecret:u}},smtpCredentials:(n,i,s,o,c,u)=>{let d=D.createString(n,i,"smtp-username",s,"SMTP username"),g=D.createSecureString(n,i,"smtp-password",o,"SMTP password"),y=D.createString(n,i,"smtp-host",c,"SMTP host"),h=D.createString(n,i,"smtp-port",u.toString(),"SMTP port");return{username:d,password:g,host:y,port:h}},redisUrl:(n,i,s)=>D.createSecureString(n,i,"redis-url",s,"Redis connection URL"),s3Bucket:(n,i,s)=>D.createString(n,i,"s3-bucket",s,"S3 bucket name"),cloudFrontDistribution:(n,i,s)=>D.createString(n,i,"cloudfront-distribution-id",s,"CloudFront distribution ID")}}class gr{static createDomain(n){let{slug:i,environment:s,domainName:o,engineVersion:c="OpenSearch_2.11",instanceType:u="t3.small.search",instanceCount:d=1,volumeSize:g=10,volumeType:y="gp3",dedicatedMaster:h=!1,dedicatedMasterType:b,dedicatedMasterCount:v=3,multiAz:A=!1,availabilityZoneCount:T=2,vpc:R,encryption:P,enforceHttps:I=!0,tlsSecurityPolicy:M="Policy-Min-TLS-1-2-2019-07",advancedSecurity:L,autoSnapshotHour:N=0,autoTune:O=!0,tags:B={}}=n,F=o||r({slug:i,environment:s,resourceType:"search"}),U=t(F);return{domain:{Type:"AWS::OpenSearchService::Domain",Properties:{DomainName:F,EngineVersion:c,ClusterConfig:{InstanceType:u,InstanceCount:d,DedicatedMasterEnabled:h,...h&&{DedicatedMasterType:b||u,DedicatedMasterCount:v},ZoneAwarenessEnabled:A,...A&&{ZoneAwarenessConfig:{AvailabilityZoneCount:T}}},EBSOptions:{EBSEnabled:!0,VolumeType:y,VolumeSize:g},DomainEndpointOptions:{EnforceHTTPS:I,TLSSecurityPolicy:M},SnapshotOptions:{AutomatedSnapshotStartHour:N},...R&&{VPCOptions:{SubnetIds:R.subnetIds,SecurityGroupIds:R.securityGroupIds}},...P&&{EncryptionAtRestOptions:{Enabled:P.atRest??!0,...P.kmsKeyId&&{KmsKeyId:P.kmsKeyId}},NodeToNodeEncryptionOptions:{Enabled:P.nodeToNode??!0}},...L&&{AdvancedSecurityOptions:{Enabled:L.enabled,InternalUserDatabaseEnabled:L.internalUserDatabase??!0,...L.masterUserName&&L.masterUserPassword&&{MasterUserOptions:{MasterUserName:L.masterUserName,MasterUserPassword:L.masterUserPassword}},...L.masterUserArn&&{MasterUserOptions:{MasterUserARN:L.masterUserArn}}}},...O&&{AutoTuneOptions:{DesiredState:"ENABLED"}},Tags:[{Key:"Name",Value:F},{Key:"Environment",Value:s},...Object.entries(B).map(([H,z])=>({Key:H,Value:z}))]}},logicalId:U}}static createAccessPolicy(n,i){let{ipAddresses:s,iamPrincipalArns:o,allowAll:c,vpcEndpoint:u}=i;if(c)return{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:"*"},Action:"es:*",Resource:n}]};let d=[];if(o&&o.length>0)d.push({Effect:"Allow",Principal:{AWS:o},Action:"es:*",Resource:n});if(s&&s.length>0)d.push({Effect:"Allow",Principal:{AWS:"*"},Action:"es:*",Resource:n,Condition:{IpAddress:{"aws:SourceIp":s}}});if(u)return{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:"*"},Action:"es:*",Resource:n}]};return{Version:"2012-10-17",Statement:d}}static DomainPresets={development:(n,i)=>gr.createDomain({slug:n,environment:i,instanceType:"t3.small.search",instanceCount:1,volumeSize:10,multiAz:!1,dedicatedMaster:!1,encryption:{atRest:!0,nodeToNode:!0},autoTune:!1}),production:(n,i,s)=>gr.createDomain({slug:n,environment:i,instanceType:"m6g.large.search",instanceCount:3,volumeSize:100,volumeType:"gp3",multiAz:!0,availabilityZoneCount:3,dedicatedMaster:!0,dedicatedMasterType:"m6g.large.search",dedicatedMasterCount:3,vpc:s,encryption:{atRest:!0,nodeToNode:!0},advancedSecurity:{enabled:!0,internalUserDatabase:!0},autoTune:!0}),costOptimized:(n,i)=>gr.createDomain({slug:n,environment:i,instanceType:"t3.medium.search",instanceCount:2,volumeSize:20,volumeType:"gp3",multiAz:!0,dedicatedMaster:!1,encryption:{atRest:!0,nodeToNode:!0},autoTune:!0}),highPerformance:(n,i,s)=>gr.createDomain({slug:n,environment:i,instanceType:"r6g.2xlarge.search",instanceCount:6,volumeSize:500,volumeType:"gp3",multiAz:!0,availabilityZoneCount:3,dedicatedMaster:!0,dedicatedMasterType:"c6g.xlarge.search",dedicatedMasterCount:3,vpc:s,encryption:{atRest:!0,nodeToNode:!0},advancedSecurity:{enabled:!0,internalUserDatabase:!1},autoTune:!0})};static InstanceTypes={"t3.small.search":"t3.small.search","t3.medium.search":"t3.medium.search","m6g.large.search":"m6g.large.search","m6g.xlarge.search":"m6g.xlarge.search","m6g.2xlarge.search":"m6g.2xlarge.search","r6g.large.search":"r6g.large.search","r6g.xlarge.search":"r6g.xlarge.search","r6g.2xlarge.search":"r6g.2xlarge.search","r6g.4xlarge.search":"r6g.4xlarge.search","c6g.large.search":"c6g.large.search","c6g.xlarge.search":"c6g.xlarge.search","c6g.2xlarge.search":"c6g.2xlarge.search"};static EngineVersions={"OpenSearch_2.11":"OpenSearch_2.11","OpenSearch_2.9":"OpenSearch_2.9","OpenSearch_2.7":"OpenSearch_2.7","OpenSearch_1.3":"OpenSearch_1.3","Elasticsearch_7.10":"Elasticsearch_7.10"}}class Bt{static createDomainRedirectBucket(n){let{slug:i,environment:s,sourceDomain:o,targetDomain:c,protocol:u="https"}=n,d=r({slug:i,environment:s,resourceType:"s3",suffix:"redirect"}),g=t(d),y=t(`${d}-policy`),h={Type:"AWS::S3::Bucket",Properties:{BucketName:o,WebsiteConfiguration:{RedirectAllRequestsTo:{HostName:c,Protocol:u}},PublicAccessBlockConfiguration:{BlockPublicAcls:!1,BlockPublicPolicy:!1,IgnorePublicAcls:!1,RestrictPublicBuckets:!1},Tags:[{Key:"Name",Value:d},{Key:"Environment",Value:s},{Key:"Purpose",Value:"Domain Redirect"}]}},b={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:x.Ref(g),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadForRedirect",Effect:"Allow",Principal:"*",Action:["s3:GetObject"],Resource:[x.Join("",[x.GetAtt(g,"Arn"),"/*"])]}]}}};return{bucket:h,bucketPolicy:b,logicalId:g,policyLogicalId:y}}static createPathRedirectFunction(n){let{slug:i,environment:s,rules:o}=n,c=r({slug:i,environment:s,resourceType:"cf-redirect"}),u=t(c),d=Bt.generateRedirectFunctionCode(o);return{function:{Type:"AWS::CloudFront::Function",Properties:{Name:c,AutoPublish:!0,FunctionConfig:{Comment:`Path redirect function for ${i} (${s})`,Runtime:"cloudfront-js-2.0"},FunctionCode:d}},logicalId:u,functionCode:d}}static generateRedirectFunctionCode(n){return`function handler(event) {
2281
+ | limit 50`,region:o,title:"Recent Errors and Warnings"}}),d+=6;return jo.createDashboard({slug:i,environment:s,widgets:u})}static DashboardTemplates={staticWebsite:(n)=>({slug:n.slug,environment:n.environment,widgets:[{type:"text",x:0,y:0,width:24,height:1,properties:{markdown:`# ${n.slug.toUpperCase()} Static Website Dashboard`}},{type:"metric",x:0,y:1,width:8,height:6,properties:{title:"CloudFront Requests",region:"us-east-1",metrics:[["AWS/CloudFront","Requests","DistributionId",n.cloudFrontDistributionId,"Region","Global"]],period:300,stat:"Sum"}},{type:"metric",x:8,y:1,width:8,height:6,properties:{title:"Error Rate",region:"us-east-1",metrics:[["AWS/CloudFront","4xxErrorRate","DistributionId",n.cloudFrontDistributionId,"Region","Global",{label:"4XX"}],["AWS/CloudFront","5xxErrorRate","DistributionId",n.cloudFrontDistributionId,"Region","Global",{label:"5XX"}]],period:300,stat:"Average"}},{type:"metric",x:16,y:1,width:8,height:6,properties:{title:"Bytes Downloaded",region:"us-east-1",metrics:[["AWS/CloudFront","BytesDownloaded","DistributionId",n.cloudFrontDistributionId,"Region","Global"]],period:300,stat:"Sum"}},{type:"metric",x:0,y:7,width:12,height:6,properties:{title:"S3 Bucket Size",region:n.region||"us-east-1",metrics:[["AWS/S3","BucketSizeBytes","BucketName",n.s3BucketName,"StorageType","StandardStorage"]],period:86400,stat:"Average"}},{type:"metric",x:12,y:7,width:12,height:6,properties:{title:"S3 Number of Objects",region:n.region||"us-east-1",metrics:[["AWS/S3","NumberOfObjects","BucketName",n.s3BucketName,"StorageType","AllStorageTypes"]],period:86400,stat:"Average"}}]}),serverlessApi:(n)=>({slug:n.slug,environment:n.environment,widgets:[{type:"text",x:0,y:0,width:24,height:1,properties:{markdown:`# ${n.slug.toUpperCase()} Serverless API Dashboard`}},{type:"metric",x:0,y:1,width:8,height:6,properties:{title:"API Requests",region:n.region||"us-east-1",metrics:[["AWS/ApiGateway","Count","ApiName",n.apiGatewayName]],period:60,stat:"Sum"}},{type:"metric",x:8,y:1,width:8,height:6,properties:{title:"API Latency",region:n.region||"us-east-1",metrics:[["AWS/ApiGateway","Latency","ApiName",n.apiGatewayName]],period:60,stat:"Average"}},{type:"metric",x:16,y:1,width:8,height:6,properties:{title:"API Errors",region:n.region||"us-east-1",metrics:[["AWS/ApiGateway","4XXError","ApiName",n.apiGatewayName,{label:"4XX"}],["AWS/ApiGateway","5XXError","ApiName",n.apiGatewayName,{label:"5XX"}]],period:60,stat:"Sum"}},...n.lambdaFunctionNames.map((i,s)=>({type:"metric",x:s%3*8,y:7+Math.floor(s/3)*6,width:8,height:6,properties:{title:`${i} Metrics`,region:n.region||"us-east-1",metrics:[["AWS/Lambda","Invocations","FunctionName",i],["AWS/Lambda","Duration","FunctionName",i],["AWS/Lambda","Errors","FunctionName",i]],period:300,stat:"Sum"}}))]}),containerService:(n)=>({slug:n.slug,environment:n.environment,widgets:[{type:"text",x:0,y:0,width:24,height:1,properties:{markdown:`# ${n.slug.toUpperCase()} Container Service Dashboard`}},{type:"metric",x:0,y:1,width:8,height:6,properties:{title:"ECS CPU",region:n.region||"us-east-1",metrics:[["AWS/ECS","CPUUtilization","ClusterName",n.ecsClusterName,"ServiceName",n.ecsServiceName]],period:60,stat:"Average"}},{type:"metric",x:8,y:1,width:8,height:6,properties:{title:"ECS Memory",region:n.region||"us-east-1",metrics:[["AWS/ECS","MemoryUtilization","ClusterName",n.ecsClusterName,"ServiceName",n.ecsServiceName]],period:60,stat:"Average"}},{type:"metric",x:16,y:1,width:8,height:6,properties:{title:"Running Tasks",region:n.region||"us-east-1",metrics:[["ECS/ContainerInsights","RunningTaskCount","ClusterName",n.ecsClusterName,"ServiceName",n.ecsServiceName]],period:60,stat:"Average"}},{type:"metric",x:0,y:7,width:8,height:6,properties:{title:"ALB Requests",region:n.region||"us-east-1",metrics:[["AWS/ApplicationELB","RequestCount","LoadBalancer",n.albName]],period:60,stat:"Sum"}},{type:"metric",x:8,y:7,width:8,height:6,properties:{title:"Response Time",region:n.region||"us-east-1",metrics:[["AWS/ApplicationELB","TargetResponseTime","LoadBalancer",n.albName]],period:60,stat:"Average"}},{type:"metric",x:16,y:7,width:8,height:6,properties:{title:"Healthy Hosts",region:n.region||"us-east-1",metrics:[["AWS/ApplicationELB","HealthyHostCount","LoadBalancer",n.albName]],period:60,stat:"Average"}},...n.rdsInstanceId?[{type:"metric",x:0,y:13,width:12,height:6,properties:{title:"RDS CPU",region:n.region||"us-east-1",metrics:[["AWS/RDS","CPUUtilization","DBInstanceIdentifier",n.rdsInstanceId]],period:300,stat:"Average"}},{type:"metric",x:12,y:13,width:12,height:6,properties:{title:"RDS Connections",region:n.region||"us-east-1",metrics:[["AWS/RDS","DatabaseConnections","DBInstanceIdentifier",n.rdsInstanceId]],period:60,stat:"Sum"}}]:[]]})};static Config={createAlarmConfig:(n)=>{let{metricName:i,namespace:s,threshold:o,comparisonOperator:c="GreaterThanThreshold",evaluationPeriods:u=1,period:d=300,statistic:g="Average",treatMissingData:y="missing"}=n;return{MetricName:i,Namespace:s,Threshold:o,ComparisonOperator:c,EvaluationPeriods:u,Period:d,Statistic:g,TreatMissingData:y}},namespaces:{ec2:"AWS/EC2",ecs:"AWS/ECS",lambda:"AWS/Lambda",rds:"AWS/RDS",sqs:"AWS/SQS",sns:"AWS/SNS",s3:"AWS/S3",cloudfront:"AWS/CloudFront",alb:"AWS/ApplicationELB",nlb:"AWS/NetworkELB",apiGateway:"AWS/ApiGateway",dynamodb:"AWS/DynamoDB",elasticache:"AWS/ElastiCache"},comparisonOperators:{greaterThan:"GreaterThanThreshold",greaterOrEqual:"GreaterThanOrEqualToThreshold",lessThan:"LessThanThreshold",lessOrEqual:"LessThanOrEqualToThreshold"},metrics:{ec2:{cpu:{metricName:"CPUUtilization",namespace:"AWS/EC2"},networkIn:{metricName:"NetworkIn",namespace:"AWS/EC2"},networkOut:{metricName:"NetworkOut",namespace:"AWS/EC2"},statusCheck:{metricName:"StatusCheckFailed",namespace:"AWS/EC2"}},ecs:{cpu:{metricName:"CPUUtilization",namespace:"AWS/ECS"},memory:{metricName:"MemoryUtilization",namespace:"AWS/ECS"}},lambda:{invocations:{metricName:"Invocations",namespace:"AWS/Lambda"},errors:{metricName:"Errors",namespace:"AWS/Lambda"},duration:{metricName:"Duration",namespace:"AWS/Lambda"},throttles:{metricName:"Throttles",namespace:"AWS/Lambda"},concurrentExecutions:{metricName:"ConcurrentExecutions",namespace:"AWS/Lambda"}},rds:{cpu:{metricName:"CPUUtilization",namespace:"AWS/RDS"},connections:{metricName:"DatabaseConnections",namespace:"AWS/RDS"},freeStorage:{metricName:"FreeStorageSpace",namespace:"AWS/RDS"},readLatency:{metricName:"ReadLatency",namespace:"AWS/RDS"},writeLatency:{metricName:"WriteLatency",namespace:"AWS/RDS"}},alb:{requestCount:{metricName:"RequestCount",namespace:"AWS/ApplicationELB"},responseTime:{metricName:"TargetResponseTime",namespace:"AWS/ApplicationELB"},httpCode4xx:{metricName:"HTTPCode_Target_4XX_Count",namespace:"AWS/ApplicationELB"},httpCode5xx:{metricName:"HTTPCode_Target_5XX_Count",namespace:"AWS/ApplicationELB"},healthyHosts:{metricName:"HealthyHostCount",namespace:"AWS/ApplicationELB"}},sqs:{messagesVisible:{metricName:"ApproximateNumberOfMessagesVisible",namespace:"AWS/SQS"},messagesDelayed:{metricName:"ApproximateNumberOfMessagesDelayed",namespace:"AWS/SQS"},messageAge:{metricName:"ApproximateAgeOfOldestMessage",namespace:"AWS/SQS"}}},presets:{highCpu:(n=80)=>({metricName:"CPUUtilization",threshold:n,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),highMemory:(n=80)=>({metricName:"MemoryUtilization",threshold:n,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),highErrors:(n=10)=>({metricName:"Errors",threshold:n,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:1,period:60,statistic:"Sum"}),highLatency:(n=5000)=>({metricName:"Duration",threshold:n,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),lowHealthyHosts:(n=1)=>({metricName:"HealthyHostCount",namespace:"AWS/ApplicationELB",threshold:n,comparisonOperator:"LessThanThreshold",evaluationPeriods:2,period:60,statistic:"Minimum"}),queueDepth:(n=1000)=>({metricName:"ApproximateNumberOfMessagesVisible",namespace:"AWS/SQS",threshold:n,comparisonOperator:"GreaterThanThreshold",evaluationPeriods:3,period:300,statistic:"Average"}),lowStorage:(n=10737418240)=>({metricName:"FreeStorageSpace",namespace:"AWS/RDS",threshold:n,comparisonOperator:"LessThanThreshold",evaluationPeriods:1,period:300,statistic:"Average"})}}}class Y{static createUserPool(n){let{slug:i,environment:s,userPoolName:o,aliasAttributes:c,autoVerifiedAttributes:u,passwordPolicy:d,mfaConfiguration:g,emailConfiguration:y,smsConfiguration:h,lambdaTriggers:b,userPoolAddOns:v,accountRecoverySetting:A}=n,T=o||r({slug:i,environment:s,resourceType:"user-pool"}),R=t(T),P={Type:"AWS::Cognito::UserPool",Properties:{UserPoolName:T,Policies:d?{PasswordPolicy:{MinimumLength:d.minimumLength,RequireLowercase:d.requireLowercase,RequireUppercase:d.requireUppercase,RequireNumbers:d.requireNumbers,RequireSymbols:d.requireSymbols,TemporaryPasswordValidityDays:d.temporaryPasswordValidityDays}}:void 0,MfaConfiguration:g,Schema:[{Name:"email",AttributeDataType:"String",Required:!0,Mutable:!1}]}};if(c&&c.length>0)P.Properties.UsernameAttributes=c;if(u&&u.length>0)P.Properties.AutoVerifiedAttributes=u;if(y)P.Properties.EmailConfiguration={EmailSendingAccount:y.emailSendingAccount,From:y.from,ReplyToEmailAddress:y.replyToEmailAddress,SourceArn:y.sourceArn,ConfigurationSet:y.configurationSet};if(h)P.Properties.SmsConfiguration={ExternalId:h.externalId,SnsCallerArn:h.snsCallerArn};if(b)P.Properties.LambdaConfig={PreSignUp:b.preSignUp,PostConfirmation:b.postConfirmation,PreAuthentication:b.preAuthentication,PostAuthentication:b.postAuthentication,CustomMessage:b.customMessage,DefineAuthChallenge:b.defineAuthChallenge,CreateAuthChallenge:b.createAuthChallenge,VerifyAuthChallengeResponse:b.verifyAuthChallengeResponse,PreTokenGeneration:b.preTokenGeneration,UserMigration:b.userMigration};if(v)P.Properties.UserPoolAddOns={AdvancedSecurityMode:v.advancedSecurityMode};if(A)P.Properties.AccountRecoverySetting={RecoveryMechanisms:A.recoveryMechanisms};return{userPool:P,logicalId:R}}static createUserPoolClient(n,i){let{slug:s,environment:o,clientName:c,generateSecret:u=!1,refreshTokenValidity:d,accessTokenValidity:g,idTokenValidity:y,tokenValidityUnits:h,readAttributes:b,writeAttributes:v,explicitAuthFlows:A,preventUserExistenceErrors:T,enableTokenRevocation:R,callbackURLs:P,logoutURLs:I,allowedOAuthFlows:M,allowedOAuthScopes:L,allowedOAuthFlowsUserPoolClient:N,supportedIdentityProviders:O}=i,B=c||r({slug:s,environment:o,resourceType:"user-pool-client"}),F=t(B);return{client:{Type:"AWS::Cognito::UserPoolClient",Properties:{ClientName:B,UserPoolId:x.Ref(n),GenerateSecret:u,RefreshTokenValidity:d,AccessTokenValidity:g,IdTokenValidity:y,TokenValidityUnits:h,ReadAttributes:b,WriteAttributes:v,ExplicitAuthFlows:A,PreventUserExistenceErrors:T,EnableTokenRevocation:R,CallbackURLs:P,LogoutURLs:I,AllowedOAuthFlows:M,AllowedOAuthScopes:L,AllowedOAuthFlowsUserPoolClient:N,SupportedIdentityProviders:O}},logicalId:F}}static createUserPoolDomain(n,i){let{slug:s,environment:o,domain:c,customDomainConfig:u}=i,d=r({slug:s,environment:o,resourceType:"user-pool-domain"}),g=t(d);return{domain:{Type:"AWS::Cognito::UserPoolDomain",Properties:{Domain:c,UserPoolId:x.Ref(n),CustomDomainConfig:u}},logicalId:g}}static createIdentityPool(n){let{slug:i,environment:s,identityPoolName:o,allowUnauthenticatedIdentities:c=!1,cognitoIdentityProviders:u,supportedLoginProviders:d,samlProviderARNs:g,openIdConnectProviderARNs:y}=n,h=o||r({slug:i,environment:s,resourceType:"identity-pool"}),b=t(h);return{identityPool:{Type:"AWS::Cognito::IdentityPool",Properties:{IdentityPoolName:h,AllowUnauthenticatedIdentities:c,CognitoIdentityProviders:u,SupportedLoginProviders:d,SamlProviderARNs:g,OpenIdConnectProviderARNs:y}},logicalId:b}}static createIdentityPoolRoleAttachment(n,i){let{slug:s,environment:o,authenticatedRole:c,unauthenticatedRole:u,roleMappings:d}=i,g=r({slug:s,environment:o,resourceType:"identity-pool-role-attachment"}),y=t(g),h={authenticated:c};if(u)h.unauthenticated=u;return{attachment:{Type:"AWS::Cognito::IdentityPoolRoleAttachment",Properties:{IdentityPoolId:x.Ref(n),Roles:h,RoleMappings:d}},logicalId:y}}static createAuthenticatedRole(n){let{slug:i,environment:s,identityPoolLogicalId:o}=n,c=r({slug:i,environment:s,resourceType:"cognito-authenticated-role"}),u=t(c);return{role:{Type:"AWS::IAM::Role",Properties:{RoleName:c,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Federated:"cognito-identity.amazonaws.com"},Action:"sts:AssumeRoleWithWebIdentity",Condition:{StringEquals:{"cognito-identity.amazonaws.com:aud":x.Ref(o)},"ForAnyValue:StringLike":{"cognito-identity.amazonaws.com:amr":"authenticated"}}}]},Policies:[{PolicyName:"CognitoAuthenticatedPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["cognito-sync:*","cognito-identity:*"],Resource:"*"}]}}],Tags:[{Key:"Name",Value:c},{Key:"Environment",Value:s}]}},logicalId:u}}static createUnauthenticatedRole(n){let{slug:i,environment:s,identityPoolLogicalId:o}=n,c=r({slug:i,environment:s,resourceType:"cognito-unauthenticated-role"}),u=t(c);return{role:{Type:"AWS::IAM::Role",Properties:{RoleName:c,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Federated:"cognito-identity.amazonaws.com"},Action:"sts:AssumeRoleWithWebIdentity",Condition:{StringEquals:{"cognito-identity.amazonaws.com:aud":x.Ref(o)},"ForAnyValue:StringLike":{"cognito-identity.amazonaws.com:amr":"unauthenticated"}}}]},Policies:[{PolicyName:"CognitoUnauthenticatedPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["cognito-sync:*"],Resource:"*"}]}}],Tags:[{Key:"Name",Value:c},{Key:"Environment",Value:s}]}},logicalId:u}}static PasswordPolicies={relaxed:()=>({minimumLength:8,requireLowercase:!1,requireUppercase:!1,requireNumbers:!1,requireSymbols:!1,temporaryPasswordValidityDays:7}),standard:()=>({minimumLength:8,requireLowercase:!0,requireUppercase:!0,requireNumbers:!0,requireSymbols:!1,temporaryPasswordValidityDays:3}),strict:()=>({minimumLength:12,requireLowercase:!0,requireUppercase:!0,requireNumbers:!0,requireSymbols:!0,temporaryPasswordValidityDays:1})};static AuthFlows={standard:["ALLOW_USER_SRP_AUTH","ALLOW_REFRESH_TOKEN_AUTH"],admin:["ALLOW_ADMIN_USER_PASSWORD_AUTH","ALLOW_REFRESH_TOKEN_AUTH"],custom:["ALLOW_CUSTOM_AUTH","ALLOW_REFRESH_TOKEN_AUTH"],all:["ALLOW_USER_SRP_AUTH","ALLOW_USER_PASSWORD_AUTH","ALLOW_ADMIN_USER_PASSWORD_AUTH","ALLOW_CUSTOM_AUTH","ALLOW_REFRESH_TOKEN_AUTH"]};static OAuthScopes={basic:["openid","email","profile"],all:["openid","email","profile","phone","aws.cognito.signin.user.admin"]};static UseCases={webApp:(n,i,s)=>{let{userPool:o,logicalId:c}=Y.createUserPool({slug:n,environment:i,aliasAttributes:["email"],autoVerifiedAttributes:["email"],passwordPolicy:Y.PasswordPolicies.standard(),mfaConfiguration:"OPTIONAL"}),{client:u,logicalId:d}=Y.createUserPoolClient(c,{slug:n,environment:i,explicitAuthFlows:[...Y.AuthFlows.standard],callbackURLs:[s],allowedOAuthFlows:["code"],allowedOAuthScopes:[...Y.OAuthScopes.basic],allowedOAuthFlowsUserPoolClient:!0});return{userPool:o,poolId:c,client:u,clientId:d}},mobileApp:(n,i)=>{let{userPool:s,logicalId:o}=Y.createUserPool({slug:n,environment:i,aliasAttributes:["email"],autoVerifiedAttributes:["email"],passwordPolicy:Y.PasswordPolicies.standard(),mfaConfiguration:"OPTIONAL"}),{client:c,logicalId:u}=Y.createUserPoolClient(o,{slug:n,environment:i,explicitAuthFlows:[...Y.AuthFlows.standard]}),{identityPool:d,logicalId:g}=Y.createIdentityPool({slug:n,environment:i,allowUnauthenticatedIdentities:!1,cognitoIdentityProviders:[{ClientId:x.Ref(u),ProviderName:x.GetAtt(o,"ProviderName")}]}),{role:y,logicalId:h}=Y.createAuthenticatedRole({slug:n,environment:i,identityPoolLogicalId:g}),{attachment:b,logicalId:v}=Y.createIdentityPoolRoleAttachment(g,{slug:n,environment:i,authenticatedRole:x.GetAtt(h,"Arn")});return{userPool:s,poolId:o,client:c,clientId:u,identityPool:d,identityPoolId:g,authRole:y,authRoleId:h,attachment:b,attachmentId:v}}}}import{createHash as xr}from"node:crypto";import{copyFileSync as kr,existsSync as Tt,readdirSync as Mr,readFileSync as ot,statSync as Lr,writeFileSync as ct}from"node:fs";import{basename as Or,dirname as cn,extname as yn,join as Ke}from"node:path";class Z{static createApplication(n){let{slug:i,environment:s,applicationName:o,computePlatform:c}=n,u=o||r({slug:i,environment:s,resourceType:"deploy-app"}),d=t(u);return{application:{Type:"AWS::CodeDeploy::Application",Properties:{ApplicationName:u,ComputePlatform:c,Tags:[{Key:"Name",Value:u},{Key:"Environment",Value:s}]}},logicalId:d}}static createDeploymentGroup(n,i){let{slug:s,environment:o,deploymentGroupName:c,serviceRoleArn:u,autoScalingGroups:d,ec2TagFilters:g,deploymentConfigName:y,autoRollbackConfiguration:h,alarmConfiguration:b,loadBalancerInfo:v,blueGreenDeploymentConfiguration:A}=i,T=c||r({slug:s,environment:o,resourceType:"deploy-group"}),R=t(T);return{deploymentGroup:{Type:"AWS::CodeDeploy::DeploymentGroup",Properties:{ApplicationName:x.Ref(n),DeploymentGroupName:T,ServiceRoleArn:u,AutoScalingGroups:d,Ec2TagFilters:g?.map((I)=>({Key:I.key,Value:I.value,Type:I.type})),DeploymentConfigName:y,AutoRollbackConfiguration:h?{Enabled:h.enabled,Events:h.events}:void 0,AlarmConfiguration:b?{Enabled:b.enabled,Alarms:b.alarms?.map((I)=>({Name:I.name})),IgnorePollAlarmFailure:b.ignorePollAlarmFailure}:void 0,LoadBalancerInfo:v?{TargetGroupInfoList:v.targetGroupInfoList?.map((I)=>({Name:I.name})),ElbInfoList:v.elbInfoList?.map((I)=>({Name:I.name}))}:void 0,BlueGreenDeploymentConfiguration:A?{TerminateBlueInstancesOnDeploymentSuccess:A.terminateBlueInstancesOnDeploymentSuccess?{Action:A.terminateBlueInstancesOnDeploymentSuccess.action,TerminationWaitTimeInMinutes:A.terminateBlueInstancesOnDeploymentSuccess.terminationWaitTimeInMinutes}:void 0,DeploymentReadyOption:A.deploymentReadyOption?{ActionOnTimeout:A.deploymentReadyOption.actionOnTimeout,WaitTimeInMinutes:A.deploymentReadyOption.waitTimeInMinutes}:void 0,GreenFleetProvisioningOption:A.greenFleetProvisioningOption?{Action:A.greenFleetProvisioningOption.action}:void 0}:void 0,Tags:[{Key:"Name",Value:T},{Key:"Environment",Value:o}]}},logicalId:R}}static createDeploymentConfig(n){let{slug:i,environment:s,deploymentConfigName:o,minimumHealthyHosts:c,trafficRoutingConfig:u}=n,d=o||r({slug:i,environment:s,resourceType:"deploy-config"}),g=t(d);return{deploymentConfig:{Type:"AWS::CodeDeploy::DeploymentConfig",Properties:{DeploymentConfigName:d,MinimumHealthyHosts:c?{Type:c.type,Value:c.value}:void 0,TrafficRoutingConfig:u?{Type:u.type,TimeBasedCanary:u.timeBasedCanary?{CanaryPercentage:u.timeBasedCanary.canaryPercentage,CanaryInterval:u.timeBasedCanary.canaryInterval}:void 0,TimeBasedLinear:u.timeBasedLinear?{LinearPercentage:u.timeBasedLinear.linearPercentage,LinearInterval:u.timeBasedLinear.linearInterval}:void 0}:void 0}},logicalId:g}}static DeploymentConfigs={allAtOnce:()=>({type:"FLEET_PERCENT",value:0}),halfAtATime:()=>({type:"FLEET_PERCENT",value:50}),oneAtATime:()=>({type:"HOST_COUNT",value:1}),custom:(n,i)=>({type:n,value:i})};static TrafficRouting={allAtOnce:()=>({type:"AllAtOnce"}),canary:(n,i)=>({type:"TimeBasedCanary",timeBasedCanary:{canaryPercentage:n,canaryInterval:i}}),linear:(n,i)=>({type:"TimeBasedLinear",timeBasedLinear:{linearPercentage:n,linearInterval:i}})};static RollbackConfigs={onFailure:()=>({enabled:!0,events:["DEPLOYMENT_FAILURE"]}),onAlarmOrFailure:()=>({enabled:!0,events:["DEPLOYMENT_FAILURE","DEPLOYMENT_STOP_ON_ALARM"]}),onAllEvents:()=>({enabled:!0,events:["DEPLOYMENT_FAILURE","DEPLOYMENT_STOP_ON_ALARM","DEPLOYMENT_STOP_ON_REQUEST"]}),disabled:()=>({enabled:!1})};static BlueGreenConfigs={standard:()=>({terminateBlueInstancesOnDeploymentSuccess:{action:"TERMINATE",terminationWaitTimeInMinutes:5},deploymentReadyOption:{actionOnTimeout:"CONTINUE_DEPLOYMENT",waitTimeInMinutes:0},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}}),withDelay:(n)=>({terminateBlueInstancesOnDeploymentSuccess:{action:"TERMINATE",terminationWaitTimeInMinutes:n},deploymentReadyOption:{actionOnTimeout:"CONTINUE_DEPLOYMENT",waitTimeInMinutes:0},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}}),withManualApproval:(n)=>({terminateBlueInstancesOnDeploymentSuccess:{action:"TERMINATE",terminationWaitTimeInMinutes:5},deploymentReadyOption:{actionOnTimeout:"STOP_DEPLOYMENT",waitTimeInMinutes:n},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}}),keepBlue:()=>({terminateBlueInstancesOnDeploymentSuccess:{action:"KEEP_ALIVE"},deploymentReadyOption:{actionOnTimeout:"CONTINUE_DEPLOYMENT",waitTimeInMinutes:0},greenFleetProvisioningOption:{action:"COPY_AUTO_SCALING_GROUP"}})};static UseCases={ec2Deployment:(n,i,s,o)=>{let{application:c,logicalId:u}=Z.createApplication({slug:n,environment:i,computePlatform:"Server"}),{deploymentGroup:d,logicalId:g}=Z.createDeploymentGroup(u,{slug:n,environment:i,serviceRoleArn:s,autoScalingGroups:o,deploymentConfigName:"CodeDeployDefault.OneAtATime",autoRollbackConfiguration:Z.RollbackConfigs.onFailure()});return{application:c,appId:u,deploymentGroup:d,groupId:g}},lambdaCanaryDeployment:(n,i,s,o=10,c=5)=>{let{application:u,logicalId:d}=Z.createApplication({slug:n,environment:i,computePlatform:"Lambda"}),{deploymentConfig:g,logicalId:y}=Z.createDeploymentConfig({slug:n,environment:i,trafficRoutingConfig:Z.TrafficRouting.canary(o,c)}),{deploymentGroup:h,logicalId:b}=Z.createDeploymentGroup(d,{slug:n,environment:i,serviceRoleArn:s,deploymentConfigName:x.Ref(y),autoRollbackConfiguration:Z.RollbackConfigs.onAlarmOrFailure()});return{application:u,appId:d,deploymentConfig:g,configId:y,deploymentGroup:h,groupId:b}},ecsBlueGreenDeployment:(n,i,s,o)=>{let{application:c,logicalId:u}=Z.createApplication({slug:n,environment:i,computePlatform:"ECS"}),{deploymentGroup:d,logicalId:g}=Z.createDeploymentGroup(u,{slug:n,environment:i,serviceRoleArn:s,loadBalancerInfo:{targetGroupInfoList:[{name:o}]},blueGreenDeploymentConfiguration:Z.BlueGreenConfigs.standard(),autoRollbackConfiguration:Z.RollbackConfigs.onFailure()});return{application:c,appId:u,deploymentGroup:d,groupId:g}}};static Strategies={rolling:(n=25)=>({type:"rolling",batchPercentage:n}),blueGreen:()=>({type:"blue-green"}),canary:(n=10,i=5)=>({type:"canary",canaryPercentage:n,canaryInterval:i}),allAtOnce:()=>({type:"all-at-once"})}}class _{static ContentTypes={".html":"text/html",".htm":"text/html",".css":"text/css",".js":"application/javascript",".mjs":"application/javascript",".json":"application/json",".xml":"application/xml",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject",".pdf":"application/pdf",".txt":"text/plain",".md":"text/markdown",".map":"application/json"};static NoHashPatterns=[/^index\.html$/,/^favicon\.ico$/,/^robots\.txt$/,/^sitemap\.xml$/,/^manifest\.json$/,/^\.well-known\//,/^_redirects$/,/^_headers$/];static computeFileHash(n,i="md5"){let s=ot(n);return xr(i).update(s).digest("hex")}static computeShortHash(n){return _.computeFileHash(n).slice(0,8)}static getContentType(n){let i=yn(n).toLowerCase();return _.ContentTypes[i]||"application/octet-stream"}static shouldHashFile(n,i){return![..._.NoHashPatterns,...i||[]].some((o)=>o.test(n))}static generateHashedFilename(n,i){let s=yn(n),o=Or(n,s),c=cn(n);if(c===".")return`${o}.${i}${s}`;return Ke(c,`${o}.${i}${s}`)}static collectFiles(n,i){let s=[],o=i||n;if(!Tt(n))return s;let c=Mr(n,{withFileTypes:!0});for(let u of c){let d=Ke(n,u.name);if(u.isDirectory())s.push(..._.collectFiles(d,o));else if(u.isFile())s.push(d)}return s}static hashDirectory(n){let{sourceDir:i,outputDir:s,excludePatterns:o=[],hashAlgorithm:c="md5",copyUnhashed:u=!0}=n,d=_.collectFiles(i),g=[],y={};for(let b of d){let v=b.replace(i,"").replace(/^[/\\]/,""),A=_.shouldHashFile(v,o),T=Lr(b),R=A?_.computeFileHash(b,c).slice(0,8):"",P=A?_.generateHashedFilename(v,R):v,I={originalPath:v,hashedPath:P,hash:R,size:T.size,contentType:_.getContentType(b)};if(g.push(I),y[v]=P,s){let M=Ke(s,P),L=cn(M);if(!Tt(L)){let{mkdirSync:N}=st("node:fs");N(L,{recursive:!0})}if(A||u)kr(b,M)}}let h={version:"1.0",timestamp:new Date().toISOString(),assets:g,hashMap:y};if(s){let b=Ke(s,"asset-manifest.json");ct(b,JSON.stringify(h,null,2))}return h}static getInvalidationPaths(n,i){let s=[];if(!n)return["/*"];let o=n.hashMap,c=i.hashMap;for(let[u,d]of Object.entries(c)){let g=o[u];if(!g||g!==d){if(s.push(`/${u}`),g&&g!==d)s.push(`/${g}`)}}for(let[u,d]of Object.entries(o))if(!c[u])s.push(`/${u}`),s.push(`/${d}`);if(s.length>100)return["/*"];return[...new Set(s)]}static updateHtmlReferences(n){let{htmlDir:i,manifest:s,basePath:o=""}=n,c=_.collectFiles(i).filter((u)=>u.endsWith(".html")||u.endsWith(".htm"));for(let u of c){let d=ot(u,"utf-8");for(let[g,y]of Object.entries(s.hashMap)){if(g===y)continue;let h=[new RegExp(`(src|href)=["']${o}/?${_.escapeRegExp(g)}["']`,"g"),new RegExp(`url\\(["']?${o}/?${_.escapeRegExp(g)}["']?\\)`,"g")];for(let b of h)d=d.replace(b,(v)=>v.replace(g,y))}ct(u,d)}}static updateCssReferences(n){let{cssDir:i,manifest:s,basePath:o=""}=n,c=_.collectFiles(i).filter((u)=>u.endsWith(".css"));for(let u of c){let d=ot(u,"utf-8");for(let[g,y]of Object.entries(s.hashMap)){if(g===y)continue;let h=new RegExp(`url\\(["']?${o}/?${_.escapeRegExp(g)}["']?\\)`,"g");d=d.replace(h,`url(${o}/${y})`)}ct(u,d)}}static escapeRegExp(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}static generateS3DeploymentManifest(n){let{sourceDir:i,keyPrefix:s="",excludePatterns:o=[],cacheControl:c={hashed:"public, max-age=31536000, immutable",unhashed:"public, max-age=3600",html:"public, max-age=0, must-revalidate"}}=n;return _.hashDirectory({sourceDir:i,excludePatterns:o}).assets.map((d)=>{let g=d.hash!=="",y=d.contentType==="text/html",h=c.unhashed||"public, max-age=3600";if(y)h=c.html||"public, max-age=0, must-revalidate";else if(g)h=c.hashed||"public, max-age=31536000, immutable";return{localPath:Ke(i,d.originalPath),s3Key:s?`${s}/${d.hashedPath}`:d.hashedPath,contentType:d.contentType,cacheControl:h,hash:d.hash}})}static compareManifests(n,i){let s={added:[],removed:[],changed:[],unchanged:[]},o=new Set(Object.keys(n.hashMap)),c=new Set(Object.keys(i.hashMap));for(let u of c)if(!o.has(u))s.added.push(u);for(let u of o)if(!c.has(u))s.removed.push(u);for(let u of c)if(o.has(u))if(n.hashMap[u]!==i.hashMap[u])s.changed.push(u);else s.unchanged.push(u);return s}static loadManifest(n){if(!Tt(n))return null;try{let i=ot(n,"utf-8");return JSON.parse(i)}catch{return null}}static saveManifest(n,i){ct(i,JSON.stringify(n,null,2))}}class Yi{static createSecret(n){let{slug:i,environment:s,secretName:o,description:c,secretString:u,kmsKeyId:d,tags:g}=n,y=o||r({slug:i,environment:s,resourceType:"secret"}),h=t(y),b={Type:"AWS::SecretsManager::Secret",Properties:{Name:y,Description:c,SecretString:u,Tags:[{Key:"Name",Value:y},{Key:"Environment",Value:s},...g?Object.entries(g).map(([v,A])=>({Key:v,Value:A})):[]]}};if(d)b.Properties.KmsKeyId=d;return{secret:b,logicalId:h}}static createGeneratedSecret(n){let{slug:i,environment:s,secretName:o,description:c,excludeCharacters:u,excludeLowercase:d,excludeNumbers:g,excludePunctuation:y,excludeUppercase:h,passwordLength:b,requireEachIncludedType:v,kmsKeyId:A,tags:T}=n,R=o||r({slug:i,environment:s,resourceType:"secret"}),P=t(R),I={Type:"AWS::SecretsManager::Secret",Properties:{Name:R,Description:c,GenerateSecretString:{ExcludeCharacters:u,ExcludeLowercase:d,ExcludeNumbers:g,ExcludePunctuation:y,ExcludeUppercase:h,PasswordLength:b||32,RequireEachIncludedType:v!==!1},Tags:[{Key:"Name",Value:R},{Key:"Environment",Value:s},...T?Object.entries(T).map(([M,L])=>({Key:M,Value:L})):[]]}};if(A)I.Properties.KmsKeyId=A;return{secret:I,logicalId:P}}static createDatabaseSecret(n){let{slug:i,environment:s,secretName:o,username:c,dbname:u,engine:d,host:g,port:y,kmsKeyId:h}=n,b=o||r({slug:i,environment:s,resourceType:"db-secret"}),v=t(b),A={username:c};if(u)A.dbname=u;if(d)A.engine=d;if(g)A.host=g;if(y)A.port=y;let T={Type:"AWS::SecretsManager::Secret",Properties:{Name:b,Description:`Database credentials for ${c}`,GenerateSecretString:{SecretStringTemplate:JSON.stringify(A),GenerateStringKey:"password",PasswordLength:32,ExcludeCharacters:'"@/\\',RequireEachIncludedType:!0},Tags:[{Key:"Name",Value:b},{Key:"Environment",Value:s},{Key:"Type",Value:"database"}]}};if(h)T.Properties.KmsKeyId=h;return{secret:T,logicalId:v}}static attachToDatabase(n){let{slug:i,environment:s,secretId:o,targetId:c,targetType:u}=n,d=r({slug:i,environment:s,resourceType:"secret-attachment"}),g=t(d);return{attachment:{Type:"AWS::SecretsManager::SecretTargetAttachment",Properties:{SecretId:o,TargetId:c,TargetType:u}},logicalId:g}}static enableRotation(n){let{slug:i,environment:s,secretId:o,rotationLambdaArn:c,automaticallyAfterDays:u,rotationType:d,kmsKeyArn:g,vpcSecurityGroupIds:y,vpcSubnetIds:h}=n,b=r({slug:i,environment:s,resourceType:"secret-rotation"}),v=t(b),A={Type:"AWS::SecretsManager::RotationSchedule",Properties:{SecretId:o,RotationRules:{AutomaticallyAfterDays:u||30}}};if(c)A.Properties.RotationLambdaARN=c;else if(d)A.Properties.HostedRotationLambda={RotationType:d,KmsKeyArn:g,VpcSecurityGroupIds:y,VpcSubnetIds:h};return{rotation:A,logicalId:v}}static SecretTypes={apiKey:(n,i,s)=>Yi.createGeneratedSecret({slug:n,environment:i,secretName:`${n}-${i}-${s}-api-key`,description:`API key for ${s}`,passwordLength:32,excludePunctuation:!0,excludeLowercase:!1,excludeUppercase:!1,excludeNumbers:!1}),oauthClientSecret:(n,i,s)=>Yi.createGeneratedSecret({slug:n,environment:i,secretName:`${n}-${i}-${s}-oauth-secret`,description:`OAuth client secret for ${s}`,passwordLength:64,excludeCharacters:"\"'`\\/@",requireEachIncludedType:!0}),jwtSecret:(n,i)=>Yi.createGeneratedSecret({slug:n,environment:i,secretName:`${n}-${i}-jwt-secret`,description:"JWT signing secret",passwordLength:64,excludePunctuation:!0}),encryptionKey:(n,i)=>Yi.createGeneratedSecret({slug:n,environment:i,secretName:`${n}-${i}-encryption-key`,description:"Data encryption key",passwordLength:64,excludeCharacters:"+/=",excludePunctuation:!0})};static RotationTypes={MySQLSingleUser:"MySQLSingleUser",MySQLMultiUser:"MySQLMultiUser",PostgreSQLSingleUser:"PostgreSQLSingleUser",PostgreSQLMultiUser:"PostgreSQLMultiUser",OracleSingleUser:"OracleSingleUser",OracleMultiUser:"OracleMultiUser",MariaDBSingleUser:"MariaDBSingleUser",MariaDBMultiUser:"MariaDBMultiUser",SQLServerSingleUser:"SQLServerSingleUser",SQLServerMultiUser:"SQLServerMultiUser",RedshiftSingleUser:"RedshiftSingleUser",RedshiftMultiUser:"RedshiftMultiUser",MongoDBSingleUser:"MongoDBSingleUser",MongoDBMultiUser:"MongoDBMultiUser"}}class D{static createParameter(n){let{slug:i,environment:s,parameterName:o,value:c,type:u="String",description:d,tier:g="Standard",tags:y}=n,h=o||r({slug:i,environment:s,resourceType:"parameter"}),b=t(h);return{parameter:{Type:"AWS::SSM::Parameter",Properties:{Name:`/${i}/${s}/${h}`,Type:u,Value:c,Description:d,Tier:g,Tags:{Name:h,Environment:s,...y}}},logicalId:b}}static createString(n,i,s,o,c){return D.createParameter({slug:n,environment:i,parameterName:s,value:o,type:"String",description:c})}static createSecureString(n,i,s,o,c){return D.createParameter({slug:n,environment:i,parameterName:s,value:o,type:"SecureString",description:c})}static createStringList(n,i,s,o,c){return D.createParameter({slug:n,environment:i,parameterName:s,value:o.join(","),type:"StringList",description:c})}static Parameters={databaseUrl:(n,i,s)=>D.createSecureString(n,i,"database-url",s,"Database connection URL"),apiEndpoint:(n,i,s)=>D.createString(n,i,"api-endpoint",s,"API endpoint URL"),appVersion:(n,i,s)=>D.createString(n,i,"app-version",s,"Application version"),featureFlags:(n,i,s)=>D.createStringList(n,i,"feature-flags",s,"Enabled feature flags"),apiKey:(n,i,s,o)=>D.createSecureString(n,i,`${s}-api-key`,o,`API key for ${s}`),oauthCredentials:(n,i,s,o)=>{let c=D.createString(n,i,"oauth-client-id",s,"OAuth client ID"),u=D.createSecureString(n,i,"oauth-client-secret",o,"OAuth client secret");return{clientId:c,clientSecret:u}},smtpCredentials:(n,i,s,o,c,u)=>{let d=D.createString(n,i,"smtp-username",s,"SMTP username"),g=D.createSecureString(n,i,"smtp-password",o,"SMTP password"),y=D.createString(n,i,"smtp-host",c,"SMTP host"),h=D.createString(n,i,"smtp-port",u.toString(),"SMTP port");return{username:d,password:g,host:y,port:h}},redisUrl:(n,i,s)=>D.createSecureString(n,i,"redis-url",s,"Redis connection URL"),s3Bucket:(n,i,s)=>D.createString(n,i,"s3-bucket",s,"S3 bucket name"),cloudFrontDistribution:(n,i,s)=>D.createString(n,i,"cloudfront-distribution-id",s,"CloudFront distribution ID")}}class gr{static createDomain(n){let{slug:i,environment:s,domainName:o,engineVersion:c="OpenSearch_2.11",instanceType:u="t3.small.search",instanceCount:d=1,volumeSize:g=10,volumeType:y="gp3",dedicatedMaster:h=!1,dedicatedMasterType:b,dedicatedMasterCount:v=3,multiAz:A=!1,availabilityZoneCount:T=2,vpc:R,encryption:P,enforceHttps:I=!0,tlsSecurityPolicy:M="Policy-Min-TLS-1-2-2019-07",advancedSecurity:L,autoSnapshotHour:N=0,autoTune:O=!0,tags:B={}}=n,F=o||r({slug:i,environment:s,resourceType:"search"}),U=t(F);return{domain:{Type:"AWS::OpenSearchService::Domain",Properties:{DomainName:F,EngineVersion:c,ClusterConfig:{InstanceType:u,InstanceCount:d,DedicatedMasterEnabled:h,...h&&{DedicatedMasterType:b||u,DedicatedMasterCount:v},ZoneAwarenessEnabled:A,...A&&{ZoneAwarenessConfig:{AvailabilityZoneCount:T}}},EBSOptions:{EBSEnabled:!0,VolumeType:y,VolumeSize:g},DomainEndpointOptions:{EnforceHTTPS:I,TLSSecurityPolicy:M},SnapshotOptions:{AutomatedSnapshotStartHour:N},...R&&{VPCOptions:{SubnetIds:R.subnetIds,SecurityGroupIds:R.securityGroupIds}},...P&&{EncryptionAtRestOptions:{Enabled:P.atRest??!0,...P.kmsKeyId&&{KmsKeyId:P.kmsKeyId}},NodeToNodeEncryptionOptions:{Enabled:P.nodeToNode??!0}},...L&&{AdvancedSecurityOptions:{Enabled:L.enabled,InternalUserDatabaseEnabled:L.internalUserDatabase??!0,...L.masterUserName&&L.masterUserPassword&&{MasterUserOptions:{MasterUserName:L.masterUserName,MasterUserPassword:L.masterUserPassword}},...L.masterUserArn&&{MasterUserOptions:{MasterUserARN:L.masterUserArn}}}},...O&&{AutoTuneOptions:{DesiredState:"ENABLED"}},Tags:[{Key:"Name",Value:F},{Key:"Environment",Value:s},...Object.entries(B).map(([H,z])=>({Key:H,Value:z}))]}},logicalId:U}}static createAccessPolicy(n,i){let{ipAddresses:s,iamPrincipalArns:o,allowAll:c,vpcEndpoint:u}=i;if(c)return{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:"*"},Action:"es:*",Resource:n}]};let d=[];if(o&&o.length>0)d.push({Effect:"Allow",Principal:{AWS:o},Action:"es:*",Resource:n});if(s&&s.length>0)d.push({Effect:"Allow",Principal:{AWS:"*"},Action:"es:*",Resource:n,Condition:{IpAddress:{"aws:SourceIp":s}}});if(u)return{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:"*"},Action:"es:*",Resource:n}]};return{Version:"2012-10-17",Statement:d}}static DomainPresets={development:(n,i)=>gr.createDomain({slug:n,environment:i,instanceType:"t3.small.search",instanceCount:1,volumeSize:10,multiAz:!1,dedicatedMaster:!1,encryption:{atRest:!0,nodeToNode:!0},autoTune:!1}),production:(n,i,s)=>gr.createDomain({slug:n,environment:i,instanceType:"m6g.large.search",instanceCount:3,volumeSize:100,volumeType:"gp3",multiAz:!0,availabilityZoneCount:3,dedicatedMaster:!0,dedicatedMasterType:"m6g.large.search",dedicatedMasterCount:3,vpc:s,encryption:{atRest:!0,nodeToNode:!0},advancedSecurity:{enabled:!0,internalUserDatabase:!0},autoTune:!0}),costOptimized:(n,i)=>gr.createDomain({slug:n,environment:i,instanceType:"t3.medium.search",instanceCount:2,volumeSize:20,volumeType:"gp3",multiAz:!0,dedicatedMaster:!1,encryption:{atRest:!0,nodeToNode:!0},autoTune:!0}),highPerformance:(n,i,s)=>gr.createDomain({slug:n,environment:i,instanceType:"r6g.2xlarge.search",instanceCount:6,volumeSize:500,volumeType:"gp3",multiAz:!0,availabilityZoneCount:3,dedicatedMaster:!0,dedicatedMasterType:"c6g.xlarge.search",dedicatedMasterCount:3,vpc:s,encryption:{atRest:!0,nodeToNode:!0},advancedSecurity:{enabled:!0,internalUserDatabase:!1},autoTune:!0})};static InstanceTypes={"t3.small.search":"t3.small.search","t3.medium.search":"t3.medium.search","m6g.large.search":"m6g.large.search","m6g.xlarge.search":"m6g.xlarge.search","m6g.2xlarge.search":"m6g.2xlarge.search","r6g.large.search":"r6g.large.search","r6g.xlarge.search":"r6g.xlarge.search","r6g.2xlarge.search":"r6g.2xlarge.search","r6g.4xlarge.search":"r6g.4xlarge.search","c6g.large.search":"c6g.large.search","c6g.xlarge.search":"c6g.xlarge.search","c6g.2xlarge.search":"c6g.2xlarge.search"};static EngineVersions={"OpenSearch_2.11":"OpenSearch_2.11","OpenSearch_2.9":"OpenSearch_2.9","OpenSearch_2.7":"OpenSearch_2.7","OpenSearch_1.3":"OpenSearch_1.3","Elasticsearch_7.10":"Elasticsearch_7.10"}}class xt{static createDomainRedirectBucket(n){let{slug:i,environment:s,sourceDomain:o,targetDomain:c,protocol:u="https"}=n,d=r({slug:i,environment:s,resourceType:"s3",suffix:"redirect"}),g=t(d),y=t(`${d}-policy`),h={Type:"AWS::S3::Bucket",Properties:{BucketName:o,WebsiteConfiguration:{RedirectAllRequestsTo:{HostName:c,Protocol:u}},PublicAccessBlockConfiguration:{BlockPublicAcls:!1,BlockPublicPolicy:!1,IgnorePublicAcls:!1,RestrictPublicBuckets:!1},Tags:[{Key:"Name",Value:d},{Key:"Environment",Value:s},{Key:"Purpose",Value:"Domain Redirect"}]}},b={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:x.Ref(g),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadForRedirect",Effect:"Allow",Principal:"*",Action:["s3:GetObject"],Resource:[x.Join("",[x.GetAtt(g,"Arn"),"/*"])]}]}}};return{bucket:h,bucketPolicy:b,logicalId:g,policyLogicalId:y}}static createPathRedirectFunction(n){let{slug:i,environment:s,rules:o}=n,c=r({slug:i,environment:s,resourceType:"cf-redirect"}),u=t(c),d=xt.generateRedirectFunctionCode(o);return{function:{Type:"AWS::CloudFront::Function",Properties:{Name:c,AutoPublish:!0,FunctionConfig:{Comment:`Path redirect function for ${i} (${s})`,Runtime:"cloudfront-js-2.0"},FunctionCode:d}},logicalId:u,functionCode:d}}static generateRedirectFunctionCode(n){return`function handler(event) {
2282
2282
  const request = event.request;
2283
2283
  const uri = request.uri;
2284
2284
  const querystring = request.querystring;
@@ -2332,7 +2332,7 @@ ${n.map((s)=>{let o=s.preserveQueryString!==!1,c=s.statusCode||301;return` '${s
2332
2332
  }
2333
2333
 
2334
2334
  return request;
2335
- }`}static CommonRedirects={wwwToApex:(n,i="https")=>({slug:n.replace(/\./g,"-"),environment:"production",sourceDomain:`www.${n}`,targetDomain:n,protocol:i,preservePath:!0}),apexToWww:(n,i="https")=>({slug:n.replace(/\./g,"-"),environment:"production",sourceDomain:n,targetDomain:`www.${n}`,protocol:i,preservePath:!0}),httpToHttps:(n="/")=>({source:n,target:n,statusCode:301}),addTrailingSlash:(n)=>n.map((i)=>({source:i.endsWith("/")?i.slice(0,-1):i,target:i.endsWith("/")?i:`${i}/`,statusCode:301})),removeTrailingSlash:(n)=>n.map((i)=>({source:i.endsWith("/")&&i!=="/"?i:`${i}/`,target:i.endsWith("/")&&i!=="/"?i.slice(0,-1):i,statusCode:301}))};static Patterns={flattenBlogUrls:(n)=>n.map(({oldPath:i,newPath:s})=>({source:i,target:s,statusCode:301,preserveQueryString:!0})),categoryRename:(n,i)=>[{source:`/${n}`,target:`/${i}`,statusCode:301},{source:`/${n}/`,target:`/${i}/`,statusCode:301}],productSlugChange:(n)=>n.map(({oldSlug:i,newSlug:s})=>({source:`/products/${i}`,target:`/products/${s}`,statusCode:301})),apiVersionRedirect:(n,i,s)=>s.map((o)=>({source:`/api/${n}/${o}`,target:`/api/${i}/${o}`,statusCode:307,preserveQueryString:!0})),gonePages:(n)=>n.map((i)=>({source:i,target:"/410",statusCode:301}))};static createRedirectSetup(n){let{slug:i,environment:s,domainRedirects:o=[],pathRedirects:c=[]}=n,u={},d=[];for(let y of o){let{bucket:h,bucketPolicy:b,logicalId:v,policyLogicalId:A}=Bt.createDomainRedirectBucket({...y,slug:i,environment:s});u[v]=h,u[A]=b,d.push(v)}let g=null;if(c.length>0){let{function:y,logicalId:h}=Bt.createPathRedirectFunction({slug:i,environment:s,rules:c});u[h]=y,g=h}return{resources:u,outputs:{domainRedirectBuckets:d,pathRedirectFunctionLogicalId:g}}}static fromMapping(n,i){return Object.entries(n).map(([s,o])=>({source:s,target:o,statusCode:i?.statusCode||301,preserveQueryString:i?.preserveQueryString??!0}))}static validateRules(n){let i=[],s=[],o=new Set;for(let c of n){if(o.has(c.source))i.push(`Duplicate source path: ${c.source}`);if(o.add(c.source),c.source===c.target)i.push(`Redirect loop detected: ${c.source} -> ${c.target}`);if(!c.target.startsWith("/")&&!c.target.startsWith("http"))s.push(`Target URL should start with / or http: ${c.target}`);if(!c.source||c.source.trim()==="")i.push("Source path cannot be empty");if(!c.target||c.target.trim()==="")i.push("Target path cannot be empty")}for(let c of n){let u=n.find((d)=>d.source===c.target);if(u)s.push(`Potential redirect chain: ${c.source} -> ${c.target} -> ${u.target}`)}return{valid:i.length===0,errors:i,warnings:s}}}class ee{static generate(n){let i={},{slug:s,environment:o,region:c="us-east-1"}=n,u=ee.createLambdaExecutionRole(s,o);if(Object.assign(i,u.resources),n.email?.enabled){let d=ee.generateEmailResources(n,u.roleArn);Object.assign(i,d)}if(n.phone?.enabled){let d=ee.generatePhoneResources(n,u.roleArn);Object.assign(i,d)}if(n.sms?.enabled){let d=ee.generateSmsResources(n,u.roleArn);Object.assign(i,d)}return i}static createLambdaExecutionRole(n,i){let s=`${n}-${i}-communication-role`,o=t(s);return{resources:{[o]:{Type:"AWS::IAM::Role",Properties:{RoleName:s,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:x.GetAtt(o,"Arn"),roleName:s}}static generateEmailResources(n,i){let{slug:s,environment:o,email:c}=n;if(!c)return{};let u={},d=`${s}-${o}`,g=`${d}-email-storage`,y=t(g);u[y]={Type:"AWS::S3::Bucket",Properties:{BucketName:g,LifecycleConfiguration:{Rules:[{Id:"ArchiveOldEmails",Status:"Enabled",Transitions:c.server?.storage?.archiveAfterDays?[{StorageClass:"GLACIER",TransitionInDays:c.server.storage.archiveAfterDays}]:[],ExpirationInDays:c.server?.storage?.retentionDays||365}]},NotificationConfiguration:{LambdaConfigurations:[]}}};let h=t(`${d}-ses-identity`);if(u[h]={Type:"AWS::SES::EmailIdentity",Properties:{EmailIdentity:c.domain,DkimSigningAttributes:{NextSigningKeyLength:"RSA_2048_BIT"},FeedbackAttributes:{EmailForwardingEnabled:!0}}},c.notifications?.bounces||c.notifications?.complaints){let b=t(`${d}-bounce-topic`);u[b]={Type:"AWS::SNS::Topic",Properties:{TopicName:`${d}-email-bounces`}};let v=t(`${d}-complaint-topic`);u[v]={Type:"AWS::SNS::Topic",Properties:{TopicName:`${d}-email-complaints`}}}if(c.server?.enabled){let b=t(`${d}-inbound-email`);u[b]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${d}-inbound-email`,Runtime:"nodejs20.x",Handler:"index.handler",Role:i,Timeout:60,MemorySize:256,Code:{ZipFile:ee.InboundEmailCode},Environment:{Variables:{EMAIL_BUCKET:g,DOMAIN:c.domain}}}};let v=t(`${d}-outbound-email`);u[v]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${d}-outbound-email`,Runtime:"nodejs20.x",Handler:"index.handler",Role:i,Timeout:30,MemorySize:256,Code:{ZipFile:ee.OutboundEmailCode},Environment:{Variables:{EMAIL_BUCKET:g,DOMAIN:c.domain}}}}}if(c.advanced?.analytics){let b=t(`${d}-email-analytics`);u[b]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${d}-email-analytics`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"messageId",AttributeType:"S"}],KeySchema:[{AttributeName:"messageId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}if(c.advanced?.scheduling){let b=t(`${d}-email-scheduler`);u[b]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${d}-email-scheduler`,Runtime:"nodejs20.x",Handler:"index.handler",Role:i,Timeout:300,MemorySize:256,Code:{ZipFile:ee.EmailSchedulerCode},Environment:{Variables:{EMAIL_BUCKET:g}}}};let v=t(`${d}-email-scheduler-rule`);u[v]={Type:"AWS::Events::Rule",Properties:{Name:`${d}-email-scheduler`,ScheduleExpression:"rate(1 minute)",State:"ENABLED",Targets:[{Id:"EmailSchedulerTarget",Arn:x.GetAtt(b,"Arn")}]}}}if(c.advanced?.threading){let b=t(`${d}-email-threading`);u[b]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${d}-email-threading`,Runtime:"nodejs20.x",Handler:"index.handler",Role:i,Timeout:60,MemorySize:256,Code:{ZipFile:ee.EmailThreadingCode},Environment:{Variables:{EMAIL_BUCKET:g}}}}}if(c.advanced?.rules){let b=t(`${d}-email-rules`);u[b]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${d}-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(c.advanced?.sharedMailboxes){let b=t(`${d}-shared-mailboxes`);u[b]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${d}-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(c.advanced?.search){let b=t(`${d}-email-search`);u[b]={Type:"AWS::OpenSearchService::Domain",Properties:{DomainName:`${d}-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 u}static generatePhoneResources(n,i){let{slug:s,environment:o,phone:c}=n;if(!c)return{};let u={},d=`${s}-${o}`,g=t(`${d}-call-log`);if(u[g]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${d}-call-log`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"contactId",AttributeType:"S"}],KeySchema:[{AttributeName:"contactId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}},c.voicemail?.enabled){let b=t(`${d}-voicemail`);u[b]={Type:"AWS::S3::Bucket",Properties:{BucketName:`${d}-voicemail`,LifecycleConfiguration:{Rules:[{Id:"DeleteOldVoicemails",Status:"Enabled",ExpirationInDays:90}]}}}}let y=t(`${d}-phone-notifications`);u[y]={Type:"AWS::SNS::Topic",Properties:{TopicName:`${d}-phone-notifications`}};let h=t(`${d}-incoming-call`);if(u[h]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${d}-incoming-call`,Runtime:"nodejs20.x",Handler:"index.handler",Role:i,Timeout:30,MemorySize:256,Code:{ZipFile:ee.IncomingCallCode},Environment:{Variables:{CALL_LOG_TABLE:`${d}-call-log`,NOTIFICATION_TOPIC_ARN:x.Ref(y)}}}},c.voicemail?.enabled){let b=t(`${d}-voicemail-handler`);u[b]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${d}-voicemail-handler`,Runtime:"nodejs20.x",Handler:"index.handler",Role:i,Timeout:c.voicemail.transcription?300:60,MemorySize:256,Code:{ZipFile:ee.VoicemailCode},Environment:{Variables:{VOICEMAIL_BUCKET:`${d}-voicemail`,TRANSCRIPTION_ENABLED:String(c.voicemail.transcription||!1),NOTIFICATION_TOPIC_ARN:x.Ref(y)}}}}}if(c.advanced?.recording){let b=t(`${d}-call-recordings`);u[b]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${d}-call-recordings`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"recordingId",AttributeType:"S"}],KeySchema:[{AttributeName:"recordingId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}if(c.advanced?.callbacks){let b=t(`${d}-callbacks`);u[b]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${d}-callbacks`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}if(c.advanced?.analytics){let b=t(`${d}-call-metrics`);u[b]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${d}-call-metrics`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"period",AttributeType:"S"}],KeySchema:[{AttributeName:"period",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}return u}static generateSmsResources(n,i){let{slug:s,environment:o,sms:c}=n;if(!c)return{};let u={},d=`${s}-${o}`,g=t(`${d}-pinpoint-app`);u[g]={Type:"AWS::Pinpoint::App",Properties:{Name:`${d}-sms`}};let y=t(`${d}-sms-channel`);u[y]={Type:"AWS::Pinpoint::SMSChannel",Properties:{ApplicationId:x.Ref(g),Enabled:!0,SenderId:c.senderId}};let h=t(`${d}-sms-log`);if(u[h]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${d}-sms-log`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"messageId",AttributeType:"S"}],KeySchema:[{AttributeName:"messageId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}},c.optOut?.enabled){let T=t(`${d}-sms-optout`);u[T]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${d}-sms-optout`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"phoneNumber",AttributeType:"S"}],KeySchema:[{AttributeName:"phoneNumber",KeyType:"HASH"}]}}}let b=t(`${d}-sms-notifications`);u[b]={Type:"AWS::SNS::Topic",Properties:{TopicName:`${d}-sms-notifications`}};let v=t(`${d}-send-sms`);u[v]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${d}-send-sms`,Runtime:"nodejs20.x",Handler:"index.handler",Role:i,Timeout:30,MemorySize:256,Code:{ZipFile:ee.SendSmsCode},Environment:{Variables:{PINPOINT_APP_ID:x.Ref(g),MESSAGE_LOG_TABLE:`${d}-sms-log`,OPT_OUT_TABLE:c.optOut?.enabled?`${d}-sms-optout`:"",MESSAGE_TYPE:c.messageType||"TRANSACTIONAL"}}}};let A=t(`${d}-receive-sms`);if(u[A]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${d}-receive-sms`,Runtime:"nodejs20.x",Handler:"index.handler",Role:i,Timeout:30,MemorySize:256,Code:{ZipFile:ee.ReceiveSmsCode},Environment:{Variables:{MESSAGE_LOG_TABLE:`${d}-sms-log`,OPT_OUT_TABLE:c.optOut?.enabled?`${d}-sms-optout`:"",NOTIFICATION_TOPIC_ARN:x.Ref(b)}}}},c.advanced?.campaigns){let T=t(`${d}-sms-campaigns`);u[T]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${d}-sms-campaigns`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}]}}}if(c.advanced?.analytics){let T=t(`${d}-sms-analytics`);u[T]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${d}-sms-analytics`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"period",AttributeType:"S"}],KeySchema:[{AttributeName:"period",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}if(c.advanced?.linkTracking){let T=t(`${d}-short-links`);u[T]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${d}-short-links`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}if(c.advanced?.chatbot){let T=t(`${d}-chatbot-sessions`);u[T]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${d}-chatbot-sessions`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"phoneNumber",AttributeType:"S"}],KeySchema:[{AttributeName:"phoneNumber",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}};let R=t(`${d}-chatbot-rules`);u[R]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${d}-chatbot-rules`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}]}}}if(c.advanced?.abTesting){let T=t(`${d}-ab-tests`);u[T]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${d}-ab-tests`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}]}}}if(c.advanced?.mms){let T=t(`${d}-mms-media`);u[T]={Type:"AWS::S3::Bucket",Properties:{BucketName:`${d}-mms-media`,LifecycleConfiguration:{Rules:[{Id:"DeleteOldMedia",Status:"Enabled",ExpirationInDays:30}]}}}}return u}static InboundEmailCode=`
2335
+ }`}static CommonRedirects={wwwToApex:(n,i="https")=>({slug:n.replace(/\./g,"-"),environment:"production",sourceDomain:`www.${n}`,targetDomain:n,protocol:i,preservePath:!0}),apexToWww:(n,i="https")=>({slug:n.replace(/\./g,"-"),environment:"production",sourceDomain:n,targetDomain:`www.${n}`,protocol:i,preservePath:!0}),httpToHttps:(n="/")=>({source:n,target:n,statusCode:301}),addTrailingSlash:(n)=>n.map((i)=>({source:i.endsWith("/")?i.slice(0,-1):i,target:i.endsWith("/")?i:`${i}/`,statusCode:301})),removeTrailingSlash:(n)=>n.map((i)=>({source:i.endsWith("/")&&i!=="/"?i:`${i}/`,target:i.endsWith("/")&&i!=="/"?i.slice(0,-1):i,statusCode:301}))};static Patterns={flattenBlogUrls:(n)=>n.map(({oldPath:i,newPath:s})=>({source:i,target:s,statusCode:301,preserveQueryString:!0})),categoryRename:(n,i)=>[{source:`/${n}`,target:`/${i}`,statusCode:301},{source:`/${n}/`,target:`/${i}/`,statusCode:301}],productSlugChange:(n)=>n.map(({oldSlug:i,newSlug:s})=>({source:`/products/${i}`,target:`/products/${s}`,statusCode:301})),apiVersionRedirect:(n,i,s)=>s.map((o)=>({source:`/api/${n}/${o}`,target:`/api/${i}/${o}`,statusCode:307,preserveQueryString:!0})),gonePages:(n)=>n.map((i)=>({source:i,target:"/410",statusCode:301}))};static createRedirectSetup(n){let{slug:i,environment:s,domainRedirects:o=[],pathRedirects:c=[]}=n,u={},d=[];for(let y of o){let{bucket:h,bucketPolicy:b,logicalId:v,policyLogicalId:A}=xt.createDomainRedirectBucket({...y,slug:i,environment:s});u[v]=h,u[A]=b,d.push(v)}let g=null;if(c.length>0){let{function:y,logicalId:h}=xt.createPathRedirectFunction({slug:i,environment:s,rules:c});u[h]=y,g=h}return{resources:u,outputs:{domainRedirectBuckets:d,pathRedirectFunctionLogicalId:g}}}static fromMapping(n,i){return Object.entries(n).map(([s,o])=>({source:s,target:o,statusCode:i?.statusCode||301,preserveQueryString:i?.preserveQueryString??!0}))}static validateRules(n){let i=[],s=[],o=new Set;for(let c of n){if(o.has(c.source))i.push(`Duplicate source path: ${c.source}`);if(o.add(c.source),c.source===c.target)i.push(`Redirect loop detected: ${c.source} -> ${c.target}`);if(!c.target.startsWith("/")&&!c.target.startsWith("http"))s.push(`Target URL should start with / or http: ${c.target}`);if(!c.source||c.source.trim()==="")i.push("Source path cannot be empty");if(!c.target||c.target.trim()==="")i.push("Target path cannot be empty")}for(let c of n){let u=n.find((d)=>d.source===c.target);if(u)s.push(`Potential redirect chain: ${c.source} -> ${c.target} -> ${u.target}`)}return{valid:i.length===0,errors:i,warnings:s}}}class ee{static generate(n){let i={},{slug:s,environment:o,region:c="us-east-1"}=n,u=ee.createLambdaExecutionRole(s,o);if(Object.assign(i,u.resources),n.email?.enabled){let d=ee.generateEmailResources(n,u.roleArn);Object.assign(i,d)}if(n.phone?.enabled){let d=ee.generatePhoneResources(n,u.roleArn);Object.assign(i,d)}if(n.sms?.enabled){let d=ee.generateSmsResources(n,u.roleArn);Object.assign(i,d)}return i}static createLambdaExecutionRole(n,i){let s=`${n}-${i}-communication-role`,o=t(s);return{resources:{[o]:{Type:"AWS::IAM::Role",Properties:{RoleName:s,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:x.GetAtt(o,"Arn"),roleName:s}}static generateEmailResources(n,i){let{slug:s,environment:o,email:c}=n;if(!c)return{};let u={},d=`${s}-${o}`,g=`${d}-email-storage`,y=t(g);u[y]={Type:"AWS::S3::Bucket",Properties:{BucketName:g,LifecycleConfiguration:{Rules:[{Id:"ArchiveOldEmails",Status:"Enabled",Transitions:c.server?.storage?.archiveAfterDays?[{StorageClass:"GLACIER",TransitionInDays:c.server.storage.archiveAfterDays}]:[],ExpirationInDays:c.server?.storage?.retentionDays||365}]},NotificationConfiguration:{LambdaConfigurations:[]}}};let h=t(`${d}-ses-identity`);if(u[h]={Type:"AWS::SES::EmailIdentity",Properties:{EmailIdentity:c.domain,DkimSigningAttributes:{NextSigningKeyLength:"RSA_2048_BIT"},FeedbackAttributes:{EmailForwardingEnabled:!0}}},c.notifications?.bounces||c.notifications?.complaints){let b=t(`${d}-bounce-topic`);u[b]={Type:"AWS::SNS::Topic",Properties:{TopicName:`${d}-email-bounces`}};let v=t(`${d}-complaint-topic`);u[v]={Type:"AWS::SNS::Topic",Properties:{TopicName:`${d}-email-complaints`}}}if(c.server?.enabled){let b=t(`${d}-inbound-email`);u[b]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${d}-inbound-email`,Runtime:"nodejs20.x",Handler:"index.handler",Role:i,Timeout:60,MemorySize:256,Code:{ZipFile:ee.InboundEmailCode},Environment:{Variables:{EMAIL_BUCKET:g,DOMAIN:c.domain}}}};let v=t(`${d}-outbound-email`);u[v]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${d}-outbound-email`,Runtime:"nodejs20.x",Handler:"index.handler",Role:i,Timeout:30,MemorySize:256,Code:{ZipFile:ee.OutboundEmailCode},Environment:{Variables:{EMAIL_BUCKET:g,DOMAIN:c.domain}}}}}if(c.advanced?.analytics){let b=t(`${d}-email-analytics`);u[b]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${d}-email-analytics`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"messageId",AttributeType:"S"}],KeySchema:[{AttributeName:"messageId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}if(c.advanced?.scheduling){let b=t(`${d}-email-scheduler`);u[b]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${d}-email-scheduler`,Runtime:"nodejs20.x",Handler:"index.handler",Role:i,Timeout:300,MemorySize:256,Code:{ZipFile:ee.EmailSchedulerCode},Environment:{Variables:{EMAIL_BUCKET:g}}}};let v=t(`${d}-email-scheduler-rule`);u[v]={Type:"AWS::Events::Rule",Properties:{Name:`${d}-email-scheduler`,ScheduleExpression:"rate(1 minute)",State:"ENABLED",Targets:[{Id:"EmailSchedulerTarget",Arn:x.GetAtt(b,"Arn")}]}}}if(c.advanced?.threading){let b=t(`${d}-email-threading`);u[b]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${d}-email-threading`,Runtime:"nodejs20.x",Handler:"index.handler",Role:i,Timeout:60,MemorySize:256,Code:{ZipFile:ee.EmailThreadingCode},Environment:{Variables:{EMAIL_BUCKET:g}}}}}if(c.advanced?.rules){let b=t(`${d}-email-rules`);u[b]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${d}-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(c.advanced?.sharedMailboxes){let b=t(`${d}-shared-mailboxes`);u[b]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${d}-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(c.advanced?.search){let b=t(`${d}-email-search`);u[b]={Type:"AWS::OpenSearchService::Domain",Properties:{DomainName:`${d}-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 u}static generatePhoneResources(n,i){let{slug:s,environment:o,phone:c}=n;if(!c)return{};let u={},d=`${s}-${o}`,g=t(`${d}-call-log`);if(u[g]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${d}-call-log`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"contactId",AttributeType:"S"}],KeySchema:[{AttributeName:"contactId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}},c.voicemail?.enabled){let b=t(`${d}-voicemail`);u[b]={Type:"AWS::S3::Bucket",Properties:{BucketName:`${d}-voicemail`,LifecycleConfiguration:{Rules:[{Id:"DeleteOldVoicemails",Status:"Enabled",ExpirationInDays:90}]}}}}let y=t(`${d}-phone-notifications`);u[y]={Type:"AWS::SNS::Topic",Properties:{TopicName:`${d}-phone-notifications`}};let h=t(`${d}-incoming-call`);if(u[h]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${d}-incoming-call`,Runtime:"nodejs20.x",Handler:"index.handler",Role:i,Timeout:30,MemorySize:256,Code:{ZipFile:ee.IncomingCallCode},Environment:{Variables:{CALL_LOG_TABLE:`${d}-call-log`,NOTIFICATION_TOPIC_ARN:x.Ref(y)}}}},c.voicemail?.enabled){let b=t(`${d}-voicemail-handler`);u[b]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${d}-voicemail-handler`,Runtime:"nodejs20.x",Handler:"index.handler",Role:i,Timeout:c.voicemail.transcription?300:60,MemorySize:256,Code:{ZipFile:ee.VoicemailCode},Environment:{Variables:{VOICEMAIL_BUCKET:`${d}-voicemail`,TRANSCRIPTION_ENABLED:String(c.voicemail.transcription||!1),NOTIFICATION_TOPIC_ARN:x.Ref(y)}}}}}if(c.advanced?.recording){let b=t(`${d}-call-recordings`);u[b]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${d}-call-recordings`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"recordingId",AttributeType:"S"}],KeySchema:[{AttributeName:"recordingId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}if(c.advanced?.callbacks){let b=t(`${d}-callbacks`);u[b]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${d}-callbacks`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}if(c.advanced?.analytics){let b=t(`${d}-call-metrics`);u[b]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${d}-call-metrics`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"period",AttributeType:"S"}],KeySchema:[{AttributeName:"period",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}return u}static generateSmsResources(n,i){let{slug:s,environment:o,sms:c}=n;if(!c)return{};let u={},d=`${s}-${o}`,g=t(`${d}-pinpoint-app`);u[g]={Type:"AWS::Pinpoint::App",Properties:{Name:`${d}-sms`}};let y=t(`${d}-sms-channel`);u[y]={Type:"AWS::Pinpoint::SMSChannel",Properties:{ApplicationId:x.Ref(g),Enabled:!0,SenderId:c.senderId}};let h=t(`${d}-sms-log`);if(u[h]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${d}-sms-log`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"messageId",AttributeType:"S"}],KeySchema:[{AttributeName:"messageId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}},c.optOut?.enabled){let T=t(`${d}-sms-optout`);u[T]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${d}-sms-optout`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"phoneNumber",AttributeType:"S"}],KeySchema:[{AttributeName:"phoneNumber",KeyType:"HASH"}]}}}let b=t(`${d}-sms-notifications`);u[b]={Type:"AWS::SNS::Topic",Properties:{TopicName:`${d}-sms-notifications`}};let v=t(`${d}-send-sms`);u[v]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${d}-send-sms`,Runtime:"nodejs20.x",Handler:"index.handler",Role:i,Timeout:30,MemorySize:256,Code:{ZipFile:ee.SendSmsCode},Environment:{Variables:{PINPOINT_APP_ID:x.Ref(g),MESSAGE_LOG_TABLE:`${d}-sms-log`,OPT_OUT_TABLE:c.optOut?.enabled?`${d}-sms-optout`:"",MESSAGE_TYPE:c.messageType||"TRANSACTIONAL"}}}};let A=t(`${d}-receive-sms`);if(u[A]={Type:"AWS::Lambda::Function",Properties:{FunctionName:`${d}-receive-sms`,Runtime:"nodejs20.x",Handler:"index.handler",Role:i,Timeout:30,MemorySize:256,Code:{ZipFile:ee.ReceiveSmsCode},Environment:{Variables:{MESSAGE_LOG_TABLE:`${d}-sms-log`,OPT_OUT_TABLE:c.optOut?.enabled?`${d}-sms-optout`:"",NOTIFICATION_TOPIC_ARN:x.Ref(b)}}}},c.advanced?.campaigns){let T=t(`${d}-sms-campaigns`);u[T]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${d}-sms-campaigns`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}]}}}if(c.advanced?.analytics){let T=t(`${d}-sms-analytics`);u[T]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${d}-sms-analytics`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"period",AttributeType:"S"}],KeySchema:[{AttributeName:"period",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}if(c.advanced?.linkTracking){let T=t(`${d}-short-links`);u[T]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${d}-short-links`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}if(c.advanced?.chatbot){let T=t(`${d}-chatbot-sessions`);u[T]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${d}-chatbot-sessions`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"phoneNumber",AttributeType:"S"}],KeySchema:[{AttributeName:"phoneNumber",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}};let R=t(`${d}-chatbot-rules`);u[R]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${d}-chatbot-rules`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}]}}}if(c.advanced?.abTesting){let T=t(`${d}-ab-tests`);u[T]={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${d}-ab-tests`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}]}}}if(c.advanced?.mms){let T=t(`${d}-mms-media`);u[T]={Type:"AWS::S3::Bucket",Properties:{BucketName:`${d}-mms-media`,LifecycleConfiguration:{Rules:[{Id:"DeleteOldMedia",Status:"Enabled",ExpirationInDays:30}]}}}}return u}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 e={ref:(n)=>({Ref:n}),getAtt:(n,i)=>({"Fn::GetAtt":[n,i]}),join:(n,i)=>({"Fn::Join":[n,i]}),sub:(n,i)=>i?{"Fn::Sub":[n,i]}:{"Fn::Sub":n},select:(n,i)=>({"Fn::Select":[n,i]}),split:(n,i)=>({"Fn::Split":[n,i]}),getAZs:(n="")=>({"Fn::GetAZs":n}),importValue:(n)=>({"Fn::ImportValue":n}),findInMap:(n,i,s)=>({"Fn::FindInMap":[n,i,s]}),base64:(n)=>({"Fn::Base64":n}),cidr:(n,i,s)=>({"Fn::Cidr":[n,i,s]}),equals:(n,i)=>({"Fn::Equals":[n,i]}),if:(n,i,s)=>({"Fn::If":[n,i,s]}),not:(n)=>({"Fn::Not":[n]}),and:(...n)=>({"Fn::And":n}),or:(...n)=>({"Fn::Or":n})},un={s3Bucket:(n)=>e.sub(`arn:aws:s3:::${n}`),s3Object:(n,i="*")=>e.sub(`arn:aws:s3:::${n}/${i}`),lambda:(n,i,s)=>e.sub(`arn:aws:lambda:\${AWS::Region}:\${AWS::AccountId}:function:${n}`,i&&s?{"AWS::Region":i,"AWS::AccountId":s}:void 0),dynamodb:(n)=>e.sub(`arn:aws:dynamodb:\${AWS::Region}:\${AWS::AccountId}:table/${n}`),sqs:(n)=>e.sub(`arn:aws:sqs:\${AWS::Region}:\${AWS::AccountId}:${n}`),sns:(n)=>e.sub(`arn:aws:sns:\${AWS::Region}:\${AWS::AccountId}:${n}`),kinesis:(n)=>e.sub(`arn:aws:kinesis:\${AWS::Region}:\${AWS::AccountId}:stream/${n}`),iam:(n,i)=>e.sub(`arn:aws:iam::\${AWS::AccountId}:${n}/${i}`),secretsManager:(n)=>e.sub(`arn:aws:secretsmanager:\${AWS::Region}:\${AWS::AccountId}:secret:${n}`),cloudwatch:(n)=>e.sub(`arn:aws:logs:\${AWS::Region}:\${AWS::AccountId}:log-group:${n}`)},XI={ACCOUNT_ID:{Ref:"AWS::AccountId"},NOTIFICATION_ARNS:{Ref:"AWS::NotificationARNs"},NO_VALUE:{Ref:"AWS::NoValue"},PARTITION:{Ref:"AWS::Partition"},REGION:{Ref:"AWS::Region"},STACK_ID:{Ref:"AWS::StackId"},STACK_NAME:{Ref:"AWS::StackName"},URL_SUFFIX:{Ref:"AWS::URLSuffix"}};function Sn(n,i){if(i.type==="http")$r(n,i);else if(i.type==="rest")Br(n,i);else if(i.type==="websocket")Fr(n,i)}function $r(n,i){let s={Name:e.sub("${AWS::StackName}-http-api"),ProtocolType:"HTTP"};if(i.cors)s.CorsConfiguration={AllowOrigins:i.cors.allowOrigins,AllowMethods:i.cors.allowMethods,AllowHeaders:i.cors.allowHeaders||["*"],MaxAge:i.cors.maxAge||300};if(n.addResource("HttpApi","AWS::ApiGatewayV2::Api",s),n.addResource("HttpApiStage","AWS::ApiGatewayV2::Stage",{ApiId:e.ref("HttpApi"),StageName:"$default",AutoDeploy:!0,DefaultRouteSettings:i.throttling?{ThrottlingBurstLimit:i.throttling.burstLimit,ThrottlingRateLimit:i.throttling.rateLimit}:void 0,AccessLogSettings:{DestinationArn:e.getAtt("ApiLogGroup","Arn"),Format:"$context.requestId $context.error.message $context.error.messageString"}},{dependsOn:["HttpApi","ApiLogGroup"]}),n.addResource("ApiLogGroup","AWS::Logs::LogGroup",{LogGroupName:e.sub("/aws/apigateway/${AWS::StackName}-http-api"),RetentionInDays:14}),i.authorizer)Gr(n,"HttpApi",i.authorizer);if(i.customDomain)Rt(n,"HttpApi",i.customDomain,"HTTP");n.addOutputs({HttpApiId:{Description:"HTTP API ID",Value:e.ref("HttpApi"),Export:{Name:e.sub("${AWS::StackName}-http-api-id")}},HttpApiEndpoint:{Description:"HTTP API endpoint",Value:e.getAtt("HttpApi","ApiEndpoint"),Export:{Name:e.sub("${AWS::StackName}-http-api-endpoint")}}})}function Br(n,i){n.addResource("RestApi","AWS::ApiGateway::RestApi",{Name:e.sub("${AWS::StackName}-rest-api"),Description:e.sub("REST API for ${AWS::StackName}"),EndpointConfiguration:{Types:["REGIONAL"]}}),n.addResource("ApiGatewayAccount","AWS::ApiGateway::Account",{CloudWatchRoleArn:e.getAtt("ApiGatewayCloudWatchRole","Arn")},{dependsOn:"ApiGatewayCloudWatchRole"}),n.addResource("ApiGatewayCloudWatchRole","AWS::IAM::Role",{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"apigateway.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs"]}),n.addResource("RestApiDeployment","AWS::ApiGateway::Deployment",{RestApiId:e.ref("RestApi"),Description:"Initial deployment"},{dependsOn:"RestApi"});let s={RestApiId:e.ref("RestApi"),DeploymentId:e.ref("RestApiDeployment"),StageName:"prod",Description:"Production stage",MethodSettings:[{ResourcePath:"/*",HttpMethod:"*",LoggingLevel:"INFO",DataTraceEnabled:!0,MetricsEnabled:!0}]};if(i.throttling)s.MethodSettings[0].ThrottlingBurstLimit=i.throttling.burstLimit,s.MethodSettings[0].ThrottlingRateLimit=i.throttling.rateLimit;if(n.addResource("RestApiStage","AWS::ApiGateway::Stage",s,{dependsOn:["RestApi","RestApiDeployment"]}),i.customDomain)Rt(n,"RestApi",i.customDomain,"REST");n.addOutputs({RestApiId:{Description:"REST API ID",Value:e.ref("RestApi"),Export:{Name:e.sub("${AWS::StackName}-rest-api-id")}},RestApiEndpoint:{Description:"REST API endpoint",Value:e.sub("https://${RestApi}.execute-api.${AWS::Region}.amazonaws.com/prod"),Export:{Name:e.sub("${AWS::StackName}-rest-api-endpoint")}}})}function Fr(n,i){if(n.addResource("WebSocketApi","AWS::ApiGatewayV2::Api",{Name:e.sub("${AWS::StackName}-websocket-api"),ProtocolType:"WEBSOCKET",RouteSelectionExpression:"$request.body.action"}),i.routes){if(i.routes.connect)lt(n,"$connect",i.routes.connect.functionName);if(i.routes.disconnect)lt(n,"$disconnect",i.routes.disconnect.functionName);if(i.routes.default)lt(n,"$default",i.routes.default.functionName);if(i.routes.custom)i.routes.custom.forEach((s)=>{lt(n,s.routeKey,s.functionName)})}if(n.addResource("WebSocketApiStage","AWS::ApiGatewayV2::Stage",{ApiId:e.ref("WebSocketApi"),StageName:"prod",AutoDeploy:!0,DefaultRouteSettings:i.throttling?{ThrottlingBurstLimit:i.throttling.burstLimit,ThrottlingRateLimit:i.throttling.rateLimit}:void 0},{dependsOn:"WebSocketApi"}),i.customDomain)Rt(n,"WebSocketApi",i.customDomain,"WEBSOCKET");n.addOutputs({WebSocketApiId:{Description:"WebSocket API ID",Value:e.ref("WebSocketApi"),Export:{Name:e.sub("${AWS::StackName}-websocket-api-id")}},WebSocketApiEndpoint:{Description:"WebSocket API endpoint",Value:e.getAtt("WebSocketApi","ApiEndpoint"),Export:{Name:e.sub("${AWS::StackName}-websocket-api-endpoint")}}})}function lt(n,i,s){let o=n.toLogicalId(`websocket-route-${i}`),c=n.toLogicalId(`websocket-integration-${i}`),u=n.toLogicalId(`${s}-function`);n.addResource(c,"AWS::ApiGatewayV2::Integration",{ApiId:e.ref("WebSocketApi"),IntegrationType:"AWS_PROXY",IntegrationUri:e.sub(`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${u}.Arn}/invocations`)},{dependsOn:["WebSocketApi",u]}),n.addResource(o,"AWS::ApiGatewayV2::Route",{ApiId:e.ref("WebSocketApi"),RouteKey:i,Target:e.join("/",["integrations",e.ref(c)])},{dependsOn:["WebSocketApi",c]}),n.addResource(`${o}Permission`,"AWS::Lambda::Permission",{FunctionName:e.ref(u),Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:e.sub("arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${WebSocketApi}/*")},{dependsOn:[u,"WebSocketApi"]})}function Rt(n,i,s,o){let c={DomainName:s.domain};if(o==="REST")c.CertificateArn=s.certificateArn,c.EndpointConfiguration={Types:["REGIONAL"]},n.addResource("ApiCustomDomain","AWS::ApiGateway::DomainName",c),n.addResource("ApiBasePathMapping","AWS::ApiGateway::BasePathMapping",{DomainName:e.ref("ApiCustomDomain"),RestApiId:e.ref(i),Stage:e.ref("RestApiStage")},{dependsOn:["ApiCustomDomain",i,"RestApiStage"]});else c.DomainNameConfigurations=[{CertificateArn:s.certificateArn,EndpointType:"REGIONAL"}],n.addResource("ApiCustomDomain","AWS::ApiGatewayV2::DomainName",c),n.addResource("ApiMapping","AWS::ApiGatewayV2::ApiMapping",{ApiId:e.ref(i),DomainName:e.ref("ApiCustomDomain"),Stage:o==="HTTP"?e.ref("HttpApiStage"):e.ref("WebSocketApiStage")},{dependsOn:["ApiCustomDomain",i]});if(s.dnsProvider!=="external")n.addResource("ApiDNSRecord","AWS::Route53::RecordSet",{HostedZoneName:e.sub(`${_r(s.domain)}.`),Name:s.domain,Type:"A",AliasTarget:{HostedZoneId:e.getAtt("ApiCustomDomain","RegionalHostedZoneId"),DNSName:e.getAtt("ApiCustomDomain","RegionalDomainName"),EvaluateTargetHealth:!1}},{dependsOn:"ApiCustomDomain"});n.addOutputs({ApiCustomDomainName:{Description:"Configured API custom domain",Value:s.domain},ApiCustomDomainTarget:{Description:"DNS target for Route53 or an external DNS provider",Value:e.getAtt("ApiCustomDomain","RegionalDomainName")},ApiCustomDomainHostedZoneId:{Description:"Regional API Gateway hosted zone ID",Value:e.getAtt("ApiCustomDomain","RegionalHostedZoneId")}})}function Gr(n,i,s){if(!s)return;if(s.type==="jwt")n.addResource("ApiAuthorizer","AWS::ApiGatewayV2::Authorizer",{ApiId:e.ref(i),AuthorizerType:"JWT",IdentitySource:[s.identitySource||"$request.header.Authorization"],JwtConfiguration:{Issuer:s.issuer,Audience:s.audience},Name:"JWTAuthorizer"},{dependsOn:i});else if(s.type==="lambda")n.addResource("ApiAuthorizer","AWS::ApiGatewayV2::Authorizer",{ApiId:e.ref(i),AuthorizerType:"REQUEST",AuthorizerUri:s.authorizerUri,IdentitySource:[s.identitySource||"$request.header.Authorization"],Name:"LambdaAuthorizer"},{dependsOn:i})}function _r(n){let i=n.split(".");if(i.length>=2)return i.slice(-2).join(".");return n}function An(n,i){if(i.redis)Wr(n,i.redis);if(i.memcached)Vr(n,i.memcached);if(i.elasticache)Ur(n,i.elasticache)}function Wr(n,i){if(!i)return;if(n.addResource("CacheSubnetGroup","AWS::ElastiCache::SubnetGroup",{Description:"Subnet group for ElastiCache Redis cluster",SubnetIds:[e.ref("PrivateSubnet1"),e.ref("PrivateSubnet2")],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-cache-subnet-group")}]},{dependsOn:["PrivateSubnet1","PrivateSubnet2"]}),n.addResource("CacheSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for ElastiCache Redis",VpcId:e.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:i.port||6379,ToPort:i.port||6379,SourceSecurityGroupId:e.ref("AppSecurityGroup")}],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-cache-sg")}]},{dependsOn:["VPC","AppSecurityGroup"]}),i.parameterGroup&&Object.keys(i.parameterGroup).length>0)n.addResource("CacheParameterGroup","AWS::ElastiCache::ParameterGroup",{Description:"Parameter group for Redis",CacheParameterGroupFamily:`redis${i.engineVersion.split(".")[0]}`,Properties:i.parameterGroup});if(i.numCacheNodes>1||i.automaticFailoverEnabled)n.addResource("RedisReplicationGroup","AWS::ElastiCache::ReplicationGroup",{ReplicationGroupDescription:"Redis replication group",ReplicationGroupId:e.sub("${AWS::StackName}-redis"),Engine:"redis",EngineVersion:i.engineVersion,CacheNodeType:i.nodeType,NumCacheClusters:i.numCacheNodes,AutomaticFailoverEnabled:i.automaticFailoverEnabled||!1,MultiAZEnabled:i.automaticFailoverEnabled||!1,Port:i.port||6379,CacheSubnetGroupName:e.ref("CacheSubnetGroup"),SecurityGroupIds:[e.ref("CacheSecurityGroup")],CacheParameterGroupName:i.parameterGroup?e.ref("CacheParameterGroup"):void 0,SnapshotRetentionLimit:i.snapshotRetentionLimit||5,SnapshotWindow:i.snapshotWindow||"03:00-05:00",PreferredMaintenanceWindow:"sun:05:00-sun:06:00",AtRestEncryptionEnabled:!0,TransitEncryptionEnabled:!0,Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-redis")}]},{dependsOn:i.parameterGroup?["CacheSubnetGroup","CacheSecurityGroup","CacheParameterGroup"]:["CacheSubnetGroup","CacheSecurityGroup"],deletionPolicy:"Snapshot",updateReplacePolicy:"Snapshot"}),n.addOutputs({RedisEndpoint:{Description:"Redis primary endpoint",Value:e.getAtt("RedisReplicationGroup","PrimaryEndPoint.Address"),Export:{Name:e.sub("${AWS::StackName}-redis-endpoint")}},RedisPort:{Description:"Redis port",Value:e.getAtt("RedisReplicationGroup","PrimaryEndPoint.Port"),Export:{Name:e.sub("${AWS::StackName}-redis-port")}}});else n.addResource("RedisCacheCluster","AWS::ElastiCache::CacheCluster",{ClusterName:e.sub("${AWS::StackName}-redis"),Engine:"redis",EngineVersion:i.engineVersion,CacheNodeType:i.nodeType,NumCacheNodes:1,Port:i.port||6379,CacheSubnetGroupName:e.ref("CacheSubnetGroup"),VpcSecurityGroupIds:[e.ref("CacheSecurityGroup")],CacheParameterGroupName:i.parameterGroup?e.ref("CacheParameterGroup"):void 0,SnapshotRetentionLimit:i.snapshotRetentionLimit||5,SnapshotWindow:i.snapshotWindow||"03:00-05:00",PreferredMaintenanceWindow:"sun:05:00-sun:06:00",Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-redis")}]},{dependsOn:i.parameterGroup?["CacheSubnetGroup","CacheSecurityGroup","CacheParameterGroup"]:["CacheSubnetGroup","CacheSecurityGroup"],deletionPolicy:"Snapshot",updateReplacePolicy:"Snapshot"}),n.addOutputs({RedisEndpoint:{Description:"Redis endpoint",Value:e.getAtt("RedisCacheCluster","RedisEndpoint.Address"),Export:{Name:e.sub("${AWS::StackName}-redis-endpoint")}},RedisPort:{Description:"Redis port",Value:e.getAtt("RedisCacheCluster","RedisEndpoint.Port"),Export:{Name:e.sub("${AWS::StackName}-redis-port")}}})}function Vr(n,i){if(!i)return;if(!n.hasResource("CacheSubnetGroup"))n.addResource("CacheSubnetGroup","AWS::ElastiCache::SubnetGroup",{Description:"Subnet group for ElastiCache",SubnetIds:[e.ref("PrivateSubnet1"),e.ref("PrivateSubnet2")]},{dependsOn:["PrivateSubnet1","PrivateSubnet2"]});if(!n.hasResource("CacheSecurityGroup"))n.addResource("CacheSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for ElastiCache Memcached",VpcId:e.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:i.port||11211,ToPort:i.port||11211,SourceSecurityGroupId:e.ref("AppSecurityGroup")}],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-cache-sg")}]},{dependsOn:["VPC","AppSecurityGroup"]});n.addResource("MemcachedCacheCluster","AWS::ElastiCache::CacheCluster",{ClusterName:e.sub("${AWS::StackName}-memcached"),Engine:"memcached",EngineVersion:i.engineVersion,CacheNodeType:i.nodeType,NumCacheNodes:i.numCacheNodes,Port:i.port||11211,CacheSubnetGroupName:e.ref("CacheSubnetGroup"),VpcSecurityGroupIds:[e.ref("CacheSecurityGroup")],PreferredMaintenanceWindow:"sun:05:00-sun:06:00",Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-memcached")}]},{dependsOn:["CacheSubnetGroup","CacheSecurityGroup"]}),n.addOutputs({MemcachedEndpoint:{Description:"Memcached configuration endpoint",Value:e.getAtt("MemcachedCacheCluster","ConfigurationEndpoint.Address"),Export:{Name:e.sub("${AWS::StackName}-memcached-endpoint")}},MemcachedPort:{Description:"Memcached port",Value:e.getAtt("MemcachedCacheCluster","ConfigurationEndpoint.Port"),Export:{Name:e.sub("${AWS::StackName}-memcached-port")}}})}function Ur(n,i){if(!i)return;let s=i.engine==="redis";if(!n.hasResource("CacheSubnetGroup"))n.addResource("CacheSubnetGroup","AWS::ElastiCache::SubnetGroup",{Description:"Subnet group for ElastiCache",SubnetIds:[e.ref("PrivateSubnet1"),e.ref("PrivateSubnet2")]},{dependsOn:["PrivateSubnet1","PrivateSubnet2"]});if(!n.hasResource("CacheSecurityGroup"))n.addResource("CacheSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for ElastiCache",VpcId:e.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:s?6379:11211,ToPort:s?6379:11211,SourceSecurityGroupId:e.ref("AppSecurityGroup")}],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-cache-sg")}]},{dependsOn:["VPC","AppSecurityGroup"]});n.addResource("CacheCluster","AWS::ElastiCache::CacheCluster",{ClusterName:e.sub(`\${AWS::StackName}-${i.engine}`),Engine:i.engine,EngineVersion:i.engineVersion,CacheNodeType:i.nodeType,NumCacheNodes:i.numCacheNodes,CacheSubnetGroupName:e.ref("CacheSubnetGroup"),VpcSecurityGroupIds:[e.ref("CacheSecurityGroup")],Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${i.engine}`)}]},{dependsOn:["CacheSubnetGroup","CacheSecurityGroup"]})}function Cn(n,i){if(!i.enabled)return;n.addResource("CloudFrontOriginAccessIdentity","AWS::CloudFront::CloudFrontOriginAccessIdentity",{CloudFrontOriginAccessIdentityConfig:{Comment:e.sub("${AWS::StackName} CloudFront OAI")}});let s=[],o=[];if(!i.origins||i.origins.length===0)s.push({Id:"S3Origin",DomainName:e.getAtt("StaticBucket","DomainName"),S3OriginConfig:{OriginAccessIdentity:e.sub("origin-access-identity/cloudfront/${CloudFrontOriginAccessIdentity}")}});else i.origins.forEach((d,g)=>{let y={Id:d.id,DomainName:d.domainName};if(d.originPath)y.OriginPath=d.originPath;if(d.domainName.includes("s3"))y.S3OriginConfig={OriginAccessIdentity:e.sub("origin-access-identity/cloudfront/${CloudFrontOriginAccessIdentity}")};else y.CustomOriginConfig={HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only",OriginSSLProtocols:["TLSv1.2"]};if(s.push(y),g>0||d.pathPattern)o.push({PathPattern:d.pathPattern||`/${d.id}/*`,TargetOriginId:d.id,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD"],Compress:i.compress!==!1,ForwardedValues:{QueryString:!0,Cookies:{Forward:"none"}},MinTTL:i.cachePolicy?.minTTL||0,DefaultTTL:i.cachePolicy?.defaultTTL||86400,MaxTTL:i.cachePolicy?.maxTTL||31536000})});let c={TargetOriginId:s[0].Id,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD"],Compress:i.compress!==!1,ForwardedValues:{QueryString:!0,Cookies:{Forward:"none"}},MinTTL:i.cachePolicy?.minTTL||0,DefaultTTL:i.cachePolicy?.defaultTTL||86400,MaxTTL:i.cachePolicy?.maxTTL||31536000};if(i.edgeFunctions&&i.edgeFunctions.length>0)c.LambdaFunctionAssociations=i.edgeFunctions.map((d)=>({EventType:d.eventType,LambdaFunctionARN:d.functionArn}));let u={Enabled:!0,HttpVersion:i.http3?"http3":"http2",IPV6Enabled:!0,Origins:s,DefaultCacheBehavior:c,PriceClass:i.priceClass||"PriceClass_100",ViewerCertificate:{}};if(o.length>0)u.CacheBehaviors=o;if(i.customDomain)u.Aliases=[i.customDomain.domain],u.ViewerCertificate={AcmCertificateArn:i.customDomain.certificateArn,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};else u.ViewerCertificate={CloudFrontDefaultCertificate:!0};if(i.errorPages)u.CustomErrorResponses=Object.entries(i.errorPages).map(([d,g])=>({ErrorCode:Number.parseInt(d),ResponseCode:200,ResponsePagePath:g,ErrorCachingMinTTL:300}));if(u.DefaultRootObject="index.html",u.Comment=e.sub("${AWS::StackName} CloudFront Distribution"),n.addResource("CloudFrontDistribution","AWS::CloudFront::Distribution",{DistributionConfig:u},{dependsOn:"CloudFrontOriginAccessIdentity"}),!i.origins||i.origins.length===0)n.addResource("StaticBucketPolicyForCloudFront","AWS::S3::BucketPolicy",{Bucket:e.ref("StaticBucket"),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontAccess",Effect:"Allow",Principal:{CanonicalUser:e.getAtt("CloudFrontOriginAccessIdentity","S3CanonicalUserId")},Action:"s3:GetObject",Resource:e.join("",[e.getAtt("StaticBucket","Arn"),"/*"])}]}},{dependsOn:["StaticBucket","CloudFrontOriginAccessIdentity"]});if(i.customDomain)n.addResource("CloudFrontDNSRecord","AWS::Route53::RecordSet",{HostedZoneName:e.sub(`${Hr(i.customDomain.domain)}.`),Name:i.customDomain.domain,Type:"A",AliasTarget:{HostedZoneId:"Z2FDTNDATAQYW2",DNSName:e.getAtt("CloudFrontDistribution","DomainName"),EvaluateTargetHealth:!1}},{dependsOn:"CloudFrontDistribution"});if(n.addOutputs({CloudFrontDistributionId:{Description:"CloudFront distribution ID",Value:e.ref("CloudFrontDistribution"),Export:{Name:e.sub("${AWS::StackName}-cloudfront-id")}},CloudFrontDomainName:{Description:"CloudFront distribution domain name",Value:e.getAtt("CloudFrontDistribution","DomainName"),Export:{Name:e.sub("${AWS::StackName}-cloudfront-domain")}}}),i.customDomain)n.addOutputs({CloudFrontURL:{Description:"CloudFront custom domain URL",Value:e.sub(`https://${i.customDomain.domain}`)}})}function Hr(n){let i=n.split(".");if(i.length>=2)return i.slice(-2).join(".");return n}function Tn(n,i){if(i.server)jr(n,i.server);if(i.fargate)vn(n,"app",i.fargate);if(i.services)i.services.forEach((s)=>{if(s.type==="fargate")vn(n,s.name,{taskDefinition:s.taskDefinition,service:s.service})})}function jr(n,i){if(!i)return;n.addResource("AppSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for application instances",VpcId:e.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:3000,ToPort:3000,SourceSecurityGroupId:e.ref("ALBSecurityGroup")},{IpProtocol:"tcp",FromPort:22,ToPort:22,CidrIp:"0.0.0.0/0"}],SecurityGroupEgress:[{IpProtocol:"-1",CidrIp:"0.0.0.0/0"}],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-app-sg")}]},{dependsOn:"VPC"}),n.addResource("EC2InstanceRole","AWS::IAM::Role",{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ec2.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore","arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy"],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-ec2-role")}]}),n.addResource("EC2InstanceProfile","AWS::IAM::InstanceProfile",{Roles:[e.ref("EC2InstanceRole")]},{dependsOn:"EC2InstanceRole"});let s=i.userData||`#!/bin/bash
2433
+ };`}var e={ref:(n)=>({Ref:n}),getAtt:(n,i)=>({"Fn::GetAtt":[n,i]}),join:(n,i)=>({"Fn::Join":[n,i]}),sub:(n,i)=>i?{"Fn::Sub":[n,i]}:{"Fn::Sub":n},select:(n,i)=>({"Fn::Select":[n,i]}),split:(n,i)=>({"Fn::Split":[n,i]}),getAZs:(n="")=>({"Fn::GetAZs":n}),importValue:(n)=>({"Fn::ImportValue":n}),findInMap:(n,i,s)=>({"Fn::FindInMap":[n,i,s]}),base64:(n)=>({"Fn::Base64":n}),cidr:(n,i,s)=>({"Fn::Cidr":[n,i,s]}),equals:(n,i)=>({"Fn::Equals":[n,i]}),if:(n,i,s)=>({"Fn::If":[n,i,s]}),not:(n)=>({"Fn::Not":[n]}),and:(...n)=>({"Fn::And":n}),or:(...n)=>({"Fn::Or":n})},gn={s3Bucket:(n)=>e.sub(`arn:aws:s3:::${n}`),s3Object:(n,i="*")=>e.sub(`arn:aws:s3:::${n}/${i}`),lambda:(n,i,s)=>e.sub(`arn:aws:lambda:\${AWS::Region}:\${AWS::AccountId}:function:${n}`,i&&s?{"AWS::Region":i,"AWS::AccountId":s}:void 0),dynamodb:(n)=>e.sub(`arn:aws:dynamodb:\${AWS::Region}:\${AWS::AccountId}:table/${n}`),sqs:(n)=>e.sub(`arn:aws:sqs:\${AWS::Region}:\${AWS::AccountId}:${n}`),sns:(n)=>e.sub(`arn:aws:sns:\${AWS::Region}:\${AWS::AccountId}:${n}`),kinesis:(n)=>e.sub(`arn:aws:kinesis:\${AWS::Region}:\${AWS::AccountId}:stream/${n}`),iam:(n,i)=>e.sub(`arn:aws:iam::\${AWS::AccountId}:${n}/${i}`),secretsManager:(n)=>e.sub(`arn:aws:secretsmanager:\${AWS::Region}:\${AWS::AccountId}:secret:${n}`),cloudwatch:(n)=>e.sub(`arn:aws:logs:\${AWS::Region}:\${AWS::AccountId}:log-group:${n}`)},XI={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 bn(n,i){if(i.type==="http")$r(n,i);else if(i.type==="rest")Br(n,i);else if(i.type==="websocket")Fr(n,i)}function $r(n,i){let s={Name:e.sub("${AWS::StackName}-http-api"),ProtocolType:"HTTP"};if(i.cors)s.CorsConfiguration={AllowOrigins:i.cors.allowOrigins,AllowMethods:i.cors.allowMethods,AllowHeaders:i.cors.allowHeaders||["*"],MaxAge:i.cors.maxAge||300};if(n.addResource("HttpApi","AWS::ApiGatewayV2::Api",s),n.addResource("HttpApiStage","AWS::ApiGatewayV2::Stage",{ApiId:e.ref("HttpApi"),StageName:"$default",AutoDeploy:!0,DefaultRouteSettings:i.throttling?{ThrottlingBurstLimit:i.throttling.burstLimit,ThrottlingRateLimit:i.throttling.rateLimit}:void 0,AccessLogSettings:{DestinationArn:e.getAtt("ApiLogGroup","Arn"),Format:"$context.requestId $context.error.message $context.error.messageString"}},{dependsOn:["HttpApi","ApiLogGroup"]}),n.addResource("ApiLogGroup","AWS::Logs::LogGroup",{LogGroupName:e.sub("/aws/apigateway/${AWS::StackName}-http-api"),RetentionInDays:14}),i.authorizer)Gr(n,"HttpApi",i.authorizer);if(i.customDomain)Rt(n,"HttpApi",i.customDomain,"HTTP");n.addOutputs({HttpApiId:{Description:"HTTP API ID",Value:e.ref("HttpApi"),Export:{Name:e.sub("${AWS::StackName}-http-api-id")}},HttpApiEndpoint:{Description:"HTTP API endpoint",Value:e.getAtt("HttpApi","ApiEndpoint"),Export:{Name:e.sub("${AWS::StackName}-http-api-endpoint")}}})}function Br(n,i){n.addResource("RestApi","AWS::ApiGateway::RestApi",{Name:e.sub("${AWS::StackName}-rest-api"),Description:e.sub("REST API for ${AWS::StackName}"),EndpointConfiguration:{Types:["REGIONAL"]}}),n.addResource("ApiGatewayAccount","AWS::ApiGateway::Account",{CloudWatchRoleArn:e.getAtt("ApiGatewayCloudWatchRole","Arn")},{dependsOn:"ApiGatewayCloudWatchRole"}),n.addResource("ApiGatewayCloudWatchRole","AWS::IAM::Role",{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"apigateway.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs"]}),n.addResource("RestApiDeployment","AWS::ApiGateway::Deployment",{RestApiId:e.ref("RestApi"),Description:"Initial deployment"},{dependsOn:"RestApi"});let s={RestApiId:e.ref("RestApi"),DeploymentId:e.ref("RestApiDeployment"),StageName:"prod",Description:"Production stage",MethodSettings:[{ResourcePath:"/*",HttpMethod:"*",LoggingLevel:"INFO",DataTraceEnabled:!0,MetricsEnabled:!0}]};if(i.throttling)s.MethodSettings[0].ThrottlingBurstLimit=i.throttling.burstLimit,s.MethodSettings[0].ThrottlingRateLimit=i.throttling.rateLimit;if(n.addResource("RestApiStage","AWS::ApiGateway::Stage",s,{dependsOn:["RestApi","RestApiDeployment"]}),i.customDomain)Rt(n,"RestApi",i.customDomain,"REST");n.addOutputs({RestApiId:{Description:"REST API ID",Value:e.ref("RestApi"),Export:{Name:e.sub("${AWS::StackName}-rest-api-id")}},RestApiEndpoint:{Description:"REST API endpoint",Value:e.sub("https://${RestApi}.execute-api.${AWS::Region}.amazonaws.com/prod"),Export:{Name:e.sub("${AWS::StackName}-rest-api-endpoint")}}})}function Fr(n,i){if(n.addResource("WebSocketApi","AWS::ApiGatewayV2::Api",{Name:e.sub("${AWS::StackName}-websocket-api"),ProtocolType:"WEBSOCKET",RouteSelectionExpression:"$request.body.action"}),i.routes){if(i.routes.connect)lt(n,"$connect",i.routes.connect.functionName);if(i.routes.disconnect)lt(n,"$disconnect",i.routes.disconnect.functionName);if(i.routes.default)lt(n,"$default",i.routes.default.functionName);if(i.routes.custom)i.routes.custom.forEach((s)=>{lt(n,s.routeKey,s.functionName)})}if(n.addResource("WebSocketApiStage","AWS::ApiGatewayV2::Stage",{ApiId:e.ref("WebSocketApi"),StageName:"prod",AutoDeploy:!0,DefaultRouteSettings:i.throttling?{ThrottlingBurstLimit:i.throttling.burstLimit,ThrottlingRateLimit:i.throttling.rateLimit}:void 0},{dependsOn:"WebSocketApi"}),i.customDomain)Rt(n,"WebSocketApi",i.customDomain,"WEBSOCKET");n.addOutputs({WebSocketApiId:{Description:"WebSocket API ID",Value:e.ref("WebSocketApi"),Export:{Name:e.sub("${AWS::StackName}-websocket-api-id")}},WebSocketApiEndpoint:{Description:"WebSocket API endpoint",Value:e.getAtt("WebSocketApi","ApiEndpoint"),Export:{Name:e.sub("${AWS::StackName}-websocket-api-endpoint")}}})}function lt(n,i,s){let o=n.toLogicalId(`websocket-route-${i}`),c=n.toLogicalId(`websocket-integration-${i}`),u=n.toLogicalId(`${s}-function`);n.addResource(c,"AWS::ApiGatewayV2::Integration",{ApiId:e.ref("WebSocketApi"),IntegrationType:"AWS_PROXY",IntegrationUri:e.sub(`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${u}.Arn}/invocations`)},{dependsOn:["WebSocketApi",u]}),n.addResource(o,"AWS::ApiGatewayV2::Route",{ApiId:e.ref("WebSocketApi"),RouteKey:i,Target:e.join("/",["integrations",e.ref(c)])},{dependsOn:["WebSocketApi",c]}),n.addResource(`${o}Permission`,"AWS::Lambda::Permission",{FunctionName:e.ref(u),Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:e.sub("arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${WebSocketApi}/*")},{dependsOn:[u,"WebSocketApi"]})}function Rt(n,i,s,o){let c={DomainName:s.domain};if(o==="REST")c.CertificateArn=s.certificateArn,c.EndpointConfiguration={Types:["REGIONAL"]},n.addResource("ApiCustomDomain","AWS::ApiGateway::DomainName",c),n.addResource("ApiBasePathMapping","AWS::ApiGateway::BasePathMapping",{DomainName:e.ref("ApiCustomDomain"),RestApiId:e.ref(i),Stage:e.ref("RestApiStage")},{dependsOn:["ApiCustomDomain",i,"RestApiStage"]});else c.DomainNameConfigurations=[{CertificateArn:s.certificateArn,EndpointType:"REGIONAL"}],n.addResource("ApiCustomDomain","AWS::ApiGatewayV2::DomainName",c),n.addResource("ApiMapping","AWS::ApiGatewayV2::ApiMapping",{ApiId:e.ref(i),DomainName:e.ref("ApiCustomDomain"),Stage:o==="HTTP"?e.ref("HttpApiStage"):e.ref("WebSocketApiStage")},{dependsOn:["ApiCustomDomain",i]});if(s.dnsProvider!=="external")n.addResource("ApiDNSRecord","AWS::Route53::RecordSet",{HostedZoneName:e.sub(`${_r(s.domain)}.`),Name:s.domain,Type:"A",AliasTarget:{HostedZoneId:e.getAtt("ApiCustomDomain","RegionalHostedZoneId"),DNSName:e.getAtt("ApiCustomDomain","RegionalDomainName"),EvaluateTargetHealth:!1}},{dependsOn:"ApiCustomDomain"});n.addOutputs({ApiCustomDomainName:{Description:"Configured API custom domain",Value:s.domain},ApiCustomDomainTarget:{Description:"DNS target for Route53 or an external DNS provider",Value:e.getAtt("ApiCustomDomain","RegionalDomainName")},ApiCustomDomainHostedZoneId:{Description:"Regional API Gateway hosted zone ID",Value:e.getAtt("ApiCustomDomain","RegionalHostedZoneId")}})}function Gr(n,i,s){if(!s)return;if(s.type==="jwt")n.addResource("ApiAuthorizer","AWS::ApiGatewayV2::Authorizer",{ApiId:e.ref(i),AuthorizerType:"JWT",IdentitySource:[s.identitySource||"$request.header.Authorization"],JwtConfiguration:{Issuer:s.issuer,Audience:s.audience},Name:"JWTAuthorizer"},{dependsOn:i});else if(s.type==="lambda")n.addResource("ApiAuthorizer","AWS::ApiGatewayV2::Authorizer",{ApiId:e.ref(i),AuthorizerType:"REQUEST",AuthorizerUri:s.authorizerUri,IdentitySource:[s.identitySource||"$request.header.Authorization"],Name:"LambdaAuthorizer"},{dependsOn:i})}function _r(n){let i=n.split(".");if(i.length>=2)return i.slice(-2).join(".");return n}function Sn(n,i){if(i.redis)Wr(n,i.redis);if(i.memcached)Vr(n,i.memcached);if(i.elasticache)Ur(n,i.elasticache)}function Wr(n,i){if(!i)return;if(n.addResource("CacheSubnetGroup","AWS::ElastiCache::SubnetGroup",{Description:"Subnet group for ElastiCache Redis cluster",SubnetIds:[e.ref("PrivateSubnet1"),e.ref("PrivateSubnet2")],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-cache-subnet-group")}]},{dependsOn:["PrivateSubnet1","PrivateSubnet2"]}),n.addResource("CacheSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for ElastiCache Redis",VpcId:e.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:i.port||6379,ToPort:i.port||6379,SourceSecurityGroupId:e.ref("AppSecurityGroup")}],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-cache-sg")}]},{dependsOn:["VPC","AppSecurityGroup"]}),i.parameterGroup&&Object.keys(i.parameterGroup).length>0)n.addResource("CacheParameterGroup","AWS::ElastiCache::ParameterGroup",{Description:"Parameter group for Redis",CacheParameterGroupFamily:`redis${i.engineVersion.split(".")[0]}`,Properties:i.parameterGroup});if(i.numCacheNodes>1||i.automaticFailoverEnabled)n.addResource("RedisReplicationGroup","AWS::ElastiCache::ReplicationGroup",{ReplicationGroupDescription:"Redis replication group",ReplicationGroupId:e.sub("${AWS::StackName}-redis"),Engine:"redis",EngineVersion:i.engineVersion,CacheNodeType:i.nodeType,NumCacheClusters:i.numCacheNodes,AutomaticFailoverEnabled:i.automaticFailoverEnabled||!1,MultiAZEnabled:i.automaticFailoverEnabled||!1,Port:i.port||6379,CacheSubnetGroupName:e.ref("CacheSubnetGroup"),SecurityGroupIds:[e.ref("CacheSecurityGroup")],CacheParameterGroupName:i.parameterGroup?e.ref("CacheParameterGroup"):void 0,SnapshotRetentionLimit:i.snapshotRetentionLimit||5,SnapshotWindow:i.snapshotWindow||"03:00-05:00",PreferredMaintenanceWindow:"sun:05:00-sun:06:00",AtRestEncryptionEnabled:!0,TransitEncryptionEnabled:!0,Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-redis")}]},{dependsOn:i.parameterGroup?["CacheSubnetGroup","CacheSecurityGroup","CacheParameterGroup"]:["CacheSubnetGroup","CacheSecurityGroup"],deletionPolicy:"Snapshot",updateReplacePolicy:"Snapshot"}),n.addOutputs({RedisEndpoint:{Description:"Redis primary endpoint",Value:e.getAtt("RedisReplicationGroup","PrimaryEndPoint.Address"),Export:{Name:e.sub("${AWS::StackName}-redis-endpoint")}},RedisPort:{Description:"Redis port",Value:e.getAtt("RedisReplicationGroup","PrimaryEndPoint.Port"),Export:{Name:e.sub("${AWS::StackName}-redis-port")}}});else n.addResource("RedisCacheCluster","AWS::ElastiCache::CacheCluster",{ClusterName:e.sub("${AWS::StackName}-redis"),Engine:"redis",EngineVersion:i.engineVersion,CacheNodeType:i.nodeType,NumCacheNodes:1,Port:i.port||6379,CacheSubnetGroupName:e.ref("CacheSubnetGroup"),VpcSecurityGroupIds:[e.ref("CacheSecurityGroup")],CacheParameterGroupName:i.parameterGroup?e.ref("CacheParameterGroup"):void 0,SnapshotRetentionLimit:i.snapshotRetentionLimit||5,SnapshotWindow:i.snapshotWindow||"03:00-05:00",PreferredMaintenanceWindow:"sun:05:00-sun:06:00",Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-redis")}]},{dependsOn:i.parameterGroup?["CacheSubnetGroup","CacheSecurityGroup","CacheParameterGroup"]:["CacheSubnetGroup","CacheSecurityGroup"],deletionPolicy:"Snapshot",updateReplacePolicy:"Snapshot"}),n.addOutputs({RedisEndpoint:{Description:"Redis endpoint",Value:e.getAtt("RedisCacheCluster","RedisEndpoint.Address"),Export:{Name:e.sub("${AWS::StackName}-redis-endpoint")}},RedisPort:{Description:"Redis port",Value:e.getAtt("RedisCacheCluster","RedisEndpoint.Port"),Export:{Name:e.sub("${AWS::StackName}-redis-port")}}})}function Vr(n,i){if(!i)return;if(!n.hasResource("CacheSubnetGroup"))n.addResource("CacheSubnetGroup","AWS::ElastiCache::SubnetGroup",{Description:"Subnet group for ElastiCache",SubnetIds:[e.ref("PrivateSubnet1"),e.ref("PrivateSubnet2")]},{dependsOn:["PrivateSubnet1","PrivateSubnet2"]});if(!n.hasResource("CacheSecurityGroup"))n.addResource("CacheSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for ElastiCache Memcached",VpcId:e.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:i.port||11211,ToPort:i.port||11211,SourceSecurityGroupId:e.ref("AppSecurityGroup")}],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-cache-sg")}]},{dependsOn:["VPC","AppSecurityGroup"]});n.addResource("MemcachedCacheCluster","AWS::ElastiCache::CacheCluster",{ClusterName:e.sub("${AWS::StackName}-memcached"),Engine:"memcached",EngineVersion:i.engineVersion,CacheNodeType:i.nodeType,NumCacheNodes:i.numCacheNodes,Port:i.port||11211,CacheSubnetGroupName:e.ref("CacheSubnetGroup"),VpcSecurityGroupIds:[e.ref("CacheSecurityGroup")],PreferredMaintenanceWindow:"sun:05:00-sun:06:00",Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-memcached")}]},{dependsOn:["CacheSubnetGroup","CacheSecurityGroup"]}),n.addOutputs({MemcachedEndpoint:{Description:"Memcached configuration endpoint",Value:e.getAtt("MemcachedCacheCluster","ConfigurationEndpoint.Address"),Export:{Name:e.sub("${AWS::StackName}-memcached-endpoint")}},MemcachedPort:{Description:"Memcached port",Value:e.getAtt("MemcachedCacheCluster","ConfigurationEndpoint.Port"),Export:{Name:e.sub("${AWS::StackName}-memcached-port")}}})}function Ur(n,i){if(!i)return;let s=i.engine==="redis";if(!n.hasResource("CacheSubnetGroup"))n.addResource("CacheSubnetGroup","AWS::ElastiCache::SubnetGroup",{Description:"Subnet group for ElastiCache",SubnetIds:[e.ref("PrivateSubnet1"),e.ref("PrivateSubnet2")]},{dependsOn:["PrivateSubnet1","PrivateSubnet2"]});if(!n.hasResource("CacheSecurityGroup"))n.addResource("CacheSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for ElastiCache",VpcId:e.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:s?6379:11211,ToPort:s?6379:11211,SourceSecurityGroupId:e.ref("AppSecurityGroup")}],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-cache-sg")}]},{dependsOn:["VPC","AppSecurityGroup"]});n.addResource("CacheCluster","AWS::ElastiCache::CacheCluster",{ClusterName:e.sub(`\${AWS::StackName}-${i.engine}`),Engine:i.engine,EngineVersion:i.engineVersion,CacheNodeType:i.nodeType,NumCacheNodes:i.numCacheNodes,CacheSubnetGroupName:e.ref("CacheSubnetGroup"),VpcSecurityGroupIds:[e.ref("CacheSecurityGroup")],Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${i.engine}`)}]},{dependsOn:["CacheSubnetGroup","CacheSecurityGroup"]})}function Cn(n,i){if(!i.enabled)return;n.addResource("CloudFrontOriginAccessIdentity","AWS::CloudFront::CloudFrontOriginAccessIdentity",{CloudFrontOriginAccessIdentityConfig:{Comment:e.sub("${AWS::StackName} CloudFront OAI")}});let s=[],o=[];if(!i.origins||i.origins.length===0)s.push({Id:"S3Origin",DomainName:e.getAtt("StaticBucket","DomainName"),S3OriginConfig:{OriginAccessIdentity:e.sub("origin-access-identity/cloudfront/${CloudFrontOriginAccessIdentity}")}});else i.origins.forEach((d,g)=>{let y={Id:d.id,DomainName:d.domainName};if(d.originPath)y.OriginPath=d.originPath;if(d.domainName.includes("s3"))y.S3OriginConfig={OriginAccessIdentity:e.sub("origin-access-identity/cloudfront/${CloudFrontOriginAccessIdentity}")};else y.CustomOriginConfig={HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only",OriginSSLProtocols:["TLSv1.2"]};if(s.push(y),g>0||d.pathPattern)o.push({PathPattern:d.pathPattern||`/${d.id}/*`,TargetOriginId:d.id,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD"],Compress:i.compress!==!1,ForwardedValues:{QueryString:!0,Cookies:{Forward:"none"}},MinTTL:i.cachePolicy?.minTTL||0,DefaultTTL:i.cachePolicy?.defaultTTL||86400,MaxTTL:i.cachePolicy?.maxTTL||31536000})});let c={TargetOriginId:s[0].Id,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD"],Compress:i.compress!==!1,ForwardedValues:{QueryString:!0,Cookies:{Forward:"none"}},MinTTL:i.cachePolicy?.minTTL||0,DefaultTTL:i.cachePolicy?.defaultTTL||86400,MaxTTL:i.cachePolicy?.maxTTL||31536000};if(i.edgeFunctions&&i.edgeFunctions.length>0)c.LambdaFunctionAssociations=i.edgeFunctions.map((d)=>({EventType:d.eventType,LambdaFunctionARN:d.functionArn}));let u={Enabled:!0,HttpVersion:i.http3?"http3":"http2",IPV6Enabled:!0,Origins:s,DefaultCacheBehavior:c,PriceClass:i.priceClass||"PriceClass_100",ViewerCertificate:{}};if(o.length>0)u.CacheBehaviors=o;if(i.customDomain)u.Aliases=[i.customDomain.domain],u.ViewerCertificate={AcmCertificateArn:i.customDomain.certificateArn,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};else u.ViewerCertificate={CloudFrontDefaultCertificate:!0};if(i.errorPages)u.CustomErrorResponses=Object.entries(i.errorPages).map(([d,g])=>({ErrorCode:Number.parseInt(d),ResponseCode:200,ResponsePagePath:g,ErrorCachingMinTTL:300}));if(u.DefaultRootObject="index.html",u.Comment=e.sub("${AWS::StackName} CloudFront Distribution"),n.addResource("CloudFrontDistribution","AWS::CloudFront::Distribution",{DistributionConfig:u},{dependsOn:"CloudFrontOriginAccessIdentity"}),!i.origins||i.origins.length===0)n.addResource("StaticBucketPolicyForCloudFront","AWS::S3::BucketPolicy",{Bucket:e.ref("StaticBucket"),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontAccess",Effect:"Allow",Principal:{CanonicalUser:e.getAtt("CloudFrontOriginAccessIdentity","S3CanonicalUserId")},Action:"s3:GetObject",Resource:e.join("",[e.getAtt("StaticBucket","Arn"),"/*"])}]}},{dependsOn:["StaticBucket","CloudFrontOriginAccessIdentity"]});if(i.customDomain)n.addResource("CloudFrontDNSRecord","AWS::Route53::RecordSet",{HostedZoneName:e.sub(`${Hr(i.customDomain.domain)}.`),Name:i.customDomain.domain,Type:"A",AliasTarget:{HostedZoneId:"Z2FDTNDATAQYW2",DNSName:e.getAtt("CloudFrontDistribution","DomainName"),EvaluateTargetHealth:!1}},{dependsOn:"CloudFrontDistribution"});if(n.addOutputs({CloudFrontDistributionId:{Description:"CloudFront distribution ID",Value:e.ref("CloudFrontDistribution"),Export:{Name:e.sub("${AWS::StackName}-cloudfront-id")}},CloudFrontDomainName:{Description:"CloudFront distribution domain name",Value:e.getAtt("CloudFrontDistribution","DomainName"),Export:{Name:e.sub("${AWS::StackName}-cloudfront-domain")}}}),i.customDomain)n.addOutputs({CloudFrontURL:{Description:"CloudFront custom domain URL",Value:e.sub(`https://${i.customDomain.domain}`)}})}function Hr(n){let i=n.split(".");if(i.length>=2)return i.slice(-2).join(".");return n}function Tn(n,i){if(i.server)jr(n,i.server);if(i.fargate)vn(n,"app",i.fargate);if(i.services)i.services.forEach((s)=>{if(s.type==="fargate")vn(n,s.name,{taskDefinition:s.taskDefinition,service:s.service})})}function jr(n,i){if(!i)return;n.addResource("AppSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for application instances",VpcId:e.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:3000,ToPort:3000,SourceSecurityGroupId:e.ref("ALBSecurityGroup")},{IpProtocol:"tcp",FromPort:22,ToPort:22,CidrIp:"0.0.0.0/0"}],SecurityGroupEgress:[{IpProtocol:"-1",CidrIp:"0.0.0.0/0"}],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-app-sg")}]},{dependsOn:"VPC"}),n.addResource("EC2InstanceRole","AWS::IAM::Role",{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ec2.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore","arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy"],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-ec2-role")}]}),n.addResource("EC2InstanceProfile","AWS::IAM::InstanceProfile",{Roles:[e.ref("EC2InstanceRole")]},{dependsOn:"EC2InstanceRole"});let s=i.userData||`#!/bin/bash
2434
2434
  set -e
2435
2435
  # Update system
2436
2436
  yum update -y || apt-get update -y
@@ -2448,31 +2448,31 @@ rpm -U ./amazon-cloudwatch-agent.rpm || true
2448
2448
  `;if(n.addResource("LaunchTemplate","AWS::EC2::LaunchTemplate",{LaunchTemplateName:e.sub("${AWS::StackName}-template"),LaunchTemplateData:{ImageId:i.ami||e.findInMap("RegionMap",e.ref("AWS::Region"),"AMI"),InstanceType:i.instanceType,IamInstanceProfile:{Arn:e.getAtt("EC2InstanceProfile","Arn")},SecurityGroupIds:[e.ref("AppSecurityGroup")],UserData:e.base64(e.sub(s)),TagSpecifications:[{ResourceType:"instance",Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-instance")}]}],MetadataOptions:{HttpTokens:"required",HttpPutResponseHopLimit:1}}},{dependsOn:["AppSecurityGroup","EC2InstanceProfile"]}),i.loadBalancer){Kr(n,i.loadBalancer);let o={LaunchTemplate:{LaunchTemplateId:e.ref("LaunchTemplate"),Version:e.getAtt("LaunchTemplate","LatestVersionNumber")},MinSize:i.autoScaling?.min.toString()||"1",MaxSize:i.autoScaling?.max.toString()||"3",DesiredCapacity:i.autoScaling?.min.toString()||"2",VPCZoneIdentifier:[e.ref("PrivateSubnet1"),e.ref("PrivateSubnet2")],TargetGroupARNs:[e.ref("TargetGroup")],HealthCheckType:"ELB",HealthCheckGracePeriod:300,Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-asg"),PropagateAtLaunch:!0}]};if(n.addResource("AutoScalingGroup","AWS::AutoScaling::AutoScalingGroup",o,{dependsOn:["LaunchTemplate","TargetGroup"]}),i.autoScaling)n.addResource("ScaleUpPolicy","AWS::AutoScaling::ScalingPolicy",{AdjustmentType:"ChangeInCapacity",AutoScalingGroupName:e.ref("AutoScalingGroup"),Cooldown:i.autoScaling.scaleUpCooldown?.toString()||"300",ScalingAdjustment:"1"},{dependsOn:"AutoScalingGroup"}),n.addResource("ScaleDownPolicy","AWS::AutoScaling::ScalingPolicy",{AdjustmentType:"ChangeInCapacity",AutoScalingGroupName:e.ref("AutoScalingGroup"),Cooldown:i.autoScaling.scaleDownCooldown?.toString()||"300",ScalingAdjustment:"-1"},{dependsOn:"AutoScalingGroup"}),n.addResource("HighCPUAlarm","AWS::CloudWatch::Alarm",{AlarmDescription:"Scale up when CPU exceeds target",MetricName:"CPUUtilization",Namespace:"AWS/EC2",Statistic:"Average",Period:"300",EvaluationPeriods:"2",Threshold:(i.autoScaling.targetCPU||70).toString(),AlarmActions:[e.ref("ScaleUpPolicy")],Dimensions:[{Name:"AutoScalingGroupName",Value:e.ref("AutoScalingGroup")}],ComparisonOperator:"GreaterThanThreshold"},{dependsOn:["AutoScalingGroup","ScaleUpPolicy"]}),n.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:((i.autoScaling.targetCPU||70)-20).toString(),AlarmActions:[e.ref("ScaleDownPolicy")],Dimensions:[{Name:"AutoScalingGroupName",Value:e.ref("AutoScalingGroup")}],ComparisonOperator:"LessThanThreshold"},{dependsOn:["AutoScalingGroup","ScaleDownPolicy"]})}}function Kr(n,i){if(!i)return;n.addResource("ALBSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for Application Load Balancer",VpcId:e.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:e.sub("${AWS::StackName}-alb-sg")}]},{dependsOn:"VPC"}),n.addResource("LoadBalancer","AWS::ElasticLoadBalancingV2::LoadBalancer",{Name:e.sub("${AWS::StackName}-alb"),Type:i.type||"application",Scheme:"internet-facing",IpAddressType:"ipv4",Subnets:[e.ref("PublicSubnet1"),e.ref("PublicSubnet2")],SecurityGroups:[e.ref("ALBSecurityGroup")],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-alb")}]},{dependsOn:["PublicSubnet1","PublicSubnet2","ALBSecurityGroup"]}),n.addResource("TargetGroup","AWS::ElasticLoadBalancingV2::TargetGroup",{Name:e.sub("${AWS::StackName}-tg"),Port:3000,Protocol:"HTTP",VpcId:e.ref("VPC"),HealthCheckEnabled:!0,HealthCheckPath:i.healthCheck?.path||"/health",HealthCheckProtocol:"HTTP",HealthCheckIntervalSeconds:i.healthCheck?.interval||30,HealthCheckTimeoutSeconds:i.healthCheck?.timeout||5,HealthyThresholdCount:i.healthCheck?.healthyThreshold||2,UnhealthyThresholdCount:i.healthCheck?.unhealthyThreshold||3,TargetType:"instance",Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-tg")}]},{dependsOn:"VPC"}),n.addResource("LoadBalancerListener","AWS::ElasticLoadBalancingV2::Listener",{LoadBalancerArn:e.ref("LoadBalancer"),Port:80,Protocol:"HTTP",DefaultActions:[{Type:"forward",TargetGroupArn:e.ref("TargetGroup")}]},{dependsOn:["LoadBalancer","TargetGroup"]}),n.addOutputs({LoadBalancerDNS:{Description:"Load Balancer DNS Name",Value:e.getAtt("LoadBalancer","DNSName"),Export:{Name:e.sub("${AWS::StackName}-alb-dns")}}})}function vn(n,i,s){let o=n.toLogicalId(i),c=s.taskDefinition.containerDefinitions?.[0],u=c?.name||c?.Name||i,d=c?.portMappings?.[0]?.containerPort||c?.PortMappings?.[0]?.ContainerPort||3000,g=(s.taskDefinition.containerDefinitions||[]).flatMap((A)=>(A.secrets||A.Secrets||[]).map((T)=>T.valueFrom||T.ValueFrom)).filter(Boolean);if(!n.hasResource("ECSCluster"))n.addResource("ECSCluster","AWS::ECS::Cluster",{ClusterName:e.sub("${AWS::StackName}-cluster"),Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-cluster")}]});if(n.addResource(`${o}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"],...g.length?{Policies:[{PolicyName:"read-task-secrets",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["secretsmanager:GetSecretValue","ssm:GetParameters"],Resource:g},{Effect:"Allow",Action:"kms:Decrypt",Resource:"*"}]}}]}:{}}),n.addResource(`${o}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:e.sub("arn:aws:sqs:${AWS::Region}:${AWS::AccountId}:${AWS::StackName}-*")},{Effect:"Allow",Action:["ses:SendEmail","ses:SendRawEmail"],Resource:"*"}]}}]}),!n.hasResource("ALBSecurityGroup"))n.addResource("ALBSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Public ingress for the application load balancer",VpcId:e.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:80,ToPort:80,CidrIp:"0.0.0.0/0"},...s.loadBalancer?.customDomain?.certificateArn?[{IpProtocol:"tcp",FromPort:443,ToPort:443,CidrIp:"0.0.0.0/0"}]:[]],SecurityGroupEgress:[{IpProtocol:"tcp",FromPort:d,ToPort:d,CidrIp:"0.0.0.0/0"}],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-alb-sg")}]},{dependsOn:"VPC"});if(!n.hasResource("AppSecurityGroup"))n.addResource("AppSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Only the application load balancer may reach Fargate tasks",VpcId:e.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:d,ToPort:d,SourceSecurityGroupId:e.ref("ALBSecurityGroup")}],SecurityGroupEgress:[{IpProtocol:"-1",CidrIp:"0.0.0.0/0"}],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-app-sg")}]},{dependsOn:["VPC","ALBSecurityGroup"]});let y=(s.taskDefinition.containerDefinitions||[{name:i,image:e.sub(`\${AWS::AccountId}.dkr.ecr.\${AWS::Region}.amazonaws.com/${i}:latest`),portMappings:[{containerPort:3000}]}]).map((A)=>({Name:A.Name||A.name,Image:A.Image||A.image,Essential:A.Essential??A.essential??!0,PortMappings:(A.PortMappings||A.portMappings||[]).map((T)=>({ContainerPort:T.ContainerPort??T.containerPort,Protocol:T.Protocol||T.protocol||"tcp"})),Environment:Array.isArray(A.Environment||A.environment)?(A.Environment||A.environment).map((T)=>({Name:T.Name||T.name,Value:T.Value??T.value})):Object.entries(A.Environment||A.environment||{}).map(([T,R])=>({Name:T,Value:R})),Secrets:(A.Secrets||A.secrets||[]).map((T)=>({Name:T.Name||T.name,ValueFrom:T.ValueFrom||T.valueFrom})),HealthCheck:A.HealthCheck||A.healthCheck,Command:A.Command||A.command,EntryPoint:A.EntryPoint||A.entryPoint,LogConfiguration:A.LogConfiguration||A.logConfiguration||{LogDriver:"awslogs",Options:{"awslogs-group":e.ref(`${o}LogGroup`),"awslogs-region":e.ref("AWS::Region"),"awslogs-stream-prefix":i}}}));n.addResource(`${o}TaskDefinition`,"AWS::ECS::TaskDefinition",{Family:e.sub(`\${AWS::StackName}-${i}`),NetworkMode:"awsvpc",RequiresCompatibilities:["FARGATE"],Cpu:s.taskDefinition.cpu,Memory:s.taskDefinition.memory,ExecutionRoleArn:e.getAtt(`${o}TaskExecutionRole`,"Arn"),TaskRoleArn:e.getAtt(`${o}TaskRole`,"Arn"),ContainerDefinitions:y},{dependsOn:[`${o}TaskExecutionRole`,`${o}TaskRole`,`${o}LogGroup`]}),n.addResource(`${o}LogGroup`,"AWS::Logs::LogGroup",{LogGroupName:e.sub(`/ecs/\${AWS::StackName}/${i}`),RetentionInDays:14});let h=s.service.healthCheck||{};n.addResource(`${o}TargetGroup`,"AWS::ElasticLoadBalancingV2::TargetGroup",{VpcId:e.ref("VPC"),Port:d,Protocol:"HTTP",TargetType:"ip",HealthCheckEnabled:!0,HealthCheckPath:h.path||"/health",HealthCheckProtocol:"HTTP",HealthCheckIntervalSeconds:h.interval||30,HealthCheckTimeoutSeconds:h.timeout||5,HealthyThresholdCount:h.healthyThreshold||2,UnhealthyThresholdCount:h.unhealthyThreshold||3,Matcher:{HttpCode:"200-399"},TargetGroupAttributes:[{Key:"deregistration_delay.timeout_seconds",Value:"30"}]},{dependsOn:"VPC"}),n.addResource(`${o}LoadBalancer`,"AWS::ElasticLoadBalancingV2::LoadBalancer",{Type:"application",Scheme:"internet-facing",IpAddressType:"ipv4",Subnets:[e.ref("PublicSubnet1"),e.ref("PublicSubnet2")],SecurityGroups:[e.ref("ALBSecurityGroup")],LoadBalancerAttributes:[{Key:"routing.http.drop_invalid_header_fields.enabled",Value:"true"},{Key:"deletion_protection.enabled",Value:String(s.loadBalancer?.deletionProtection===!0)}],Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${i}-alb`)}]},{dependsOn:["PublicSubnet1","PublicSubnet2","ALBSecurityGroup"]});let b=s.loadBalancer?.customDomain?.certificateArn,v=s.loadBalancer?.originVerifyHeader;if(n.addResource(`${o}HttpListener`,"AWS::ElasticLoadBalancingV2::Listener",{LoadBalancerArn:e.ref(`${o}LoadBalancer`),Port:80,Protocol:"HTTP",DefaultActions:b?[{Type:"redirect",RedirectConfig:{Protocol:"HTTPS",Port:"443",StatusCode:"HTTP_301"}}]:v?[{Type:"fixed-response",FixedResponseConfig:{StatusCode:"403",ContentType:"text/plain",MessageBody:"Forbidden"}}]:[{Type:"forward",TargetGroupArn:e.ref(`${o}TargetGroup`)}]},{dependsOn:[`${o}LoadBalancer`,`${o}TargetGroup`]}),b)n.addResource(`${o}HttpsListener`,"AWS::ElasticLoadBalancingV2::Listener",{LoadBalancerArn:e.ref(`${o}LoadBalancer`),Port:443,Protocol:"HTTPS",Certificates:[{CertificateArn:b}],SslPolicy:"ELBSecurityPolicy-TLS13-1-2-2021-06",DefaultActions:v?[{Type:"fixed-response",FixedResponseConfig:{StatusCode:"403",ContentType:"text/plain",MessageBody:"Forbidden"}}]:[{Type:"forward",TargetGroupArn:e.ref(`${o}TargetGroup`)}]},{dependsOn:[`${o}LoadBalancer`,`${o}TargetGroup`]});if(v){let A=b?`${o}HttpsListener`:`${o}HttpListener`;n.addResource(`${o}OriginVerifyRule`,"AWS::ElasticLoadBalancingV2::ListenerRule",{ListenerArn:e.ref(A),Priority:1,Conditions:[{Field:"http-header",HttpHeaderConfig:{HttpHeaderName:v.name,Values:[v.value]}}],Actions:[{Type:"forward",TargetGroupArn:e.ref(`${o}TargetGroup`)}]},{dependsOn:[A,`${o}TargetGroup`]})}if(n.addResource(`${o}Service`,"AWS::ECS::Service",{ServiceName:e.sub(`\${AWS::StackName}-${i}`),Cluster:e.ref("ECSCluster"),TaskDefinition:e.ref(`${o}TaskDefinition`),DesiredCount:s.service.desiredCount,LaunchType:"FARGATE",PlatformVersion:"LATEST",HealthCheckGracePeriodSeconds:60,DeploymentConfiguration:{MinimumHealthyPercent:100,MaximumPercent:200,DeploymentCircuitBreaker:{Enable:!0,Rollback:!0}},LoadBalancers:[{ContainerName:u,ContainerPort:d,TargetGroupArn:e.ref(`${o}TargetGroup`)}],NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"DISABLED",Subnets:[e.ref("PrivateSubnet1"),e.ref("PrivateSubnet2")],SecurityGroups:[e.ref("AppSecurityGroup")]}}},{dependsOn:["ECSCluster",`${o}TaskDefinition`,v?`${o}OriginVerifyRule`:b?`${o}HttpsListener`:`${o}HttpListener`]}),s.service.autoScaling){let A=s.service.autoScaling;n.addResource(`${o}ScalableTarget`,"AWS::ApplicationAutoScaling::ScalableTarget",{MinCapacity:A.min,MaxCapacity:A.max,ResourceId:e.join("/",["service",e.ref("ECSCluster"),e.getAtt(`${o}Service`,"Name")]),RoleARN:e.sub("arn:aws:iam::${AWS::AccountId}:role/aws-service-role/ecs.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_ECSService"),ScalableDimension:"ecs:service:DesiredCount",ServiceNamespace:"ecs"},{dependsOn:`${o}Service`}),n.addResource(`${o}ScalingPolicy`,"AWS::ApplicationAutoScaling::ScalingPolicy",{PolicyType:"TargetTrackingScaling",ScalingTargetId:e.ref(`${o}ScalableTarget`),TargetTrackingScalingPolicyConfiguration:{TargetValue:A.targetCPU||70,PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageCPUUtilization"},ScaleInCooldown:60,ScaleOutCooldown:30}},{dependsOn:`${o}ScalableTarget`})}n.addOutputs({[`${o}ClusterName`]:{Description:"ECS cluster name",Value:e.ref("ECSCluster")},[`${o}ServiceName`]:{Description:"ECS service name",Value:e.getAtt(`${o}Service`,"Name")},[`${o}LoadBalancerDnsName`]:{Description:"ALB origin hostname",Value:e.getAtt(`${o}LoadBalancer`,"DNSName")},[`${o}LoadBalancerHostedZoneId`]:{Description:"ALB canonical hosted zone ID",Value:e.getAtt(`${o}LoadBalancer`,"CanonicalHostedZoneID")},[`${o}TargetGroupArn`]:{Description:"ECS target group ARN",Value:e.ref(`${o}TargetGroup`)}})}function Pn(n,i){if(i.postgres)Rn(n,"postgres",i.postgres);if(i.mysql)Rn(n,"mysql",i.mysql);if(i.dynamodb?.tables)i.dynamodb.tables.forEach((s)=>{qr(n,s)})}function Rn(n,i,s){if(!s)return;let o=i==="postgres"?"postgres":"mysql",c=n.toLogicalId(`${o}-db`);n.addResource("DBSubnetGroup","AWS::RDS::DBSubnetGroup",{DBSubnetGroupDescription:"Subnet group for RDS instance",SubnetIds:[e.ref("PrivateSubnet1"),e.ref("PrivateSubnet2")],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-db-subnet-group")}]},{dependsOn:["PrivateSubnet1","PrivateSubnet2"]}),n.addResource("DBSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for RDS instance",VpcId:e.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:i==="postgres"?5432:3306,ToPort:i==="postgres"?5432:3306,SourceSecurityGroupId:e.ref("AppSecurityGroup")}],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-db-sg")}]},{dependsOn:["VPC","AppSecurityGroup"]});let u=i==="postgres"?`postgres${s.version.split(".")[0]}`:`mysql${s.version.split(".")[0]}.${s.version.split(".")[1]||"0"}`;if(s.parameters&&Object.keys(s.parameters).length>0)n.addResource("DBParameterGroup","AWS::RDS::DBParameterGroup",{Description:`Parameter group for ${o}`,Family:u,Parameters:s.parameters,Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-db-params")}]});n.addResource("DBSecret","AWS::SecretsManager::Secret",{Description:"Database credentials",GenerateSecretString:{SecretStringTemplate:JSON.stringify({username:"admin"}),GenerateStringKey:"password",PasswordLength:32,ExcludeCharacters:'"@/\\'},Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-db-secret")}]},{deletionPolicy:"Retain",updateReplacePolicy:"Retain"});let d={Engine:o,EngineVersion:s.version,DBInstanceClass:s.instanceClass,AllocatedStorage:s.allocatedStorage.toString(),MaxAllocatedStorage:s.maxAllocatedStorage?.toString(),StorageType:"gp3",StorageEncrypted:!0,MultiAZ:s.multiAZ!==!1,DBSubnetGroupName:e.ref("DBSubnetGroup"),VPCSecurityGroups:[e.ref("DBSecurityGroup")],MasterUsername:e.sub("{{resolve:secretsmanager:${DBSecret}:SecretString:username}}"),MasterUserPassword:e.sub("{{resolve:secretsmanager:${DBSecret}:SecretString:password}}"),BackupRetentionPeriod:s.backupRetentionDays||7,PreferredBackupWindow:s.preferredBackupWindow||"03:00-04:00",PreferredMaintenanceWindow:s.preferredMaintenanceWindow||"sun:04:00-sun:05:00",EnablePerformanceInsights:s.enablePerformanceInsights!==!1,PerformanceInsightsRetentionPeriod:s.performanceInsightsRetention||7,DeletionProtection:s.deletionProtection!==!1,CopyTagsToSnapshot:!0,EnableCloudwatchLogsExports:i==="postgres"?["postgresql"]:["error","general","slowquery"],Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${o}-db`)}]};if(s.parameters&&Object.keys(s.parameters).length>0)d.DBParameterGroupName=e.ref("DBParameterGroup");n.addResource(c,"AWS::RDS::DBInstance",d,{dependsOn:["DBSubnetGroup","DBSecurityGroup","DBSecret"],deletionPolicy:"Snapshot",updateReplacePolicy:"Snapshot"}),n.addResource("DBSecretAttachment","AWS::SecretsManager::SecretTargetAttachment",{SecretId:e.ref("DBSecret"),TargetId:e.ref(c),TargetType:"AWS::RDS::DBInstance"},{dependsOn:[c,"DBSecret"]}),n.addOutputs({DBEndpoint:{Description:"Database endpoint",Value:e.getAtt(c,"Endpoint.Address"),Export:{Name:e.sub("${AWS::StackName}-db-endpoint")}},DBPort:{Description:"Database port",Value:e.getAtt(c,"Endpoint.Port"),Export:{Name:e.sub("${AWS::StackName}-db-port")}},DBSecretArn:{Description:"ARN of the database credentials secret",Value:e.ref("DBSecret"),Export:{Name:e.sub("${AWS::StackName}-db-secret-arn")}}})}function qr(n,i){let s=n.toLogicalId(`${i.name}-table`),o={TableName:e.sub(`\${AWS::StackName}-${i.name}`),BillingMode:i.billingMode||"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:i.partitionKey,AttributeType:"S"}],KeySchema:[{AttributeName:i.partitionKey,KeyType:"HASH"}],Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${i.name}`)}]};if(i.sortKey)o.AttributeDefinitions.push({AttributeName:i.sortKey,AttributeType:"S"}),o.KeySchema.push({AttributeName:i.sortKey,KeyType:"RANGE"});if(i.billingMode==="PROVISIONED")o.ProvisionedThroughput={ReadCapacityUnits:i.readCapacity||5,WriteCapacityUnits:i.writeCapacity||5};if(i.streamEnabled)o.StreamSpecification={StreamViewType:"NEW_AND_OLD_IMAGES"};if(i.pointInTimeRecovery)o.PointInTimeRecoverySpecification={PointInTimeRecoveryEnabled:!0};if(i.ttl?.enabled)o.TimeToLiveSpecification={Enabled:!0,AttributeName:i.ttl.attributeName};if(i.globalSecondaryIndexes&&i.globalSecondaryIndexes.length>0)o.GlobalSecondaryIndexes=i.globalSecondaryIndexes.map((c)=>{let u=new Set(o.AttributeDefinitions.map((g)=>g.AttributeName));if(!u.has(c.partitionKey))o.AttributeDefinitions.push({AttributeName:c.partitionKey,AttributeType:"S"});if(c.sortKey&&!u.has(c.sortKey))o.AttributeDefinitions.push({AttributeName:c.sortKey,AttributeType:"S"});let d={IndexName:c.name,KeySchema:[{AttributeName:c.partitionKey,KeyType:"HASH"}],Projection:{ProjectionType:c.projectionType||"ALL"}};if(c.sortKey)d.KeySchema.push({AttributeName:c.sortKey,KeyType:"RANGE"});if(c.projectionType==="INCLUDE"&&c.nonKeyAttributes)d.Projection.NonKeyAttributes=c.nonKeyAttributes;if(i.billingMode==="PROVISIONED")d.ProvisionedThroughput={ReadCapacityUnits:i.readCapacity||5,WriteCapacityUnits:i.writeCapacity||5};return d});if(n.addResource(s,"AWS::DynamoDB::Table",o,{deletionPolicy:"Retain"}),n.addOutputs({[`${s}Name`]:{Description:`${i.name} table name`,Value:e.ref(s),Export:{Name:e.sub(`\${AWS::StackName}-${i.name}-table`)}},[`${s}Arn`]:{Description:`${i.name} table ARN`,Value:e.getAtt(s,"Arn"),Export:{Name:e.sub(`\${AWS::StackName}-${i.name}-table-arn`)}}}),i.streamEnabled)n.addOutputs({[`${s}StreamArn`]:{Description:`${i.name} stream ARN`,Value:e.getAtt(s,"StreamArn"),Export:{Name:e.sub(`\${AWS::StackName}-${i.name}-stream-arn`)}}})}function En(n,i){for(let[s,o]of Object.entries(i))o.forEach((c)=>{zr(n,c,s)})}function zr(n,i,s){let o=n.toLogicalId(`${s}-${i.name}-function`),c=`${o}Role`;n.addResource(c,"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:[...Jr(i.events||[])]}}],Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${i.name}-role`)}]});let u={FunctionName:e.sub(`\${AWS::StackName}-${i.name}`),Runtime:i.runtime,Handler:i.handler,Role:e.getAtt(c,"Arn"),MemorySize:i.memory,Timeout:i.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:i.environment?{Variables:i.environment}:void 0,Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${i.name}`)}]};if(s!=="edge")u.VpcConfig={SubnetIds:[e.ref("PrivateSubnet1"),e.ref("PrivateSubnet2")],SecurityGroupIds:[e.ref("AppSecurityGroup")]};if(n.addResource(o,"AWS::Lambda::Function",u,{dependsOn:c}),n.addResource(`${o}LogGroup`,"AWS::Logs::LogGroup",{LogGroupName:e.sub(`/aws/lambda/\${AWS::StackName}-${i.name}`),RetentionInDays:14}),i.events)i.events.forEach((d,g)=>{Qr(n,o,d,g)});n.addOutputs({[`${o}Arn`]:{Description:`${i.name} function ARN`,Value:e.getAtt(o,"Arn"),Export:{Name:e.sub(`\${AWS::StackName}-${i.name}-function-arn`)}}})}function Qr(n,i,s,o){let c=`${i}EventSource${o}`;switch(s.type){case"http":break;case"s3":if(s.bucket){let u=n.toLogicalId(`${s.bucket}-bucket`);n.addResource(`${c}Permission`,"AWS::Lambda::Permission",{FunctionName:e.ref(i),Action:"lambda:InvokeFunction",Principal:"s3.amazonaws.com",SourceArn:un.s3Bucket(e.ref(u))},{dependsOn:[i,u]})}break;case"sqs":if(s.queueName){let u=n.toLogicalId(`${s.queueName}-queue`);n.addResource(c,"AWS::Lambda::EventSourceMapping",{EventSourceArn:e.getAtt(u,"Arn"),FunctionName:e.ref(i),BatchSize:s.batchSize||10},{dependsOn:[i,u]})}break;case"kinesis":if(s.streamName){let u=n.toLogicalId(`${s.streamName}-stream`);n.addResource(c,"AWS::Lambda::EventSourceMapping",{EventSourceArn:e.getAtt(u,"Arn"),FunctionName:e.ref(i),BatchSize:s.batchSize||100,StartingPosition:s.startingPosition||"LATEST",ParallelizationFactor:s.parallelizationFactor||1},{dependsOn:[i,u]})}break;case"dynamodb-stream":if(s.tableName){let u=n.toLogicalId(`${s.tableName}-table`);n.addResource(c,"AWS::Lambda::EventSourceMapping",{EventSourceArn:e.getAtt(u,"StreamArn"),FunctionName:e.ref(i),BatchSize:s.batchSize||100,StartingPosition:s.startingPosition||"LATEST"},{dependsOn:[i,u]})}break;case"schedule":if(s.expression)n.addResource(`${c}Rule`,"AWS::Events::Rule",{ScheduleExpression:s.expression,State:"ENABLED",Targets:[{Arn:e.getAtt(i,"Arn"),Id:`${i}Target`}]},{dependsOn:i}),n.addResource(`${c}Permission`,"AWS::Lambda::Permission",{FunctionName:e.ref(i),Action:"lambda:InvokeFunction",Principal:"events.amazonaws.com",SourceArn:e.getAtt(`${c}Rule`,"Arn")},{dependsOn:[i,`${c}Rule`]});break}}function Jr(n){let i=[];if(!n)return i;if(n.forEach((s)=>{switch(s.type){case"s3":i.push({Effect:"Allow",Action:["s3:GetObject","s3:GetObjectVersion"],Resource:s.bucket?`arn:aws:s3:::${s.bucket}/*`:"arn:aws:s3:::*/*"});break;case"sqs":i.push({Effect:"Allow",Action:["sqs:ReceiveMessage","sqs:DeleteMessage","sqs:GetQueueAttributes"],Resource:s.queueName?un.sqs(s.queueName):"arn:aws:sqs:*:*:*"});break;case"kinesis":i.push({Effect:"Allow",Action:["kinesis:GetRecords","kinesis:GetShardIterator","kinesis:DescribeStream","kinesis:ListStreams"],Resource:s.streamName?un.kinesis(s.streamName):"arn:aws:kinesis:*:*:stream/*"});break;case"dynamodb-stream":i.push({Effect:"Allow",Action:["dynamodb:GetRecords","dynamodb:GetShardIterator","dynamodb:DescribeStream","dynamodb:ListStreams"],Resource:s.tableName?e.sub(`arn:aws:dynamodb:\${AWS::Region}:\${AWS::AccountId}:table/${s.tableName}/stream/*`):"arn:aws:dynamodb:*:*:table/*/stream/*"});break}}),i.length===0)i.push({Effect:"Allow",Action:["logs:CreateLogGroup","logs:CreateLogStream","logs:PutLogEvents"],Resource:"arn:aws:logs:*:*:*"});return i}function wn(n,i){if(i.topics)i.topics.forEach((s)=>{Yr(n,s)})}function Yr(n,i){let s=n.toLogicalId(`${i.name}-topic`);if(n.addResource(s,"AWS::SNS::Topic",{TopicName:e.sub(`\${AWS::StackName}-${i.name}`),DisplayName:i.displayName||i.name,Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${i.name}`)}]}),n.addResource(`${s}Policy`,"AWS::SNS::TopicPolicy",{Topics:[e.ref(s)],PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:["events.amazonaws.com","cloudwatch.amazonaws.com","s3.amazonaws.com"]},Action:"sns:Publish",Resource:e.ref(s)},{Effect:"Allow",Principal:{AWS:e.sub("arn:aws:iam::${AWS::AccountId}:root")},Action:["sns:Subscribe","sns:Publish","sns:Receive"],Resource:e.ref(s)}]}},{dependsOn:s}),i.subscriptions)i.subscriptions.forEach((o,c)=>{let u=`${s}Subscription${c+1}`,d={Protocol:o.protocol,TopicArn:e.ref(s),Endpoint:o.endpoint};if(o.filterPolicy)d.FilterPolicy=o.filterPolicy;if(o.protocol==="sqs"){let g=n.toLogicalId(`${o.endpoint}-queue`);d.Endpoint=e.getAtt(g,"Arn")}if(o.protocol==="lambda"){let g=n.toLogicalId(o.endpoint);d.Endpoint=e.getAtt(g,"Arn"),n.addResource(`${u}Permission`,"AWS::Lambda::Permission",{FunctionName:e.ref(g),Action:"lambda:InvokeFunction",Principal:"sns.amazonaws.com",SourceArn:e.ref(s)},{dependsOn:[g,s]})}n.addResource(u,"AWS::SNS::Subscription",d,{dependsOn:s})});n.addOutputs({[`${s}Arn`]:{Description:`${i.name} topic ARN`,Value:e.ref(s),Export:{Name:e.sub(`\${AWS::StackName}-${i.name}-topic-arn`)}}})}function In(n,i){if(i.alarms&&i.alarms.length>0)n.addResource("AlarmTopic","AWS::SNS::Topic",{TopicName:e.sub("${AWS::StackName}-alarms"),DisplayName:"CloudWatch Alarms",Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-alarms")}]}),i.alarms.forEach((s,o)=>{Zr(n,s,o)});if(i.dashboard)Xr(n,i.dashboard);if(i.logs?.groups)i.logs.groups.forEach((s)=>{ei(n,s,i.logs?.retention)})}function Zr(n,i,s){let o=n.toLogicalId(`alarm-${i.name||i.metric}-${s}`),c={AlarmName:i.name||e.sub(`\${AWS::StackName}-${i.metric}`),AlarmDescription:`Alarm for ${i.metric}`,MetricName:i.metric,Namespace:i.namespace||Et(i.metric,i.service),Statistic:i.statistic||"Average",Period:i.period||300,EvaluationPeriods:i.evaluationPeriods||1,Threshold:i.threshold,ComparisonOperator:i.comparisonOperator||"GreaterThanThreshold",TreatMissingData:i.treatMissingData||"notBreaching",AlarmActions:[e.ref("AlarmTopic")],OKActions:[e.ref("AlarmTopic")]};if(i.dimensions)c.Dimensions=Object.entries(i.dimensions).map(([u,d])=>({Name:u,Value:d}));else if(i.service)c.Dimensions=ti(i.service);n.addResource(o,"AWS::CloudWatch::Alarm",c,{dependsOn:"AlarmTopic"})}function Xr(n,i){if(!i)return;let s=[],o=0,c=0;i.widgets?.forEach((u)=>{let d=u.width||12,g=u.height||6;if(u.type==="metric"&&u.metrics){let y=u.metrics.map((h)=>{if(typeof h==="string")return[Et(h),h];else return[Et(h.metric,h.service),h.metric]});s.push({type:"metric",x:o,y:c,width:d,height:g,properties:{metrics:y,period:300,stat:"Average",region:e.ref("AWS::Region"),title:u.metrics.length>1?"Multiple Metrics":typeof u.metrics[0]==="string"?u.metrics[0]:u.metrics[0].metric}})}else if(u.type==="log"&&u.logGroup)s.push({type:"log",x:o,y:c,width:d,height:g,properties:{query:`SOURCE '${u.logGroup}'
2451
+ };`},Environment:i.environment?{Variables:i.environment}:void 0,Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${i.name}`)}]};if(s!=="edge")u.VpcConfig={SubnetIds:[e.ref("PrivateSubnet1"),e.ref("PrivateSubnet2")],SecurityGroupIds:[e.ref("AppSecurityGroup")]};if(n.addResource(o,"AWS::Lambda::Function",u,{dependsOn:c}),n.addResource(`${o}LogGroup`,"AWS::Logs::LogGroup",{LogGroupName:e.sub(`/aws/lambda/\${AWS::StackName}-${i.name}`),RetentionInDays:14}),i.events)i.events.forEach((d,g)=>{Qr(n,o,d,g)});n.addOutputs({[`${o}Arn`]:{Description:`${i.name} function ARN`,Value:e.getAtt(o,"Arn"),Export:{Name:e.sub(`\${AWS::StackName}-${i.name}-function-arn`)}}})}function Qr(n,i,s,o){let c=`${i}EventSource${o}`;switch(s.type){case"http":break;case"s3":if(s.bucket){let u=n.toLogicalId(`${s.bucket}-bucket`);n.addResource(`${c}Permission`,"AWS::Lambda::Permission",{FunctionName:e.ref(i),Action:"lambda:InvokeFunction",Principal:"s3.amazonaws.com",SourceArn:gn.s3Bucket(e.ref(u))},{dependsOn:[i,u]})}break;case"sqs":if(s.queueName){let u=n.toLogicalId(`${s.queueName}-queue`);n.addResource(c,"AWS::Lambda::EventSourceMapping",{EventSourceArn:e.getAtt(u,"Arn"),FunctionName:e.ref(i),BatchSize:s.batchSize||10},{dependsOn:[i,u]})}break;case"kinesis":if(s.streamName){let u=n.toLogicalId(`${s.streamName}-stream`);n.addResource(c,"AWS::Lambda::EventSourceMapping",{EventSourceArn:e.getAtt(u,"Arn"),FunctionName:e.ref(i),BatchSize:s.batchSize||100,StartingPosition:s.startingPosition||"LATEST",ParallelizationFactor:s.parallelizationFactor||1},{dependsOn:[i,u]})}break;case"dynamodb-stream":if(s.tableName){let u=n.toLogicalId(`${s.tableName}-table`);n.addResource(c,"AWS::Lambda::EventSourceMapping",{EventSourceArn:e.getAtt(u,"StreamArn"),FunctionName:e.ref(i),BatchSize:s.batchSize||100,StartingPosition:s.startingPosition||"LATEST"},{dependsOn:[i,u]})}break;case"schedule":if(s.expression)n.addResource(`${c}Rule`,"AWS::Events::Rule",{ScheduleExpression:s.expression,State:"ENABLED",Targets:[{Arn:e.getAtt(i,"Arn"),Id:`${i}Target`}]},{dependsOn:i}),n.addResource(`${c}Permission`,"AWS::Lambda::Permission",{FunctionName:e.ref(i),Action:"lambda:InvokeFunction",Principal:"events.amazonaws.com",SourceArn:e.getAtt(`${c}Rule`,"Arn")},{dependsOn:[i,`${c}Rule`]});break}}function Jr(n){let i=[];if(!n)return i;if(n.forEach((s)=>{switch(s.type){case"s3":i.push({Effect:"Allow",Action:["s3:GetObject","s3:GetObjectVersion"],Resource:s.bucket?`arn:aws:s3:::${s.bucket}/*`:"arn:aws:s3:::*/*"});break;case"sqs":i.push({Effect:"Allow",Action:["sqs:ReceiveMessage","sqs:DeleteMessage","sqs:GetQueueAttributes"],Resource:s.queueName?gn.sqs(s.queueName):"arn:aws:sqs:*:*:*"});break;case"kinesis":i.push({Effect:"Allow",Action:["kinesis:GetRecords","kinesis:GetShardIterator","kinesis:DescribeStream","kinesis:ListStreams"],Resource:s.streamName?gn.kinesis(s.streamName):"arn:aws:kinesis:*:*:stream/*"});break;case"dynamodb-stream":i.push({Effect:"Allow",Action:["dynamodb:GetRecords","dynamodb:GetShardIterator","dynamodb:DescribeStream","dynamodb:ListStreams"],Resource:s.tableName?e.sub(`arn:aws:dynamodb:\${AWS::Region}:\${AWS::AccountId}:table/${s.tableName}/stream/*`):"arn:aws:dynamodb:*:*:table/*/stream/*"});break}}),i.length===0)i.push({Effect:"Allow",Action:["logs:CreateLogGroup","logs:CreateLogStream","logs:PutLogEvents"],Resource:"arn:aws:logs:*:*:*"});return i}function wn(n,i){if(i.topics)i.topics.forEach((s)=>{Yr(n,s)})}function Yr(n,i){let s=n.toLogicalId(`${i.name}-topic`);if(n.addResource(s,"AWS::SNS::Topic",{TopicName:e.sub(`\${AWS::StackName}-${i.name}`),DisplayName:i.displayName||i.name,Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${i.name}`)}]}),n.addResource(`${s}Policy`,"AWS::SNS::TopicPolicy",{Topics:[e.ref(s)],PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:["events.amazonaws.com","cloudwatch.amazonaws.com","s3.amazonaws.com"]},Action:"sns:Publish",Resource:e.ref(s)},{Effect:"Allow",Principal:{AWS:e.sub("arn:aws:iam::${AWS::AccountId}:root")},Action:["sns:Subscribe","sns:Publish","sns:Receive"],Resource:e.ref(s)}]}},{dependsOn:s}),i.subscriptions)i.subscriptions.forEach((o,c)=>{let u=`${s}Subscription${c+1}`,d={Protocol:o.protocol,TopicArn:e.ref(s),Endpoint:o.endpoint};if(o.filterPolicy)d.FilterPolicy=o.filterPolicy;if(o.protocol==="sqs"){let g=n.toLogicalId(`${o.endpoint}-queue`);d.Endpoint=e.getAtt(g,"Arn")}if(o.protocol==="lambda"){let g=n.toLogicalId(o.endpoint);d.Endpoint=e.getAtt(g,"Arn"),n.addResource(`${u}Permission`,"AWS::Lambda::Permission",{FunctionName:e.ref(g),Action:"lambda:InvokeFunction",Principal:"sns.amazonaws.com",SourceArn:e.ref(s)},{dependsOn:[g,s]})}n.addResource(u,"AWS::SNS::Subscription",d,{dependsOn:s})});n.addOutputs({[`${s}Arn`]:{Description:`${i.name} topic ARN`,Value:e.ref(s),Export:{Name:e.sub(`\${AWS::StackName}-${i.name}-topic-arn`)}}})}function In(n,i){if(i.alarms&&i.alarms.length>0)n.addResource("AlarmTopic","AWS::SNS::Topic",{TopicName:e.sub("${AWS::StackName}-alarms"),DisplayName:"CloudWatch Alarms",Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-alarms")}]}),i.alarms.forEach((s,o)=>{Zr(n,s,o)});if(i.dashboard)Xr(n,i.dashboard);if(i.logs?.groups)i.logs.groups.forEach((s)=>{ei(n,s,i.logs?.retention)})}function Zr(n,i,s){let o=n.toLogicalId(`alarm-${i.name||i.metric}-${s}`),c={AlarmName:i.name||e.sub(`\${AWS::StackName}-${i.metric}`),AlarmDescription:`Alarm for ${i.metric}`,MetricName:i.metric,Namespace:i.namespace||Pt(i.metric,i.service),Statistic:i.statistic||"Average",Period:i.period||300,EvaluationPeriods:i.evaluationPeriods||1,Threshold:i.threshold,ComparisonOperator:i.comparisonOperator||"GreaterThanThreshold",TreatMissingData:i.treatMissingData||"notBreaching",AlarmActions:[e.ref("AlarmTopic")],OKActions:[e.ref("AlarmTopic")]};if(i.dimensions)c.Dimensions=Object.entries(i.dimensions).map(([u,d])=>({Name:u,Value:d}));else if(i.service)c.Dimensions=ti(i.service);n.addResource(o,"AWS::CloudWatch::Alarm",c,{dependsOn:"AlarmTopic"})}function Xr(n,i){if(!i)return;let s=[],o=0,c=0;i.widgets?.forEach((u)=>{let d=u.width||12,g=u.height||6;if(u.type==="metric"&&u.metrics){let y=u.metrics.map((h)=>{if(typeof h==="string")return[Pt(h),h];else return[Pt(h.metric,h.service),h.metric]});s.push({type:"metric",x:o,y:c,width:d,height:g,properties:{metrics:y,period:300,stat:"Average",region:e.ref("AWS::Region"),title:u.metrics.length>1?"Multiple Metrics":typeof u.metrics[0]==="string"?u.metrics[0]:u.metrics[0].metric}})}else if(u.type==="log"&&u.logGroup)s.push({type:"log",x:o,y:c,width:d,height:g,properties:{query:`SOURCE '${u.logGroup}'
2452
2452
  | fields @timestamp, @message
2453
2453
  | sort @timestamp desc
2454
- | limit 20`,region:e.ref("AWS::Region"),title:`Logs: ${u.logGroup}`}});else if(u.type==="text"&&u.text)s.push({type:"text",x:o,y:c,width:d,height:g,properties:{markdown:u.text}});if(o+=d,o>=24)o=0,c+=g}),n.addResource("CloudWatchDashboard","AWS::CloudWatch::Dashboard",{DashboardName:e.sub(`\${AWS::StackName}-${i.name}`),DashboardBody:JSON.stringify({widgets:s})}),n.addOutputs({DashboardURL:{Description:"CloudWatch Dashboard URL",Value:e.sub("https://console.aws.amazon.com/cloudwatch/home?region=${AWS::Region}#dashboards:name=${CloudWatchDashboard}")}})}function ei(n,i,s){let o=n.toLogicalId(`${i}-log-group`);n.addResource(o,"AWS::Logs::LogGroup",{LogGroupName:e.sub(`/aws/\${AWS::StackName}/${i}`),RetentionInDays:s||14,Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${i}`)}]})}function Et(n,i){if(i)return{ec2:"AWS/EC2",ecs:"AWS/ECS",lambda:"AWS/Lambda",rds:"AWS/RDS",dynamodb:"AWS/DynamoDB",s3:"AWS/S3",cloudfront:"AWS/CloudFront",alb:"AWS/ApplicationELB",nlb:"AWS/NetworkELB",apigateway:"AWS/ApiGateway",sqs:"AWS/SQS",sns:"AWS/SNS",kinesis:"AWS/Kinesis",elasticache:"AWS/ElastiCache"}[i.toLowerCase()]||"AWS/CloudWatch";let s=n.toLowerCase();if(s.includes("cpu")||s.includes("memory")||s.includes("network"))return"AWS/EC2";if(s.includes("lambda")||s.includes("invocation")||s.includes("duration"))return"AWS/Lambda";if(s.includes("request")||s.includes("latency")||s.includes("target"))return"AWS/ApplicationELB";if(s.includes("database")||s.includes("connection"))return"AWS/RDS";if(s.includes("read")||s.includes("write")||s.includes("consumed"))return"AWS/DynamoDB";return"AWS/CloudWatch"}function ti(n){return{ec2:[{Name:"InstanceId",Value:e.ref("EC2Instance")}],ecs:[{Name:"ClusterName",Value:e.ref("ECSCluster")},{Name:"ServiceName",Value:e.getAtt("ECSService","Name")}],lambda:[{Name:"FunctionName",Value:e.ref("LambdaFunction")}],rds:[{Name:"DBInstanceIdentifier",Value:e.ref("Database")}],dynamodb:[{Name:"TableName",Value:e.ref("DynamoDBTable")}],alb:[{Name:"LoadBalancer",Value:e.getAtt("LoadBalancer","LoadBalancerFullName")}],apigateway:[{Name:"ApiName",Value:e.ref("HttpApi")}]}[n.toLowerCase()]||[]}function Dn(n,i){if(!i.vpc)return;let{cidr:s="10.0.0.0/16",availabilityZones:o=2,natGateways:c=1,enableDnsHostnames:u=!0,enableDnsSupport:d=!0}=i.vpc;n.addResource("VPC","AWS::EC2::VPC",{CidrBlock:s,EnableDnsHostnames:u,EnableDnsSupport:d,Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-vpc")}]}),n.addResource("InternetGateway","AWS::EC2::InternetGateway",{Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-igw")}]}),n.addResource("VPCGatewayAttachment","AWS::EC2::VPCGatewayAttachment",{VpcId:e.ref("VPC"),InternetGatewayId:e.ref("InternetGateway")},{dependsOn:["VPC","InternetGateway"]});let g=[];for(let v=0;v<o;v++){let A=`PublicSubnet${v+1}`;g.push(A),n.addResource(A,"AWS::EC2::Subnet",{VpcId:e.ref("VPC"),CidrBlock:e.select(v,e.cidr(e.getAtt("VPC","CidrBlock"),o*2,8)),AvailabilityZone:e.select(v,e.getAZs()),MapPublicIpOnLaunch:!0,Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-public-${v+1}`)},{Key:"Type",Value:"public"}]},{dependsOn:"VPC"})}let y=[];for(let v=0;v<o;v++){let A=`PrivateSubnet${v+1}`;y.push(A),n.addResource(A,"AWS::EC2::Subnet",{VpcId:e.ref("VPC"),CidrBlock:e.select(v+o,e.cidr(e.getAtt("VPC","CidrBlock"),o*2,8)),AvailabilityZone:e.select(v,e.getAZs()),MapPublicIpOnLaunch:!1,Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-private-${v+1}`)},{Key:"Type",Value:"private"}]},{dependsOn:"VPC"})}let h=[];for(let v=0;v<c;v++){let A=`NatEIP${v+1}`;h.push(A),n.addResource(A,"AWS::EC2::EIP",{Domain:"vpc",Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-nat-eip-${v+1}`)}]},{dependsOn:"VPCGatewayAttachment"})}let b=[];for(let v=0;v<c;v++){let A=`NatGateway${v+1}`;b.push(A);let T=v%o;n.addResource(A,"AWS::EC2::NatGateway",{AllocationId:e.getAtt(h[v],"AllocationId"),SubnetId:e.ref(g[T]),Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-nat-${v+1}`)}]},{dependsOn:[h[v],g[T]]})}n.addResource("PublicRouteTable","AWS::EC2::RouteTable",{VpcId:e.ref("VPC"),Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-public-rt")}]},{dependsOn:"VPC"}),n.addResource("PublicRoute","AWS::EC2::Route",{RouteTableId:e.ref("PublicRouteTable"),DestinationCidrBlock:"0.0.0.0/0",GatewayId:e.ref("InternetGateway")},{dependsOn:["PublicRouteTable","VPCGatewayAttachment"]}),g.forEach((v,A)=>{n.addResource(`PublicSubnetRouteTableAssociation${A+1}`,"AWS::EC2::SubnetRouteTableAssociation",{SubnetId:e.ref(v),RouteTableId:e.ref("PublicRouteTable")},{dependsOn:[v,"PublicRouteTable"]})}),y.forEach((v,A)=>{let T=`PrivateRouteTable${A+1}`,R=A%c;n.addResource(T,"AWS::EC2::RouteTable",{VpcId:e.ref("VPC"),Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-private-rt-${A+1}`)}]},{dependsOn:"VPC"}),n.addResource(`PrivateRoute${A+1}`,"AWS::EC2::Route",{RouteTableId:e.ref(T),DestinationCidrBlock:"0.0.0.0/0",NatGatewayId:e.ref(b[R])},{dependsOn:[T,b[R]]}),n.addResource(`PrivateSubnetRouteTableAssociation${A+1}`,"AWS::EC2::SubnetRouteTableAssociation",{SubnetId:e.ref(v),RouteTableId:e.ref(T)},{dependsOn:[v,T]})}),n.addResource("S3VPCEndpoint","AWS::EC2::VPCEndpoint",{VpcId:e.ref("VPC"),ServiceName:e.sub("com.amazonaws.${AWS::Region}.s3"),VpcEndpointType:"Gateway",RouteTableIds:[e.ref("PublicRouteTable"),...Array.from({length:o},(v,A)=>e.ref(`PrivateRouteTable${A+1}`))]},{dependsOn:"VPC"}),n.addResource("NetworkAcl","AWS::EC2::NetworkAcl",{VpcId:e.ref("VPC"),Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-nacl")}]},{dependsOn:"VPC"}),n.addResource("NetworkAclEntryInbound","AWS::EC2::NetworkAclEntry",{NetworkAclId:e.ref("NetworkAcl"),RuleNumber:100,Protocol:-1,RuleAction:"allow",CidrBlock:"0.0.0.0/0"},{dependsOn:"NetworkAcl"}),n.addResource("NetworkAclEntryOutbound","AWS::EC2::NetworkAclEntry",{NetworkAclId:e.ref("NetworkAcl"),RuleNumber:100,Protocol:-1,Egress:!0,RuleAction:"allow",CidrBlock:"0.0.0.0/0"},{dependsOn:"NetworkAcl"}),n.addOutputs({VPCId:{Description:"VPC ID",Value:e.ref("VPC"),Export:{Name:e.sub("${AWS::StackName}-VPC")}},PublicSubnets:{Description:"Public subnet IDs",Value:e.join(",",g.map((v)=>e.ref(v))),Export:{Name:e.sub("${AWS::StackName}-PublicSubnets")}},PrivateSubnets:{Description:"Private subnet IDs",Value:e.join(",",y.map((v)=>e.ref(v))),Export:{Name:e.sub("${AWS::StackName}-PrivateSubnets")}}})}function Nn(n,i){for(let[s,o]of Object.entries(i))ni(n,s,o)}function ni(n,i,s){let o=n.toLogicalId(`${i}-queue`),c=s.fifo||!1,u;if(s.deadLetterQueue){let g=`${o}DLQ`;n.addResource(g,"AWS::SQS::Queue",{QueueName:c?e.sub(`\${AWS::StackName}-${i}-dlq.fifo`):e.sub(`\${AWS::StackName}-${i}-dlq`),FifoQueue:c,MessageRetentionPeriod:1209600,Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${i}-dlq`)}]},{deletionPolicy:"Retain",updateReplacePolicy:"Retain"}),u=e.getAtt(g,"Arn")}let d={QueueName:c?e.sub(`\${AWS::StackName}-${i}.fifo`):e.sub(`\${AWS::StackName}-${i}`),FifoQueue:c,VisibilityTimeout:s.visibilityTimeout||30,MessageRetentionPeriod:s.messageRetentionPeriod||345600,ReceiveMessageWaitTimeSeconds:s.receiveMessageWaitTime||0,Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${i}`)}]};if(c&&s.contentBasedDeduplication)d.ContentBasedDeduplication=!0;if(s.deadLetterQueue&&u)d.RedrivePolicy={deadLetterTargetArn:u,maxReceiveCount:s.maxReceiveCount||3};if(n.addResource(o,"AWS::SQS::Queue",d,{dependsOn:s.deadLetterQueue?`${o}DLQ`:void 0,deletionPolicy:"Retain",updateReplacePolicy:"Retain"}),n.addResource(`${o}Policy`,"AWS::SQS::QueuePolicy",{Queues:[e.ref(o)],PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:["lambda.amazonaws.com","events.amazonaws.com","sns.amazonaws.com"]},Action:"sqs:SendMessage",Resource:e.getAtt(o,"Arn"),Condition:{ArnEquals:{"aws:SourceArn":e.sub("arn:aws:*:${AWS::Region}:${AWS::AccountId}:*")}}}]}},{dependsOn:o}),n.addOutputs({[`${o}Url`]:{Description:`${i} queue URL`,Value:e.ref(o),Export:{Name:e.sub(`\${AWS::StackName}-${i}-queue-url`)}},[`${o}Arn`]:{Description:`${i} queue ARN`,Value:e.getAtt(o,"Arn"),Export:{Name:e.sub(`\${AWS::StackName}-${i}-queue-arn`)}}}),s.deadLetterQueue)n.addOutputs({[`${o}DLQUrl`]:{Description:`${i} dead letter queue URL`,Value:e.ref(`${o}DLQ`),Export:{Name:e.sub(`\${AWS::StackName}-${i}-dlq-url`)}}})}function xn(n,i){if(i.certificate)ri(n,i.certificate);if(i.waf?.enabled)ii(n,i.waf);if(i.securityGroups)for(let[s,o]of Object.entries(i.securityGroups))si(n,s,o)}function ri(n,i){if(!i)return;let s=[i.domain];if(i.subdomains)s.push(...i.subdomains);n.addResource("Certificate","AWS::CertificateManager::Certificate",{DomainName:i.domain,SubjectAlternativeNames:i.subdomains,ValidationMethod:i.validationMethod||"DNS",DomainValidationOptions:s.map((o)=>({DomainName:o,HostedZoneId:e.ref("HostedZone")})),Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-certificate")}]}),n.addOutputs({CertificateArn:{Description:"ACM Certificate ARN",Value:e.ref("Certificate"),Export:{Name:e.sub("${AWS::StackName}-certificate-arn")}}})}function ii(n,i){if(!i)return;let s=[],o=i.rules||["rateLimit","sqlInjection","xss"];if(o.includes("rateLimit"))s.push({Name:"RateLimitRule",Priority:1,Statement:{RateBasedStatement:{Limit:i.rateLimit||2000,AggregateKeyType:"IP"}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"RateLimitRule"}});let c=s.length+1;if(o.includes("sqlInjection"))s.push({Name:"AWSManagedRulesSQLi",Priority:c++,Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:"AWSManagedRulesSQLiRuleSet"}},OverrideAction:{None:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"AWSManagedRulesSQLi"}});if(o.includes("xss"))s.push({Name:"AWSManagedRulesXSS",Priority:c++,Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:"AWSManagedRulesKnownBadInputsRuleSet"}},OverrideAction:{None:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"AWSManagedRulesXSS"}});if(o.includes("knownBadInputs"))s.push({Name:"AWSManagedRulesKnownBadInputs",Priority:c++,Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:"AWSManagedRulesKnownBadInputsRuleSet"}},OverrideAction:{None:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"AWSManagedRulesKnownBadInputs"}});if(o.includes("coreRuleSet"))s.push({Name:"AWSManagedRulesCoreRuleSet",Priority:c++,Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:"AWSManagedRulesCommonRuleSet"}},OverrideAction:{None:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"AWSManagedRulesCoreRuleSet"}});if(o.includes("linuxRuleSet"))s.push({Name:"AWSManagedRulesLinuxRuleSet",Priority:c++,Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:"AWSManagedRulesLinuxRuleSet"}},OverrideAction:{None:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"AWSManagedRulesLinuxRuleSet"}});if(o.includes("apiProtection"))s.push({Name:"AWSManagedRulesAPIProtection",Priority:c++,Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:"AWSManagedRulesAmazonIpReputationList"}},OverrideAction:{None:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"AWSManagedRulesAPIProtection"}});if(o.includes("geoBlock"))s.push({Name:"GeoBlockRule",Priority:c++,Statement:{GeoMatchStatement:{CountryCodes:["CN","RU"]}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"GeoBlockRule"}});if(o.includes("connectionLimit"))s.push({Name:"ConnectionLimitRule",Priority:c++,Statement:{RateBasedStatement:{Limit:100,AggregateKeyType:"IP"}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"ConnectionLimitRule"}});if(n.addResource("WebACL","AWS::WAFv2::WebACL",{Name:e.sub("${AWS::StackName}-waf"),Scope:i.scope||"REGIONAL",DefaultAction:{Allow:{}},Rules:s,VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:e.sub("${AWS::StackName}-waf")},Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-waf")}]}),n.hasResource("LoadBalancer"))n.addResource("WebACLAssociation","AWS::WAFv2::WebACLAssociation",{ResourceArn:e.ref("LoadBalancer"),WebACLArn:e.getAtt("WebACL","Arn")},{dependsOn:["WebACL","LoadBalancer"]});n.addOutputs({WebACLId:{Description:"WAF Web ACL ID",Value:e.ref("WebACL"),Export:{Name:e.sub("${AWS::StackName}-waf-id")}},WebACLArn:{Description:"WAF Web ACL ARN",Value:e.getAtt("WebACL","Arn"),Export:{Name:e.sub("${AWS::StackName}-waf-arn")}}})}function si(n,i,s){if(!s)return;let o=n.toLogicalId(`${i}-security-group`),c=s.ingress?.map((d)=>({IpProtocol:d.protocol,FromPort:d.port,ToPort:d.port,CidrIp:d.cidr,SourceSecurityGroupId:d.source?e.ref(d.source):void 0}))||[],u=s.egress?.map((d)=>({IpProtocol:d.protocol,FromPort:d.port,ToPort:d.port,CidrIp:d.cidr||"0.0.0.0/0"}))||[{IpProtocol:"-1",CidrIp:"0.0.0.0/0"}];n.addResource(o,"AWS::EC2::SecurityGroup",{GroupDescription:`Security group for ${i}`,VpcId:e.ref("VPC"),SecurityGroupIngress:c,SecurityGroupEgress:u,Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${i}-sg`)}]},{dependsOn:"VPC"}),n.addOutputs({[`${o}Id`]:{Description:`${i} security group ID`,Value:e.ref(o),Export:{Name:e.sub(`\${AWS::StackName}-${i}-sg-id`)}}})}function kn(n,i){for(let[s,o]of Object.entries(i)){if(o.type==="efs"){oi(n,s,o);continue}ai(n,s,o)}}function ai(n,i,s){let o=n.toLogicalId(`${i}-bucket`),c={BucketName:e.sub(`\${AWS::StackName}-${i}`),Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${i}`)}]};if(s.versioning)c.VersioningConfiguration={Status:"Enabled"};if(s.encryption)c.BucketEncryption={ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]};if(!s.public)c.PublicAccessBlockConfiguration={BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0};if(s.website)c.WebsiteConfiguration={IndexDocument:"index.html",ErrorDocument:"index.html"};if(s.cors&&s.cors.length>0)c.CorsConfiguration={CorsRules:s.cors.map((u)=>({AllowedOrigins:u.allowedOrigins,AllowedMethods:u.allowedMethods,AllowedHeaders:u.allowedHeaders||["*"],MaxAge:u.maxAge||3600}))};if(s.lifecycleRules&&s.lifecycleRules.length>0)c.LifecycleConfiguration={Rules:s.lifecycleRules.map((u)=>({Id:u.id,Status:u.enabled?"Enabled":"Disabled",ExpirationInDays:u.expirationDays,Transitions:u.transitions?.map((d)=>({TransitionInDays:d.days,StorageClass:d.storageClass}))}))};if(s.intelligentTiering)c.IntelligentTieringConfigurations=[{Id:"EntireBucket",Status:"Enabled",Tierings:[{AccessTier:"ARCHIVE_ACCESS",Days:90},{AccessTier:"DEEP_ARCHIVE_ACCESS",Days:180}]}];if(n.addResource(o,"AWS::S3::Bucket",c,{deletionPolicy:s.versioning?"Retain":"Delete"}),s.public)n.addResource(`${o}Policy`,"AWS::S3::BucketPolicy",{Bucket:e.ref(o),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadGetObject",Effect:"Allow",Principal:"*",Action:"s3:GetObject",Resource:e.join("",[un.s3Bucket(e.ref(o)),"/*"])}]}},{dependsOn:o});if(n.addOutputs({[`${o}Name`]:{Description:`${i} bucket name`,Value:e.ref(o),Export:{Name:e.sub(`\${AWS::StackName}-${i}-bucket`)}},[`${o}Arn`]:{Description:`${i} bucket ARN`,Value:e.getAtt(o,"Arn"),Export:{Name:e.sub(`\${AWS::StackName}-${i}-bucket-arn`)}}}),s.website)n.addOutputs({[`${o}WebsiteURL`]:{Description:`${i} website URL`,Value:e.getAtt(o,"WebsiteURL")}})}function oi(n,i,s){let o=n.toLogicalId(`${i}-efs`),c={Encrypted:s.encryption!==!1,PerformanceMode:s.performanceMode||"generalPurpose",ThroughputMode:s.throughputMode||"bursting",FileSystemTags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${i}`)}]};if(s.lifecyclePolicy){if(c.LifecyclePolicies=[],s.lifecyclePolicy.transitionToIA)c.LifecyclePolicies.push({TransitionToIA:`AFTER_${s.lifecyclePolicy.transitionToIA}_DAYS`});if(s.lifecyclePolicy.transitionToPrimaryStorageClass)c.LifecyclePolicies.push({TransitionToPrimaryStorageClass:"AFTER_1_ACCESS"})}n.addResource(o,"AWS::EFS::FileSystem",c,{deletionPolicy:"Retain"});let u=2;for(let d=0;d<u;d++)n.addResource(`${o}MountTarget${d+1}`,"AWS::EFS::MountTarget",{FileSystemId:e.ref(o),SubnetId:e.ref(`PrivateSubnet${d+1}`),SecurityGroups:[e.ref("EFSSecurityGroup")]},{dependsOn:[o,`PrivateSubnet${d+1}`]});n.addResource("EFSSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for EFS mount targets",VpcId:e.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:2049,ToPort:2049,SourceSecurityGroupId:e.ref("AppSecurityGroup")}],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-efs-sg")}]},{dependsOn:"VPC"}),n.addOutputs({[`${o}Id`]:{Description:`${i} EFS file system ID`,Value:e.ref(o),Export:{Name:e.sub(`\${AWS::StackName}-${i}-efs`)}}})}class xm{template;config;resourceDependencies;constructor(n){this.config=n,this.resourceDependencies=new Map,this.template={AWSTemplateFormatVersion:"2010-09-09",Description:`Infrastructure for ${n.project.name} (${n.project.slug})`,Resources:{}}}build(){return this.addParameters(),this.addMappings(),this.addConditions(),this.addResources(),this.initializeOutputs(),this.resolveDependencies(),this.template}addParameters(){this.template.Parameters={Environment:{Type:"String",Default:"production",AllowedValues:["development","staging","production"],Description:"Environment name"}}}addMappings(){this.template.Mappings={RegionMap:{"us-east-1":{AMI:"ami-0f3caa1cf4417e51b"},"us-west-2":{AMI:"ami-0d1cd67c26f5fca19"},"eu-west-1":{AMI:"ami-0bbc25e23a7640b9b"}}}}addConditions(){this.template.Conditions={IsProduction:e.equals(e.ref("Environment"),"production"),HasDomain:e.not([e.equals(this.config.environments?.production?.domain||"","")])}}addResources(){let{infrastructure:n}=this.config;if(!n)return;if(n.network)this.addNetworkResources(n.network);if(n.storage)this.addStorageResources(n.storage);if(n.compute)this.addComputeResources(n.compute);if(n.databases)this.addDatabaseResources(n.databases);if(n.cache)this.addCacheResources(n.cache);if(n.cdn)this.addCDNResources(n.cdn);if(n.apiGateway)this.addApiGatewayResources(n.apiGateway);if(n.functions)this.addFunctionResources(n.functions);if(n.queues)this.addQueueResources(n.queues);if(n.messaging)this.addMessagingResources(n.messaging);if(n.monitoring)this.addMonitoringResources(n.monitoring);if(n.security)this.addSecurityResources(n.security)}initializeOutputs(){let n=this.template.Outputs||{};if(this.template.Outputs={StackName:{Description:"Stack name",Value:e.ref("AWS::StackName"),Export:{Name:e.sub("${AWS::StackName}-Name")}},Region:{Description:"AWS Region",Value:e.ref("AWS::Region"),Export:{Name:e.sub("${AWS::StackName}-Region")}},...n},this.config.environments?.production?.domain)this.template.Outputs.Domain={Description:"Production domain",Value:this.config.environments.production.domain,Condition:"HasDomain"}}addResource(n,i,s,o){let c={Type:i,Properties:s};if(o?.dependsOn)c.DependsOn=o.dependsOn,this.trackDependency(n,o.dependsOn);if(o?.condition)c.Condition=o.condition;if(o?.deletionPolicy)c.DeletionPolicy=o.deletionPolicy;if(o?.updateReplacePolicy)c.UpdateReplacePolicy=o.updateReplacePolicy;this.template.Resources[n]=c}addOutputs(n){this.template.Outputs={...this.template.Outputs,...n}}getOutputs(){return this.template.Outputs||{}}hasResource(n){return n in this.template.Resources}getResource(n){return this.template.Resources[n]}trackDependency(n,i){if(!this.resourceDependencies.has(n))this.resourceDependencies.set(n,new Set);(Array.isArray(i)?i:[i]).forEach((o)=>this.resourceDependencies.get(n).add(o))}resolveDependencies(){let n=new Set,i=new Set,s=(o)=>{if(i.has(o))throw Error(`Circular dependency detected involving resource: ${o}`);if(n.has(o))return!0;n.add(o),i.add(o);let c=this.resourceDependencies.get(o);if(c)for(let u of c)s(u);return i.delete(o),!0};for(let o of this.resourceDependencies.keys())s(o)}toLogicalId(n){return n.split(/[-_\s]/).map((i)=>i.charAt(0).toUpperCase()+i.slice(1).toLowerCase()).join("")}addNetworkResources(n){Dn(this,n)}addStorageResources(n){kn(this,n)}addComputeResources(n){Tn(this,n)}addDatabaseResources(n){Pn(this,n)}addFunctionResources(n){En(this,n)}addCacheResources(n){An(this,n)}addQueueResources(n){Nn(this,n)}addMessagingResources(n){wn(this,n)}addCDNResources(n){Cn(this,n)}addApiGatewayResources(n){Sn(this,n)}addMonitoringResources(n){In(this,n)}addSecurityResources(n){xn(this,n)}}function fl(n){return new xm(n).build()}function YI(n){let{name:i,slug:s,domain:o,subdomain:c}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:c&&o?`${c}.${o}`:o}},infrastructure:{storage:{assets:{public:!0,versioning:!1,website:!0,encryption:!1,cors:[{allowedOrigins:["*"],allowedMethods:["GET","HEAD"],allowedHeaders:["*"],maxAge:3600}]}},cdn:{enabled:!0,customDomain:o?{domain:c&&o?`${c}.${o}`:o,certificateArn:"TO_BE_GENERATED"}:void 0,cachePolicy:{minTTL:0,defaultTTL:86400,maxTTL:31536000},compress:!0,http3:!0,errorPages:{404:"/index.html",403:"/index.html"}}}}}function ZI(n){let{name:i,slug:s,domain:o,instanceType:c="t3.small",minInstances:u=2,maxInstances:d=10}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"server",environments:{production:{type:"production",domain:o}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:2,natGateways:1}},compute:{server:{instanceType:c,ami:"ubuntu-22.04",keyPair:`${s}-key`,autoScaling:{min:u,max:d,desired:u,targetCPU:70},loadBalancer:{type:"application",healthCheck:{path:"/health",interval:30,timeout:5,healthyThreshold:2,unhealthyThreshold:3}},userData:{packages:["nodejs","npm","nginx"],commands:["curl -fsSL https://bun.sh/install | bash","npm install -g pm2"]}}},databases:{postgres:{engine:"postgres",version:"15",instanceClass:"db.t3.micro",allocatedStorage:20,multiAZ:!0,backupRetentionDays:7,deletionProtection:!0}},cache:{redis:{nodeType:"cache.t3.micro",numCacheNodes:1,engine:"redis",engineVersion:"7.0"}},security:{certificate:o?{domain:o,subdomains:[`*.${o}`],validationMethod:"DNS"}:void 0}}}}function eb(n){let{name:i,slug:s,domain:o,taskCpu:c="256",taskMemory:u="512",desiredCount:d=2}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:o}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:2,natGateways:0}},compute:{fargate:{taskDefinition:{cpu:c,memory:u,containerDefinitions:[{name:"app",image:`${s}-app:latest`,portMappings:[{containerPort:3000}],environment:[],secrets:[]}]},service:{desiredCount:d,healthCheck:{path:"/health",interval:30,timeout:5,healthyThreshold:2,unhealthyThreshold:3},autoScaling:{min:d,max:d*5,targetCPU:70,targetMemory:80}},loadBalancer:{type:"application"}}},databases:{dynamodb:{tables:{[`${s}-main`]:{partitionKey:{name:"id",type:"S"},sortKey:{name:"createdAt",type:"S"},billingMode:"PAY_PER_REQUEST",streamEnabled:!0,pointInTimeRecovery:!0}}}},functions:{"process-queue":{runtime:"nodejs20.x",handler:"dist/workers/queue.handler",memory:512,timeout:60,events:[{type:"sqs",queueName:`${s}-queue`}]}},security:{certificate:o?{domain:o,subdomains:[`*.${o}`],validationMethod:"DNS"}:void 0}}}}function tb(n){let{name:i,slug:s,entry:o,domain:c,runtime:u="nodejs20.x",memory:d=1024,build:g,deploy:y,assets:h,queues:b=!0,scheduler:v="on",region:A="us-east-1"}=n;return{project:{name:i,slug:s,region:A},mode:"serverless",environments:{production:{type:"production",domain:c,app:{kind:"node",runtime:u,entry:o,memory:d,build:g,deploy:y,assets:h,queues:b,scheduler:v,domain:c}}}}}function hl(n){let i=n.database!==!1,s=n.cache!==!1,o=n.queue!==!1;return{project:{name:n.name,slug:n.slug,region:"us-east-1"},mode:"server",environments:{production:{type:"production",domain:n.domain}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:2,natGateways:1}},compute:{fargate:{taskDefinition:{cpu:"256",memory:"512",containerDefinitions:[{name:"api",image:n.imageUri,portMappings:[{containerPort:3000}],environment:[{name:"NODE_ENV",value:"production"},{name:"PORT",value:"3000"},{name:"AWS_REGION",value:e.ref("AWS::Region")},...i?[{name:"DB_HOST",value:e.getAtt("PostgresDb","Endpoint.Address")},{name:"DB_PORT",value:e.getAtt("PostgresDb","Endpoint.Port")}]:[],...s?[{name:"REDIS_HOST",value:e.getAtt("RedisReplicationGroup","PrimaryEndPoint.Address")},{name:"REDIS_PORT",value:e.getAtt("RedisReplicationGroup","PrimaryEndPoint.Port")},{name:"REDIS_TLS",value:"true"}]:[],...o?[{name:"QUEUE_URL",value:e.ref("JobsQueue")}]:[],{name:"MAIL_TRANSPORT",value:"ses"}],secrets:i?[{name:"DB_USERNAME",valueFrom:e.sub("${DBSecret}:username::")},{name:"DB_PASSWORD",valueFrom:e.sub("${DBSecret}:password::")}]:[]}]},service:{desiredCount:n.desiredCount||1,healthCheck:{path:"/api/health",interval:30,timeout:5},autoScaling:{min:n.desiredCount||1,max:6,targetCPU:70}},loadBalancer:{type:"application",...n.certificateArn?{customDomain:{domain:n.domain,certificateArn:n.certificateArn}}:{},...n.originVerifySecret?{originVerifyHeader:{name:"X-Origin-Verify",value:n.originVerifySecret}}:{}}}},...i?{databases:{postgres:{engine:"postgres",version:"16",instanceClass:"db.t4g.micro",allocatedStorage:20,maxAllocatedStorage:100,multiAZ:!1,backupRetentionDays:7,deletionProtection:!0}}}:{},...s?{cache:{redis:{nodeType:"cache.t4g.micro",numCacheNodes:2,engine:"redis",engineVersion:"7.1",automaticFailoverEnabled:!0,snapshotRetentionLimit:5}}}:{},...o?{queues:{jobs:{fifo:!1,visibilityTimeout:300,messageRetentionPeriod:345600,deadLetterQueue:!0,maxReceiveCount:3,receiveMessageWaitTime:20}}}:{}}}}function rb(n){let{name:i,slug:s,domain:o,apiSubdomain:c="api"}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"server",environments:{production:{type:"production",domain:o}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:2,natGateways:1}},storage:{frontend:{public:!0,versioning:!0,website:!0,encryption:!1}},cdn:{enabled:!0,customDomain:{domain:o,certificateArn:"TO_BE_GENERATED"},cachePolicy:{minTTL:0,defaultTTL:86400,maxTTL:31536000},compress:!0,http3:!0,errorPages:{404:"/index.html"}},compute:{fargate:{taskDefinition:{cpu:"512",memory:"1024",containerDefinitions:[{name:"api",image:`${s}-api:latest`,portMappings:[{containerPort:3000}]}]},service:{desiredCount:2,healthCheck:{path:"/api/health",interval:30},autoScaling:{min:2,max:10,targetCPU:70}},loadBalancer:{type:"application",customDomain:{domain:`${c}.${o}`,certificateArn:"TO_BE_GENERATED"}}}},databases:{postgres:{engine:"postgres",version:"15",instanceClass:"db.t3.small",allocatedStorage:50,multiAZ:!0,backupRetentionDays:14,deletionProtection:!0}},cache:{redis:{nodeType:"cache.t3.small",numCacheNodes:2,engine:"redis",engineVersion:"7.0"}},queues:{jobs:{fifo:!1,visibilityTimeout:300,messageRetentionPeriod:345600,deadLetterQueue:!0}},security:{certificate:{domain:o,subdomains:[`*.${o}`],validationMethod:"DNS"},waf:{enabled:!0,rules:["rateLimit","sqlInjection","xss"]}}}}}function nb(n){let{name:i,slug:s,domain:o}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:o}},infrastructure:{apiGateway:{type:"HTTP",cors:{allowOrigins:["*"],allowMethods:["GET","POST","PUT","DELETE","PATCH"],allowHeaders:["Content-Type","Authorization"],maxAge:3600},customDomain:o?{domain:o,certificateArn:"TO_BE_GENERATED"}:void 0,throttling:{rateLimit:1e4,burstLimit:5000},authorizer:{type:"JWT",identitySource:"$request.header.Authorization"}},functions:{users:{runtime:"nodejs20.x",handler:"dist/api/users.handler",memory:512,timeout:30,events:[{type:"http",path:"/users",method:"GET"},{type:"http",path:"/users",method:"POST"}]},products:{runtime:"nodejs20.x",handler:"dist/api/products.handler",memory:512,timeout:30,events:[{type:"http",path:"/products",method:"GET"}]}},databases:{dynamodb:{tables:{[`${s}-users`]:{partitionKey:{name:"userId",type:"S"},billingMode:"PAY_PER_REQUEST",streamEnabled:!0,pointInTimeRecovery:!0,globalSecondaryIndexes:[{name:"EmailIndex",partitionKey:{name:"email",type:"S"},projection:"ALL"}]},[`${s}-products`]:{partitionKey:{name:"productId",type:"S"},sortKey:{name:"category",type:"S"},billingMode:"PAY_PER_REQUEST",streamEnabled:!1}}}},cache:{elasticache:{nodeType:"cache.t3.micro",numCacheNodes:1,engine:"redis",engineVersion:"7.0"}},security:{certificate:o?{domain:o,validationMethod:"DNS"}:void 0,waf:{enabled:!0,rules:["rateLimit","sqlInjection"]}},monitoring:{alarms:[{metric:"Errors",threshold:10,period:300,evaluationPeriods:1},{metric:"Duration",threshold:3000,period:300,evaluationPeriods:2}]}}}}function ib(n){let{name:i,slug:s,domain:o,instanceType:c="t3.small"}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"server",environments:{production:{type:"production",domain:o}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:2,natGateways:1}},compute:{server:{instanceType:c,ami:"ubuntu-22.04",keyPair:`${s}-key`,autoScaling:{min:2,max:6,desired:2,targetCPU:75},loadBalancer:{type:"application",healthCheck:{path:"/wp-admin/install.php",interval:30}},userData:{packages:["nginx","php8.1-fpm","php8.1-mysql","php8.1-curl","php8.1-gd","php8.1-mbstring","php8.1-xml","php8.1-zip"],commands:["cd /var/www","wget https://wordpress.org/latest.tar.gz","tar -xzf latest.tar.gz","chown -R www-data:www-data wordpress","rm /etc/nginx/sites-enabled/default","systemctl restart nginx","systemctl restart php8.1-fpm"]}}},fileSystem:{uploads:{performanceMode:"generalPurpose",throughputMode:"bursting",encrypted:!0,lifecyclePolicy:{transitionToIA:30},mountPath:"/var/www/wordpress/wp-content/uploads"}},databases:{mysql:{engine:"mysql",version:"8.0",instanceClass:"db.t3.small",allocatedStorage:50,multiAZ:!0,backupRetentionDays:7,deletionProtection:!0,databaseName:"wordpress"}},cache:{redis:{nodeType:"cache.t3.micro",numCacheNodes:1,engine:"redis",engineVersion:"7.0"}},cdn:{enabled:!0,customDomain:{domain:o,certificateArn:"TO_BE_GENERATED"},cachePolicy:{minTTL:0,defaultTTL:86400,maxTTL:31536000},compress:!0,origins:[{type:"alb",pathPattern:"/wp-content/*"}]},security:{certificate:{domain:o,subdomains:[`www.${o}`],validationMethod:"DNS"},waf:{enabled:!0,rules:["rateLimit","sqlInjection","xss","wordpressRules"]}}}}}function sb(n){let{name:i,slug:s,domain:o,apiDomain:c}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:o}},infrastructure:{storage:{static:{public:!0,versioning:!0,website:!0,encryption:!1,cors:[{allowedOrigins:["*"],allowedMethods:["GET","HEAD"]}],lifecycleRules:[{id:"DeleteOldVersions",enabled:!0,expirationDays:90}]}},cdn:{enabled:!0,customDomain:{domain:o,certificateArn:"TO_BE_GENERATED"},cachePolicy:{minTTL:0,defaultTTL:0,maxTTL:31536000},compress:!0,http3:!0,errorPages:{404:"/404.html",500:"/500.html"},edgeFunctions:[{eventType:"origin-request",functionArn:"TO_BE_CREATED",name:"ssr-handler"}]},functions:{ssr:{runtime:"nodejs20.x",handler:"dist/edge/ssr.handler",memory:512,timeout:5},...c?{api:{runtime:"nodejs20.x",handler:"dist/api/index.handler",memory:1024,timeout:30,events:[{type:"http",path:"/{proxy+}",method:"ANY"}]}}:{}},apiGateway:c?{type:"HTTP",customDomain:{domain:c,certificateArn:"TO_BE_GENERATED"},cors:{allowOrigins:[o],allowMethods:["GET","POST","PUT","DELETE"],allowHeaders:["Content-Type","Authorization"]}}:void 0,databases:{dynamodb:{tables:{content:{partitionKey:{name:"id",type:"S"},sortKey:{name:"type",type:"S"},billingMode:"PAY_PER_REQUEST",streamEnabled:!1}}}},security:{certificate:{domain:o,subdomains:c?[c]:[],validationMethod:"DNS"},waf:{enabled:!0,rules:["rateLimit","geoBlock"]}}}}}function ob(n){let{name:i,slug:s,domain:o,services:c}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:o}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:3,natGateways:2}},compute:{services:c.map((u)=>({name:u.name,type:"fargate",taskDefinition:{cpu:u.cpu||"256",memory:u.memory||"512",containerDefinitions:[{name:u.name,image:`${s}-${u.name}:latest`,portMappings:[{containerPort:u.port}],healthCheck:{command:["CMD-SHELL",`curl -f http://localhost:${u.port}/health || exit 1`],interval:30,timeout:5,retries:3}}]},service:{desiredCount:u.desiredCount||2,serviceDiscovery:{enabled:!0,namespace:`${s}.local`},autoScaling:{min:2,max:10,targetCPU:70}}}))},apiGateway:{type:"HTTP",customDomain:{domain:o,certificateArn:"TO_BE_GENERATED"},cors:{allowOrigins:["*"],allowMethods:["GET","POST","PUT","DELETE","PATCH"]},routes:c.map((u)=>({path:`/${u.name}/{proxy+}`,integration:{type:"vpc-link",service:u.name}}))},databases:{dynamodb:{tables:Object.fromEntries(c.map((u)=>[`${s}-${u.name}`,{partitionKey:{name:"id",type:"S"},billingMode:"PAY_PER_REQUEST",streamEnabled:!0,pointInTimeRecovery:!0}]))}},queues:{events:{fifo:!1,visibilityTimeout:300,messageRetentionPeriod:345600,deadLetterQueue:!0}},messaging:{topics:{events:{name:`${s}-events`,subscriptions:c.map((u)=>({protocol:"sqs",endpoint:`${s}-${u.name}-queue`,filterPolicy:{service:[u.name]}}))}}},monitoring:{dashboard:{name:`${s}-microservices`,widgets:c.map((u)=>({type:"metric",metrics:[{service:u.name,metric:"CPUUtilization"},{service:u.name,metric:"MemoryUtilization"},{service:u.name,metric:"RequestCount"}]}))},alarms:c.flatMap((u)=>[{name:`${u.name}-high-cpu`,metric:"CPUUtilization",threshold:80,service:u.name},{name:`${u.name}-errors`,metric:"Errors",threshold:10,service:u.name}])},security:{certificate:{domain:o,validationMethod:"DNS"},waf:{enabled:!0,rules:["rateLimit","sqlInjection"]}}}}}function ab(n){let{name:i,slug:s,domain:o}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:o}},infrastructure:{apiGateway:{type:"websocket",customDomain:o?{domain:o,certificateArn:"TO_BE_GENERATED"}:void 0,routes:[{path:"$connect",method:"WEBSOCKET",integration:"websocket-connect"},{path:"$disconnect",method:"WEBSOCKET",integration:"websocket-disconnect"},{path:"$default",method:"WEBSOCKET",integration:"websocket-default"},{path:"sendMessage",method:"WEBSOCKET",integration:"websocket-send-message"},{path:"joinRoom",method:"WEBSOCKET",integration:"websocket-join-room"}]},functions:{connect:{runtime:"nodejs20.x",handler:"dist/websocket/connect.handler",memory:512,timeout:30},disconnect:{runtime:"nodejs20.x",handler:"dist/websocket/disconnect.handler",memory:512,timeout:30},default:{runtime:"nodejs20.x",handler:"dist/websocket/default.handler",memory:512,timeout:30},"send-message":{runtime:"nodejs20.x",handler:"dist/websocket/sendMessage.handler",memory:512,timeout:30},"join-room":{runtime:"nodejs20.x",handler:"dist/websocket/joinRoom.handler",memory:512,timeout:30},broadcast:{runtime:"nodejs20.x",handler:"dist/streams/broadcast.handler",memory:1024,timeout:60,events:[{type:"dynamodb-stream",tableName:`${s}-messages`,startingPosition:"LATEST",batchSize:100}]}},databases:{dynamodb:{tables:{[`${s}-connections`]:{partitionKey:{name:"connectionId",type:"S"},billingMode:"PAY_PER_REQUEST",globalSecondaryIndexes:[{name:"RoomIndex",partitionKey:{name:"roomId",type:"S"},sortKey:{name:"connectionId",type:"S"},projection:"ALL"}]},[`${s}-messages`]:{partitionKey:{name:"roomId",type:"S"},sortKey:{name:"timestamp",type:"S"},billingMode:"PAY_PER_REQUEST",streamEnabled:!0,pointInTimeRecovery:!0,globalSecondaryIndexes:[{name:"UserIndex",partitionKey:{name:"userId",type:"S"},sortKey:{name:"timestamp",type:"S"},projection:"ALL"}]},[`${s}-rooms`]:{partitionKey:{name:"roomId",type:"S"},billingMode:"PAY_PER_REQUEST"}}}},cache:{elasticache:{nodeType:"cache.t3.small",numCacheNodes:2,engine:"redis",engineVersion:"7.0"}},monitoring:{alarms:[{metric:"WebSocketConnections",threshold:1e4,evaluationPeriods:1},{metric:"IntegrationLatency",threshold:1000,evaluationPeriods:2}],dashboard:{name:`${s}-realtime`,widgets:[{type:"metric",metrics:["WebSocketConnections","MessagesSent","IntegrationLatency"]}]}},security:{certificate:o?{domain:o,validationMethod:"DNS"}:void 0,waf:{enabled:!0,rules:["rateLimit","connectionLimit"]}}}}}function cb(n){let{name:i,slug:s,retentionDays:o=7}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"serverless",infrastructure:{streaming:{dataStream:{name:`${s}-stream`,shardCount:2,retentionPeriod:o*24,encryption:!0}},storage:{raw:{public:!1,versioning:!0,encryption:!0,intelligentTiering:!0,lifecycleRules:[{id:"ArchiveOldData",enabled:!0,transitions:[{days:30,storageClass:"GLACIER"},{days:90,storageClass:"DEEP_ARCHIVE"}]}]},processed:{public:!1,versioning:!0,encryption:!0,intelligentTiering:!0}},functions:{"stream-processor":{runtime:"nodejs20.x",handler:"dist/processors/stream.handler",memory:2048,timeout:300,events:[{type:"kinesis",streamName:`${s}-stream`,batchSize:1000,startingPosition:"LATEST",parallelizationFactor:10}]},transformer:{runtime:"nodejs20.x",handler:"dist/processors/transform.handler",memory:3008,timeout:900,events:[{type:"s3",bucket:`${s}-raw`,prefix:"incoming/"}]},aggregator:{runtime:"nodejs20.x",handler:"dist/processors/aggregate.handler",memory:2048,timeout:600,events:[{type:"schedule",expression:"cron(0 * * * ? *)"}]}},analytics:{athena:{database:`${s}_analytics`,workgroup:`${s}-workgroup`,outputBucket:`${s}-query-results`,tables:[{name:"raw_events",location:`s3://${s}-raw/events/`,format:"parquet",partitionKeys:["year","month","day"]},{name:"processed_events",location:`s3://${s}-processed/events/`,format:"parquet",partitionKeys:["year","month","day"]}]},glue:{crawlers:[{name:`${s}-crawler`,databaseName:`${s}_analytics`,s3Targets:[`s3://${s}-raw/`,`s3://${s}-processed/`],schedule:"cron(0 2 * * ? *)"}],jobs:[{name:`${s}-etl-job`,scriptLocation:`s3://${s}-scripts/etl.py`,role:`${s}-glue-role`,maxCapacity:10,timeout:120}]}},databases:{dynamodb:{tables:{[`${s}-metadata`]:{partitionKey:{name:"pipelineId",type:"S"},sortKey:{name:"timestamp",type:"S"},billingMode:"PAY_PER_REQUEST"}}}},queues:{failedJobs:{fifo:!1,visibilityTimeout:900,messageRetentionPeriod:1209600,deadLetterQueue:!0,maxReceiveCount:3}},workflow:{pipelines:[{name:`${s}-daily-pipeline`,type:"stepFunctions",definition:{StartAt:"ExtractData",States:{ExtractData:{Type:"Task",Resource:"arn:aws:states:::lambda:invoke",Next:"TransformData"},TransformData:{Type:"Task",Resource:"arn:aws:states:::lambda:invoke",Next:"LoadData"},LoadData:{Type:"Task",Resource:"arn:aws:states:::lambda:invoke",End:!0}}},schedule:"cron(0 0 * * ? *)"}]},monitoring:{dashboard:{name:`${s}-pipeline`,widgets:[{type:"metric",metrics:["KinesisIncomingRecords","LambdaInvocations","S3ObjectsCreated","GlueJobsSucceeded"]}]},alarms:[{metric:"LambdaErrors",threshold:10,evaluationPeriods:1},{metric:"KinesisIteratorAge",threshold:60000,evaluationPeriods:2}]}}}}function db(n){let{name:i,slug:s,domain:o,modelS3Path:c=`s3://${s}-models/`,instanceType:u="ml.t3.medium"}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:o}},infrastructure:{storage:{models:{public:!1,versioning:!0,encryption:!0,intelligentTiering:!0},datasets:{public:!1,versioning:!0,encryption:!0,lifecycleRules:[{id:"ArchiveOldDatasets",enabled:!0,transitions:[{days:90,storageClass:"GLACIER"}]}]},predictions:{public:!1,versioning:!1,encryption:!0,lifecycleRules:[{id:"DeleteOldPredictions",enabled:!0,expirationDays:30}]}},machineLearning:{sagemaker:{endpoints:[{name:`${s}-inference`,modelS3Path:c,instanceType:u,initialInstanceCount:1,autoScaling:{minInstances:1,maxInstances:5,targetInvocationsPerInstance:1000}}],trainingJobs:[{name:`${s}-training`,algorithmSpecification:{trainingImage:"TO_BE_SPECIFIED",trainingInputMode:"File"},instanceType:"ml.p3.2xlarge",instanceCount:1,volumeSizeInGB:50,maxRuntimeInSeconds:86400}]}},apiGateway:{type:"HTTP",customDomain:o?{domain:o,certificateArn:"TO_BE_GENERATED"}:void 0,cors:{allowOrigins:["*"],allowMethods:["POST"],allowHeaders:["Content-Type","Authorization"]},throttling:{rateLimit:1000,burstLimit:500}},functions:{predict:{runtime:"python3.11",handler:"handlers/predict.handler",memory:2048,timeout:60,events:[{type:"http",path:"/predict",method:"POST"}],environment:{SAGEMAKER_ENDPOINT:`${s}-inference`,MODEL_BUCKET:`${s}-models`}},"batch-predict":{runtime:"python3.11",handler:"handlers/batchPredict.handler",memory:3008,timeout:900,events:[{type:"s3",bucket:`${s}-datasets`,suffix:".csv"}]},"trigger-training":{runtime:"python3.11",handler:"handlers/training.handler",memory:1024,timeout:300,events:[{type:"schedule",expression:"cron(0 2 * * ? *)"}]}},databases:{dynamodb:{tables:{[`${s}-predictions`]:{partitionKey:{name:"requestId",type:"S"},sortKey:{name:"timestamp",type:"S"},billingMode:"PAY_PER_REQUEST",streamEnabled:!0},[`${s}-models`]:{partitionKey:{name:"modelId",type:"S"},sortKey:{name:"version",type:"S"},billingMode:"PAY_PER_REQUEST"}}}},queues:{predictions:{fifo:!1,visibilityTimeout:300,messageRetentionPeriod:86400,deadLetterQueue:!0}},monitoring:{dashboard:{name:`${s}-ml`,widgets:[{type:"metric",metrics:["SageMakerInvocations","SageMakerModelLatency","APIGatewayRequests","LambdaErrors"]}]},alarms:[{metric:"SageMakerModelLatency",threshold:1000,evaluationPeriods:2},{metric:"SageMakerInvocationErrors",threshold:10,evaluationPeriods:1}]},security:{certificate:o?{domain:o,validationMethod:"DNS"}:void 0,waf:{enabled:!0,rules:["rateLimit","apiProtection"]}}}}}function lb(n){let{name:i,slug:s,domain:o,instanceType:c="t3.medium",minInstances:u=2,maxInstances:d=10,databaseEngine:g="mysql",sessionStore:y="redis"}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"server",environments:{production:{type:"production",domain:o}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:2,natGateways:2}},compute:{server:{instanceType:c,ami:"ubuntu-22.04",autoScaling:{min:u,max:d,targetCPU:70,scaleUpCooldown:300,scaleDownCooldown:300},loadBalancer:{type:"application",healthCheck:{path:"/health",interval:30,timeout:5,healthyThreshold:2,unhealthyThreshold:3},stickySession:{enabled:!0,duration:86400}},userData:`#!/bin/bash
2454
+ | limit 20`,region:e.ref("AWS::Region"),title:`Logs: ${u.logGroup}`}});else if(u.type==="text"&&u.text)s.push({type:"text",x:o,y:c,width:d,height:g,properties:{markdown:u.text}});if(o+=d,o>=24)o=0,c+=g}),n.addResource("CloudWatchDashboard","AWS::CloudWatch::Dashboard",{DashboardName:e.sub(`\${AWS::StackName}-${i.name}`),DashboardBody:JSON.stringify({widgets:s})}),n.addOutputs({DashboardURL:{Description:"CloudWatch Dashboard URL",Value:e.sub("https://console.aws.amazon.com/cloudwatch/home?region=${AWS::Region}#dashboards:name=${CloudWatchDashboard}")}})}function ei(n,i,s){let o=n.toLogicalId(`${i}-log-group`);n.addResource(o,"AWS::Logs::LogGroup",{LogGroupName:e.sub(`/aws/\${AWS::StackName}/${i}`),RetentionInDays:s||14,Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${i}`)}]})}function Pt(n,i){if(i)return{ec2:"AWS/EC2",ecs:"AWS/ECS",lambda:"AWS/Lambda",rds:"AWS/RDS",dynamodb:"AWS/DynamoDB",s3:"AWS/S3",cloudfront:"AWS/CloudFront",alb:"AWS/ApplicationELB",nlb:"AWS/NetworkELB",apigateway:"AWS/ApiGateway",sqs:"AWS/SQS",sns:"AWS/SNS",kinesis:"AWS/Kinesis",elasticache:"AWS/ElastiCache"}[i.toLowerCase()]||"AWS/CloudWatch";let s=n.toLowerCase();if(s.includes("cpu")||s.includes("memory")||s.includes("network"))return"AWS/EC2";if(s.includes("lambda")||s.includes("invocation")||s.includes("duration"))return"AWS/Lambda";if(s.includes("request")||s.includes("latency")||s.includes("target"))return"AWS/ApplicationELB";if(s.includes("database")||s.includes("connection"))return"AWS/RDS";if(s.includes("read")||s.includes("write")||s.includes("consumed"))return"AWS/DynamoDB";return"AWS/CloudWatch"}function ti(n){return{ec2:[{Name:"InstanceId",Value:e.ref("EC2Instance")}],ecs:[{Name:"ClusterName",Value:e.ref("ECSCluster")},{Name:"ServiceName",Value:e.getAtt("ECSService","Name")}],lambda:[{Name:"FunctionName",Value:e.ref("LambdaFunction")}],rds:[{Name:"DBInstanceIdentifier",Value:e.ref("Database")}],dynamodb:[{Name:"TableName",Value:e.ref("DynamoDBTable")}],alb:[{Name:"LoadBalancer",Value:e.getAtt("LoadBalancer","LoadBalancerFullName")}],apigateway:[{Name:"ApiName",Value:e.ref("HttpApi")}]}[n.toLowerCase()]||[]}function Dn(n,i){if(!i.vpc)return;let{cidr:s="10.0.0.0/16",availabilityZones:o=2,natGateways:c=1,enableDnsHostnames:u=!0,enableDnsSupport:d=!0}=i.vpc;n.addResource("VPC","AWS::EC2::VPC",{CidrBlock:s,EnableDnsHostnames:u,EnableDnsSupport:d,Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-vpc")}]}),n.addResource("InternetGateway","AWS::EC2::InternetGateway",{Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-igw")}]}),n.addResource("VPCGatewayAttachment","AWS::EC2::VPCGatewayAttachment",{VpcId:e.ref("VPC"),InternetGatewayId:e.ref("InternetGateway")},{dependsOn:["VPC","InternetGateway"]});let g=[];for(let v=0;v<o;v++){let A=`PublicSubnet${v+1}`;g.push(A),n.addResource(A,"AWS::EC2::Subnet",{VpcId:e.ref("VPC"),CidrBlock:e.select(v,e.cidr(e.getAtt("VPC","CidrBlock"),o*2,8)),AvailabilityZone:e.select(v,e.getAZs()),MapPublicIpOnLaunch:!0,Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-public-${v+1}`)},{Key:"Type",Value:"public"}]},{dependsOn:"VPC"})}let y=[];for(let v=0;v<o;v++){let A=`PrivateSubnet${v+1}`;y.push(A),n.addResource(A,"AWS::EC2::Subnet",{VpcId:e.ref("VPC"),CidrBlock:e.select(v+o,e.cidr(e.getAtt("VPC","CidrBlock"),o*2,8)),AvailabilityZone:e.select(v,e.getAZs()),MapPublicIpOnLaunch:!1,Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-private-${v+1}`)},{Key:"Type",Value:"private"}]},{dependsOn:"VPC"})}let h=[];for(let v=0;v<c;v++){let A=`NatEIP${v+1}`;h.push(A),n.addResource(A,"AWS::EC2::EIP",{Domain:"vpc",Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-nat-eip-${v+1}`)}]},{dependsOn:"VPCGatewayAttachment"})}let b=[];for(let v=0;v<c;v++){let A=`NatGateway${v+1}`;b.push(A);let T=v%o;n.addResource(A,"AWS::EC2::NatGateway",{AllocationId:e.getAtt(h[v],"AllocationId"),SubnetId:e.ref(g[T]),Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-nat-${v+1}`)}]},{dependsOn:[h[v],g[T]]})}n.addResource("PublicRouteTable","AWS::EC2::RouteTable",{VpcId:e.ref("VPC"),Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-public-rt")}]},{dependsOn:"VPC"}),n.addResource("PublicRoute","AWS::EC2::Route",{RouteTableId:e.ref("PublicRouteTable"),DestinationCidrBlock:"0.0.0.0/0",GatewayId:e.ref("InternetGateway")},{dependsOn:["PublicRouteTable","VPCGatewayAttachment"]}),g.forEach((v,A)=>{n.addResource(`PublicSubnetRouteTableAssociation${A+1}`,"AWS::EC2::SubnetRouteTableAssociation",{SubnetId:e.ref(v),RouteTableId:e.ref("PublicRouteTable")},{dependsOn:[v,"PublicRouteTable"]})}),y.forEach((v,A)=>{let T=`PrivateRouteTable${A+1}`,R=A%c;n.addResource(T,"AWS::EC2::RouteTable",{VpcId:e.ref("VPC"),Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-private-rt-${A+1}`)}]},{dependsOn:"VPC"}),n.addResource(`PrivateRoute${A+1}`,"AWS::EC2::Route",{RouteTableId:e.ref(T),DestinationCidrBlock:"0.0.0.0/0",NatGatewayId:e.ref(b[R])},{dependsOn:[T,b[R]]}),n.addResource(`PrivateSubnetRouteTableAssociation${A+1}`,"AWS::EC2::SubnetRouteTableAssociation",{SubnetId:e.ref(v),RouteTableId:e.ref(T)},{dependsOn:[v,T]})}),n.addResource("S3VPCEndpoint","AWS::EC2::VPCEndpoint",{VpcId:e.ref("VPC"),ServiceName:e.sub("com.amazonaws.${AWS::Region}.s3"),VpcEndpointType:"Gateway",RouteTableIds:[e.ref("PublicRouteTable"),...Array.from({length:o},(v,A)=>e.ref(`PrivateRouteTable${A+1}`))]},{dependsOn:"VPC"}),n.addResource("NetworkAcl","AWS::EC2::NetworkAcl",{VpcId:e.ref("VPC"),Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-nacl")}]},{dependsOn:"VPC"}),n.addResource("NetworkAclEntryInbound","AWS::EC2::NetworkAclEntry",{NetworkAclId:e.ref("NetworkAcl"),RuleNumber:100,Protocol:-1,RuleAction:"allow",CidrBlock:"0.0.0.0/0"},{dependsOn:"NetworkAcl"}),n.addResource("NetworkAclEntryOutbound","AWS::EC2::NetworkAclEntry",{NetworkAclId:e.ref("NetworkAcl"),RuleNumber:100,Protocol:-1,Egress:!0,RuleAction:"allow",CidrBlock:"0.0.0.0/0"},{dependsOn:"NetworkAcl"}),n.addOutputs({VPCId:{Description:"VPC ID",Value:e.ref("VPC"),Export:{Name:e.sub("${AWS::StackName}-VPC")}},PublicSubnets:{Description:"Public subnet IDs",Value:e.join(",",g.map((v)=>e.ref(v))),Export:{Name:e.sub("${AWS::StackName}-PublicSubnets")}},PrivateSubnets:{Description:"Private subnet IDs",Value:e.join(",",y.map((v)=>e.ref(v))),Export:{Name:e.sub("${AWS::StackName}-PrivateSubnets")}}})}function Nn(n,i){for(let[s,o]of Object.entries(i))ni(n,s,o)}function ni(n,i,s){let o=n.toLogicalId(`${i}-queue`),c=s.fifo||!1,u;if(s.deadLetterQueue){let g=`${o}DLQ`;n.addResource(g,"AWS::SQS::Queue",{QueueName:c?e.sub(`\${AWS::StackName}-${i}-dlq.fifo`):e.sub(`\${AWS::StackName}-${i}-dlq`),FifoQueue:c,MessageRetentionPeriod:1209600,Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${i}-dlq`)}]},{deletionPolicy:"Retain",updateReplacePolicy:"Retain"}),u=e.getAtt(g,"Arn")}let d={QueueName:c?e.sub(`\${AWS::StackName}-${i}.fifo`):e.sub(`\${AWS::StackName}-${i}`),FifoQueue:c,VisibilityTimeout:s.visibilityTimeout||30,MessageRetentionPeriod:s.messageRetentionPeriod||345600,ReceiveMessageWaitTimeSeconds:s.receiveMessageWaitTime||0,Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${i}`)}]};if(c&&s.contentBasedDeduplication)d.ContentBasedDeduplication=!0;if(s.deadLetterQueue&&u)d.RedrivePolicy={deadLetterTargetArn:u,maxReceiveCount:s.maxReceiveCount||3};if(n.addResource(o,"AWS::SQS::Queue",d,{dependsOn:s.deadLetterQueue?`${o}DLQ`:void 0,deletionPolicy:"Retain",updateReplacePolicy:"Retain"}),n.addResource(`${o}Policy`,"AWS::SQS::QueuePolicy",{Queues:[e.ref(o)],PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:["lambda.amazonaws.com","events.amazonaws.com","sns.amazonaws.com"]},Action:"sqs:SendMessage",Resource:e.getAtt(o,"Arn"),Condition:{ArnEquals:{"aws:SourceArn":e.sub("arn:aws:*:${AWS::Region}:${AWS::AccountId}:*")}}}]}},{dependsOn:o}),n.addOutputs({[`${o}Url`]:{Description:`${i} queue URL`,Value:e.ref(o),Export:{Name:e.sub(`\${AWS::StackName}-${i}-queue-url`)}},[`${o}Arn`]:{Description:`${i} queue ARN`,Value:e.getAtt(o,"Arn"),Export:{Name:e.sub(`\${AWS::StackName}-${i}-queue-arn`)}}}),s.deadLetterQueue)n.addOutputs({[`${o}DLQUrl`]:{Description:`${i} dead letter queue URL`,Value:e.ref(`${o}DLQ`),Export:{Name:e.sub(`\${AWS::StackName}-${i}-dlq-url`)}}})}function xn(n,i){if(i.certificate)ri(n,i.certificate);if(i.waf?.enabled)ii(n,i.waf);if(i.securityGroups)for(let[s,o]of Object.entries(i.securityGroups))si(n,s,o)}function ri(n,i){if(!i)return;let s=[i.domain];if(i.subdomains)s.push(...i.subdomains);n.addResource("Certificate","AWS::CertificateManager::Certificate",{DomainName:i.domain,SubjectAlternativeNames:i.subdomains,ValidationMethod:i.validationMethod||"DNS",DomainValidationOptions:s.map((o)=>({DomainName:o,HostedZoneId:e.ref("HostedZone")})),Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-certificate")}]}),n.addOutputs({CertificateArn:{Description:"ACM Certificate ARN",Value:e.ref("Certificate"),Export:{Name:e.sub("${AWS::StackName}-certificate-arn")}}})}function ii(n,i){if(!i)return;let s=[],o=i.rules||["rateLimit","sqlInjection","xss"];if(o.includes("rateLimit"))s.push({Name:"RateLimitRule",Priority:1,Statement:{RateBasedStatement:{Limit:i.rateLimit||2000,AggregateKeyType:"IP"}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"RateLimitRule"}});let c=s.length+1;if(o.includes("sqlInjection"))s.push({Name:"AWSManagedRulesSQLi",Priority:c++,Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:"AWSManagedRulesSQLiRuleSet"}},OverrideAction:{None:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"AWSManagedRulesSQLi"}});if(o.includes("xss"))s.push({Name:"AWSManagedRulesXSS",Priority:c++,Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:"AWSManagedRulesKnownBadInputsRuleSet"}},OverrideAction:{None:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"AWSManagedRulesXSS"}});if(o.includes("knownBadInputs"))s.push({Name:"AWSManagedRulesKnownBadInputs",Priority:c++,Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:"AWSManagedRulesKnownBadInputsRuleSet"}},OverrideAction:{None:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"AWSManagedRulesKnownBadInputs"}});if(o.includes("coreRuleSet"))s.push({Name:"AWSManagedRulesCoreRuleSet",Priority:c++,Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:"AWSManagedRulesCommonRuleSet"}},OverrideAction:{None:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"AWSManagedRulesCoreRuleSet"}});if(o.includes("linuxRuleSet"))s.push({Name:"AWSManagedRulesLinuxRuleSet",Priority:c++,Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:"AWSManagedRulesLinuxRuleSet"}},OverrideAction:{None:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"AWSManagedRulesLinuxRuleSet"}});if(o.includes("apiProtection"))s.push({Name:"AWSManagedRulesAPIProtection",Priority:c++,Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:"AWSManagedRulesAmazonIpReputationList"}},OverrideAction:{None:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"AWSManagedRulesAPIProtection"}});if(o.includes("geoBlock"))s.push({Name:"GeoBlockRule",Priority:c++,Statement:{GeoMatchStatement:{CountryCodes:["CN","RU"]}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"GeoBlockRule"}});if(o.includes("connectionLimit"))s.push({Name:"ConnectionLimitRule",Priority:c++,Statement:{RateBasedStatement:{Limit:100,AggregateKeyType:"IP"}},Action:{Block:{}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:"ConnectionLimitRule"}});if(n.addResource("WebACL","AWS::WAFv2::WebACL",{Name:e.sub("${AWS::StackName}-waf"),Scope:i.scope||"REGIONAL",DefaultAction:{Allow:{}},Rules:s,VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:e.sub("${AWS::StackName}-waf")},Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-waf")}]}),n.hasResource("LoadBalancer"))n.addResource("WebACLAssociation","AWS::WAFv2::WebACLAssociation",{ResourceArn:e.ref("LoadBalancer"),WebACLArn:e.getAtt("WebACL","Arn")},{dependsOn:["WebACL","LoadBalancer"]});n.addOutputs({WebACLId:{Description:"WAF Web ACL ID",Value:e.ref("WebACL"),Export:{Name:e.sub("${AWS::StackName}-waf-id")}},WebACLArn:{Description:"WAF Web ACL ARN",Value:e.getAtt("WebACL","Arn"),Export:{Name:e.sub("${AWS::StackName}-waf-arn")}}})}function si(n,i,s){if(!s)return;let o=n.toLogicalId(`${i}-security-group`),c=s.ingress?.map((d)=>({IpProtocol:d.protocol,FromPort:d.port,ToPort:d.port,CidrIp:d.cidr,SourceSecurityGroupId:d.source?e.ref(d.source):void 0}))||[],u=s.egress?.map((d)=>({IpProtocol:d.protocol,FromPort:d.port,ToPort:d.port,CidrIp:d.cidr||"0.0.0.0/0"}))||[{IpProtocol:"-1",CidrIp:"0.0.0.0/0"}];n.addResource(o,"AWS::EC2::SecurityGroup",{GroupDescription:`Security group for ${i}`,VpcId:e.ref("VPC"),SecurityGroupIngress:c,SecurityGroupEgress:u,Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${i}-sg`)}]},{dependsOn:"VPC"}),n.addOutputs({[`${o}Id`]:{Description:`${i} security group ID`,Value:e.ref(o),Export:{Name:e.sub(`\${AWS::StackName}-${i}-sg-id`)}}})}function kn(n,i){for(let[s,o]of Object.entries(i)){if(o.type==="efs"){oi(n,s,o);continue}ai(n,s,o)}}function ai(n,i,s){let o=n.toLogicalId(`${i}-bucket`),c={BucketName:e.sub(`\${AWS::StackName}-${i}`),Tags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${i}`)}]};if(s.versioning)c.VersioningConfiguration={Status:"Enabled"};if(s.encryption)c.BucketEncryption={ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]};if(!s.public)c.PublicAccessBlockConfiguration={BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0};if(s.website)c.WebsiteConfiguration={IndexDocument:"index.html",ErrorDocument:"index.html"};if(s.cors&&s.cors.length>0)c.CorsConfiguration={CorsRules:s.cors.map((u)=>({AllowedOrigins:u.allowedOrigins,AllowedMethods:u.allowedMethods,AllowedHeaders:u.allowedHeaders||["*"],MaxAge:u.maxAge||3600}))};if(s.lifecycleRules&&s.lifecycleRules.length>0)c.LifecycleConfiguration={Rules:s.lifecycleRules.map((u)=>({Id:u.id,Status:u.enabled?"Enabled":"Disabled",ExpirationInDays:u.expirationDays,Transitions:u.transitions?.map((d)=>({TransitionInDays:d.days,StorageClass:d.storageClass}))}))};if(s.intelligentTiering)c.IntelligentTieringConfigurations=[{Id:"EntireBucket",Status:"Enabled",Tierings:[{AccessTier:"ARCHIVE_ACCESS",Days:90},{AccessTier:"DEEP_ARCHIVE_ACCESS",Days:180}]}];if(n.addResource(o,"AWS::S3::Bucket",c,{deletionPolicy:s.versioning?"Retain":"Delete"}),s.public)n.addResource(`${o}Policy`,"AWS::S3::BucketPolicy",{Bucket:e.ref(o),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadGetObject",Effect:"Allow",Principal:"*",Action:"s3:GetObject",Resource:e.join("",[gn.s3Bucket(e.ref(o)),"/*"])}]}},{dependsOn:o});if(n.addOutputs({[`${o}Name`]:{Description:`${i} bucket name`,Value:e.ref(o),Export:{Name:e.sub(`\${AWS::StackName}-${i}-bucket`)}},[`${o}Arn`]:{Description:`${i} bucket ARN`,Value:e.getAtt(o,"Arn"),Export:{Name:e.sub(`\${AWS::StackName}-${i}-bucket-arn`)}}}),s.website)n.addOutputs({[`${o}WebsiteURL`]:{Description:`${i} website URL`,Value:e.getAtt(o,"WebsiteURL")}})}function oi(n,i,s){let o=n.toLogicalId(`${i}-efs`),c={Encrypted:s.encryption!==!1,PerformanceMode:s.performanceMode||"generalPurpose",ThroughputMode:s.throughputMode||"bursting",FileSystemTags:[{Key:"Name",Value:e.sub(`\${AWS::StackName}-${i}`)}]};if(s.lifecyclePolicy){if(c.LifecyclePolicies=[],s.lifecyclePolicy.transitionToIA)c.LifecyclePolicies.push({TransitionToIA:`AFTER_${s.lifecyclePolicy.transitionToIA}_DAYS`});if(s.lifecyclePolicy.transitionToPrimaryStorageClass)c.LifecyclePolicies.push({TransitionToPrimaryStorageClass:"AFTER_1_ACCESS"})}n.addResource(o,"AWS::EFS::FileSystem",c,{deletionPolicy:"Retain"});let u=2;for(let d=0;d<u;d++)n.addResource(`${o}MountTarget${d+1}`,"AWS::EFS::MountTarget",{FileSystemId:e.ref(o),SubnetId:e.ref(`PrivateSubnet${d+1}`),SecurityGroups:[e.ref("EFSSecurityGroup")]},{dependsOn:[o,`PrivateSubnet${d+1}`]});n.addResource("EFSSecurityGroup","AWS::EC2::SecurityGroup",{GroupDescription:"Security group for EFS mount targets",VpcId:e.ref("VPC"),SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:2049,ToPort:2049,SourceSecurityGroupId:e.ref("AppSecurityGroup")}],Tags:[{Key:"Name",Value:e.sub("${AWS::StackName}-efs-sg")}]},{dependsOn:"VPC"}),n.addOutputs({[`${o}Id`]:{Description:`${i} EFS file system ID`,Value:e.ref(o),Export:{Name:e.sub(`\${AWS::StackName}-${i}-efs`)}}})}class xm{template;config;resourceDependencies;constructor(n){this.config=n,this.resourceDependencies=new Map,this.template={AWSTemplateFormatVersion:"2010-09-09",Description:`Infrastructure for ${n.project.name} (${n.project.slug})`,Resources:{}}}build(){return this.addParameters(),this.addMappings(),this.addConditions(),this.addResources(),this.initializeOutputs(),this.resolveDependencies(),this.template}addParameters(){this.template.Parameters={Environment:{Type:"String",Default:"production",AllowedValues:["development","staging","production"],Description:"Environment name"}}}addMappings(){this.template.Mappings={RegionMap:{"us-east-1":{AMI:"ami-0f3caa1cf4417e51b"},"us-west-2":{AMI:"ami-0d1cd67c26f5fca19"},"eu-west-1":{AMI:"ami-0bbc25e23a7640b9b"}}}}addConditions(){this.template.Conditions={IsProduction:e.equals(e.ref("Environment"),"production"),HasDomain:e.not([e.equals(this.config.environments?.production?.domain||"","")])}}addResources(){let{infrastructure:n}=this.config;if(!n)return;if(n.network)this.addNetworkResources(n.network);if(n.storage)this.addStorageResources(n.storage);if(n.compute)this.addComputeResources(n.compute);if(n.databases)this.addDatabaseResources(n.databases);if(n.cache)this.addCacheResources(n.cache);if(n.cdn)this.addCDNResources(n.cdn);if(n.apiGateway)this.addApiGatewayResources(n.apiGateway);if(n.functions)this.addFunctionResources(n.functions);if(n.queues)this.addQueueResources(n.queues);if(n.messaging)this.addMessagingResources(n.messaging);if(n.monitoring)this.addMonitoringResources(n.monitoring);if(n.security)this.addSecurityResources(n.security)}initializeOutputs(){let n=this.template.Outputs||{};if(this.template.Outputs={StackName:{Description:"Stack name",Value:e.ref("AWS::StackName"),Export:{Name:e.sub("${AWS::StackName}-Name")}},Region:{Description:"AWS Region",Value:e.ref("AWS::Region"),Export:{Name:e.sub("${AWS::StackName}-Region")}},...n},this.config.environments?.production?.domain)this.template.Outputs.Domain={Description:"Production domain",Value:this.config.environments.production.domain,Condition:"HasDomain"}}addResource(n,i,s,o){let c={Type:i,Properties:s};if(o?.dependsOn)c.DependsOn=o.dependsOn,this.trackDependency(n,o.dependsOn);if(o?.condition)c.Condition=o.condition;if(o?.deletionPolicy)c.DeletionPolicy=o.deletionPolicy;if(o?.updateReplacePolicy)c.UpdateReplacePolicy=o.updateReplacePolicy;this.template.Resources[n]=c}addOutputs(n){this.template.Outputs={...this.template.Outputs,...n}}getOutputs(){return this.template.Outputs||{}}hasResource(n){return n in this.template.Resources}getResource(n){return this.template.Resources[n]}trackDependency(n,i){if(!this.resourceDependencies.has(n))this.resourceDependencies.set(n,new Set);(Array.isArray(i)?i:[i]).forEach((o)=>this.resourceDependencies.get(n).add(o))}resolveDependencies(){let n=new Set,i=new Set,s=(o)=>{if(i.has(o))throw Error(`Circular dependency detected involving resource: ${o}`);if(n.has(o))return!0;n.add(o),i.add(o);let c=this.resourceDependencies.get(o);if(c)for(let u of c)s(u);return i.delete(o),!0};for(let o of this.resourceDependencies.keys())s(o)}toLogicalId(n){return n.split(/[-_\s]/).map((i)=>i.charAt(0).toUpperCase()+i.slice(1).toLowerCase()).join("")}addNetworkResources(n){Dn(this,n)}addStorageResources(n){kn(this,n)}addComputeResources(n){Tn(this,n)}addDatabaseResources(n){Pn(this,n)}addFunctionResources(n){En(this,n)}addCacheResources(n){Sn(this,n)}addQueueResources(n){Nn(this,n)}addMessagingResources(n){wn(this,n)}addCDNResources(n){Cn(this,n)}addApiGatewayResources(n){bn(this,n)}addMonitoringResources(n){In(this,n)}addSecurityResources(n){xn(this,n)}}function fl(n){return new xm(n).build()}function YI(n){let{name:i,slug:s,domain:o,subdomain:c}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:c&&o?`${c}.${o}`:o}},infrastructure:{storage:{assets:{public:!0,versioning:!1,website:!0,encryption:!1,cors:[{allowedOrigins:["*"],allowedMethods:["GET","HEAD"],allowedHeaders:["*"],maxAge:3600}]}},cdn:{enabled:!0,customDomain:o?{domain:c&&o?`${c}.${o}`:o,certificateArn:"TO_BE_GENERATED"}:void 0,cachePolicy:{minTTL:0,defaultTTL:86400,maxTTL:31536000},compress:!0,http3:!0,errorPages:{404:"/index.html",403:"/index.html"}}}}}function ZI(n){let{name:i,slug:s,domain:o,instanceType:c="t3.small",minInstances:u=2,maxInstances:d=10}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"server",environments:{production:{type:"production",domain:o}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:2,natGateways:1}},compute:{server:{instanceType:c,ami:"ubuntu-22.04",keyPair:`${s}-key`,autoScaling:{min:u,max:d,desired:u,targetCPU:70},loadBalancer:{type:"application",healthCheck:{path:"/health",interval:30,timeout:5,healthyThreshold:2,unhealthyThreshold:3}},userData:{packages:["nodejs","npm","nginx"],commands:["curl -fsSL https://bun.sh/install | bash","npm install -g pm2"]}}},databases:{postgres:{engine:"postgres",version:"15",instanceClass:"db.t3.micro",allocatedStorage:20,multiAZ:!0,backupRetentionDays:7,deletionProtection:!0}},cache:{redis:{nodeType:"cache.t3.micro",numCacheNodes:1,engine:"redis",engineVersion:"7.0"}},security:{certificate:o?{domain:o,subdomains:[`*.${o}`],validationMethod:"DNS"}:void 0}}}}function eb(n){let{name:i,slug:s,domain:o,taskCpu:c="256",taskMemory:u="512",desiredCount:d=2}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:o}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:2,natGateways:0}},compute:{fargate:{taskDefinition:{cpu:c,memory:u,containerDefinitions:[{name:"app",image:`${s}-app:latest`,portMappings:[{containerPort:3000}],environment:[],secrets:[]}]},service:{desiredCount:d,healthCheck:{path:"/health",interval:30,timeout:5,healthyThreshold:2,unhealthyThreshold:3},autoScaling:{min:d,max:d*5,targetCPU:70,targetMemory:80}},loadBalancer:{type:"application"}}},databases:{dynamodb:{tables:{[`${s}-main`]:{partitionKey:{name:"id",type:"S"},sortKey:{name:"createdAt",type:"S"},billingMode:"PAY_PER_REQUEST",streamEnabled:!0,pointInTimeRecovery:!0}}}},functions:{"process-queue":{runtime:"nodejs20.x",handler:"dist/workers/queue.handler",memory:512,timeout:60,events:[{type:"sqs",queueName:`${s}-queue`}]}},security:{certificate:o?{domain:o,subdomains:[`*.${o}`],validationMethod:"DNS"}:void 0}}}}function tb(n){let{name:i,slug:s,entry:o,domain:c,runtime:u="nodejs20.x",memory:d=1024,build:g,deploy:y,assets:h,queues:b=!0,scheduler:v="on",region:A="us-east-1"}=n;return{project:{name:i,slug:s,region:A},mode:"serverless",environments:{production:{type:"production",domain:c,app:{kind:"node",runtime:u,entry:o,memory:d,build:g,deploy:y,assets:h,queues:b,scheduler:v,domain:c}}}}}function hl(n){let i=n.database!==!1,s=n.cache!==!1,o=n.queue!==!1;return{project:{name:n.name,slug:n.slug,region:"us-east-1"},mode:"server",environments:{production:{type:"production",domain:n.domain}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:2,natGateways:1}},compute:{fargate:{taskDefinition:{cpu:"256",memory:"512",containerDefinitions:[{name:"api",image:n.imageUri,portMappings:[{containerPort:3000}],environment:[{name:"NODE_ENV",value:"production"},{name:"PORT",value:"3000"},{name:"AWS_REGION",value:e.ref("AWS::Region")},...i?[{name:"DB_HOST",value:e.getAtt("PostgresDb","Endpoint.Address")},{name:"DB_PORT",value:e.getAtt("PostgresDb","Endpoint.Port")}]:[],...s?[{name:"REDIS_HOST",value:e.getAtt("RedisReplicationGroup","PrimaryEndPoint.Address")},{name:"REDIS_PORT",value:e.getAtt("RedisReplicationGroup","PrimaryEndPoint.Port")},{name:"REDIS_TLS",value:"true"}]:[],...o?[{name:"QUEUE_URL",value:e.ref("JobsQueue")}]:[],{name:"MAIL_TRANSPORT",value:"ses"}],secrets:i?[{name:"DB_USERNAME",valueFrom:e.sub("${DBSecret}:username::")},{name:"DB_PASSWORD",valueFrom:e.sub("${DBSecret}:password::")}]:[]}]},service:{desiredCount:n.desiredCount||1,healthCheck:{path:"/api/health",interval:30,timeout:5},autoScaling:{min:n.desiredCount||1,max:6,targetCPU:70}},loadBalancer:{type:"application",...n.certificateArn?{customDomain:{domain:n.domain,certificateArn:n.certificateArn}}:{},...n.originVerifySecret?{originVerifyHeader:{name:"X-Origin-Verify",value:n.originVerifySecret}}:{}}}},...i?{databases:{postgres:{engine:"postgres",version:"16",instanceClass:"db.t4g.micro",allocatedStorage:20,maxAllocatedStorage:100,multiAZ:!1,backupRetentionDays:7,deletionProtection:!0}}}:{},...s?{cache:{redis:{nodeType:"cache.t4g.micro",numCacheNodes:2,engine:"redis",engineVersion:"7.1",automaticFailoverEnabled:!0,snapshotRetentionLimit:5}}}:{},...o?{queues:{jobs:{fifo:!1,visibilityTimeout:300,messageRetentionPeriod:345600,deadLetterQueue:!0,maxReceiveCount:3,receiveMessageWaitTime:20}}}:{}}}}function rb(n){let{name:i,slug:s,domain:o,apiSubdomain:c="api"}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"server",environments:{production:{type:"production",domain:o}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:2,natGateways:1}},storage:{frontend:{public:!0,versioning:!0,website:!0,encryption:!1}},cdn:{enabled:!0,customDomain:{domain:o,certificateArn:"TO_BE_GENERATED"},cachePolicy:{minTTL:0,defaultTTL:86400,maxTTL:31536000},compress:!0,http3:!0,errorPages:{404:"/index.html"}},compute:{fargate:{taskDefinition:{cpu:"512",memory:"1024",containerDefinitions:[{name:"api",image:`${s}-api:latest`,portMappings:[{containerPort:3000}]}]},service:{desiredCount:2,healthCheck:{path:"/api/health",interval:30},autoScaling:{min:2,max:10,targetCPU:70}},loadBalancer:{type:"application",customDomain:{domain:`${c}.${o}`,certificateArn:"TO_BE_GENERATED"}}}},databases:{postgres:{engine:"postgres",version:"15",instanceClass:"db.t3.small",allocatedStorage:50,multiAZ:!0,backupRetentionDays:14,deletionProtection:!0}},cache:{redis:{nodeType:"cache.t3.small",numCacheNodes:2,engine:"redis",engineVersion:"7.0"}},queues:{jobs:{fifo:!1,visibilityTimeout:300,messageRetentionPeriod:345600,deadLetterQueue:!0}},security:{certificate:{domain:o,subdomains:[`*.${o}`],validationMethod:"DNS"},waf:{enabled:!0,rules:["rateLimit","sqlInjection","xss"]}}}}}function nb(n){let{name:i,slug:s,domain:o}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:o}},infrastructure:{apiGateway:{type:"HTTP",cors:{allowOrigins:["*"],allowMethods:["GET","POST","PUT","DELETE","PATCH"],allowHeaders:["Content-Type","Authorization"],maxAge:3600},customDomain:o?{domain:o,certificateArn:"TO_BE_GENERATED"}:void 0,throttling:{rateLimit:1e4,burstLimit:5000},authorizer:{type:"JWT",identitySource:"$request.header.Authorization"}},functions:{users:{runtime:"nodejs20.x",handler:"dist/api/users.handler",memory:512,timeout:30,events:[{type:"http",path:"/users",method:"GET"},{type:"http",path:"/users",method:"POST"}]},products:{runtime:"nodejs20.x",handler:"dist/api/products.handler",memory:512,timeout:30,events:[{type:"http",path:"/products",method:"GET"}]}},databases:{dynamodb:{tables:{[`${s}-users`]:{partitionKey:{name:"userId",type:"S"},billingMode:"PAY_PER_REQUEST",streamEnabled:!0,pointInTimeRecovery:!0,globalSecondaryIndexes:[{name:"EmailIndex",partitionKey:{name:"email",type:"S"},projection:"ALL"}]},[`${s}-products`]:{partitionKey:{name:"productId",type:"S"},sortKey:{name:"category",type:"S"},billingMode:"PAY_PER_REQUEST",streamEnabled:!1}}}},cache:{elasticache:{nodeType:"cache.t3.micro",numCacheNodes:1,engine:"redis",engineVersion:"7.0"}},security:{certificate:o?{domain:o,validationMethod:"DNS"}:void 0,waf:{enabled:!0,rules:["rateLimit","sqlInjection"]}},monitoring:{alarms:[{metric:"Errors",threshold:10,period:300,evaluationPeriods:1},{metric:"Duration",threshold:3000,period:300,evaluationPeriods:2}]}}}}function ib(n){let{name:i,slug:s,domain:o,instanceType:c="t3.small"}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"server",environments:{production:{type:"production",domain:o}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:2,natGateways:1}},compute:{server:{instanceType:c,ami:"ubuntu-22.04",keyPair:`${s}-key`,autoScaling:{min:2,max:6,desired:2,targetCPU:75},loadBalancer:{type:"application",healthCheck:{path:"/wp-admin/install.php",interval:30}},userData:{packages:["nginx","php8.1-fpm","php8.1-mysql","php8.1-curl","php8.1-gd","php8.1-mbstring","php8.1-xml","php8.1-zip"],commands:["cd /var/www","wget https://wordpress.org/latest.tar.gz","tar -xzf latest.tar.gz","chown -R www-data:www-data wordpress","rm /etc/nginx/sites-enabled/default","systemctl restart nginx","systemctl restart php8.1-fpm"]}}},fileSystem:{uploads:{performanceMode:"generalPurpose",throughputMode:"bursting",encrypted:!0,lifecyclePolicy:{transitionToIA:30},mountPath:"/var/www/wordpress/wp-content/uploads"}},databases:{mysql:{engine:"mysql",version:"8.0",instanceClass:"db.t3.small",allocatedStorage:50,multiAZ:!0,backupRetentionDays:7,deletionProtection:!0,databaseName:"wordpress"}},cache:{redis:{nodeType:"cache.t3.micro",numCacheNodes:1,engine:"redis",engineVersion:"7.0"}},cdn:{enabled:!0,customDomain:{domain:o,certificateArn:"TO_BE_GENERATED"},cachePolicy:{minTTL:0,defaultTTL:86400,maxTTL:31536000},compress:!0,origins:[{type:"alb",pathPattern:"/wp-content/*"}]},security:{certificate:{domain:o,subdomains:[`www.${o}`],validationMethod:"DNS"},waf:{enabled:!0,rules:["rateLimit","sqlInjection","xss","wordpressRules"]}}}}}function sb(n){let{name:i,slug:s,domain:o,apiDomain:c}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:o}},infrastructure:{storage:{static:{public:!0,versioning:!0,website:!0,encryption:!1,cors:[{allowedOrigins:["*"],allowedMethods:["GET","HEAD"]}],lifecycleRules:[{id:"DeleteOldVersions",enabled:!0,expirationDays:90}]}},cdn:{enabled:!0,customDomain:{domain:o,certificateArn:"TO_BE_GENERATED"},cachePolicy:{minTTL:0,defaultTTL:0,maxTTL:31536000},compress:!0,http3:!0,errorPages:{404:"/404.html",500:"/500.html"},edgeFunctions:[{eventType:"origin-request",functionArn:"TO_BE_CREATED",name:"ssr-handler"}]},functions:{ssr:{runtime:"nodejs20.x",handler:"dist/edge/ssr.handler",memory:512,timeout:5},...c?{api:{runtime:"nodejs20.x",handler:"dist/api/index.handler",memory:1024,timeout:30,events:[{type:"http",path:"/{proxy+}",method:"ANY"}]}}:{}},apiGateway:c?{type:"HTTP",customDomain:{domain:c,certificateArn:"TO_BE_GENERATED"},cors:{allowOrigins:[o],allowMethods:["GET","POST","PUT","DELETE"],allowHeaders:["Content-Type","Authorization"]}}:void 0,databases:{dynamodb:{tables:{content:{partitionKey:{name:"id",type:"S"},sortKey:{name:"type",type:"S"},billingMode:"PAY_PER_REQUEST",streamEnabled:!1}}}},security:{certificate:{domain:o,subdomains:c?[c]:[],validationMethod:"DNS"},waf:{enabled:!0,rules:["rateLimit","geoBlock"]}}}}}function ob(n){let{name:i,slug:s,domain:o,services:c}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:o}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:3,natGateways:2}},compute:{services:c.map((u)=>({name:u.name,type:"fargate",taskDefinition:{cpu:u.cpu||"256",memory:u.memory||"512",containerDefinitions:[{name:u.name,image:`${s}-${u.name}:latest`,portMappings:[{containerPort:u.port}],healthCheck:{command:["CMD-SHELL",`curl -f http://localhost:${u.port}/health || exit 1`],interval:30,timeout:5,retries:3}}]},service:{desiredCount:u.desiredCount||2,serviceDiscovery:{enabled:!0,namespace:`${s}.local`},autoScaling:{min:2,max:10,targetCPU:70}}}))},apiGateway:{type:"HTTP",customDomain:{domain:o,certificateArn:"TO_BE_GENERATED"},cors:{allowOrigins:["*"],allowMethods:["GET","POST","PUT","DELETE","PATCH"]},routes:c.map((u)=>({path:`/${u.name}/{proxy+}`,integration:{type:"vpc-link",service:u.name}}))},databases:{dynamodb:{tables:Object.fromEntries(c.map((u)=>[`${s}-${u.name}`,{partitionKey:{name:"id",type:"S"},billingMode:"PAY_PER_REQUEST",streamEnabled:!0,pointInTimeRecovery:!0}]))}},queues:{events:{fifo:!1,visibilityTimeout:300,messageRetentionPeriod:345600,deadLetterQueue:!0}},messaging:{topics:{events:{name:`${s}-events`,subscriptions:c.map((u)=>({protocol:"sqs",endpoint:`${s}-${u.name}-queue`,filterPolicy:{service:[u.name]}}))}}},monitoring:{dashboard:{name:`${s}-microservices`,widgets:c.map((u)=>({type:"metric",metrics:[{service:u.name,metric:"CPUUtilization"},{service:u.name,metric:"MemoryUtilization"},{service:u.name,metric:"RequestCount"}]}))},alarms:c.flatMap((u)=>[{name:`${u.name}-high-cpu`,metric:"CPUUtilization",threshold:80,service:u.name},{name:`${u.name}-errors`,metric:"Errors",threshold:10,service:u.name}])},security:{certificate:{domain:o,validationMethod:"DNS"},waf:{enabled:!0,rules:["rateLimit","sqlInjection"]}}}}}function ab(n){let{name:i,slug:s,domain:o}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:o}},infrastructure:{apiGateway:{type:"websocket",customDomain:o?{domain:o,certificateArn:"TO_BE_GENERATED"}:void 0,routes:[{path:"$connect",method:"WEBSOCKET",integration:"websocket-connect"},{path:"$disconnect",method:"WEBSOCKET",integration:"websocket-disconnect"},{path:"$default",method:"WEBSOCKET",integration:"websocket-default"},{path:"sendMessage",method:"WEBSOCKET",integration:"websocket-send-message"},{path:"joinRoom",method:"WEBSOCKET",integration:"websocket-join-room"}]},functions:{connect:{runtime:"nodejs20.x",handler:"dist/websocket/connect.handler",memory:512,timeout:30},disconnect:{runtime:"nodejs20.x",handler:"dist/websocket/disconnect.handler",memory:512,timeout:30},default:{runtime:"nodejs20.x",handler:"dist/websocket/default.handler",memory:512,timeout:30},"send-message":{runtime:"nodejs20.x",handler:"dist/websocket/sendMessage.handler",memory:512,timeout:30},"join-room":{runtime:"nodejs20.x",handler:"dist/websocket/joinRoom.handler",memory:512,timeout:30},broadcast:{runtime:"nodejs20.x",handler:"dist/streams/broadcast.handler",memory:1024,timeout:60,events:[{type:"dynamodb-stream",tableName:`${s}-messages`,startingPosition:"LATEST",batchSize:100}]}},databases:{dynamodb:{tables:{[`${s}-connections`]:{partitionKey:{name:"connectionId",type:"S"},billingMode:"PAY_PER_REQUEST",globalSecondaryIndexes:[{name:"RoomIndex",partitionKey:{name:"roomId",type:"S"},sortKey:{name:"connectionId",type:"S"},projection:"ALL"}]},[`${s}-messages`]:{partitionKey:{name:"roomId",type:"S"},sortKey:{name:"timestamp",type:"S"},billingMode:"PAY_PER_REQUEST",streamEnabled:!0,pointInTimeRecovery:!0,globalSecondaryIndexes:[{name:"UserIndex",partitionKey:{name:"userId",type:"S"},sortKey:{name:"timestamp",type:"S"},projection:"ALL"}]},[`${s}-rooms`]:{partitionKey:{name:"roomId",type:"S"},billingMode:"PAY_PER_REQUEST"}}}},cache:{elasticache:{nodeType:"cache.t3.small",numCacheNodes:2,engine:"redis",engineVersion:"7.0"}},monitoring:{alarms:[{metric:"WebSocketConnections",threshold:1e4,evaluationPeriods:1},{metric:"IntegrationLatency",threshold:1000,evaluationPeriods:2}],dashboard:{name:`${s}-realtime`,widgets:[{type:"metric",metrics:["WebSocketConnections","MessagesSent","IntegrationLatency"]}]}},security:{certificate:o?{domain:o,validationMethod:"DNS"}:void 0,waf:{enabled:!0,rules:["rateLimit","connectionLimit"]}}}}}function cb(n){let{name:i,slug:s,retentionDays:o=7}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"serverless",infrastructure:{streaming:{dataStream:{name:`${s}-stream`,shardCount:2,retentionPeriod:o*24,encryption:!0}},storage:{raw:{public:!1,versioning:!0,encryption:!0,intelligentTiering:!0,lifecycleRules:[{id:"ArchiveOldData",enabled:!0,transitions:[{days:30,storageClass:"GLACIER"},{days:90,storageClass:"DEEP_ARCHIVE"}]}]},processed:{public:!1,versioning:!0,encryption:!0,intelligentTiering:!0}},functions:{"stream-processor":{runtime:"nodejs20.x",handler:"dist/processors/stream.handler",memory:2048,timeout:300,events:[{type:"kinesis",streamName:`${s}-stream`,batchSize:1000,startingPosition:"LATEST",parallelizationFactor:10}]},transformer:{runtime:"nodejs20.x",handler:"dist/processors/transform.handler",memory:3008,timeout:900,events:[{type:"s3",bucket:`${s}-raw`,prefix:"incoming/"}]},aggregator:{runtime:"nodejs20.x",handler:"dist/processors/aggregate.handler",memory:2048,timeout:600,events:[{type:"schedule",expression:"cron(0 * * * ? *)"}]}},analytics:{athena:{database:`${s}_analytics`,workgroup:`${s}-workgroup`,outputBucket:`${s}-query-results`,tables:[{name:"raw_events",location:`s3://${s}-raw/events/`,format:"parquet",partitionKeys:["year","month","day"]},{name:"processed_events",location:`s3://${s}-processed/events/`,format:"parquet",partitionKeys:["year","month","day"]}]},glue:{crawlers:[{name:`${s}-crawler`,databaseName:`${s}_analytics`,s3Targets:[`s3://${s}-raw/`,`s3://${s}-processed/`],schedule:"cron(0 2 * * ? *)"}],jobs:[{name:`${s}-etl-job`,scriptLocation:`s3://${s}-scripts/etl.py`,role:`${s}-glue-role`,maxCapacity:10,timeout:120}]}},databases:{dynamodb:{tables:{[`${s}-metadata`]:{partitionKey:{name:"pipelineId",type:"S"},sortKey:{name:"timestamp",type:"S"},billingMode:"PAY_PER_REQUEST"}}}},queues:{failedJobs:{fifo:!1,visibilityTimeout:900,messageRetentionPeriod:1209600,deadLetterQueue:!0,maxReceiveCount:3}},workflow:{pipelines:[{name:`${s}-daily-pipeline`,type:"stepFunctions",definition:{StartAt:"ExtractData",States:{ExtractData:{Type:"Task",Resource:"arn:aws:states:::lambda:invoke",Next:"TransformData"},TransformData:{Type:"Task",Resource:"arn:aws:states:::lambda:invoke",Next:"LoadData"},LoadData:{Type:"Task",Resource:"arn:aws:states:::lambda:invoke",End:!0}}},schedule:"cron(0 0 * * ? *)"}]},monitoring:{dashboard:{name:`${s}-pipeline`,widgets:[{type:"metric",metrics:["KinesisIncomingRecords","LambdaInvocations","S3ObjectsCreated","GlueJobsSucceeded"]}]},alarms:[{metric:"LambdaErrors",threshold:10,evaluationPeriods:1},{metric:"KinesisIteratorAge",threshold:60000,evaluationPeriods:2}]}}}}function db(n){let{name:i,slug:s,domain:o,modelS3Path:c=`s3://${s}-models/`,instanceType:u="ml.t3.medium"}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"serverless",environments:{production:{type:"production",domain:o}},infrastructure:{storage:{models:{public:!1,versioning:!0,encryption:!0,intelligentTiering:!0},datasets:{public:!1,versioning:!0,encryption:!0,lifecycleRules:[{id:"ArchiveOldDatasets",enabled:!0,transitions:[{days:90,storageClass:"GLACIER"}]}]},predictions:{public:!1,versioning:!1,encryption:!0,lifecycleRules:[{id:"DeleteOldPredictions",enabled:!0,expirationDays:30}]}},machineLearning:{sagemaker:{endpoints:[{name:`${s}-inference`,modelS3Path:c,instanceType:u,initialInstanceCount:1,autoScaling:{minInstances:1,maxInstances:5,targetInvocationsPerInstance:1000}}],trainingJobs:[{name:`${s}-training`,algorithmSpecification:{trainingImage:"TO_BE_SPECIFIED",trainingInputMode:"File"},instanceType:"ml.p3.2xlarge",instanceCount:1,volumeSizeInGB:50,maxRuntimeInSeconds:86400}]}},apiGateway:{type:"HTTP",customDomain:o?{domain:o,certificateArn:"TO_BE_GENERATED"}:void 0,cors:{allowOrigins:["*"],allowMethods:["POST"],allowHeaders:["Content-Type","Authorization"]},throttling:{rateLimit:1000,burstLimit:500}},functions:{predict:{runtime:"python3.11",handler:"handlers/predict.handler",memory:2048,timeout:60,events:[{type:"http",path:"/predict",method:"POST"}],environment:{SAGEMAKER_ENDPOINT:`${s}-inference`,MODEL_BUCKET:`${s}-models`}},"batch-predict":{runtime:"python3.11",handler:"handlers/batchPredict.handler",memory:3008,timeout:900,events:[{type:"s3",bucket:`${s}-datasets`,suffix:".csv"}]},"trigger-training":{runtime:"python3.11",handler:"handlers/training.handler",memory:1024,timeout:300,events:[{type:"schedule",expression:"cron(0 2 * * ? *)"}]}},databases:{dynamodb:{tables:{[`${s}-predictions`]:{partitionKey:{name:"requestId",type:"S"},sortKey:{name:"timestamp",type:"S"},billingMode:"PAY_PER_REQUEST",streamEnabled:!0},[`${s}-models`]:{partitionKey:{name:"modelId",type:"S"},sortKey:{name:"version",type:"S"},billingMode:"PAY_PER_REQUEST"}}}},queues:{predictions:{fifo:!1,visibilityTimeout:300,messageRetentionPeriod:86400,deadLetterQueue:!0}},monitoring:{dashboard:{name:`${s}-ml`,widgets:[{type:"metric",metrics:["SageMakerInvocations","SageMakerModelLatency","APIGatewayRequests","LambdaErrors"]}]},alarms:[{metric:"SageMakerModelLatency",threshold:1000,evaluationPeriods:2},{metric:"SageMakerInvocationErrors",threshold:10,evaluationPeriods:1}]},security:{certificate:o?{domain:o,validationMethod:"DNS"}:void 0,waf:{enabled:!0,rules:["rateLimit","apiProtection"]}}}}}function lb(n){let{name:i,slug:s,domain:o,instanceType:c="t3.medium",minInstances:u=2,maxInstances:d=10,databaseEngine:g="mysql",sessionStore:y="redis"}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"server",environments:{production:{type:"production",domain:o}},infrastructure:{network:{vpc:{cidr:"10.0.0.0/16",availabilityZones:2,natGateways:2}},compute:{server:{instanceType:c,ami:"ubuntu-22.04",autoScaling:{min:u,max:d,targetCPU:70,scaleUpCooldown:300,scaleDownCooldown:300},loadBalancer:{type:"application",healthCheck:{path:"/health",interval:30,timeout:5,healthyThreshold:2,unhealthyThreshold:3},stickySession:{enabled:!0,duration:86400}},userData:`#!/bin/bash
2455
2455
  # Install Node.js or PHP/Python based on app needs
2456
2456
  # Configure application server (PM2, Nginx, Apache)
2457
2457
  # Mount EFS for shared file storage
2458
- `}},storage:{uploads:{type:"efs",performanceMode:"generalPurpose",throughputMode:"bursting",encrypted:!0,lifecyclePolicy:{transitionToIA:30}},backups:{public:!1,versioning:!0,encryption:!0,lifecycleRules:[{id:"ArchiveOldBackups",enabled:!0,transitions:[{days:90,storageClass:"GLACIER"}]}]},static:{public:!0,versioning:!1,encryption:!1,cors:[{allowedOrigins:[o||"*"],allowedMethods:["GET","HEAD"]}]}},cdn:{enabled:!0,origins:[{originId:"static-assets",domainName:`${s}-static.s3.amazonaws.com`,pathPattern:"/static/*"}],customDomain:o?{domain:o,certificateArn:"TO_BE_GENERATED"}:void 0,cachePolicy:{minTTL:0,defaultTTL:86400,maxTTL:31536000},compress:!0,http3:!0},databases:g==="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:y==="redis"?{redis:{nodeType:"cache.t3.medium",numCacheNodes:2,engine:"redis",engineVersion:"7.0",port:6379,parameterGroup:{maxmemoryPolicy:"allkeys-lru",timeout:"300"},snapshotRetentionLimit:5,snapshotWindow:"03:00-05:00",automaticFailoverEnabled:!0}}:void 0,queues:{jobs:{fifo:!1,visibilityTimeout:900,messageRetentionPeriod:345600,receiveMessageWaitTime:20,deadLetterQueue:!0,maxReceiveCount:3},emails:{fifo:!1,visibilityTimeout:300,messageRetentionPeriod:86400,deadLetterQueue:!0}},functions:{"job-worker":{runtime:"nodejs20.x",handler:"dist/workers/jobs.handler",memory:2048,timeout:900,events:[{type:"sqs",queueName:`${s}-jobs`,batchSize:10}]},"email-sender":{runtime:"nodejs20.x",handler:"dist/workers/email.handler",memory:512,timeout:60,events:[{type:"sqs",queueName:`${s}-emails`,batchSize:10}]},cleanup:{runtime:"nodejs20.x",handler:"dist/tasks/cleanup.handler",memory:512,timeout:300,events:[{type:"schedule",expression:"cron(0 2 * * ? *)"}]}},monitoring:{dashboard:{name:`${s}-web-app`,widgets:[{type:"metric",metrics:["EC2CPUUtilization","ALBRequestCount","ALBTargetResponseTime","RDSCPUUtilization","RDSDatabaseConnections","RDSReadLatency","RDSWriteLatency"]}]},alarms:[{metric:"EC2CPUUtilization",threshold:80,evaluationPeriods:2},{metric:"RDSCPUUtilization",threshold:80,evaluationPeriods:2},{metric:"RDSDatabaseConnections",threshold:400,evaluationPeriods:1},{metric:"ALBTargetResponseTime",threshold:2000,evaluationPeriods:2},{metric:"ALBUnhealthyHostCount",threshold:1,evaluationPeriods:1}],logs:{retention:14,groups:[`${s}-app`,`${s}-nginx`,`${s}-workers`]}},security:{certificate:o?{domain:o,validationMethod:"DNS"}:void 0,waf:{enabled:!0,rules:["rateLimit","sqlInjection","xss","knownBadInputs"]},securityGroups:{alb:{ingress:[{port:80,protocol:"tcp",cidr:"0.0.0.0/0"},{port:443,protocol:"tcp",cidr:"0.0.0.0/0"}]},app:{ingress:[{port:3000,protocol:"tcp",source:"alb-sg"}]},database:{ingress:[{port:g==="mysql"?3306:5432,protocol:"tcp",source:"app-sg"}]},...y==="redis"&&{cache:{ingress:[{port:6379,protocol:"tcp",source:"app-sg"}]}}}}}}}function ub(n){let{name:i,slug:s,domain:o,repository:c,phpVersion:u="8.3",size:d="small",database:g=s.replace(/-/g,"_"),databasePassword:y,sslEmail:h,deployStrategy:b="push",provider:v="hetzner"}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"server",cloud:{provider:v},environments:{production:{type:"production",domain:o}},infrastructure:{compute:{mode:"server",size:d,runtime:"php",webServer:"nginx",php:{versions:[u],default:u},managedServices:{mysql:!0,redis:!0},firewall:{enabled:!0},autoUpdates:!0,monitoring:!0,backups:{enabled:!0,schedule:"0 2 * * *",retentionCount:7}},appDatabase:{engine:"mysql",name:g,username:g,password:y}},sites:{main:{root:".",type:"laravel",domain:o,phpVersion:u,repository:{...c,strategy:b},scheduler:!0,queues:[{connection:"redis",queue:"default",processes:1}],ssl:{provider:"letsencrypt",email:h}}}}}function gb(n){let{name:i,slug:s,domain:o,layers:c,phpVersion:u="8.3",architecture:d="x86_64",memory:g=1024,build:y,deploy:h=["migrate --force"],cache:b="dynamodb",scheduler:v="on",region:A="us-east-1"}=n;return{project:{name:i,slug:s,region:A},mode:"serverless",environments:{production:{type:"production",domain:o,app:{kind:"php",runtime:"provided.al2023",phpVersion:u,architecture:d,layers:c,memory:g,build:y,deploy:h,assets:"public",queues:!0,scheduler:v,cache:{driver:b},domain:o}}}}}function pb(n){return{root:n.root??"packages/ui/dist",deploy:"server",type:"static",domain:n.domain,build:n.build??"cd packages/ui && bun install && bun run build",ssl:{provider:"letsencrypt"},auth:{username:n.username??"admin",password:n.password}}}var dy=rl,ly="./node_modules/@stacksjs/ts-cloud/dist/bin/dashboard-server.js";function ci(n){let i=n.split(".").filter(Boolean);return i.length<=2?n:i.slice(-2).join(".")}function li(n){let i=2166136261;for(let s=0;s<n.length;s++)i^=n.charCodeAt(s),i=Math.imul(i,16777619);return i>>>0}var uy=20000,gy=12000;function py(n){return uy+li(n)%gy}function Mn(n,i){let s=ci(n);if(s===n)return`dashboard.${s}`;for(let o of i)if(o===s)return`dashboard.${s}`;return`dashboard.${n}`}function Ln(n,i){let s=[],o=n.infrastructure?.dns?.domain;if(o&&!n.cloud?.attachTo)s.push(o);if(i&&n.environments?.[i]?.domain)s.push(n.environments[i].domain);for(let c of Object.values(n.sites??{})){let u=c;if(!u||u.redirect)continue;let d=u.domain;if(typeof d==="string")s.push(d);else if(Array.isArray(d))s.push(...d.filter((g)=>typeof g==="string"))}return s.filter((c)=>c&&!c.startsWith("dashboard."))}function my(n,i,s){if(s)return s;let o=Ln(n,i),c=o[0];if(!c)return null;return Mn(c,o)}function fy(n,i,s){if(s)return[s];let o=Ln(n,i),c=[];for(let u of o){let d=Mn(u,o);if(!c.includes(d))c.push(d)}return c}function pr(n){return Object.entries(n.sites??{}).some(([i,s])=>{if(!s)return!1;let o=s.root??"";return mr(i)||o==="ui/dist"||o.endsWith("/ui/dist")||o.endsWith("/dist/ui")})}var Om="dashboard-";function _m(n){return Om+n.replace(/^dashboard\./,"").replace(/\./g,"-")}function mr(n){return n==="dashboard"||n.startsWith(Om)}function Zi(n,i,s){if(pr(n))return[];if(n.cloud?.attachTo)return[];let o=s.password?{auth:{username:s.username||"admin",password:s.password,realm:s.realm}}:{},c=s.build===!1||s.build===void 0?{}:{build:s.build};if(s.live!==!1){let d=my(n,i,s.domain);if(!d)return[];let g=s.port??py(d),y=n.infrastructure?.appDatabase??n.infrastructure?.compute?.database,h={root:s.uiRoot,deploy:"server",domain:d,preStart:["bun install --production --no-save"],start:`bun ${ly} --box --host 127.0.0.1 --port ${g}`,port:g,cpuWeight:10,ioWeight:10,tasksMax:128,env:{APP_ENV:"production",NODE_ENV:"production",TS_CLOUD_DASHBOARD_TELEMETRY:"1",...y?.password?{TS_CLOUD_DASHBOARD_DB_PASSWORD:y.password}:{}},zeroDowntime:!1,sharedPaths:[dy],healthCheck:{path:"/login"},ssl:{provider:"letsencrypt"}};return[{name:_m(d),site:h}]}return fy(n,i,s.domain).map((d)=>({name:_m(d),site:{root:s.uiRoot,deploy:"server",type:"static",domain:d,ssl:{provider:"letsencrypt"},...c,...o}}))}function mb(n,i,s){return Zi(n,i,s)[0]??null}function wt(n,i){let s={...n};for(let o in i){let c=i[o],u=s[o];if(c===void 0)continue;if(Array.isArray(c)&&Array.isArray(u))s[o]=[...u,...c];else if(typeof c==="object"&&c!==null&&!Array.isArray(c)&&typeof u==="object"&&u!==null&&!Array.isArray(u))s[o]=wt(u,c);else s[o]=c}return s}function Lm(n,i){return wt(n,i)}function fb(...n){return n.reduce((i,s)=>wt(i,s),{})}function hb(n,i){return(s)=>{let o=n(s);if(typeof i==="function")return Lm(o,i(o,s));return Lm(o,i)}}function gn(n){return{infrastructure:n}}function Ab(n){return gn({monitoring:n})}function yb(n){return gn({security:n})}function Sb(n){return gn({databases:n})}function Ib(n){return gn({cache:n})}function bb(n){return gn({cdn:n})}function Cb(n){return gn({queues:n})}import{existsSync as On,readFileSync as It}from"node:fs";import{homedir as $n}from"node:os";import{join as Bn}from"node:path";function hy(){let n=process.env.AWS_ACCESS_KEY_ID,i=process.env.AWS_SECRET_ACCESS_KEY;if(!n||!i)return null;return{accessKeyId:n,secretAccessKey:i,sessionToken:process.env.AWS_SESSION_TOKEN}}function Ay(n){let i=n?.profile||process.env.AWS_PROFILE||"default",s=n?.credentialsFile||Bn($n(),".aws","credentials");if(!On(s))return null;try{let o=It(s,"utf-8");return ui(o,i)}catch{return null}}function ui(n,i){let s=n.split(`
2459
- `),o=null,c,u,d;for(let g of s){let y=g.trim();if(!y||y.startsWith("#")||y.startsWith(";"))continue;let h=y.match(/^\[([^\]]+)\]$/);if(h){if(o===i&&c&&u)return{accessKeyId:c,secretAccessKey:u,sessionToken:d};o=h[1],c=void 0,u=void 0,d=void 0;continue}if(o===i){let[b,...v]=y.split("="),A=v.join("=").trim();switch(b.trim().toLowerCase()){case"aws_access_key_id":c=A;break;case"aws_secret_access_key":u=A;break;case"aws_session_token":d=A;break}}}if(o===i&&c&&u)return{accessKeyId:c,secretAccessKey:u,sessionToken:d};return null}async function yy(n){let i=n?.timeout??1000,s="http://169.254.169.254";try{let o=await ze("http://169.254.169.254/latest/api/token",{method:"PUT",headers:{"X-aws-ec2-metadata-token-ttl-seconds":"21600"}},i);if(!o.ok)return null;let c=await o.text(),u=await ze("http://169.254.169.254/latest/meta-data/iam/security-credentials/",{headers:{"X-aws-ec2-metadata-token":c}},i);if(!u.ok)return null;let d=(await u.text()).trim(),g=await ze(`http://169.254.169.254/latest/meta-data/iam/security-credentials/${d}`,{headers:{"X-aws-ec2-metadata-token":c}},i);if(!g.ok)return null;let y=await g.json();return{accessKeyId:y.AccessKeyId,secretAccessKey:y.SecretAccessKey,sessionToken:y.Token,expiration:new Date(y.Expiration)}}catch{return null}}async function Sy(n){let i=n?.timeout??1000,s=process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI,o=process.env.AWS_CONTAINER_CREDENTIALS_FULL_URI,c=null;if(s)c=`http://169.254.170.2${s}`;else if(o)c=o;if(!c)return null;try{let u={},d=process.env.AWS_CONTAINER_AUTHORIZATION_TOKEN;if(d)u.Authorization=d;let g=await ze(c,{headers:u},i);if(!g.ok)return null;let y=await g.json();return{accessKeyId:y.AccessKeyId,secretAccessKey:y.SecretAccessKey,sessionToken:y.Token,expiration:new Date(y.Expiration)}}catch{return null}}async function Iy(n){let i=n?.timeout??5000,s=process.env.AWS_WEB_IDENTITY_TOKEN_FILE,o=process.env.AWS_ROLE_ARN,c=process.env.AWS_ROLE_SESSION_NAME||"ts-cloud-session";if(!s||!o)return null;try{let u=It(s,"utf-8").trim(),d=process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||"us-east-1",g=d.startsWith("us-gov")?`https://sts.${d}.amazonaws.com`:d==="us-east-1"?"https://sts.amazonaws.com":`https://sts.${d}.amazonaws.com`,y=new URLSearchParams({Action:"AssumeRoleWithWebIdentity",Version:"2011-06-15",RoleArn:o,RoleSessionName:c,WebIdentityToken:u}),h=await ze(`${g}/?${y.toString()}`,{method:"POST"},i);if(!h.ok)return null;let b=await h.text(),v=qe(b,"AccessKeyId"),A=qe(b,"SecretAccessKey"),T=qe(b,"SessionToken"),R=qe(b,"Expiration");if(!v||!A)return null;return{accessKeyId:v,secretAccessKey:A,sessionToken:T??void 0,expiration:R?new Date(R):void 0}}catch{return null}}async function es(n){let i=hy();if(i)return i;let s=Ay(n);if(s)return s;let o=await Iy(n);if(o)return o;let c=await Sy(n);if(c)return c;let u=await yy(n);if(u)return u;throw Error("Could not find AWS credentials. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables, or configure ~/.aws/credentials, or run on an EC2 instance with an IAM role.")}function Eb(n){let i=null,s=null;return async()=>{if(i){if(!i.expiration)return i;let o=300000;if(i.expiration.getTime()-Date.now()>o)return i}if(s)return s;return s=es(n).then((o)=>(i=o,s=null,o)).catch((o)=>{throw s=null,o}),s}}async function ze(n,i,s){let o=new AbortController,c=setTimeout(()=>o.abort(),s);try{let u=await fetch(n,{...i,signal:o.signal});return clearTimeout(c),u}catch(u){throw clearTimeout(c),u}}function qe(n,i){let s=new RegExp(`<${i}>([^<]+)</${i}>`),o=n.match(s);return o?o[1]:null}async function zo(n){return es({profile:n})}function by(n){let i=process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION;if(i)return i;let s=Bn($n(),".aws","config");if(On(s))try{let o=It(s,"utf-8"),c=n||process.env.AWS_PROFILE||"default",u=c==="default"?"[default]":`[profile ${c}]`,d=o.split(`
2460
- `),g=!1;for(let y of d){let h=y.trim();if(h.startsWith("[")){g=h===u;continue}if(g&&h.startsWith("region")){let[,b]=h.split("=");if(b)return b.trim()}}}catch{}return"us-east-1"}async function $m(n){let i=n||await es(),s=by(),{signRequest:o}=await import("./chunk-ypsfkgme.js"),c=s.startsWith("us-gov")?`https://sts.${s}.amazonaws.com`:s==="us-east-1"?"https://sts.amazonaws.com":`https://sts.${s}.amazonaws.com`,u="Action=GetCallerIdentity&Version=2011-06-15",d=o({method:"POST",url:c,body:"Action=GetCallerIdentity&Version=2011-06-15",headers:{"Content-Type":"application/x-www-form-urlencoded"},...i,service:"sts",region:s}),g=await fetch(d.url,{method:d.method,headers:d.headers,body:d.body});if(!g.ok)throw Error(`Failed to get account ID: ${await g.text()}`);let y=await g.text(),h=qe(y,"Account");if(!h)throw Error("Failed to parse account ID from response");return h}var mi=5242880,Dt=5242880;var pi=5242880;class Mt{region;endpoint;forcePathStyle;credentials;credentialOptions;retryOptions;constructor(n={}){this.region=n.region||process.env.AWS_REGION||"us-east-1",this.endpoint=n.endpoint||`https://s3.${this.region}.amazonaws.com`,this.forcePathStyle=n.forcePathStyle||!1,this.credentials=n.credentials,this.credentialOptions=n.credentialOptions,this.retryOptions=n.retryOptions||{}}async getCredentials(){if(this.credentials)return this.credentials;return es(this.credentialOptions)}buildUrl(n,i){let s=i?encodeURIComponent(i).replace(/%2F/g,"/"):"";if(this.forcePathStyle)return i?`${this.endpoint}/${n}/${s}`:`${this.endpoint}/${n}`;let o=new URL(this.endpoint);return o.hostname=`${n}.${o.hostname}`,i?`${o.origin}/${s}`:o.origin}async get(n,i,s={}){let o=await this.getCredentials(),c=this.buildUrl(n,i),u={};if(s.range)u.Range=s.range;if(s.ifModifiedSince)u["If-Modified-Since"]=s.ifModifiedSince.toUTCString();if(s.ifMatch)u["If-Match"]=s.ifMatch;if(s.ifNoneMatch)u["If-None-Match"]=s.ifNoneMatch;let d=new URL(c);if(s.responseContentType)d.searchParams.set("response-content-type",s.responseContentType);if(s.responseContentDisposition)d.searchParams.set("response-content-disposition",s.responseContentDisposition);let g=k({method:"GET",url:d.toString(),headers:u,...o,service:"s3",region:this.region}),y=await fetch(g.url,{method:g.method,headers:g.headers});if(!y.ok&&y.status!==304){let h=await y.text();throw new V(`Failed to get object: ${h}`,y.status,n,i)}return y}async getText(n,i,s={}){return(await this.get(n,i,s)).text()}async getJSON(n,i,s={}){return(await this.get(n,i,s)).json()}async getBuffer(n,i,s={}){return(await this.get(n,i,s)).arrayBuffer()}async put(n,i,s,o={}){let c,u;if(typeof s==="string")c=new TextEncoder().encode(s).length,u=s;else if(s instanceof ArrayBuffer)c=s.byteLength,u=s;else if(s instanceof Uint8Array)c=s.byteLength,u=s;else if(s instanceof Blob)c=s.size,u=s;else return this.uploadMultipart(n,i,s,{...o,partSize:Dt});if(c>pi){let d=fi(u).stream();return this.uploadMultipart(n,i,d,{...o,partSize:Dt})}return this.putSimple(n,i,u,c,o)}async putSimple(n,i,s,o,c){let u=await this.getCredentials(),d=this.buildUrl(n,i),g={"Content-Length":String(o),"Content-Type":c.contentType||Fn(i)};if(c.contentEncoding)g["Content-Encoding"]=c.contentEncoding;if(c.cacheControl)g["Cache-Control"]=c.cacheControl;if(c.contentDisposition)g["Content-Disposition"]=c.contentDisposition;if(c.storageClass)g["x-amz-storage-class"]=c.storageClass;if(c.serverSideEncryption)g["x-amz-server-side-encryption"]=c.serverSideEncryption;if(c.acl)g["x-amz-acl"]=c.acl;if(c.tagging)g["x-amz-tagging"]=c.tagging;if(c.metadata)for(let[A,T]of Object.entries(c.metadata))g[`x-amz-meta-${A.toLowerCase()}`]=T;let y;if(typeof s==="string")y=s;else if(s instanceof Blob)y=await s.text();else y=new TextDecoder().decode(s instanceof ArrayBuffer?new Uint8Array(s):s);let h=k({method:"PUT",url:d,headers:g,body:y,...u,service:"s3",region:this.region}),b=await fetch(h.url,{method:h.method,headers:h.headers,body:s});if(!b.ok){let A=await b.text();throw new V(`Failed to put object: ${A}`,b.status,n,i)}return{etag:(b.headers.get("ETag")||"").replace(/"/g,"")}}async delete(n,i){let s=await this.getCredentials(),o=this.buildUrl(n,i),c=k({method:"DELETE",url:o,...s,service:"s3",region:this.region}),u=await fetch(c.url,{method:c.method,headers:c.headers});if(!u.ok&&u.status!==204){let d=await u.text();throw new V(`Failed to delete object: ${d}`,u.status,n,i)}}async deleteMany(n,i){let s=await this.getCredentials(),o=`${this.buildUrl(n)}?delete`,u=`<?xml version="1.0" encoding="UTF-8"?><Delete><Quiet>false</Quiet>${i.map((R)=>`<Object><Key>${yi(R)}</Key></Object>`).join("")}</Delete>`,d=k({method:"POST",url:o,headers:{"Content-Type":"application/xml"},body:u,...s,service:"s3",region:this.region}),g=await fetch(d.url,{method:d.method,headers:d.headers,body:u});if(!g.ok){let R=await g.text();throw new V(`Failed to delete objects: ${R}`,g.status,n)}let y=await g.text(),h=[],b=[],v=/<Deleted><Key>([^<]+)<\/Key>/g,A;while((A=v.exec(y))!==null)h.push(A[1]);let T=/<Error><Key>([^<]+)<\/Key><Code>([^<]+)<\/Code><Message>([^<]+)<\/Message>/g;while((A=T.exec(y))!==null)b.push({key:A[1],error:`${A[2]}: ${A[3]}`});return{deleted:h,errors:b}}async list(n,i={}){let s=await this.getCredentials(),o=new URL(this.buildUrl(n));if(o.searchParams.set("list-type","2"),i.prefix)o.searchParams.set("prefix",i.prefix);if(i.delimiter)o.searchParams.set("delimiter",i.delimiter);if(i.maxKeys)o.searchParams.set("max-keys",String(i.maxKeys));if(i.continuationToken)o.searchParams.set("continuation-token",i.continuationToken);if(i.startAfter)o.searchParams.set("start-after",i.startAfter);let c=k({method:"GET",url:o.toString(),...s,service:"s3",region:this.region}),u=await fetch(c.url,{method:c.method,headers:c.headers});if(!u.ok){let g=await u.text();throw new V(`Failed to list objects: ${g}`,u.status,n)}let d=await u.text();return gi(d)}async*listAll(n,i={}){let s;do{let o=await this.list(n,{...i,continuationToken:s});for(let c of o.contents)yield c;s=o.nextContinuationToken}while(s)}async head(n,i){let s=await this.getCredentials(),o=this.buildUrl(n,i),c=k({method:"HEAD",url:o,...s,service:"s3",region:this.region}),u=await fetch(c.url,{method:c.method,headers:c.headers});if(u.status===404)return null;if(!u.ok){let g=await u.text();throw new V(`Failed to head object: ${g}`,u.status,n,i)}let d={};return u.headers.forEach((g,y)=>{if(y.toLowerCase().startsWith("x-amz-meta-"))d[y.slice(11)]=g}),{contentLength:Number(u.headers.get("Content-Length")||0),contentType:u.headers.get("Content-Type")||"application/octet-stream",etag:(u.headers.get("ETag")||"").replace(/"/g,""),lastModified:new Date(u.headers.get("Last-Modified")||0),metadata:d,storageClass:u.headers.get("x-amz-storage-class")||void 0,serverSideEncryption:u.headers.get("x-amz-server-side-encryption")||void 0}}async exists(n,i){return await this.head(n,i)!==null}async copy(n,i,s,o,c={}){let u=await this.getCredentials(),d=this.buildUrl(s,o),g={"x-amz-copy-source":`/${n}/${encodeURIComponent(i)}`};if(c.metadataDirective)g["x-amz-metadata-directive"]=c.metadataDirective;if(c.contentType)g["Content-Type"]=c.contentType;if(c.storageClass)g["x-amz-storage-class"]=c.storageClass;if(c.acl)g["x-amz-acl"]=c.acl;if(c.metadata)for(let[T,R]of Object.entries(c.metadata))g[`x-amz-meta-${T.toLowerCase()}`]=R;let y=k({method:"PUT",url:d,headers:g,...u,service:"s3",region:this.region}),h=await fetch(y.url,{method:y.method,headers:y.headers});if(!h.ok){let T=await h.text();throw new V(`Failed to copy object: ${T}`,h.status,s,o)}let v=(await h.text()).match(/<ETag>"?([^"<]+)"?<\/ETag>/);return{etag:v?v[1]:""}}async getPresignedUrl(n,i,s={}){let o=await this.getCredentials(),c=this.buildUrl(n,i);return na({url:c,method:s.method||"GET",expiresIn:s.expiresIn||3600,...o,service:"s3",region:this.region})}async uploadMultipart(n,i,s,o={}){let c=await this.getCredentials(),u=Math.max(o.partSize||Dt,mi),d,g;if(s instanceof ReadableStream)d=s;else if(s instanceof Blob)d=s.stream(),g=s.size;else{let b=new Blob([s]);d=b.stream(),g=b.size}let{uploadId:y,baseUrl:h}=await this.initiateMultipartUpload(n,i,o);try{let b=await this.uploadParts(n,i,h,y,d,u,c,g,o.concurrency||4,o.onProgress);return await this.completeMultipartUpload(n,i,h,y,b)}catch(b){throw await this.abortMultipartUpload(n,i,y,h).catch(()=>{}),b}}async initiateMultipartUpload(n,i,s){let o=await this.getCredentials(),c=this.buildUrl(n,i),u=`${c}?uploads`,d={"Content-Type":s.contentType||Fn(i)};if(s.storageClass)d["x-amz-storage-class"]=s.storageClass;if(s.serverSideEncryption)d["x-amz-server-side-encryption"]=s.serverSideEncryption;if(s.acl)d["x-amz-acl"]=s.acl;if(s.metadata)for(let[A,T]of Object.entries(s.metadata))d[`x-amz-meta-${A.toLowerCase()}`]=T;let g=k({method:"POST",url:u,headers:d,...o,service:"s3",region:this.region}),y=await fetch(g.url,{method:g.method,headers:g.headers});if(!y.ok){let A=await y.text();throw new V(`Failed to initiate multipart upload: ${A}`,y.status,n,i)}let b=(await y.text()).match(/<UploadId>([^<]+)<\/UploadId>/);if(!b)throw new V("Failed to parse upload ID from response",0,n,i);let v=c;if(y.url)try{let A=new URL(y.url);A.search="",v=A.toString()}catch{}return{uploadId:b[1],baseUrl:v}}async uploadParts(n,i,s,o,c,u,d,g,y,h){let b=[],v=c.getReader(),A=1,T=new Uint8Array(0),R=0,P=g?Math.ceil(g/u):void 0,I=new Map,M=async(N,O)=>{let B=`${s}?partNumber=${O}&uploadId=${encodeURIComponent(o)}`,F={"Content-Length":String(N.byteLength),"x-amz-content-sha256":"UNSIGNED-PAYLOAD"},U=k({method:"PUT",url:B,headers:F,...d,service:"s3",region:this.region}),j=await fetch(U.url,{method:U.method,headers:U.headers,body:N,redirect:"error"});if(!j.ok){let z=await j.text();throw new V(`Failed to upload part ${O}: ${z}`,j.status,n,i)}let H=(j.headers.get("ETag")||"").replace(/"/g,"");if(!H)throw new V(`Missing ETag for part ${O}`,j.status,n,i);return{partNumber:O,etag:H}},L=async()=>{let N=await Promise.race(I.values());I.delete(N.partNumber),b.push(N)};while(!0){let{done:N,value:O}=await v.read();if(O){let B=new Uint8Array(T.length+O.length);B.set(T),B.set(O,T.length),T=B}while(T.length>=u||N&&T.length>0){let B=T.slice(0,u);T=T.slice(u);let F=A++;if(I.size>=y)await L();if(I.set(F,M(B,F)),R+=B.byteLength,h)h({loaded:R,total:g||R,part:F,totalParts:P||F})}if(N)break}while(I.size>0)await L();return b.sort((N,O)=>N.partNumber-O.partNumber),b}async completeMultipartUpload(n,i,s,o,c){let u=await this.getCredentials(),d=`${s}?uploadId=${encodeURIComponent(o)}`,y=`<?xml version="1.0" encoding="UTF-8"?><CompleteMultipartUpload>${c.map((R)=>`<Part><PartNumber>${R.partNumber}</PartNumber><ETag>"${R.etag}"</ETag></Part>`).join("")}</CompleteMultipartUpload>`,h=k({method:"POST",url:d,headers:{"Content-Type":"application/xml"},body:y,...u,service:"s3",region:this.region}),b=await fetch(h.url,{method:h.method,headers:h.headers,body:y});if(!b.ok){let R=await b.text();throw new V(`Failed to complete multipart upload: ${R}`,b.status,n,i)}let A=(await b.text()).match(/<ETag>"?([^"<]+)"?<\/ETag>/);return{etag:A?A[1]:""}}async abortMultipartUpload(n,i,s,o){let c=await this.getCredentials(),u=`${o??this.buildUrl(n,i)}?uploadId=${encodeURIComponent(s)}`,d=k({method:"DELETE",url:u,...c,service:"s3",region:this.region});await fetch(d.url,{method:d.method,headers:d.headers})}async emptyAndDeleteBucket(n){let s=[];for await(let d of this.listAll(n,{}))if(s.push(d.key),s.length>=1000)await this.deleteMany(n,s),s=[];if(s.length>0)await this.deleteMany(n,s);let o=await this.getCredentials(),c=this.buildUrl(n),u=k({method:"DELETE",url:c,...o,service:"s3",region:this.region});await fetch(u.url,{method:u.method,headers:u.headers})}}class V extends Error{statusCode;bucket;key;constructor(n,i,s,o){super(n);this.statusCode=i;this.bucket=s;this.key=o;this.name="S3Error"}}function gi(n){let i=[],s=[],o=/<Contents>([\s\S]*?)<\/Contents>/g,c;while((c=o.exec(n))!==null){let d=c[1];i.push({key:me(d,"Key")||"",lastModified:new Date(me(d,"LastModified")||0),etag:(me(d,"ETag")||"").replace(/"/g,""),size:Number(me(d,"Size")||0),storageClass:me(d,"StorageClass")||"STANDARD"})}let u=/<CommonPrefixes><Prefix>([^<]+)<\/Prefix><\/CommonPrefixes>/g;while((c=u.exec(n))!==null)s.push(c[1]);return{contents:i,commonPrefixes:s,isTruncated:me(n,"IsTruncated")==="true",continuationToken:me(n,"ContinuationToken")||void 0,nextContinuationToken:me(n,"NextContinuationToken")||void 0,keyCount:Number(me(n,"KeyCount")||0),maxKeys:Number(me(n,"MaxKeys")||1000),prefix:me(n,"Prefix")||void 0,delimiter:me(n,"Delimiter")||void 0}}function me(n,i){let s=new RegExp(`<${i}>([^<]*)</${i}>`),o=n.match(s);return o?o[1]:null}function yi(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function Fn(n){let i=n.split(".").pop()?.toLowerCase();return{html:"text/html",htm:"text/html",css:"text/css",js:"application/javascript",mjs:"application/javascript",json:"application/json",xml:"application/xml",txt:"text/plain",md:"text/markdown",csv:"text/csv",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",ico:"image/x-icon",avif:"image/avif",mp4:"video/mp4",webm:"video/webm",mov:"video/quicktime",avi:"video/x-msvideo",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",zip:"application/zip",gz:"application/gzip",tar:"application/x-tar",rar:"application/vnd.rar","7z":"application/x-7z-compressed",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",otf:"font/otf",eot:"application/vnd.ms-fontobject",wasm:"application/wasm"}[i||""]||"application/octet-stream"}function fi(n){if(n instanceof Blob)return n;if(typeof n==="string")return new Blob([n],{type:"text/plain"});return new Blob([n])}function Cy(n){return new Mt(n)}class rt extends Error{code;solution;details;constructor(n,i,s,o){super(n);this.code=i;this.solution=s;this.details=o;this.name="CloudError",Error.captureStackTrace?.(this,rt)}toString(){let n=`${this.name} [${this.code}]: ${this.message}`;if(this.solution)n+=`
2458
+ `}},storage:{uploads:{type:"efs",performanceMode:"generalPurpose",throughputMode:"bursting",encrypted:!0,lifecyclePolicy:{transitionToIA:30}},backups:{public:!1,versioning:!0,encryption:!0,lifecycleRules:[{id:"ArchiveOldBackups",enabled:!0,transitions:[{days:90,storageClass:"GLACIER"}]}]},static:{public:!0,versioning:!1,encryption:!1,cors:[{allowedOrigins:[o||"*"],allowedMethods:["GET","HEAD"]}]}},cdn:{enabled:!0,origins:[{originId:"static-assets",domainName:`${s}-static.s3.amazonaws.com`,pathPattern:"/static/*"}],customDomain:o?{domain:o,certificateArn:"TO_BE_GENERATED"}:void 0,cachePolicy:{minTTL:0,defaultTTL:86400,maxTTL:31536000},compress:!0,http3:!0},databases:g==="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:y==="redis"?{redis:{nodeType:"cache.t3.medium",numCacheNodes:2,engine:"redis",engineVersion:"7.0",port:6379,parameterGroup:{maxmemoryPolicy:"allkeys-lru",timeout:"300"},snapshotRetentionLimit:5,snapshotWindow:"03:00-05:00",automaticFailoverEnabled:!0}}:void 0,queues:{jobs:{fifo:!1,visibilityTimeout:900,messageRetentionPeriod:345600,receiveMessageWaitTime:20,deadLetterQueue:!0,maxReceiveCount:3},emails:{fifo:!1,visibilityTimeout:300,messageRetentionPeriod:86400,deadLetterQueue:!0}},functions:{"job-worker":{runtime:"nodejs20.x",handler:"dist/workers/jobs.handler",memory:2048,timeout:900,events:[{type:"sqs",queueName:`${s}-jobs`,batchSize:10}]},"email-sender":{runtime:"nodejs20.x",handler:"dist/workers/email.handler",memory:512,timeout:60,events:[{type:"sqs",queueName:`${s}-emails`,batchSize:10}]},cleanup:{runtime:"nodejs20.x",handler:"dist/tasks/cleanup.handler",memory:512,timeout:300,events:[{type:"schedule",expression:"cron(0 2 * * ? *)"}]}},monitoring:{dashboard:{name:`${s}-web-app`,widgets:[{type:"metric",metrics:["EC2CPUUtilization","ALBRequestCount","ALBTargetResponseTime","RDSCPUUtilization","RDSDatabaseConnections","RDSReadLatency","RDSWriteLatency"]}]},alarms:[{metric:"EC2CPUUtilization",threshold:80,evaluationPeriods:2},{metric:"RDSCPUUtilization",threshold:80,evaluationPeriods:2},{metric:"RDSDatabaseConnections",threshold:400,evaluationPeriods:1},{metric:"ALBTargetResponseTime",threshold:2000,evaluationPeriods:2},{metric:"ALBUnhealthyHostCount",threshold:1,evaluationPeriods:1}],logs:{retention:14,groups:[`${s}-app`,`${s}-nginx`,`${s}-workers`]}},security:{certificate:o?{domain:o,validationMethod:"DNS"}:void 0,waf:{enabled:!0,rules:["rateLimit","sqlInjection","xss","knownBadInputs"]},securityGroups:{alb:{ingress:[{port:80,protocol:"tcp",cidr:"0.0.0.0/0"},{port:443,protocol:"tcp",cidr:"0.0.0.0/0"}]},app:{ingress:[{port:3000,protocol:"tcp",source:"alb-sg"}]},database:{ingress:[{port:g==="mysql"?3306:5432,protocol:"tcp",source:"app-sg"}]},...y==="redis"&&{cache:{ingress:[{port:6379,protocol:"tcp",source:"app-sg"}]}}}}}}}function ub(n){let{name:i,slug:s,domain:o,repository:c,phpVersion:u="8.3",size:d="small",database:g=s.replace(/-/g,"_"),databasePassword:y,sslEmail:h,deployStrategy:b="push",provider:v="hetzner"}=n;return{project:{name:i,slug:s,region:"us-east-1"},mode:"server",cloud:{provider:v},environments:{production:{type:"production",domain:o}},infrastructure:{compute:{mode:"server",size:d,runtime:"php",webServer:"nginx",php:{versions:[u],default:u},managedServices:{mysql:!0,redis:!0},firewall:{enabled:!0},autoUpdates:!0,monitoring:!0,backups:{enabled:!0,schedule:"0 2 * * *",retentionCount:7}},appDatabase:{engine:"mysql",name:g,username:g,password:y}},sites:{main:{root:".",type:"laravel",domain:o,phpVersion:u,repository:{...c,strategy:b},scheduler:!0,queues:[{connection:"redis",queue:"default",processes:1}],ssl:{provider:"letsencrypt",email:h}}}}}function gb(n){let{name:i,slug:s,domain:o,layers:c,phpVersion:u="8.3",architecture:d="x86_64",memory:g=1024,build:y,deploy:h=["migrate --force"],cache:b="dynamodb",scheduler:v="on",region:A="us-east-1"}=n;return{project:{name:i,slug:s,region:A},mode:"serverless",environments:{production:{type:"production",domain:o,app:{kind:"php",runtime:"provided.al2023",phpVersion:u,architecture:d,layers:c,memory:g,build:y,deploy:h,assets:"public",queues:!0,scheduler:v,cache:{driver:b},domain:o}}}}}function pb(n){return{root:n.root??"packages/ui/dist",deploy:"server",type:"static",domain:n.domain,build:n.build??"cd packages/ui && bun install && bun run build",ssl:{provider:"letsencrypt"},auth:{username:n.username??"admin",password:n.password}}}var dy=rl,ly="./node_modules/@stacksjs/ts-cloud/dist/bin/dashboard-server.js";function ci(n){let i=n.split(".").filter(Boolean);return i.length<=2?n:i.slice(-2).join(".")}function li(n){let i=2166136261;for(let s=0;s<n.length;s++)i^=n.charCodeAt(s),i=Math.imul(i,16777619);return i>>>0}var uy=20000,gy=12000;function py(n){return uy+li(n)%gy}function Mn(n,i){let s=ci(n);if(s===n)return`dashboard.${s}`;for(let o of i)if(o===s)return`dashboard.${s}`;return`dashboard.${n}`}function Ln(n,i){let s=[],o=n.infrastructure?.dns?.domain;if(o&&!n.cloud?.attachTo)s.push(o);if(i&&n.environments?.[i]?.domain)s.push(n.environments[i].domain);for(let c of Object.values(n.sites??{})){let u=c;if(!u||u.redirect)continue;let d=u.domain;if(typeof d==="string")s.push(d);else if(Array.isArray(d))s.push(...d.filter((g)=>typeof g==="string"))}return s.filter((c)=>c&&!c.startsWith("dashboard."))}function my(n,i,s){if(s)return s;let o=Ln(n,i),c=o[0];if(!c)return null;return Mn(c,o)}function fy(n,i,s){if(s)return[s];let o=Ln(n,i),c=[];for(let u of o){let d=Mn(u,o);if(!c.includes(d))c.push(d)}return c}function pr(n){return Object.entries(n.sites??{}).some(([i,s])=>{if(!s)return!1;let o=s.root??"";return mr(i)||o==="ui/dist"||o.endsWith("/ui/dist")||o.endsWith("/dist/ui")})}var Om="dashboard-";function _m(n){return Om+n.replace(/^dashboard\./,"").replace(/\./g,"-")}function mr(n){return n==="dashboard"||n.startsWith(Om)}function Zi(n,i,s){if(pr(n))return[];if(n.cloud?.attachTo)return[];let o=s.password?{auth:{username:s.username||"admin",password:s.password,realm:s.realm}}:{},c=s.build===!1||s.build===void 0?{}:{build:s.build};if(s.live!==!1){let d=my(n,i,s.domain);if(!d)return[];let g=s.port??py(d),y=n.infrastructure?.appDatabase??n.infrastructure?.compute?.database,h={root:s.uiRoot,deploy:"server",domain:d,preStart:["bun install --production --no-save"],start:`bun ${ly} --box --host 127.0.0.1 --port ${g}`,port:g,cpuWeight:10,ioWeight:10,tasksMax:128,env:{APP_ENV:"production",NODE_ENV:"production",TS_CLOUD_DASHBOARD_TELEMETRY:"1",...y?.password?{TS_CLOUD_DASHBOARD_DB_PASSWORD:y.password}:{}},zeroDowntime:!1,sharedPaths:[dy],healthCheck:{path:"/login"},ssl:{provider:"letsencrypt"}};return[{name:_m(d),site:h}]}return fy(n,i,s.domain).map((d)=>({name:_m(d),site:{root:s.uiRoot,deploy:"server",type:"static",domain:d,ssl:{provider:"letsencrypt"},...c,...o}}))}function mb(n,i,s){return Zi(n,i,s)[0]??null}function Et(n,i){let s={...n};for(let o in i){let c=i[o],u=s[o];if(c===void 0)continue;if(Array.isArray(c)&&Array.isArray(u))s[o]=[...u,...c];else if(typeof c==="object"&&c!==null&&!Array.isArray(c)&&typeof u==="object"&&u!==null&&!Array.isArray(u))s[o]=Et(u,c);else s[o]=c}return s}function Lm(n,i){return Et(n,i)}function fb(...n){return n.reduce((i,s)=>Et(i,s),{})}function hb(n,i){return(s)=>{let o=n(s);if(typeof i==="function")return Lm(o,i(o,s));return Lm(o,i)}}function pn(n){return{infrastructure:n}}function Ab(n){return pn({monitoring:n})}function yb(n){return pn({security:n})}function Sb(n){return pn({databases:n})}function Ib(n){return pn({cache:n})}function bb(n){return pn({cdn:n})}function Cb(n){return pn({queues:n})}import{existsSync as On,readFileSync as wt}from"node:fs";import{homedir as $n}from"node:os";import{join as Bn}from"node:path";function hy(){let n=process.env.AWS_ACCESS_KEY_ID,i=process.env.AWS_SECRET_ACCESS_KEY;if(!n||!i)return null;return{accessKeyId:n,secretAccessKey:i,sessionToken:process.env.AWS_SESSION_TOKEN}}function Ay(n){let i=n?.profile||process.env.AWS_PROFILE||"default",s=n?.credentialsFile||Bn($n(),".aws","credentials");if(!On(s))return null;try{let o=wt(s,"utf-8");return ui(o,i)}catch{return null}}function ui(n,i){let s=n.split(`
2459
+ `),o=null,c,u,d;for(let g of s){let y=g.trim();if(!y||y.startsWith("#")||y.startsWith(";"))continue;let h=y.match(/^\[([^\]]+)\]$/);if(h){if(o===i&&c&&u)return{accessKeyId:c,secretAccessKey:u,sessionToken:d};o=h[1],c=void 0,u=void 0,d=void 0;continue}if(o===i){let[b,...v]=y.split("="),A=v.join("=").trim();switch(b.trim().toLowerCase()){case"aws_access_key_id":c=A;break;case"aws_secret_access_key":u=A;break;case"aws_session_token":d=A;break}}}if(o===i&&c&&u)return{accessKeyId:c,secretAccessKey:u,sessionToken:d};return null}async function yy(n){let i=n?.timeout??1000,s="http://169.254.169.254";try{let o=await ze("http://169.254.169.254/latest/api/token",{method:"PUT",headers:{"X-aws-ec2-metadata-token-ttl-seconds":"21600"}},i);if(!o.ok)return null;let c=await o.text(),u=await ze("http://169.254.169.254/latest/meta-data/iam/security-credentials/",{headers:{"X-aws-ec2-metadata-token":c}},i);if(!u.ok)return null;let d=(await u.text()).trim(),g=await ze(`http://169.254.169.254/latest/meta-data/iam/security-credentials/${d}`,{headers:{"X-aws-ec2-metadata-token":c}},i);if(!g.ok)return null;let y=await g.json();return{accessKeyId:y.AccessKeyId,secretAccessKey:y.SecretAccessKey,sessionToken:y.Token,expiration:new Date(y.Expiration)}}catch{return null}}async function Sy(n){let i=n?.timeout??1000,s=process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI,o=process.env.AWS_CONTAINER_CREDENTIALS_FULL_URI,c=null;if(s)c=`http://169.254.170.2${s}`;else if(o)c=o;if(!c)return null;try{let u={},d=process.env.AWS_CONTAINER_AUTHORIZATION_TOKEN;if(d)u.Authorization=d;let g=await ze(c,{headers:u},i);if(!g.ok)return null;let y=await g.json();return{accessKeyId:y.AccessKeyId,secretAccessKey:y.SecretAccessKey,sessionToken:y.Token,expiration:new Date(y.Expiration)}}catch{return null}}async function Iy(n){let i=n?.timeout??5000,s=process.env.AWS_WEB_IDENTITY_TOKEN_FILE,o=process.env.AWS_ROLE_ARN,c=process.env.AWS_ROLE_SESSION_NAME||"ts-cloud-session";if(!s||!o)return null;try{let u=wt(s,"utf-8").trim(),d=process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||"us-east-1",g=d.startsWith("us-gov")?`https://sts.${d}.amazonaws.com`:d==="us-east-1"?"https://sts.amazonaws.com":`https://sts.${d}.amazonaws.com`,y=new URLSearchParams({Action:"AssumeRoleWithWebIdentity",Version:"2011-06-15",RoleArn:o,RoleSessionName:c,WebIdentityToken:u}),h=await ze(`${g}/?${y.toString()}`,{method:"POST"},i);if(!h.ok)return null;let b=await h.text(),v=qe(b,"AccessKeyId"),A=qe(b,"SecretAccessKey"),T=qe(b,"SessionToken"),R=qe(b,"Expiration");if(!v||!A)return null;return{accessKeyId:v,secretAccessKey:A,sessionToken:T??void 0,expiration:R?new Date(R):void 0}}catch{return null}}async function es(n){let i=hy();if(i)return i;let s=Ay(n);if(s)return s;let o=await Iy(n);if(o)return o;let c=await Sy(n);if(c)return c;let u=await yy(n);if(u)return u;throw Error("Could not find AWS credentials. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables, or configure ~/.aws/credentials, or run on an EC2 instance with an IAM role.")}function Eb(n){let i=null,s=null;return async()=>{if(i){if(!i.expiration)return i;let o=300000;if(i.expiration.getTime()-Date.now()>o)return i}if(s)return s;return s=es(n).then((o)=>(i=o,s=null,o)).catch((o)=>{throw s=null,o}),s}}async function ze(n,i,s){let o=new AbortController,c=setTimeout(()=>o.abort(),s);try{let u=await fetch(n,{...i,signal:o.signal});return clearTimeout(c),u}catch(u){throw clearTimeout(c),u}}function qe(n,i){let s=new RegExp(`<${i}>([^<]+)</${i}>`),o=n.match(s);return o?o[1]:null}async function zo(n){return es({profile:n})}function by(n){let i=process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION;if(i)return i;let s=Bn($n(),".aws","config");if(On(s))try{let o=wt(s,"utf-8"),c=n||process.env.AWS_PROFILE||"default",u=c==="default"?"[default]":`[profile ${c}]`,d=o.split(`
2460
+ `),g=!1;for(let y of d){let h=y.trim();if(h.startsWith("[")){g=h===u;continue}if(g&&h.startsWith("region")){let[,b]=h.split("=");if(b)return b.trim()}}}catch{}return"us-east-1"}async function $m(n){let i=n||await es(),s=by(),{signRequest:o}=await import("./chunk-ypsfkgme.js"),c=s.startsWith("us-gov")?`https://sts.${s}.amazonaws.com`:s==="us-east-1"?"https://sts.amazonaws.com":`https://sts.${s}.amazonaws.com`,u="Action=GetCallerIdentity&Version=2011-06-15",d=o({method:"POST",url:c,body:"Action=GetCallerIdentity&Version=2011-06-15",headers:{"Content-Type":"application/x-www-form-urlencoded"},...i,service:"sts",region:s}),g=await fetch(d.url,{method:d.method,headers:d.headers,body:d.body});if(!g.ok)throw Error(`Failed to get account ID: ${await g.text()}`);let y=await g.text(),h=qe(y,"Account");if(!h)throw Error("Failed to parse account ID from response");return h}var mi=5242880,It=5242880;var pi=5242880;class Dt{region;endpoint;forcePathStyle;credentials;credentialOptions;retryOptions;constructor(n={}){this.region=n.region||process.env.AWS_REGION||"us-east-1",this.endpoint=n.endpoint||`https://s3.${this.region}.amazonaws.com`,this.forcePathStyle=n.forcePathStyle||!1,this.credentials=n.credentials,this.credentialOptions=n.credentialOptions,this.retryOptions=n.retryOptions||{}}async getCredentials(){if(this.credentials)return this.credentials;return es(this.credentialOptions)}buildUrl(n,i){let s=i?encodeURIComponent(i).replace(/%2F/g,"/"):"";if(this.forcePathStyle)return i?`${this.endpoint}/${n}/${s}`:`${this.endpoint}/${n}`;let o=new URL(this.endpoint);return o.hostname=`${n}.${o.hostname}`,i?`${o.origin}/${s}`:o.origin}async get(n,i,s={}){let o=await this.getCredentials(),c=this.buildUrl(n,i),u={};if(s.range)u.Range=s.range;if(s.ifModifiedSince)u["If-Modified-Since"]=s.ifModifiedSince.toUTCString();if(s.ifMatch)u["If-Match"]=s.ifMatch;if(s.ifNoneMatch)u["If-None-Match"]=s.ifNoneMatch;let d=new URL(c);if(s.responseContentType)d.searchParams.set("response-content-type",s.responseContentType);if(s.responseContentDisposition)d.searchParams.set("response-content-disposition",s.responseContentDisposition);let g=k({method:"GET",url:d.toString(),headers:u,...o,service:"s3",region:this.region}),y=await fetch(g.url,{method:g.method,headers:g.headers});if(!y.ok&&y.status!==304){let h=await y.text();throw new V(`Failed to get object: ${h}`,y.status,n,i)}return y}async getText(n,i,s={}){return(await this.get(n,i,s)).text()}async getJSON(n,i,s={}){return(await this.get(n,i,s)).json()}async getBuffer(n,i,s={}){return(await this.get(n,i,s)).arrayBuffer()}async put(n,i,s,o={}){let c,u;if(typeof s==="string")c=new TextEncoder().encode(s).length,u=s;else if(s instanceof ArrayBuffer)c=s.byteLength,u=s;else if(s instanceof Uint8Array)c=s.byteLength,u=s;else if(s instanceof Blob)c=s.size,u=s;else return this.uploadMultipart(n,i,s,{...o,partSize:It});if(c>pi){let d=fi(u).stream();return this.uploadMultipart(n,i,d,{...o,partSize:It})}return this.putSimple(n,i,u,c,o)}async putSimple(n,i,s,o,c){let u=await this.getCredentials(),d=this.buildUrl(n,i),g={"Content-Length":String(o),"Content-Type":c.contentType||Fn(i)};if(c.contentEncoding)g["Content-Encoding"]=c.contentEncoding;if(c.cacheControl)g["Cache-Control"]=c.cacheControl;if(c.contentDisposition)g["Content-Disposition"]=c.contentDisposition;if(c.storageClass)g["x-amz-storage-class"]=c.storageClass;if(c.serverSideEncryption)g["x-amz-server-side-encryption"]=c.serverSideEncryption;if(c.acl)g["x-amz-acl"]=c.acl;if(c.tagging)g["x-amz-tagging"]=c.tagging;if(c.metadata)for(let[A,T]of Object.entries(c.metadata))g[`x-amz-meta-${A.toLowerCase()}`]=T;let y;if(typeof s==="string")y=s;else if(s instanceof Blob)y=await s.text();else y=new TextDecoder().decode(s instanceof ArrayBuffer?new Uint8Array(s):s);let h=k({method:"PUT",url:d,headers:g,body:y,...u,service:"s3",region:this.region}),b=await fetch(h.url,{method:h.method,headers:h.headers,body:s});if(!b.ok){let A=await b.text();throw new V(`Failed to put object: ${A}`,b.status,n,i)}return{etag:(b.headers.get("ETag")||"").replace(/"/g,"")}}async delete(n,i){let s=await this.getCredentials(),o=this.buildUrl(n,i),c=k({method:"DELETE",url:o,...s,service:"s3",region:this.region}),u=await fetch(c.url,{method:c.method,headers:c.headers});if(!u.ok&&u.status!==204){let d=await u.text();throw new V(`Failed to delete object: ${d}`,u.status,n,i)}}async deleteMany(n,i){let s=await this.getCredentials(),o=`${this.buildUrl(n)}?delete`,u=`<?xml version="1.0" encoding="UTF-8"?><Delete><Quiet>false</Quiet>${i.map((R)=>`<Object><Key>${yi(R)}</Key></Object>`).join("")}</Delete>`,d=k({method:"POST",url:o,headers:{"Content-Type":"application/xml"},body:u,...s,service:"s3",region:this.region}),g=await fetch(d.url,{method:d.method,headers:d.headers,body:u});if(!g.ok){let R=await g.text();throw new V(`Failed to delete objects: ${R}`,g.status,n)}let y=await g.text(),h=[],b=[],v=/<Deleted><Key>([^<]+)<\/Key>/g,A;while((A=v.exec(y))!==null)h.push(A[1]);let T=/<Error><Key>([^<]+)<\/Key><Code>([^<]+)<\/Code><Message>([^<]+)<\/Message>/g;while((A=T.exec(y))!==null)b.push({key:A[1],error:`${A[2]}: ${A[3]}`});return{deleted:h,errors:b}}async list(n,i={}){let s=await this.getCredentials(),o=new URL(this.buildUrl(n));if(o.searchParams.set("list-type","2"),i.prefix)o.searchParams.set("prefix",i.prefix);if(i.delimiter)o.searchParams.set("delimiter",i.delimiter);if(i.maxKeys)o.searchParams.set("max-keys",String(i.maxKeys));if(i.continuationToken)o.searchParams.set("continuation-token",i.continuationToken);if(i.startAfter)o.searchParams.set("start-after",i.startAfter);let c=k({method:"GET",url:o.toString(),...s,service:"s3",region:this.region}),u=await fetch(c.url,{method:c.method,headers:c.headers});if(!u.ok){let g=await u.text();throw new V(`Failed to list objects: ${g}`,u.status,n)}let d=await u.text();return gi(d)}async*listAll(n,i={}){let s;do{let o=await this.list(n,{...i,continuationToken:s});for(let c of o.contents)yield c;s=o.nextContinuationToken}while(s)}async head(n,i){let s=await this.getCredentials(),o=this.buildUrl(n,i),c=k({method:"HEAD",url:o,...s,service:"s3",region:this.region}),u=await fetch(c.url,{method:c.method,headers:c.headers});if(u.status===404)return null;if(!u.ok){let g=await u.text();throw new V(`Failed to head object: ${g}`,u.status,n,i)}let d={};return u.headers.forEach((g,y)=>{if(y.toLowerCase().startsWith("x-amz-meta-"))d[y.slice(11)]=g}),{contentLength:Number(u.headers.get("Content-Length")||0),contentType:u.headers.get("Content-Type")||"application/octet-stream",etag:(u.headers.get("ETag")||"").replace(/"/g,""),lastModified:new Date(u.headers.get("Last-Modified")||0),metadata:d,storageClass:u.headers.get("x-amz-storage-class")||void 0,serverSideEncryption:u.headers.get("x-amz-server-side-encryption")||void 0}}async exists(n,i){return await this.head(n,i)!==null}async copy(n,i,s,o,c={}){let u=await this.getCredentials(),d=this.buildUrl(s,o),g={"x-amz-copy-source":`/${n}/${encodeURIComponent(i)}`};if(c.metadataDirective)g["x-amz-metadata-directive"]=c.metadataDirective;if(c.contentType)g["Content-Type"]=c.contentType;if(c.storageClass)g["x-amz-storage-class"]=c.storageClass;if(c.acl)g["x-amz-acl"]=c.acl;if(c.metadata)for(let[T,R]of Object.entries(c.metadata))g[`x-amz-meta-${T.toLowerCase()}`]=R;let y=k({method:"PUT",url:d,headers:g,...u,service:"s3",region:this.region}),h=await fetch(y.url,{method:y.method,headers:y.headers});if(!h.ok){let T=await h.text();throw new V(`Failed to copy object: ${T}`,h.status,s,o)}let v=(await h.text()).match(/<ETag>"?([^"<]+)"?<\/ETag>/);return{etag:v?v[1]:""}}async getPresignedUrl(n,i,s={}){let o=await this.getCredentials(),c=this.buildUrl(n,i);return na({url:c,method:s.method||"GET",expiresIn:s.expiresIn||3600,...o,service:"s3",region:this.region})}async uploadMultipart(n,i,s,o={}){let c=await this.getCredentials(),u=Math.max(o.partSize||It,mi),d,g;if(s instanceof ReadableStream)d=s;else if(s instanceof Blob)d=s.stream(),g=s.size;else{let b=new Blob([s]);d=b.stream(),g=b.size}let{uploadId:y,baseUrl:h}=await this.initiateMultipartUpload(n,i,o);try{let b=await this.uploadParts(n,i,h,y,d,u,c,g,o.concurrency||4,o.onProgress);return await this.completeMultipartUpload(n,i,h,y,b)}catch(b){throw await this.abortMultipartUpload(n,i,y,h).catch(()=>{}),b}}async initiateMultipartUpload(n,i,s){let o=await this.getCredentials(),c=this.buildUrl(n,i),u=`${c}?uploads`,d={"Content-Type":s.contentType||Fn(i)};if(s.storageClass)d["x-amz-storage-class"]=s.storageClass;if(s.serverSideEncryption)d["x-amz-server-side-encryption"]=s.serverSideEncryption;if(s.acl)d["x-amz-acl"]=s.acl;if(s.metadata)for(let[A,T]of Object.entries(s.metadata))d[`x-amz-meta-${A.toLowerCase()}`]=T;let g=k({method:"POST",url:u,headers:d,...o,service:"s3",region:this.region}),y=await fetch(g.url,{method:g.method,headers:g.headers});if(!y.ok){let A=await y.text();throw new V(`Failed to initiate multipart upload: ${A}`,y.status,n,i)}let b=(await y.text()).match(/<UploadId>([^<]+)<\/UploadId>/);if(!b)throw new V("Failed to parse upload ID from response",0,n,i);let v=c;if(y.url)try{let A=new URL(y.url);A.search="",v=A.toString()}catch{}return{uploadId:b[1],baseUrl:v}}async uploadParts(n,i,s,o,c,u,d,g,y,h){let b=[],v=c.getReader(),A=1,T=new Uint8Array(0),R=0,P=g?Math.ceil(g/u):void 0,I=new Map,M=async(N,O)=>{let B=`${s}?partNumber=${O}&uploadId=${encodeURIComponent(o)}`,F={"Content-Length":String(N.byteLength),"x-amz-content-sha256":"UNSIGNED-PAYLOAD"},U=k({method:"PUT",url:B,headers:F,...d,service:"s3",region:this.region}),j=await fetch(U.url,{method:U.method,headers:U.headers,body:N,redirect:"error"});if(!j.ok){let z=await j.text();throw new V(`Failed to upload part ${O}: ${z}`,j.status,n,i)}let H=(j.headers.get("ETag")||"").replace(/"/g,"");if(!H)throw new V(`Missing ETag for part ${O}`,j.status,n,i);return{partNumber:O,etag:H}},L=async()=>{let N=await Promise.race(I.values());I.delete(N.partNumber),b.push(N)};while(!0){let{done:N,value:O}=await v.read();if(O){let B=new Uint8Array(T.length+O.length);B.set(T),B.set(O,T.length),T=B}while(T.length>=u||N&&T.length>0){let B=T.slice(0,u);T=T.slice(u);let F=A++;if(I.size>=y)await L();if(I.set(F,M(B,F)),R+=B.byteLength,h)h({loaded:R,total:g||R,part:F,totalParts:P||F})}if(N)break}while(I.size>0)await L();return b.sort((N,O)=>N.partNumber-O.partNumber),b}async completeMultipartUpload(n,i,s,o,c){let u=await this.getCredentials(),d=`${s}?uploadId=${encodeURIComponent(o)}`,y=`<?xml version="1.0" encoding="UTF-8"?><CompleteMultipartUpload>${c.map((R)=>`<Part><PartNumber>${R.partNumber}</PartNumber><ETag>"${R.etag}"</ETag></Part>`).join("")}</CompleteMultipartUpload>`,h=k({method:"POST",url:d,headers:{"Content-Type":"application/xml"},body:y,...u,service:"s3",region:this.region}),b=await fetch(h.url,{method:h.method,headers:h.headers,body:y});if(!b.ok){let R=await b.text();throw new V(`Failed to complete multipart upload: ${R}`,b.status,n,i)}let A=(await b.text()).match(/<ETag>"?([^"<]+)"?<\/ETag>/);return{etag:A?A[1]:""}}async abortMultipartUpload(n,i,s,o){let c=await this.getCredentials(),u=`${o??this.buildUrl(n,i)}?uploadId=${encodeURIComponent(s)}`,d=k({method:"DELETE",url:u,...c,service:"s3",region:this.region});await fetch(d.url,{method:d.method,headers:d.headers})}async emptyAndDeleteBucket(n){let s=[];for await(let d of this.listAll(n,{}))if(s.push(d.key),s.length>=1000)await this.deleteMany(n,s),s=[];if(s.length>0)await this.deleteMany(n,s);let o=await this.getCredentials(),c=this.buildUrl(n),u=k({method:"DELETE",url:c,...o,service:"s3",region:this.region});await fetch(u.url,{method:u.method,headers:u.headers})}}class V extends Error{statusCode;bucket;key;constructor(n,i,s,o){super(n);this.statusCode=i;this.bucket=s;this.key=o;this.name="S3Error"}}function gi(n){let i=[],s=[],o=/<Contents>([\s\S]*?)<\/Contents>/g,c;while((c=o.exec(n))!==null){let d=c[1];i.push({key:me(d,"Key")||"",lastModified:new Date(me(d,"LastModified")||0),etag:(me(d,"ETag")||"").replace(/"/g,""),size:Number(me(d,"Size")||0),storageClass:me(d,"StorageClass")||"STANDARD"})}let u=/<CommonPrefixes><Prefix>([^<]+)<\/Prefix><\/CommonPrefixes>/g;while((c=u.exec(n))!==null)s.push(c[1]);return{contents:i,commonPrefixes:s,isTruncated:me(n,"IsTruncated")==="true",continuationToken:me(n,"ContinuationToken")||void 0,nextContinuationToken:me(n,"NextContinuationToken")||void 0,keyCount:Number(me(n,"KeyCount")||0),maxKeys:Number(me(n,"MaxKeys")||1000),prefix:me(n,"Prefix")||void 0,delimiter:me(n,"Delimiter")||void 0}}function me(n,i){let s=new RegExp(`<${i}>([^<]*)</${i}>`),o=n.match(s);return o?o[1]:null}function yi(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function Fn(n){let i=n.split(".").pop()?.toLowerCase();return{html:"text/html",htm:"text/html",css:"text/css",js:"application/javascript",mjs:"application/javascript",json:"application/json",xml:"application/xml",txt:"text/plain",md:"text/markdown",csv:"text/csv",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",ico:"image/x-icon",avif:"image/avif",mp4:"video/mp4",webm:"video/webm",mov:"video/quicktime",avi:"video/x-msvideo",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",zip:"application/zip",gz:"application/gzip",tar:"application/x-tar",rar:"application/vnd.rar","7z":"application/x-7z-compressed",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",otf:"font/otf",eot:"application/vnd.ms-fontobject",wasm:"application/wasm"}[i||""]||"application/octet-stream"}function fi(n){if(n instanceof Blob)return n;if(typeof n==="string")return new Blob([n],{type:"text/plain"});return new Blob([n])}function Cy(n){return new Dt(n)}class nt extends Error{code;solution;details;constructor(n,i,s,o){super(n);this.code=i;this.solution=s;this.details=o;this.name="CloudError",Error.captureStackTrace?.(this,nt)}toString(){let n=`${this.name} [${this.code}]: ${this.message}`;if(this.solution)n+=`
2461
2461
 
2462
2462
  \uD83D\uDCA1 Solution: ${this.solution}`;if(this.details&&Object.keys(this.details).length>0){n+=`
2463
2463
 
2464
2464
  Details:`;for(let[i,s]of Object.entries(this.details))n+=`
2465
- ${i}: ${JSON.stringify(s)}`}return n}}class Ko extends rt{constructor(n,i,s){super(n,"CONFIG_ERROR",i,s);this.name="ConfigurationError"}}class xt extends rt{constructor(n,i,s){super(n,"CREDENTIAL_ERROR",i,s);this.name="CredentialError"}}class Ey extends rt{constructor(n,i,s){super(n,"DEPLOYMENT_ERROR",i,s);this.name="DeploymentError"}}class Mm extends rt{constructor(n,i,s){super(n,"VALIDATION_ERROR",i,s);this.name="ValidationError"}}class vy extends rt{statusCode;constructor(n,i,s,o){super(n,"AWS_API_ERROR",s,o);this.statusCode=i;this.name="AWSAPIError"}}var Ty={NO_CREDENTIALS:{message:"AWS credentials not found",solution:`Configure AWS credentials using one of these methods:
2465
+ ${i}: ${JSON.stringify(s)}`}return n}}class Ko extends nt{constructor(n,i,s){super(n,"CONFIG_ERROR",i,s);this.name="ConfigurationError"}}class Ot extends nt{constructor(n,i,s){super(n,"CREDENTIAL_ERROR",i,s);this.name="CredentialError"}}class Ey extends nt{constructor(n,i,s){super(n,"DEPLOYMENT_ERROR",i,s);this.name="DeploymentError"}}class Mm extends nt{constructor(n,i,s){super(n,"VALIDATION_ERROR",i,s);this.name="ValidationError"}}class vy extends nt{statusCode;constructor(n,i,s,o){super(n,"AWS_API_ERROR",s,o);this.statusCode=i;this.name="AWSAPIError"}}var Ty={NO_CREDENTIALS:{message:"AWS credentials not found",solution:`Configure AWS credentials using one of these methods:
2466
2466
  1. Set environment variables: AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY
2467
2467
  2. Create ~/.aws/credentials file with your credentials
2468
2468
  3. Use an IAM role (for EC2 instances)
2469
- 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 wy(n){return Ty[n]}function Fm(n,i){let s=wy(n);return new rt(s.message,n,s.solution,i)}class q{static verboseMode=!1;static debugMode=!1;static setVerbose(n){this.verboseMode=n}static setDebug(n){this.debugMode=n}static verbose(n,...i){if(this.verboseMode)console.log(`[VERBOSE] ${n}`,...i)}static debug(n,...i){if(this.debugMode)console.log(`[DEBUG] ${n}`,...i)}static info(n,...i){console.log(`ℹ ${n}`,...i)}static warn(n,...i){console.warn(`⚠ ${n}`,...i)}static error(n,i){if(console.error(`✖ ${n}`),i){if(i instanceof rt)console.error(i.toString());else console.error(i.message);if(this.debugMode&&i.stack)console.error(`
2470
- Stack trace:`),console.error(i.stack)}}static success(n){console.log(`✔ ${n}`)}}function vb(n){if(!n)throw Fm("MISSING_CONFIG");if(!n.project)throw new Ko("Missing required field: project","Add a project configuration with name, slug, and region",{field:"project"});if(!n.project.name)throw new Ko("Missing required field: project.name","Add a project name to your configuration",{field:"project.name"});if(!n.project.slug)throw new Ko("Missing required field: project.slug","Add a project slug (lowercase, alphanumeric with hyphens)",{field:"project.slug"});if(!/^[a-z0-9-]+$/.test(n.project.slug))throw new Mm("Invalid project slug format","Use only lowercase letters, numbers, and hyphens",{slug:n.project.slug});if(n.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(n.project.region))throw Fm("INVALID_REGION",{region:n.project.region})}q.success("Configuration validation passed")}function Tb(n){let i=[];if(n.environments?.production&&n.infrastructure?.database){let s=n.infrastructure.database;if((s.postgres||s.mysql)&&!s.postgres?.multiAZ&&!s.mysql?.multiAZ)i.push("Production database should use Multi-AZ for high availability")}if(n.infrastructure?.storage){for(let[s,o]of Object.entries(n.infrastructure.storage))if(o.encryption===!1)i.push(`Storage "${s}" is not encrypted - consider enabling encryption for security`)}if(n.infrastructure?.storage){for(let[s,o]of Object.entries(n.infrastructure.storage))if(o.public===!0)i.push(`Storage "${s}" is publicly accessible - ensure this is intentional`)}if(n.infrastructure?.database){let s=n.infrastructure.database;if(s.postgres||s.mysql){let o=s.postgres?.backupRetentionDays||s.mysql?.backupRetentionDays;if(!o||o<7)i.push("Database backup retention is less than 7 days - consider increasing for production")}}if(!n.infrastructure?.monitoring)i.push("No monitoring configured - consider adding CloudWatch alarms");return i}async function wb(n="default"){try{q.verbose("Resolving AWS credentials...");let i=await zo(n);if(!i.accessKeyId||!i.secretAccessKey)throw new xt("AWS credentials are incomplete","Ensure both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are set");q.verbose("Credentials resolved successfully"),q.debug("Access Key ID:",i.accessKeyId.substring(0,8)+"..."),q.verbose("Testing credentials with GetCallerIdentity...");let s;try{s=await $m(i),q.verbose("Credentials are valid"),q.debug("Account ID:",s)}catch(o){if(o instanceof Error)if(o.message.includes("InvalidClientTokenId"))throw new xt("Invalid AWS access key ID","Check that your AWS_ACCESS_KEY_ID is correct");else if(o.message.includes("SignatureDoesNotMatch"))throw new xt("Invalid AWS secret access key","Check that your AWS_SECRET_ACCESS_KEY is correct");else if(o.message.includes("ExpiredToken"))throw new xt("AWS credentials have expired","Refresh your temporary credentials or use long-term credentials");else throw new xt(`Failed to validate credentials: ${o.message}`,"Verify your AWS credentials are correct and have the necessary permissions");throw o}return{valid:!0,accountId:s,region:i.region}}catch(i){if(i instanceof xt)throw i;return{valid:!1,error:i instanceof Error?i.message:"Unknown error"}}}async function Rb(n,i){return{allowed:i,denied:[]}}function Ry(n){let i=new Set(["cloudformation:CreateStack","cloudformation:UpdateStack","cloudformation:DeleteStack","cloudformation:DescribeStacks","cloudformation:DescribeStackEvents","cloudformation:GetTemplate","cloudformation:ListStacks"]);if(n.infrastructure){if(n.infrastructure.storage)i.add("s3:CreateBucket"),i.add("s3:DeleteBucket"),i.add("s3:PutBucketPolicy"),i.add("s3:PutBucketVersioning"),i.add("s3:PutBucketEncryption"),i.add("s3:PutObject"),i.add("s3:GetObject");if(n.infrastructure.compute){if(n.infrastructure.compute.server)i.add("ec2:RunInstances"),i.add("ec2:TerminateInstances"),i.add("ec2:DescribeInstances"),i.add("autoscaling:CreateAutoScalingGroup"),i.add("autoscaling:UpdateAutoScalingGroup"),i.add("autoscaling:DeleteAutoScalingGroup"),i.add("elasticloadbalancing:CreateLoadBalancer"),i.add("elasticloadbalancing:DeleteLoadBalancer");if(n.infrastructure.compute.fargate)i.add("ecs:CreateCluster"),i.add("ecs:DeleteCluster"),i.add("ecs:CreateService"),i.add("ecs:UpdateService"),i.add("ecs:DeleteService"),i.add("ecs:RegisterTaskDefinition")}if(n.infrastructure.database){if(n.infrastructure.database.postgres||n.infrastructure.database.mysql)i.add("rds:CreateDBInstance"),i.add("rds:DeleteDBInstance"),i.add("rds:ModifyDBInstance"),i.add("rds:DescribeDBInstances");if(n.infrastructure.database.dynamodb)i.add("dynamodb:CreateTable"),i.add("dynamodb:DeleteTable"),i.add("dynamodb:UpdateTable"),i.add("dynamodb:DescribeTable")}if(n.infrastructure.functions)i.add("lambda:CreateFunction"),i.add("lambda:DeleteFunction"),i.add("lambda:UpdateFunctionCode"),i.add("lambda:UpdateFunctionConfiguration"),i.add("lambda:AddPermission");if(n.infrastructure.cdn)i.add("cloudfront:CreateDistribution"),i.add("cloudfront:UpdateDistribution"),i.add("cloudfront:DeleteDistribution"),i.add("cloudfront:GetDistribution");if(n.infrastructure.network)i.add("ec2:CreateVpc"),i.add("ec2:DeleteVpc"),i.add("ec2:CreateSubnet"),i.add("ec2:DeleteSubnet"),i.add("ec2:CreateInternetGateway"),i.add("ec2:DeleteInternetGateway"),i.add("ec2:CreateNatGateway"),i.add("ec2:DeleteNatGateway"),i.add("ec2:CreateRouteTable"),i.add("ec2:DeleteRouteTable"),i.add("ec2:CreateSecurityGroup"),i.add("ec2:DeleteSecurityGroup")}return i.add("iam:CreateRole"),i.add("iam:DeleteRole"),i.add("iam:AttachRolePolicy"),i.add("iam:DetachRolePolicy"),i.add("iam:PutRolePolicy"),i.add("iam:GetRole"),i.add("iam:PassRole"),Array.from(i).sort()}function Db(n){let i=Ry(n);return JSON.stringify({Version:"2012-10-17",Statement:[{Effect:"Allow",Action:i,Resource:"*"}]},null,2)}var te={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 Pb(n){let i=[];if(q.verbose("Checking AWS service quotas..."),n.infrastructure?.compute?.server){let o=n.infrastructure.compute.server.autoScaling?.max||1;i.push({service:"EC2",quotaName:"Running On-Demand Instances",currentValue:o,limit:te.ec2["Running On-Demand Instances"],percentage:o/te.ec2["Running On-Demand Instances"]*100,warning:o>te.ec2["Running On-Demand Instances"]*0.8})}if(n.infrastructure?.network?.vpc)i.push({service:"EC2",quotaName:"VPCs",currentValue:1,limit:te.ec2.VPCs,percentage:1/te.ec2.VPCs*100,warning:!1});if(n.infrastructure?.database?.postgres||n.infrastructure?.database?.mysql)i.push({service:"RDS",quotaName:"DB Instances",currentValue:1,limit:te.rds["DB Instances"],percentage:1/te.rds["DB Instances"]*100,warning:!1});if(n.infrastructure?.storage){let o=Object.keys(n.infrastructure.storage).length;i.push({service:"S3",quotaName:"Buckets",currentValue:o,limit:te.s3.Buckets,percentage:o/te.s3.Buckets*100,warning:o>te.s3.Buckets*0.8})}if(n.infrastructure?.functions){let o=0;for(let c of Object.values(n.infrastructure.functions))if(Array.isArray(c))o+=c.length;i.push({service:"Lambda",quotaName:"Functions (estimated)",currentValue:o,limit:1000,percentage:o/1000*100,warning:o>800})}if(n.infrastructure?.database?.dynamodb){let o=n.infrastructure.database.dynamodb.tables?.length||0;i.push({service:"DynamoDB",quotaName:"Tables",currentValue:o,limit:te.dynamodb.Tables,percentage:o/te.dynamodb.Tables*100,warning:o>te.dynamodb.Tables*0.8})}let s=i.filter((o)=>o.warning);if(s.length>0){q.warn("Service quota warnings detected:");for(let o of s)q.warn(` ${o.service} - ${o.quotaName}: ${o.currentValue}/${o.limit} (${o.percentage.toFixed(1)}%)`)}else q.verbose("All service quotas are within limits");return i}function kb(n){if(n.length===0)return"No quotas to check";let i=`Service Quota Usage:
2469
+ 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 wy(n){return Ty[n]}function Fm(n,i){let s=wy(n);return new nt(s.message,n,s.solution,i)}class q{static verboseMode=!1;static debugMode=!1;static setVerbose(n){this.verboseMode=n}static setDebug(n){this.debugMode=n}static verbose(n,...i){if(this.verboseMode)console.log(`[VERBOSE] ${n}`,...i)}static debug(n,...i){if(this.debugMode)console.log(`[DEBUG] ${n}`,...i)}static info(n,...i){console.log(`ℹ ${n}`,...i)}static warn(n,...i){console.warn(`⚠ ${n}`,...i)}static error(n,i){if(console.error(`✖ ${n}`),i){if(i instanceof nt)console.error(i.toString());else console.error(i.message);if(this.debugMode&&i.stack)console.error(`
2470
+ Stack trace:`),console.error(i.stack)}}static success(n){console.log(`✔ ${n}`)}}function vb(n){if(!n)throw Fm("MISSING_CONFIG");if(!n.project)throw new Ko("Missing required field: project","Add a project configuration with name, slug, and region",{field:"project"});if(!n.project.name)throw new Ko("Missing required field: project.name","Add a project name to your configuration",{field:"project.name"});if(!n.project.slug)throw new Ko("Missing required field: project.slug","Add a project slug (lowercase, alphanumeric with hyphens)",{field:"project.slug"});if(!/^[a-z0-9-]+$/.test(n.project.slug))throw new Mm("Invalid project slug format","Use only lowercase letters, numbers, and hyphens",{slug:n.project.slug});if(n.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(n.project.region))throw Fm("INVALID_REGION",{region:n.project.region})}q.success("Configuration validation passed")}function Tb(n){let i=[];if(n.environments?.production&&n.infrastructure?.database){let s=n.infrastructure.database;if((s.postgres||s.mysql)&&!s.postgres?.multiAZ&&!s.mysql?.multiAZ)i.push("Production database should use Multi-AZ for high availability")}if(n.infrastructure?.storage){for(let[s,o]of Object.entries(n.infrastructure.storage))if(o.encryption===!1)i.push(`Storage "${s}" is not encrypted - consider enabling encryption for security`)}if(n.infrastructure?.storage){for(let[s,o]of Object.entries(n.infrastructure.storage))if(o.public===!0)i.push(`Storage "${s}" is publicly accessible - ensure this is intentional`)}if(n.infrastructure?.database){let s=n.infrastructure.database;if(s.postgres||s.mysql){let o=s.postgres?.backupRetentionDays||s.mysql?.backupRetentionDays;if(!o||o<7)i.push("Database backup retention is less than 7 days - consider increasing for production")}}if(!n.infrastructure?.monitoring)i.push("No monitoring configured - consider adding CloudWatch alarms");return i}async function wb(n="default"){try{q.verbose("Resolving AWS credentials...");let i=await zo(n);if(!i.accessKeyId||!i.secretAccessKey)throw new Ot("AWS credentials are incomplete","Ensure both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are set");q.verbose("Credentials resolved successfully"),q.debug("Access Key ID:",i.accessKeyId.substring(0,8)+"..."),q.verbose("Testing credentials with GetCallerIdentity...");let s;try{s=await $m(i),q.verbose("Credentials are valid"),q.debug("Account ID:",s)}catch(o){if(o instanceof Error)if(o.message.includes("InvalidClientTokenId"))throw new Ot("Invalid AWS access key ID","Check that your AWS_ACCESS_KEY_ID is correct");else if(o.message.includes("SignatureDoesNotMatch"))throw new Ot("Invalid AWS secret access key","Check that your AWS_SECRET_ACCESS_KEY is correct");else if(o.message.includes("ExpiredToken"))throw new Ot("AWS credentials have expired","Refresh your temporary credentials or use long-term credentials");else throw new Ot(`Failed to validate credentials: ${o.message}`,"Verify your AWS credentials are correct and have the necessary permissions");throw o}return{valid:!0,accountId:s,region:i.region}}catch(i){if(i instanceof Ot)throw i;return{valid:!1,error:i instanceof Error?i.message:"Unknown error"}}}async function Rb(n,i){return{allowed:i,denied:[]}}function Ry(n){let i=new Set(["cloudformation:CreateStack","cloudformation:UpdateStack","cloudformation:DeleteStack","cloudformation:DescribeStacks","cloudformation:DescribeStackEvents","cloudformation:GetTemplate","cloudformation:ListStacks"]);if(n.infrastructure){if(n.infrastructure.storage)i.add("s3:CreateBucket"),i.add("s3:DeleteBucket"),i.add("s3:PutBucketPolicy"),i.add("s3:PutBucketVersioning"),i.add("s3:PutBucketEncryption"),i.add("s3:PutObject"),i.add("s3:GetObject");if(n.infrastructure.compute){if(n.infrastructure.compute.server)i.add("ec2:RunInstances"),i.add("ec2:TerminateInstances"),i.add("ec2:DescribeInstances"),i.add("autoscaling:CreateAutoScalingGroup"),i.add("autoscaling:UpdateAutoScalingGroup"),i.add("autoscaling:DeleteAutoScalingGroup"),i.add("elasticloadbalancing:CreateLoadBalancer"),i.add("elasticloadbalancing:DeleteLoadBalancer");if(n.infrastructure.compute.fargate)i.add("ecs:CreateCluster"),i.add("ecs:DeleteCluster"),i.add("ecs:CreateService"),i.add("ecs:UpdateService"),i.add("ecs:DeleteService"),i.add("ecs:RegisterTaskDefinition")}if(n.infrastructure.database){if(n.infrastructure.database.postgres||n.infrastructure.database.mysql)i.add("rds:CreateDBInstance"),i.add("rds:DeleteDBInstance"),i.add("rds:ModifyDBInstance"),i.add("rds:DescribeDBInstances");if(n.infrastructure.database.dynamodb)i.add("dynamodb:CreateTable"),i.add("dynamodb:DeleteTable"),i.add("dynamodb:UpdateTable"),i.add("dynamodb:DescribeTable")}if(n.infrastructure.functions)i.add("lambda:CreateFunction"),i.add("lambda:DeleteFunction"),i.add("lambda:UpdateFunctionCode"),i.add("lambda:UpdateFunctionConfiguration"),i.add("lambda:AddPermission");if(n.infrastructure.cdn)i.add("cloudfront:CreateDistribution"),i.add("cloudfront:UpdateDistribution"),i.add("cloudfront:DeleteDistribution"),i.add("cloudfront:GetDistribution");if(n.infrastructure.network)i.add("ec2:CreateVpc"),i.add("ec2:DeleteVpc"),i.add("ec2:CreateSubnet"),i.add("ec2:DeleteSubnet"),i.add("ec2:CreateInternetGateway"),i.add("ec2:DeleteInternetGateway"),i.add("ec2:CreateNatGateway"),i.add("ec2:DeleteNatGateway"),i.add("ec2:CreateRouteTable"),i.add("ec2:DeleteRouteTable"),i.add("ec2:CreateSecurityGroup"),i.add("ec2:DeleteSecurityGroup")}return i.add("iam:CreateRole"),i.add("iam:DeleteRole"),i.add("iam:AttachRolePolicy"),i.add("iam:DetachRolePolicy"),i.add("iam:PutRolePolicy"),i.add("iam:GetRole"),i.add("iam:PassRole"),Array.from(i).sort()}function Db(n){let i=Ry(n);return JSON.stringify({Version:"2012-10-17",Statement:[{Effect:"Allow",Action:i,Resource:"*"}]},null,2)}var te={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 Pb(n){let i=[];if(q.verbose("Checking AWS service quotas..."),n.infrastructure?.compute?.server){let o=n.infrastructure.compute.server.autoScaling?.max||1;i.push({service:"EC2",quotaName:"Running On-Demand Instances",currentValue:o,limit:te.ec2["Running On-Demand Instances"],percentage:o/te.ec2["Running On-Demand Instances"]*100,warning:o>te.ec2["Running On-Demand Instances"]*0.8})}if(n.infrastructure?.network?.vpc)i.push({service:"EC2",quotaName:"VPCs",currentValue:1,limit:te.ec2.VPCs,percentage:1/te.ec2.VPCs*100,warning:!1});if(n.infrastructure?.database?.postgres||n.infrastructure?.database?.mysql)i.push({service:"RDS",quotaName:"DB Instances",currentValue:1,limit:te.rds["DB Instances"],percentage:1/te.rds["DB Instances"]*100,warning:!1});if(n.infrastructure?.storage){let o=Object.keys(n.infrastructure.storage).length;i.push({service:"S3",quotaName:"Buckets",currentValue:o,limit:te.s3.Buckets,percentage:o/te.s3.Buckets*100,warning:o>te.s3.Buckets*0.8})}if(n.infrastructure?.functions){let o=0;for(let c of Object.values(n.infrastructure.functions))if(Array.isArray(c))o+=c.length;i.push({service:"Lambda",quotaName:"Functions (estimated)",currentValue:o,limit:1000,percentage:o/1000*100,warning:o>800})}if(n.infrastructure?.database?.dynamodb){let o=n.infrastructure.database.dynamodb.tables?.length||0;i.push({service:"DynamoDB",quotaName:"Tables",currentValue:o,limit:te.dynamodb.Tables,percentage:o/te.dynamodb.Tables*100,warning:o>te.dynamodb.Tables*0.8})}let s=i.filter((o)=>o.warning);if(s.length>0){q.warn("Service quota warnings detected:");for(let o of s)q.warn(` ${o.service} - ${o.quotaName}: ${o.currentValue}/${o.limit} (${o.percentage.toFixed(1)}%)`)}else q.verbose("All service quotas are within limits");return i}function kb(n){if(n.length===0)return"No quotas to check";let i=`Service Quota Usage:
2471
2471
 
2472
2472
  `,s=n.reduce((o,c)=>{if(!o[c.service])o[c.service]=[];return o[c.service].push(c),o},{});for(let[o,c]of Object.entries(s)){i+=`${o}:
2473
2473
  `;for(let u of c){let d=u.warning?"⚠":"✓";i+=` ${d} ${u.quotaName}: ${u.currentValue}/${u.limit} (${u.percentage.toFixed(1)}%)
2474
2474
  `}i+=`
2475
- `}return i}function Nb(n){let i=[];for(let s of n)if(s.percentage>=100)i.push(`Request quota increase for ${s.service} - ${s.quotaName} (currently ${s.limit})`);else if(s.warning)i.push(`Consider requesting quota increase for ${s.service} - ${s.quotaName} (${s.percentage.toFixed(1)}% used)`);return i}import{createHash as Wn}from"node:crypto";import{existsSync as ut,mkdirSync as hi,readdirSync as Gn,readFileSync as _n,unlinkSync as Qe,writeFileSync as bi}from"node:fs";import{join as Lt}from"node:path";class Al{cacheDir;ttl;constructor(n,i={}){this.cacheDir=n,this.ttl=i.ttl||86400000}ensureCacheDir(){if(!ut(this.cacheDir))hi(this.cacheDir,{recursive:!0})}getCachePath(n){let i=Wn("sha256").update(n).digest("hex");return Lt(this.cacheDir,`${i}.json`)}get(n){let i=this.getCachePath(n);if(!ut(i))return;try{let s=_n(i,"utf-8"),o=JSON.parse(s);if(Date.now()-o.timestamp>this.ttl){Qe(i);return}return o.value}catch{Qe(i);return}}set(n,i,s){this.ensureCacheDir();let o=this.getCachePath(n),c={value:i,timestamp:Date.now(),hash:s};bi(o,JSON.stringify(c),"utf-8")}has(n){return this.get(n)!==void 0}clear(){if(!ut(this.cacheDir))return;let n=Gn(this.cacheDir);for(let i of n)Qe(Lt(this.cacheDir,i))}prune(){if(!ut(this.cacheDir))return;let n=Gn(this.cacheDir),i=Date.now();for(let s of n){let o=Lt(this.cacheDir,s);try{let c=_n(o,"utf-8"),u=JSON.parse(c);if(i-u.timestamp>this.ttl)Qe(o)}catch{Qe(o)}}}}class yl{cache;constructor(n=Q("cache","templates")){this.cache=new Al(n,{ttl:86400000})}getTemplate(n){return this.cache.get(`template:${n}`)}setTemplate(n,i){let s=this.hashTemplate(i);this.cache.set(`template:${n}`,i,s)}hasChanged(n,i){let s=this.cache.get(`template:${n}`);if(!s)return!0;let o=this.hashTemplate(s),c=this.hashTemplate(i);return o!==c}hashTemplate(n){return Wn("sha256").update(n).digest("hex")}clear(){this.cache.clear()}prune(){this.cache.prune()}}var Ot=null;function Dy(){if(!Ot)Ot=new yl;return Ot}import{createHash as $t}from"node:crypto";import{createReadStream as Si,readdirSync as Ai,statSync as dt}from"node:fs";import{join as Ci,relative as vi}from"node:path";async function Um(n,i={}){let s=i.algorithm||"sha256",o=i.chunkSize||65536;return new Promise((c,u)=>{let d=$t(s),g=Si(n,{highWaterMark:o});g.on("data",(y)=>d.update(y)),g.on("end",()=>c(d.digest("hex"))),g.on("error",u)})}function Qm(n,i="sha256"){return $t(i).update(n).digest("hex")}function Bb(n,i="sha256"){return $t(i).update(n).digest("hex")}async function xb(n,i={}){let s=i.ignorePatterns||["node_modules",".git","dist","build",cn()],o=[];async function c(u){let d=Ai(u,{withFileTypes:!0});for(let g of d){let y=Ci(u,g.name),h=vi(n,y);if(s.some((b)=>h.includes(b)))continue;if(g.isDirectory())await c(y);else if(g.isFile()){let b=dt(y),v=await Um(y,i);o.push({path:h,hash:v,size:b.size,mtime:b.mtimeMs})}}}return await c(n),o}function Ob(n){let s=[...n].sort((o,c)=>o.path.localeCompare(c.path)).map((o)=>`${o.path}:${o.hash}`).join(`
2475
+ `}return i}function Nb(n){let i=[];for(let s of n)if(s.percentage>=100)i.push(`Request quota increase for ${s.service} - ${s.quotaName} (currently ${s.limit})`);else if(s.warning)i.push(`Consider requesting quota increase for ${s.service} - ${s.quotaName} (${s.percentage.toFixed(1)}% used)`);return i}import{createHash as Wn}from"node:crypto";import{existsSync as ut,mkdirSync as hi,readdirSync as Gn,readFileSync as _n,unlinkSync as Qe,writeFileSync as bi}from"node:fs";import{join as Mt}from"node:path";class Al{cacheDir;ttl;constructor(n,i={}){this.cacheDir=n,this.ttl=i.ttl||86400000}ensureCacheDir(){if(!ut(this.cacheDir))hi(this.cacheDir,{recursive:!0})}getCachePath(n){let i=Wn("sha256").update(n).digest("hex");return Mt(this.cacheDir,`${i}.json`)}get(n){let i=this.getCachePath(n);if(!ut(i))return;try{let s=_n(i,"utf-8"),o=JSON.parse(s);if(Date.now()-o.timestamp>this.ttl){Qe(i);return}return o.value}catch{Qe(i);return}}set(n,i,s){this.ensureCacheDir();let o=this.getCachePath(n),c={value:i,timestamp:Date.now(),hash:s};bi(o,JSON.stringify(c),"utf-8")}has(n){return this.get(n)!==void 0}clear(){if(!ut(this.cacheDir))return;let n=Gn(this.cacheDir);for(let i of n)Qe(Mt(this.cacheDir,i))}prune(){if(!ut(this.cacheDir))return;let n=Gn(this.cacheDir),i=Date.now();for(let s of n){let o=Mt(this.cacheDir,s);try{let c=_n(o,"utf-8"),u=JSON.parse(c);if(i-u.timestamp>this.ttl)Qe(o)}catch{Qe(o)}}}}class yl{cache;constructor(n=Q("cache","templates")){this.cache=new Al(n,{ttl:86400000})}getTemplate(n){return this.cache.get(`template:${n}`)}setTemplate(n,i){let s=this.hashTemplate(i);this.cache.set(`template:${n}`,i,s)}hasChanged(n,i){let s=this.cache.get(`template:${n}`);if(!s)return!0;let o=this.hashTemplate(s),c=this.hashTemplate(i);return o!==c}hashTemplate(n){return Wn("sha256").update(n).digest("hex")}clear(){this.cache.clear()}prune(){this.cache.prune()}}var Lt=null;function Dy(){if(!Lt)Lt=new yl;return Lt}import{createHash as $t}from"node:crypto";import{createReadStream as Si,readdirSync as Ai,statSync as dt}from"node:fs";import{join as Ci,relative as vi}from"node:path";async function Um(n,i={}){let s=i.algorithm||"sha256",o=i.chunkSize||65536;return new Promise((c,u)=>{let d=$t(s),g=Si(n,{highWaterMark:o});g.on("data",(y)=>d.update(y)),g.on("end",()=>c(d.digest("hex"))),g.on("error",u)})}function Qm(n,i="sha256"){return $t(i).update(n).digest("hex")}function Bb(n,i="sha256"){return $t(i).update(n).digest("hex")}async function xb(n,i={}){let s=i.ignorePatterns||["node_modules",".git","dist","build",dn()],o=[];async function c(u){let d=Ai(u,{withFileTypes:!0});for(let g of d){let y=Ci(u,g.name),h=vi(n,y);if(s.some((b)=>h.includes(b)))continue;if(g.isDirectory())await c(y);else if(g.isFile()){let b=dt(y),v=await Um(y,i);o.push({path:h,hash:v,size:b.size,mtime:b.mtimeMs})}}}return await c(n),o}function Ob(n){let s=[...n].sort((o,c)=>o.path.localeCompare(c.path)).map((o)=>`${o.path}:${o.hash}`).join(`
2476
2476
  `);return Qm(s)}function _b(n){let i=dt(n);return Qm(`${n}:${i.size}:${i.mtimeMs}`)}function Lb(n,i){let s=new Map(n.map((g)=>[g.path,g])),o=new Map(i.map((g)=>[g.path,g])),c=[],u=[],d=[];for(let[g,y]of o){let h=s.get(g);if(!h)c.push(y);else if(h.hash!==y.hash)u.push(y)}for(let[g,y]of s)if(!o.has(g))d.push(y);return{added:c,modified:u,deleted:d}}class Py{cache;constructor(){this.cache=new Map}get(n){let i=dt(n),s=this.cache.get(n);if(s&&s.mtime===i.mtimeMs&&s.size===i.size)return s.hash;return}set(n,i){let s=dt(n);this.cache.set(n,{hash:i,mtime:s.mtimeMs,size:s.size})}async getOrCompute(n,i={}){let s=this.get(n);if(s)return s;let o=await Um(n,i);return this.set(n,o),o}clear(){this.cache.clear()}}async function Sl(n,i={}){let s=i.concurrency||5,o=i.stopOnError??!0,c=[],u=[],d=Date.now(),g=[...n],y=[];async function h(A,T){try{let R=await A();c[T]=R}catch(R){let P=R instanceof Error?R:Error(String(R));if(u.push(P),o)throw g.length=0,P}}let b=0;while(g.length>0||y.length>0){while(y.length<s&&g.length>0){let A=g.shift(),T=b++,R=h(A,T);y.push(R)}if(y.length>0){await Promise.race(y);for(let A=y.length-1;A>=0;A--)if(await Promise.race([y[A].then(()=>!0),Promise.resolve(!1)]))y.splice(A,1)}if(o&&u.length>0)break}let v=Date.now()-d;return{results:c.filter((A)=>A!==void 0),errors:u,duration:v}}async function $b(n,i,s={}){let o=n.map((c)=>()=>i(c));return Sl(o,s)}async function Mb(n,i,s=5){let o=n.map((u,d)=>()=>i(u,d)),c=await Sl(o,{concurrency:s,stopOnError:!1});if(c.errors.length>0)throw AggregateError(c.errors,"Parallel map failed");return c.results}async function Fb(n,i={}){let s=i.retries||3,o=i.retryDelay||1000,c=n.map((u)=>async()=>{let d;for(let g=0;g<=s;g++)try{return await u()}catch(y){if(d=y instanceof Error?y:Error(String(y)),g<s)await Vn(o*(g+1))}throw d});return Sl(c,i)}async function Ub(n){let i=[];for(let s of n){let o=await s();i.push(o)}return i}function Vn(n){return new Promise((i)=>setTimeout(i,n))}async function Qb(n,i,s="Operation timed out"){return Promise.race([n(),new Promise((o,c)=>setTimeout(()=>c(Error(s)),i))])}class ky{maxConcurrent;minInterval;queue=[];running=0;lastExecution=0;constructor(n=5,i=100){this.maxConcurrent=n;this.minInterval=i}async execute(n){await this.waitForSlot(),this.running++,this.lastExecution=Date.now();try{return await n()}finally{this.running--,this.processQueue()}}waitForSlot(){if(this.running<this.maxConcurrent){let n=Date.now()-this.lastExecution;if(n>=this.minInterval)return Promise.resolve();return Vn(this.minInterval-n)}return new Promise((n)=>this.queue.push(n))}processQueue(){if(this.queue.length>0&&this.running<this.maxConcurrent)this.queue.shift()()}stats(){return{running:this.running,queued:this.queue.length}}}function Ny(n,i){let s=[];for(let o=0;o<n.length;o+=i)s.push(n.slice(o,o+i));return s}async function Hb(n,i,s){let o=Ny(n,i),c=[];for(let u of o){let d=await s(u);c.push(...d)}return c}function Gb(n,i){let s=[],o=[],c=[],u=[],d=n.Resources||{},g=i.Resources||{},y=new Set(Object.keys(d)),h=new Set(Object.keys(g));for(let A of h)if(!y.has(A))s.push(A);for(let A of y)if(!h.has(A))c.push(A);for(let A of h)if(y.has(A)){let T=d[A],R=g[A];if(JSON.stringify(T)!==JSON.stringify(R))o.push(A);else u.push(A)}let b=JSON.stringify(n.Parameters||{})!==JSON.stringify(i.Parameters||{}),v=JSON.stringify(n.Outputs||{})!==JSON.stringify(i.Outputs||{});return{added:s,modified:o,deleted:c,unchanged:u,parametersChanged:b,outputsChanged:v,hasChanges:s.length>0||o.length>0||c.length>0||b||v}}function Vb(n){let i=[];if(!n.hasChanges)return"No changes detected";if(n.added.length>0){i.push(`Added resources (${n.added.length}):`);for(let s of n.added)i.push(` + ${s}`)}if(n.modified.length>0){i.push(`Modified resources (${n.modified.length}):`);for(let s of n.modified)i.push(` ~ ${s}`)}if(n.deleted.length>0){i.push(`Deleted resources (${n.deleted.length}):`);for(let s of n.deleted)i.push(` - ${s}`)}if(n.parametersChanged)i.push("Parameters changed");if(n.outputsChanged)i.push("Outputs changed");return i.join(`
2477
2477
  `)}function qb(n,i,s){if(n.deleted.length>0)return!0;for(let o of n.modified){let c=i.Resources[o],u=s.Resources[o];if(c.Type!==u.Type)return!0;let d=Ti(u.Type);for(let g of d){let y=c.Properties?.[g],h=u.Properties?.[g];if(JSON.stringify(y)!==JSON.stringify(h))return!0}}return!1}function Ti(n){return{"AWS::S3::Bucket":["BucketName"],"AWS::EC2::Instance":["ImageId","InstanceType","KeyName"],"AWS::RDS::DBInstance":["DBInstanceIdentifier","Engine"],"AWS::DynamoDB::Table":["TableName","KeySchema"],"AWS::Lambda::Function":["FunctionName"],"AWS::ECS::Service":["ServiceName"],"AWS::ElasticLoadBalancingV2::LoadBalancer":["Name","Type"]}[n]||[]}function jb(n){let i=[],s=[],o=[];i.push(...n.added);for(let c of n.modified)s.push(c);return o.push(...n.deleted),{safe:i,caution:s,dangerous:o}}function zb(n){if(!n.hasChanges)return{strategy:"skip",reason:"No changes detected"};if(n.deleted.length>0)return{strategy:"replace",reason:"Resources will be deleted"};if(n.added.length>0&&n.modified.length===0)return{strategy:"update",reason:"Only new resources added"};return{strategy:"update",reason:"Resources will be updated"}}function Kb(n){let i=n.added.length+n.modified.length+n.deleted.length+n.unchanged.length,s=n.added.length+n.modified.length+n.deleted.length,o=i>0?s/i*100:0;return{total:i,added:n.added.length,modified:n.modified.length,deleted:n.deleted.length,unchanged:n.unchanged.length,changePercentage:o}}var By={$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 Wb(n){let i=[];if(!n.project)i.push("Missing required field: project");else{if(!n.project.name)i.push("Missing required field: project.name");if(!n.project.slug)i.push("Missing required field: project.slug")}if(n.project?.slug&&!/^[a-z0-9-]+$/.test(n.project.slug))i.push("Invalid project.slug: must contain only lowercase letters, numbers, and hyphens");let s=["us-east-1","us-east-2","us-west-1","us-west-2","eu-west-1","eu-west-2","eu-west-3","eu-central-1","ap-southeast-1","ap-southeast-2","ap-northeast-1","ap-northeast-2","sa-east-1","ca-central-1"];if(n.project?.region&&!s.includes(n.project.region))i.push(`Invalid region: ${n.project.region}. Must be one of: ${s.join(", ")}`);if(n.mode&&!["server","serverless"].includes(n.mode))i.push("Invalid mode: must be one of server or serverless");return{valid:i.length===0,errors:i}}var Hm={enabled:process.env.TS_CLOUD_LOCAL==="true"||!0,localstackEndpoint:process.env.LOCALSTACK_ENDPOINT||"http://localhost:4566",postgresUrl:process.env.POSTGRES_URL||"postgresql://tscloud:tscloud@localhost:5432/tscloud",redisUrl:process.env.REDIS_URL||"redis://localhost:6379",dynamodbEndpoint:process.env.DYNAMODB_ENDPOINT||"http://localhost:8000",s3Endpoint:process.env.S3_ENDPOINT||"http://localhost:9000",emailEndpoint:process.env.EMAIL_ENDPOINT||"smtp://localhost:1025",awsRegion:process.env.AWS_REGION||"us-east-1",awsAccessKeyId:process.env.AWS_ACCESS_KEY_ID||"test",awsSecretAccessKey:process.env.AWS_SECRET_ACCESS_KEY||"test"};function Il(){return Hm}function Jb(){return Hm.enabled}function Xb(n){let i=Il();if(!i.enabled)return"";switch(n.toLowerCase()){case"dynamodb":return i.dynamodbEndpoint;case"s3":return i.s3Endpoint;case"localstack":case"cloudformation":case"lambda":case"apigateway":case"sns":case"sqs":case"cloudwatch":case"iam":case"sts":return i.localstackEndpoint;default:return i.localstackEndpoint}}function Yb(){let n=Il();return{accessKeyId:n.awsAccessKeyId,secretAccessKey:n.awsSecretAccessKey,region:n.awsRegion}}function Zb(){let n=Il();if(!n.enabled)return{};return{AWS_ACCESS_KEY_ID:n.awsAccessKeyId,AWS_SECRET_ACCESS_KEY:n.awsSecretAccessKey,AWS_REGION:n.awsRegion,AWS_ENDPOINT_URL:n.localstackEndpoint,LOCALSTACK_ENDPOINT:n.localstackEndpoint,TS_CLOUD_LOCAL:"true"}}class Gm{stacks=new Map;stackEvents=new Map;async createStack(n){let i=`arn:aws:cloudformation:${n.region||"us-east-1"}:123456789012:stack/${n.StackName}/${Date.now()}`;return this.stacks.set(n.StackName,{StackId:i,StackName:n.StackName,StackStatus:"CREATE_IN_PROGRESS",CreationTime:new Date().toISOString(),TemplateBody:n.TemplateBody,Parameters:n.Parameters||[]}),this.addEvent(n.StackName,{EventId:Date.now().toString(),StackName:n.StackName,LogicalResourceId:n.StackName,ResourceType:"AWS::CloudFormation::Stack",Timestamp:new Date().toISOString(),ResourceStatus:"CREATE_IN_PROGRESS"}),setTimeout(()=>{let s=this.stacks.get(n.StackName);if(s)s.StackStatus="CREATE_COMPLETE",this.addEvent(n.StackName,{EventId:(Date.now()+1).toString(),StackName:n.StackName,LogicalResourceId:n.StackName,ResourceType:"AWS::CloudFormation::Stack",Timestamp:new Date().toISOString(),ResourceStatus:"CREATE_COMPLETE"})},100),{StackId:i}}async updateStack(n){let i=this.stacks.get(n.StackName);if(!i)throw Error(`Stack ${n.StackName} does not exist`);return i.StackStatus="UPDATE_IN_PROGRESS",i.TemplateBody=n.TemplateBody||i.TemplateBody,this.addEvent(n.StackName,{EventId:Date.now().toString(),StackName:n.StackName,LogicalResourceId:n.StackName,ResourceType:"AWS::CloudFormation::Stack",Timestamp:new Date().toISOString(),ResourceStatus:"UPDATE_IN_PROGRESS"}),setTimeout(()=>{i.StackStatus="UPDATE_COMPLETE",this.addEvent(n.StackName,{EventId:(Date.now()+1).toString(),StackName:n.StackName,LogicalResourceId:n.StackName,ResourceType:"AWS::CloudFormation::Stack",Timestamp:new Date().toISOString(),ResourceStatus:"UPDATE_COMPLETE"})},100),{StackId:i.StackId}}async deleteStack(n){let i=this.stacks.get(n.StackName);if(!i)throw Error(`Stack ${n.StackName} does not exist`);i.StackStatus="DELETE_IN_PROGRESS",this.addEvent(n.StackName,{EventId:Date.now().toString(),StackName:n.StackName,LogicalResourceId:n.StackName,ResourceType:"AWS::CloudFormation::Stack",Timestamp:new Date().toISOString(),ResourceStatus:"DELETE_IN_PROGRESS"}),setTimeout(()=>{this.stacks.delete(n.StackName),this.addEvent(n.StackName,{EventId:(Date.now()+1).toString(),StackName:n.StackName,LogicalResourceId:n.StackName,ResourceType:"AWS::CloudFormation::Stack",Timestamp:new Date().toISOString(),ResourceStatus:"DELETE_COMPLETE"})},100)}async describeStacks(n){if(n.StackName){let i=this.stacks.get(n.StackName);if(!i)throw Error(`Stack ${n.StackName} does not exist`);return{Stacks:[i]}}return{Stacks:Array.from(this.stacks.values())}}async describeStackEvents(n){return{StackEvents:this.stackEvents.get(n.StackName)||[]}}addEvent(n,i){if(!this.stackEvents.has(n))this.stackEvents.set(n,[]);this.stackEvents.get(n).unshift(i)}reset(){this.stacks.clear(),this.stackEvents.clear()}}class Vm{buckets=new Map;async createBucket(n){return this.buckets.set(n.Bucket,new Map),{Location:`/${n.Bucket}`}}async deleteBucket(n){this.buckets.delete(n.Bucket)}async putObject(n){let i=this.buckets.get(n.Bucket);if(!i)i=new Map,this.buckets.set(n.Bucket,i);return i.set(n.Key,Buffer.from(n.Body||"")),{ETag:`"${Date.now()}"`}}async getObject(n){let i=this.buckets.get(n.Bucket);if(!i)throw Error(`Bucket ${n.Bucket} does not exist`);let s=i.get(n.Key);if(!s)throw Error(`Object ${n.Key} does not exist`);return{Body:s,ContentLength:s.length}}async deleteObject(n){let i=this.buckets.get(n.Bucket);if(i)i.delete(n.Key)}async listObjects(n){let i=this.buckets.get(n.Bucket);if(!i)throw Error(`Bucket ${n.Bucket} does not exist`);return{Contents:Array.from(i.keys()).map((o)=>({Key:o,Size:i.get(o).length,LastModified:new Date().toISOString()}))}}reset(){this.buckets.clear()}}class qm{tables=new Map;data=new Map;async createTable(n){return this.tables.set(n.TableName,{TableName:n.TableName,KeySchema:n.KeySchema,AttributeDefinitions:n.AttributeDefinitions,TableStatus:"ACTIVE",CreationDateTime:new Date().toISOString()}),this.data.set(n.TableName,new Map),{TableDescription:this.tables.get(n.TableName)}}async deleteTable(n){this.tables.delete(n.TableName),this.data.delete(n.TableName)}async putItem(n){let i=this.data.get(n.TableName);if(!i)i=new Map,this.data.set(n.TableName,i);let s=JSON.stringify(n.Item);i.set(s,n.Item)}async getItem(n){let i=this.data.get(n.TableName);if(!i)return{};let s=JSON.stringify(n.Key),o=i.get(s);return o?{Item:o}:{}}async deleteItem(n){let i=this.data.get(n.TableName);if(i){let s=JSON.stringify(n.Key);i.delete(s)}}async scan(n){let i=this.data.get(n.TableName);if(!i)return{Items:[]};return{Items:Array.from(i.values())}}reset(){this.tables.clear(),this.data.clear()}}function eC(n){return{cloudformation:new Gm,s3:new Vm,dynamodb:new qm}}class bl{environments=new Map;async createPreviewEnvironment(n){let{branch:i,pr:s,commitSha:o,ttl:c=24,baseConfig:u,region:d="us-east-1"}=n,g=this.generatePreviewId(i,s,o),y=this.generatePreviewName(i,s),h=`preview-${y}`,b=new Date,v=new Date(b.getTime()+c*60*60*1000),A={id:g,name:y,branch:i,pr:s,commitSha:o,createdAt:b,expiresAt:v,status:"creating",stackName:h,region:d,resources:[]};this.environments.set(g,A);try{let T=this.createPreviewConfig(u,y);return A.status="active",A.url=`https://${y}.preview.example.com`,A}catch(T){throw A.status="failed",T}}async destroyPreviewEnvironment(n){let i=this.environments.get(n);if(!i)throw Error(`Preview environment ${n} not found`);i.status="destroying";try{i.status="destroyed",this.environments.delete(n)}catch(s){throw Error(`Failed to destroy preview environment: ${s}`)}}getPreviewEnvironment(n){return this.environments.get(n)}getPreviewEnvironmentByBranch(n){return Array.from(this.environments.values()).find((i)=>i.branch===n)}getPreviewEnvironmentByPR(n){return Array.from(this.environments.values()).find((i)=>i.pr===n)}listPreviewEnvironments(){return Array.from(this.environments.values())}listActivePreviewEnvironments(){return this.listPreviewEnvironments().filter((n)=>n.status==="active")}async cleanupExpiredEnvironments(n={}){let{maxAge:i,keepCount:s,dryRun:o=!1}=n,c=[],u=[],d=new Date,g=this.listPreviewEnvironments().sort((y,h)=>h.createdAt.getTime()-y.createdAt.getTime());for(let y=0;y<g.length;y++){let h=g[y];if(h.status!=="active")continue;let b=!1;if(h.expiresAt<d)b=!0;if(i){if((d.getTime()-h.createdAt.getTime())/3600000>i)b=!0}if(s&&y>=s)b=!0;if(b)if(o)c.push(h.id);else try{await this.destroyPreviewEnvironment(h.id),c.push(h.id)}catch(v){u.push(h.id)}}return{destroyed:c,failed:u}}async updatePreviewEnvironment(n,i){let s=this.environments.get(n);if(!s)throw Error(`Preview environment ${n} not found`);s.commitSha=i,s.status="creating";try{return s.status="active",s}catch(o){throw s.status="failed",o}}async getPreviewEnvironmentsCost(){let n={},i=0;for(let s of this.environments.values())n[s.id]=0,i+=0;return{total:i,byEnvironment:n}}generatePreviewId(n,i,s){let o=n.replace(/[^a-z0-9-]/gi,"-").toLowerCase(),c=s?.substring(0,7)||Date.now().toString();return i?`pr-${i}-${c}`:`${o}-${c}`}generatePreviewName(n,i){let s=n.replace(/[^a-z0-9-]/gi,"-").toLowerCase();return i?`pr-${i}`:s}createPreviewConfig(n,i){return{...n,project:{...n.project,name:`${n.project.name} Preview (${i})`,slug:`${n.project.slug}-preview-${i}`}}}}var xy=new bl;function Oy(n={}){let{workflowName:i="Preview Environment",trigger:s="pull_request",branches:o=["main","develop"],awsRegion:c="us-east-1",awsRole:u,configFile:d="cloud.config.ts",ttl:g=24}=n;return`name: ${i}
2478
2478
 
@@ -4127,7 +4127,7 @@ else {
4127
4127
 
4128
4128
  return raw;
4129
4129
  }
4130
- `;static createSchedulerLambda(n){return{[`${n.slug}EmailSchedulerLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${n.slug}-email-scheduler`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n.roleArn,Timeout:300,MemorySize:256,Code:{ZipFile:Wt.SchedulerLambdaCode},Environment:{Variables:{EMAIL_BUCKET:n.emailBucket}}}}}}static createSchedulerRule(n){return{[`${n.slug}EmailSchedulerRule`]:{Type:"AWS::Events::Rule",Properties:{Name:`${n.slug}-email-scheduler`,Description:"Trigger email scheduler every minute",ScheduleExpression:n.scheduleExpression||"rate(1 minute)",State:"ENABLED",Targets:[{Id:"EmailSchedulerTarget",Arn:n.lambdaArn}]}},[`${n.slug}EmailSchedulerPermission`]:{Type:"AWS::Lambda::Permission",Properties:{FunctionName:n.lambdaArn,Action:"lambda:InvokeFunction",Principal:"events.amazonaws.com",SourceArn:{"Fn::GetAtt":[`${n.slug}EmailSchedulerRule`,"Arn"]}}}}}static async scheduleEmail(n){let{s3Client:i,bucket:s,email:o,scheduledFor:c,timezone:u}=n,d=`sched-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,g={id:d,email:o,scheduledFor:typeof c==="string"?c:c.toISOString(),timezone:u,status:"pending",createdAt:new Date().toISOString()};return await i.send({Bucket:s,Key:`scheduled/${d}.json`,Body:JSON.stringify(g,null,2),ContentType:"application/json"}),g}static async cancelScheduledEmail(n){let{s3Client:i,bucket:s,id:o}=n;try{let c=await i.send({Bucket:s,Key:`scheduled/${o}.json`}),u=JSON.parse(c.Body);if(u.status!=="pending")return!1;return u.status="cancelled",await i.send({Bucket:s,Key:`scheduled/${o}.json`,Body:JSON.stringify(u,null,2),ContentType:"application/json"}),!0}catch{return!1}}static async listScheduledEmails(n){let{s3Client:i,bucket:s,status:o}=n,c=await i.send({Bucket:s,Prefix:"scheduled/"}),u=[];for(let d of c.Contents||[]){if(!d.Key.endsWith(".json"))continue;try{let g=await i.send({Bucket:s,Key:d.Key}),y=JSON.parse(g.Body);if(!o||y.status===o)u.push(y)}catch{}}return u.sort((d,g)=>new Date(d.scheduledFor).getTime()-new Date(g.scheduledFor).getTime()),u}}class Xe{static TrackingPixelLambdaCode=`
4130
+ `;static createSchedulerLambda(n){return{[`${n.slug}EmailSchedulerLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${n.slug}-email-scheduler`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n.roleArn,Timeout:300,MemorySize:256,Code:{ZipFile:Wt.SchedulerLambdaCode},Environment:{Variables:{EMAIL_BUCKET:n.emailBucket}}}}}}static createSchedulerRule(n){return{[`${n.slug}EmailSchedulerRule`]:{Type:"AWS::Events::Rule",Properties:{Name:`${n.slug}-email-scheduler`,Description:"Trigger email scheduler every minute",ScheduleExpression:n.scheduleExpression||"rate(1 minute)",State:"ENABLED",Targets:[{Id:"EmailSchedulerTarget",Arn:n.lambdaArn}]}},[`${n.slug}EmailSchedulerPermission`]:{Type:"AWS::Lambda::Permission",Properties:{FunctionName:n.lambdaArn,Action:"lambda:InvokeFunction",Principal:"events.amazonaws.com",SourceArn:{"Fn::GetAtt":[`${n.slug}EmailSchedulerRule`,"Arn"]}}}}}static async scheduleEmail(n){let{s3Client:i,bucket:s,email:o,scheduledFor:c,timezone:u}=n,d=`sched-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,g={id:d,email:o,scheduledFor:typeof c==="string"?c:c.toISOString(),timezone:u,status:"pending",createdAt:new Date().toISOString()};return await i.send({Bucket:s,Key:`scheduled/${d}.json`,Body:JSON.stringify(g,null,2),ContentType:"application/json"}),g}static async cancelScheduledEmail(n){let{s3Client:i,bucket:s,id:o}=n;try{let c=await i.send({Bucket:s,Key:`scheduled/${o}.json`}),u=JSON.parse(c.Body);if(u.status!=="pending")return!1;return u.status="cancelled",await i.send({Bucket:s,Key:`scheduled/${o}.json`,Body:JSON.stringify(u,null,2),ContentType:"application/json"}),!0}catch{return!1}}static async listScheduledEmails(n){let{s3Client:i,bucket:s,status:o}=n,c=await i.send({Bucket:s,Prefix:"scheduled/"}),u=[];for(let d of c.Contents||[]){if(!d.Key.endsWith(".json"))continue;try{let g=await i.send({Bucket:s,Key:d.Key}),y=JSON.parse(g.Body);if(!o||y.status===o)u.push(y)}catch{}}return u.sort((d,g)=>new Date(d.scheduledFor).getTime()-new Date(g.scheduledFor).getTime()),u}}class Ye{static TrackingPixelLambdaCode=`
4131
4131
  const { DynamoDBClient, UpdateItemCommand } = require('@aws-sdk/client-dynamodb');
4132
4132
 
4133
4133
  const dynamodb = new DynamoDBClient({});
@@ -4330,7 +4330,7 @@ catch (error) {
4330
4330
 
4331
4331
  return { statusCode: 200 };
4332
4332
  };
4333
- `;static createAnalyticsTable(n){return{[`${n.slug}EmailAnalyticsTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${n.slug}-email-analytics`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"messageId",AttributeType:"S"}],KeySchema:[{AttributeName:"messageId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createTrackingPixelLambda(n){return{[`${n.slug}TrackingPixelLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${n.slug}-tracking-pixel`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n.roleArn,Timeout:10,MemorySize:128,Code:{ZipFile:Xe.TrackingPixelLambdaCode},Environment:{Variables:{ANALYTICS_TABLE:n.analyticsTable}}}}}}static createClickTrackingLambda(n){return{[`${n.slug}ClickTrackingLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${n.slug}-click-tracking`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n.roleArn,Timeout:10,MemorySize:128,Code:{ZipFile:Xe.ClickTrackingLambdaCode},Environment:{Variables:{ANALYTICS_TABLE:n.analyticsTable}}}}}}static createSesEventProcessorLambda(n){return{[`${n.slug}SesEventProcessorLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${n.slug}-ses-event-processor`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:Xe.SesEventProcessorCode},Environment:{Variables:{ANALYTICS_TABLE:n.analyticsTable}}}}}}static injectTracking(n){let{html:i,messageId:s,trackingDomain:o}=n,c=`<img src="https://${o}/track/open/${s}" width="1" height="1" style="display:none" alt="" />`,u=i.replace("</body>",`${c}</body>`);return u=u.replace(/href="(https?:\/\/[^"]+)"/g,(d,g)=>{let y=encodeURIComponent(g);return`href="https://${o}/track/click/${s}?url=${y}"`}),u}static calculateMetrics(n){let i=n.filter((y)=>y.sent).length,s=n.filter((y)=>y.delivered).length,o=n.filter((y)=>y.opened).length,c=n.filter((y)=>y.clicked).length,u=n.filter((y)=>y.bounced).length,d=n.filter((y)=>y.complained).length,g=n.filter((y)=>y.unsubscribed).length;return{period:new Date().toISOString(),sent:i,delivered:s,opened:o,clicked:c,bounced:u,complained:d,unsubscribed:g,deliveryRate:i>0?s/i*100:0,openRate:s>0?o/s*100:0,clickRate:o>0?c/o*100:0,bounceRate:i>0?u/i*100:0,complaintRate:s>0?d/s*100:0}}}class ke{static TemplateRendererCode=`
4333
+ `;static createAnalyticsTable(n){return{[`${n.slug}EmailAnalyticsTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${n.slug}-email-analytics`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"messageId",AttributeType:"S"}],KeySchema:[{AttributeName:"messageId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createTrackingPixelLambda(n){return{[`${n.slug}TrackingPixelLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${n.slug}-tracking-pixel`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n.roleArn,Timeout:10,MemorySize:128,Code:{ZipFile:Ye.TrackingPixelLambdaCode},Environment:{Variables:{ANALYTICS_TABLE:n.analyticsTable}}}}}}static createClickTrackingLambda(n){return{[`${n.slug}ClickTrackingLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${n.slug}-click-tracking`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n.roleArn,Timeout:10,MemorySize:128,Code:{ZipFile:Ye.ClickTrackingLambdaCode},Environment:{Variables:{ANALYTICS_TABLE:n.analyticsTable}}}}}}static createSesEventProcessorLambda(n){return{[`${n.slug}SesEventProcessorLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${n.slug}-ses-event-processor`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:Ye.SesEventProcessorCode},Environment:{Variables:{ANALYTICS_TABLE:n.analyticsTable}}}}}}static injectTracking(n){let{html:i,messageId:s,trackingDomain:o}=n,c=`<img src="https://${o}/track/open/${s}" width="1" height="1" style="display:none" alt="" />`,u=i.replace("</body>",`${c}</body>`);return u=u.replace(/href="(https?:\/\/[^"]+)"/g,(d,g)=>{let y=encodeURIComponent(g);return`href="https://${o}/track/click/${s}?url=${y}"`}),u}static calculateMetrics(n){let i=n.filter((y)=>y.sent).length,s=n.filter((y)=>y.delivered).length,o=n.filter((y)=>y.opened).length,c=n.filter((y)=>y.clicked).length,u=n.filter((y)=>y.bounced).length,d=n.filter((y)=>y.complained).length,g=n.filter((y)=>y.unsubscribed).length;return{period:new Date().toISOString(),sent:i,delivered:s,opened:o,clicked:c,bounced:u,complained:d,unsubscribed:g,deliveryRate:i>0?s/i*100:0,openRate:s>0?o/s*100:0,clickRate:o>0?c/o*100:0,bounceRate:i>0?u/i*100:0,complaintRate:s>0?d/s*100:0}}}class ke{static TemplateRendererCode=`
4334
4334
  const { S3Client, GetObjectCommand } = require('@aws-sdk/client-s3');
4335
4335
 
4336
4336
  const s3 = new S3Client({});
@@ -7226,7 +7226,7 @@ function unmarshallTest(item) {
7226
7226
 
7227
7227
  return test;
7228
7228
  }
7229
- `;static createAbTestsTable(n){return{[`${n.slug}AbTestsTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${n.slug}-ab-tests`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}]}}}}static createAbTestManagerLambda(n){return{[`${n.slug}AbTestManagerLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${n.slug}-ab-test-manager`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:Ee.AbTestManagerCode},Environment:{Variables:{AB_TESTS_TABLE:n.abTestsTable}}}}}}static selectVariant(n,i){let o=Ee.hashString(i+n.id)%100,c=0;for(let u=0;u<n.variants.length;u++)if(c+=n.trafficSplit[u],o<c)return n.variants[u];return n.variants[n.variants.length-1]}static determineWinner(n){if(n.variants.length===0)return null;let i=n.winningCriteria,s=n.variants[0],o=Ee.getMetricValue(s,i);for(let c of n.variants.slice(1)){let u=Ee.getMetricValue(c,i);if(u>o)o=u,s=c}return s}static calculateSignificance(n,i,s){let o=n.stats.sent,c=i.stats.sent;if(o<30||c<30)return 0;let u=Ee.getMetricValue(n,s)/100,d=Ee.getMetricValue(i,s)/100,g=(u*o+d*c)/(o+c),y=Math.sqrt(g*(1-g)*(1/o+1/c));if(y===0)return 0;let h=Math.abs(u-d)/y;if(h>=2.576)return 99;if(h>=1.96)return 95;if(h>=1.645)return 90;if(h>=1.28)return 80;return Math.round(h*30)}static getMetricValue(n,i){switch(i){case"delivery_rate":return n.stats.deliveryRate;case"click_rate":return n.stats.clickRate;case"reply_rate":return n.stats.replyRate;case"conversion_rate":return n.stats.conversionRate;default:return n.stats.deliveryRate}}static hashString(n){let i=0;for(let s=0;s<n.length;s++){let o=n.charCodeAt(s);i=(i<<5)-i+o,i=i&i}return Math.abs(i)}}class Rf{queues=new Map;messageGroups=new Map;deduplicationConfigs=new Map;messages=new Map;queueCounter=0;groupCounter=0;deduplicationCounter=0;messageCounter=0;sequenceCounter=0;createFIFOQueue(n){let i=`fifo-queue-${Date.now()}-${this.queueCounter++}`,s=n.name.endsWith(".fifo")?n.name:`${n.name}.fifo`,{name:o,...c}=n,u={id:i,name:s,queueUrl:`https://sqs.us-east-1.amazonaws.com/123456789012/${s}`,...c};return this.queues.set(i,u),this.createDeduplicationConfig({queueId:i,contentBasedDeduplication:n.contentBasedDeduplication,deduplicationInterval:300}),u}createHighThroughputFIFO(n){return this.createFIFOQueue({name:n.name,contentBasedDeduplication:n.contentBasedDeduplication??!0,deduplicationScope:"messageGroup",fifoThroughputLimit:"perMessageGroupId",messageRetentionPeriod:345600,visibilityTimeout:30,receiveMessageWaitTime:0})}createStandardFIFO(n){return this.createFIFOQueue({name:n.name,contentBasedDeduplication:n.contentBasedDeduplication??!1,deduplicationScope:"queue",fifoThroughputLimit:"perQueue",messageRetentionPeriod:345600,visibilityTimeout:30,receiveMessageWaitTime:0})}createDeduplicationConfig(n){let s={id:`dedup-${Date.now()}-${this.deduplicationCounter++}`,deduplicationHashes:new Map,...n};return this.deduplicationConfigs.set(n.queueId,s),s}sendMessage(n){let i=this.queues.get(n.queueId);if(!i)throw Error(`Queue not found: ${n.queueId}`);let s=this.deduplicationConfigs.get(n.queueId);if(s){let d=n.messageDeduplicationId||(i.contentBasedDeduplication?this.generateHash(n.messageBody):void 0);if(d&&this.isDuplicate(s,d))return null;if(d)s.deduplicationHashes.set(d,new Date)}let o=`msg-${Date.now()}-${this.messageCounter++}`,c=this.generateSequenceNumber(),u={id:o,messageId:o,messageGroupId:n.messageGroupId,messageDeduplicationId:n.messageDeduplicationId,body:n.messageBody,attributes:n.messageAttributes||{},sentTimestamp:new Date,sequenceNumber:c};return this.messages.set(o,u),this.updateMessageGroup(n.queueId,n.messageGroupId),u}isDuplicate(n,i){let s=n.deduplicationHashes.get(i);if(!s)return!1;if((Date.now()-s.getTime())/1000>n.deduplicationInterval)return n.deduplicationHashes.delete(i),!1;return!0}generateHash(n){let i=0;for(let s=0;s<n.length;s++){let o=n.charCodeAt(s);i=(i<<5)-i+o,i=i&i}return Math.abs(i).toString(36)}generateSequenceNumber(){return`${Date.now()}${this.sequenceCounter++}`.padStart(20,"0")}updateMessageGroup(n,i){let s=`${n}-${i}`,o=this.messageGroups.get(s);if(!o)o={id:`group-${Date.now()}-${this.groupCounter++}`,messageGroupId:i,queueId:n,messagesInFlight:0},this.messageGroups.set(s,o);o.messagesInFlight++,o.lastMessageTimestamp=new Date}getMessageGroups(n){return Array.from(this.messageGroups.values()).filter((i)=>i.queueId===n)}getQueue(n){return this.queues.get(n)}listQueues(){return Array.from(this.queues.values())}getMessages(n,i){let s=Array.from(this.messages.values());if(i)s=s.filter((o)=>o.messageGroupId===i);return s.sort((o,c)=>o.sequenceNumber.localeCompare(c.sequenceNumber))}generateFIFOQueueCF(n){return{Type:"AWS::SQS::Queue",Properties:{QueueName:n.name,FifoQueue:!0,ContentBasedDeduplication:n.contentBasedDeduplication,DeduplicationScope:n.deduplicationScope,FifoThroughputLimit:n.fifoThroughputLimit,MessageRetentionPeriod:n.messageRetentionPeriod,VisibilityTimeout:n.visibilityTimeout,ReceiveMessageWaitTimeSeconds:n.receiveMessageWaitTime,...n.deadLetterTargetArn&&{RedrivePolicy:{deadLetterTargetArn:n.deadLetterTargetArn,maxReceiveCount:n.maxReceiveCount||3}}}}}clear(){this.queues.clear(),this.messageGroups.clear(),this.deduplicationConfigs.clear(),this.messages.clear(),this.queueCounter=0,this.groupCounter=0,this.deduplicationCounter=0,this.messageCounter=0,this.sequenceCounter=0}}var TE=new Rf;class Df{monitors=new Map;metrics=new Map;alerts=new Map;reprocessJobs=new Map;monitorCounter=0;metricsCounter=0;alertCounter=0;jobCounter=0;createDLQMonitor(n){let i=`dlq-monitor-${Date.now()}-${this.monitorCounter++}`,s={id:i,...n};return this.monitors.set(i,s),s}createAutomatedMonitor(n){return this.createDLQMonitor({name:n.name,queueUrl:n.queueUrl,sourceQueues:n.sourceQueues,maxReceiveCount:3,alarmThreshold:10,autoReprocess:!0,reprocessStrategy:"scheduled",notificationTopicArn:n.notificationTopicArn})}collectMetrics(n){let s={id:`metrics-${Date.now()}-${this.metricsCounter++}`,queueUrl:n,timestamp:new Date,approximateNumberOfMessages:Math.floor(Math.random()*100),approximateAgeOfOldestMessage:Math.floor(Math.random()*86400),messagesReceived:Math.floor(Math.random()*50),messagesDeleted:Math.floor(Math.random()*30),messagesReprocessed:Math.floor(Math.random()*20)},o=this.metrics.get(n)||[];return o.push(s),this.metrics.set(n,o),this.checkForAlerts(n,s),s}checkForAlerts(n,i){let s=Array.from(this.monitors.values()).find((c)=>c.queueUrl===n);if(!s)return;if(i.approximateNumberOfMessages>=s.alarmThreshold)this.createAlert({monitorId:s.id,alertType:"threshold_exceeded",severity:"high",message:`DLQ ${s.name} has ${i.approximateNumberOfMessages} messages (threshold: ${s.alarmThreshold})`});let o=3600;if(i.approximateAgeOfOldestMessage>o)this.createAlert({monitorId:s.id,alertType:"old_message",severity:"medium",message:`DLQ ${s.name} has messages older than ${o} seconds`})}createAlert(n){let i=`alert-${Date.now()}-${this.alertCounter++}`,s={id:i,timestamp:new Date,acknowledged:!1,...n};return this.alerts.set(i,s),s}acknowledgeAlert(n){let i=this.alerts.get(n);if(!i)throw Error(`Alert not found: ${n}`);return i.acknowledged=!0,i}createReprocessJob(n){let i=`reprocess-${Date.now()}-${this.jobCounter++}`,s={id:i,queueUrl:n.queueUrl,messageId:n.messageId,attempts:0,status:"pending"};return this.reprocessJobs.set(i,s),s}async executeReprocessJob(n){let i=this.reprocessJobs.get(n);if(!i)throw Error(`Reprocess job not found: ${n}`);i.status="processing",i.startedAt=new Date,i.attempts++,await new Promise((o)=>setTimeout(o,100));let s=Math.random()>0.3;if(i.status=s?"success":"failed",i.completedAt=new Date,!s)i.error="Reprocessing failed - original error still present";return i}async batchReprocess(n){let i=[];for(let s=0;s<n.maxMessages;s++){let o=this.createReprocessJob({queueUrl:n.queueUrl,messageId:`msg-${s}`});await this.executeReprocessJob(o.id),i.push(o)}return i}getDLQStatistics(n,i=24){let s=new Date(Date.now()-i*60*60*1000),o=(this.metrics.get(n)||[]).filter((b)=>b.timestamp>=s);if(o.length===0)return{totalMessages:0,avgAge:0,messagesReceived:0,messagesDeleted:0,messagesReprocessed:0,successRate:0};let c=o[o.length-1],u=o.reduce((b,v)=>b+v.messagesReceived,0),d=o.reduce((b,v)=>b+v.messagesDeleted,0),g=o.reduce((b,v)=>b+v.messagesReprocessed,0),y=o.reduce((b,v)=>b+v.approximateAgeOfOldestMessage,0)/o.length,h=g>0?d/g*100:0;return{totalMessages:c.approximateNumberOfMessages,avgAge:y,messagesReceived:u,messagesDeleted:d,messagesReprocessed:g,successRate:h}}getMonitor(n){return this.monitors.get(n)}listMonitors(){return Array.from(this.monitors.values())}getAlerts(n,i){let s=Array.from(this.alerts.values());if(n)s=s.filter((o)=>o.monitorId===n);if(i!==void 0)s=s.filter((o)=>o.acknowledged===i);return s.sort((o,c)=>c.timestamp.getTime()-o.timestamp.getTime())}getReprocessJobs(n){let i=Array.from(this.reprocessJobs.values());if(n)i=i.filter((s)=>s.queueUrl===n);return i}generateDLQAlarmCF(n){return{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${n.name}-messages-alarm`,AlarmDescription:`Alert when DLQ ${n.name} exceeds threshold`,MetricName:"ApproximateNumberOfMessagesVisible",Namespace:"AWS/SQS",Statistic:"Average",Period:300,EvaluationPeriods:1,Threshold:n.alarmThreshold,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:n.queueUrl.split("/").pop()}],...n.notificationTopicArn&&{AlarmActions:[n.notificationTopicArn]}}}}clear(){this.monitors.clear(),this.metrics.clear(),this.alerts.clear(),this.reprocessJobs.clear(),this.monitorCounter=0,this.metricsCounter=0,this.alertCounter=0,this.jobCounter=0}}var wE=new Df;class Pf{configs=new Map;jobs=new Map;metrics=new Map;configCounter=0;jobCounter=0;metricsCounter=0;createBatchConfig(n){let i=`batch-config-${Date.now()}-${this.configCounter++}`,s={id:i,...n};return this.configs.set(i,s),s}createHighThroughputConfig(n){return this.createBatchConfig({queueUrl:n.queueUrl,batchSize:10,maxWaitTime:100,parallelProcessors:10,retryAttempts:3,visibilityTimeout:30})}createLowLatencyConfig(n){return this.createBatchConfig({queueUrl:n.queueUrl,batchSize:1,maxWaitTime:0,parallelProcessors:5,retryAttempts:2,visibilityTimeout:10})}createBatchJob(n){let i=`batch-job-${Date.now()}-${this.jobCounter++}`;if(!this.configs.get(n.configId))throw Error(`Batch config not found: ${n.configId}`);let o=[];for(let u=0;u<n.messageCount;u++)o.push({id:`msg-${i}-${u}`,messageId:`${i}-${u}`,body:`Message ${u}`,receiptHandle:`receipt-${i}-${u}`,attributes:{},status:"pending"});let c={id:i,configId:n.configId,messages:o,status:"pending",processedCount:0,failedCount:0};return this.jobs.set(i,c),c}async processBatchJob(n){let i=this.jobs.get(n);if(!i)throw Error(`Batch job not found: ${n}`);let s=this.configs.get(i.configId);if(!s)throw Error(`Batch config not found: ${i.configId}`);i.status="processing",i.startedAt=new Date;let o=this.chunkArray(i.messages,s.batchSize);for(let c of o)await this.processBatch(c,s);return i.processedCount=i.messages.filter((c)=>c.status==="success").length,i.failedCount=i.messages.filter((c)=>c.status==="failed").length,i.status=i.failedCount===0?"completed":"failed",i.completedAt=new Date,this.collectProcessorMetrics(s.id,i),i}async processBatch(n,i){let s=n.map((o)=>this.processMessage(o,i));await Promise.all(s)}async processMessage(n,i){n.status="processing";let s=Date.now();await new Promise((u)=>setTimeout(u,Math.random()*100));let o=Date.now()-s;if(n.processingTime=o,Math.random()>0.1)n.status="success";else n.status="failed",n.error="Processing error"}chunkArray(n,i){let s=[];for(let o=0;o<n.length;o+=i)s.push(n.slice(o,o+i));return s}collectProcessorMetrics(n,i){let s=`metrics-${Date.now()}-${this.metricsCounter++}`,c=i.messages.filter((v)=>v.status==="success").map((v)=>v.processingTime||0).filter((v)=>v>0),u=c.length>0?c.reduce((v,A)=>v+A,0)/c.length:0,d=i.completedAt&&i.startedAt?(i.completedAt.getTime()-i.startedAt.getTime())/1000:1,g=i.processedCount/d,y=i.messages.length>0?i.failedCount/i.messages.length*100:0,h={id:s,configId:n,timestamp:new Date,messagesProcessed:i.processedCount,averageProcessingTime:u,throughput:g,errorRate:y},b=this.metrics.get(n)||[];b.push(h),this.metrics.set(n,b)}getBatchStatistics(n){let i=this.metrics.get(n)||[];if(i.length===0)return{totalJobsProcessed:0,totalMessagesProcessed:0,averageThroughput:0,averageErrorRate:0,averageProcessingTime:0};let s=i.reduce((d,g)=>d+g.messagesProcessed,0),o=i.reduce((d,g)=>d+g.throughput,0)/i.length,c=i.reduce((d,g)=>d+g.errorRate,0)/i.length,u=i.reduce((d,g)=>d+g.averageProcessingTime,0)/i.length;return{totalJobsProcessed:i.length,totalMessagesProcessed:s,averageThroughput:o,averageErrorRate:c,averageProcessingTime:u}}optimizeBatchConfig(n){let i=this.configs.get(n);if(!i)throw Error(`Batch config not found: ${n}`);let s=this.getBatchStatistics(n);if(s.averageErrorRate<5&&i.batchSize<10)i.batchSize=Math.min(10,i.batchSize+1);if(s.averageErrorRate>20&&i.batchSize>1)i.batchSize=Math.max(1,i.batchSize-1);if(s.averageThroughput<5&&i.parallelProcessors<20)i.parallelProcessors++;return i}getConfig(n){return this.configs.get(n)}listConfigs(){return Array.from(this.configs.values())}getJob(n){return this.jobs.get(n)}listJobs(n){let i=Array.from(this.jobs.values());if(n)i=i.filter((s)=>s.configId===n);return i}generateBatchProcessorCF(n){return{Type:"AWS::Lambda::EventSourceMapping",Properties:{EventSourceArn:`arn:aws:sqs:us-east-1:123456789012:${n.queueUrl.split("/").pop()}`,FunctionName:"batch-processor-function",BatchSize:n.batchSize,MaximumBatchingWindowInSeconds:n.maxWaitTime/1000,FunctionResponseTypes:["ReportBatchItemFailures"]}}}clear(){this.configs.clear(),this.jobs.clear(),this.metrics.clear(),this.configCounter=0,this.jobCounter=0,this.metricsCounter=0}}var RE=new Pf;class kf{queues=new Map;retentionPolicies=new Map;delayQueues=new Map;purgeOperations=new Map;metrics=new Map;queueCounter=0;retentionCounter=0;delayCounter=0;purgeCounter=0;metricsCounter=0;createQueue(n){let i=`queue-${Date.now()}-${this.queueCounter++}`,s={id:i,purgeInProgress:!1,...n};return this.queues.set(i,s),s}createStandardQueue(n){return this.createQueue({queueUrl:`https://sqs.us-east-1.amazonaws.com/123456789012/${n.queueName}`,queueName:n.queueName,messageRetentionPeriod:(n.messageRetentionDays||4)*24*60*60,delaySeconds:0,maximumMessageSize:262144,receiveMessageWaitTime:0})}createLongPollingQueue(n){return this.createQueue({queueUrl:`https://sqs.us-east-1.amazonaws.com/123456789012/${n.queueName}`,queueName:n.queueName,messageRetentionPeriod:345600,delaySeconds:0,maximumMessageSize:262144,receiveMessageWaitTime:n.waitTimeSeconds||20})}createRetentionPolicy(n){let i=`retention-${Date.now()}-${this.retentionCounter++}`,s={id:i,...n};this.retentionPolicies.set(i,s);let o=this.queues.get(n.queueId);if(o)o.messageRetentionPeriod=n.retentionPeriod;return s}createShortRetentionPolicy(n){return this.createRetentionPolicy({queueId:n.queueId,retentionPeriod:n.retentionHours*60*60,autoCleanup:!0,archiveExpiredMessages:!1})}createArchivalRetentionPolicy(n){return this.createRetentionPolicy({queueId:n.queueId,retentionPeriod:n.retentionDays*24*60*60,autoCleanup:!0,cleanupSchedule:"cron(0 0 * * ? *)",archiveExpiredMessages:!0,archiveS3Bucket:n.s3Bucket})}createDelayQueue(n){let i=`delay-${Date.now()}-${this.delayCounter++}`,s={id:i,...n};this.delayQueues.set(i,s);let o=Array.from(this.queues.values()).find((c)=>c.queueUrl===n.queueUrl);if(o)o.delaySeconds=n.defaultDelay;return s}createScheduledDelayQueue(n){return this.createDelayQueue({queueUrl:n.queueUrl,defaultDelay:n.delayMinutes*60,perMessageDelay:!1,maxDelay:900})}async purgeQueue(n){let i=this.queues.get(n);if(!i)throw Error(`Queue not found: ${n}`);if(i.purgeInProgress)throw Error("Purge already in progress for this queue");let s=`purge-${Date.now()}-${this.purgeCounter++}`,o={id:s,queueUrl:i.queueUrl,status:"in_progress",startedAt:new Date};return this.purgeOperations.set(s,o),i.purgeInProgress=!0,setTimeout(()=>{o.status="completed",o.completedAt=new Date,o.messagesPurged=Math.floor(Math.random()*1000),i.purgeInProgress=!1},100),o}collectQueueMetrics(n){let s={id:`metrics-${Date.now()}-${this.metricsCounter++}`,queueUrl:n,timestamp:new Date,approximateNumberOfMessages:Math.floor(Math.random()*1000),approximateNumberOfMessagesNotVisible:Math.floor(Math.random()*100),approximateNumberOfMessagesDelayed:Math.floor(Math.random()*50),oldestMessageAge:Math.floor(Math.random()*86400)},o=this.metrics.get(n)||[];return o.push(s),this.metrics.set(n,o),s}getQueueHealth(n){let i=this.metrics.get(n)||[];if(i.length===0)return{status:"healthy",issues:[],recommendations:[]};let s=i[i.length-1],o=[],c=[],u="healthy";if(s.approximateNumberOfMessages>1e4)u="critical",o.push("Large message backlog detected"),c.push("Increase consumer capacity");else if(s.approximateNumberOfMessages>1000)u="warning",o.push("Growing message backlog"),c.push("Monitor consumer performance");if(s.oldestMessageAge&&s.oldestMessageAge>3600){if(u!=="critical")u="warning";o.push("Old messages in queue"),c.push("Review message processing")}if(s.approximateNumberOfMessagesDelayed>100){if(u!=="critical")u="warning";o.push("High number of delayed messages")}return{status:u,issues:o,recommendations:c}}getQueue(n){return this.queues.get(n)}listQueues(){return Array.from(this.queues.values())}getRetentionPolicy(n){return this.retentionPolicies.get(n)}listRetentionPolicies(){return Array.from(this.retentionPolicies.values())}getPurgeOperations(n){let i=Array.from(this.purgeOperations.values());if(n)i=i.filter((s)=>s.queueUrl===n);return i}generateQueueCF(n){return{Type:"AWS::SQS::Queue",Properties:{QueueName:n.queueName,MessageRetentionPeriod:n.messageRetentionPeriod,DelaySeconds:n.delaySeconds,MaximumMessageSize:n.maximumMessageSize,ReceiveMessageWaitTimeSeconds:n.receiveMessageWaitTime}}}generateCleanupRuleCF(n){return{Type:"AWS::Events::Rule",Properties:{Name:`${n.id}-cleanup`,Description:"Automated queue cleanup",ScheduleExpression:n.cleanupSchedule||"cron(0 0 * * ? *)",State:"ENABLED",Targets:[{Arn:"arn:aws:lambda:us-east-1:123456789012:function:queue-cleanup",Id:n.id,Input:JSON.stringify({queueId:n.queueId,archiveBucket:n.archiveS3Bucket})}]}}}clear(){this.queues.clear(),this.retentionPolicies.clear(),this.delayQueues.clear(),this.purgeOperations.clear(),this.metrics.clear(),this.queueCounter=0,this.retentionCounter=0,this.delayCounter=0,this.purgeCounter=0,this.metricsCounter=0}}var DE=new kf;import{deflateRawSync as Mi}from"node:zlib";var Li=(()=>{let n=[];for(let i=0;i<256;i++){let s=i;for(let o=0;o<8;o++)s=s&1?3988292384^s>>>1:s>>>1;n[i]=s>>>0}return n})();function Oi(n){let i=4294967295;for(let s=0;s<n.length;s++)i=Li[(i^n[s])&255]^i>>>8;return(i^4294967295)>>>0}function $i(n){if(typeof n==="string")return Buffer.from(n,"utf-8");if(Buffer.isBuffer(n))return n;return Buffer.from(n)}function Bi(n){let i=Math.max(1980,n.getFullYear()),s=(n.getHours()<<11|n.getMinutes()<<5|n.getSeconds()>>1)&65535,o=(i-1980<<9|n.getMonth()+1<<5|n.getDate())&65535;return{time:s,date:o}}function nt(n){let i=[],s=[],o=0;for(let d of n){let g=$i(d.data),y=Mi(g),h=Oi(g),b=Buffer.from(d.name.replace(/\\/g,"/"),"utf-8"),{time:v,date:A}=Bi(d.date??new Date(0)),T=d.mode??420,R=Buffer.alloc(30+b.length);R.writeUInt32LE(67324752,0),R.writeUInt16LE(20,4),R.writeUInt16LE(0,6),R.writeUInt16LE(8,8),R.writeUInt16LE(v,10),R.writeUInt16LE(A,12),R.writeUInt32LE(h,14),R.writeUInt32LE(y.length,18),R.writeUInt32LE(g.length,22),R.writeUInt16LE(b.length,26),R.writeUInt16LE(0,28),b.copy(R,30);let P=Buffer.alloc(46+b.length);P.writeUInt32LE(33639248,0),P.writeUInt16LE(798,4),P.writeUInt16LE(20,6),P.writeUInt16LE(0,8),P.writeUInt16LE(8,10),P.writeUInt16LE(v,12),P.writeUInt16LE(A,14),P.writeUInt32LE(h,16),P.writeUInt32LE(y.length,20),P.writeUInt32LE(g.length,24),P.writeUInt16LE(b.length,28),P.writeUInt16LE(0,30),P.writeUInt16LE(0,32),P.writeUInt16LE(0,34),P.writeUInt16LE(0,36),P.writeUInt32LE((T&65535)<<16,38),P.writeUInt32LE(o,42),b.copy(P,46),i.push(R,y),s.push(P),o+=R.length+y.length}let c=Buffer.concat(s),u=Buffer.alloc(22);return u.writeUInt32LE(101010256,0),u.writeUInt16LE(0,4),u.writeUInt16LE(0,6),u.writeUInt16LE(n.length,8),u.writeUInt16LE(n.length,10),u.writeUInt32LE(c.length,12),u.writeUInt32LE(o,16),u.writeUInt16LE(0,20),Buffer.concat([...i,c,u])}function Nf(n){let i=n.adapterImport??"./adapter",s=n.entryImport.replace(/\\/g,"/");return`// Generated by ts-cloud — serverless app bootstrap. Do not edit.
7229
+ `;static createAbTestsTable(n){return{[`${n.slug}AbTestsTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${n.slug}-ab-tests`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}]}}}}static createAbTestManagerLambda(n){return{[`${n.slug}AbTestManagerLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${n.slug}-ab-test-manager`,Runtime:"nodejs20.x",Handler:"index.handler",Role:n.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:Ee.AbTestManagerCode},Environment:{Variables:{AB_TESTS_TABLE:n.abTestsTable}}}}}}static selectVariant(n,i){let o=Ee.hashString(i+n.id)%100,c=0;for(let u=0;u<n.variants.length;u++)if(c+=n.trafficSplit[u],o<c)return n.variants[u];return n.variants[n.variants.length-1]}static determineWinner(n){if(n.variants.length===0)return null;let i=n.winningCriteria,s=n.variants[0],o=Ee.getMetricValue(s,i);for(let c of n.variants.slice(1)){let u=Ee.getMetricValue(c,i);if(u>o)o=u,s=c}return s}static calculateSignificance(n,i,s){let o=n.stats.sent,c=i.stats.sent;if(o<30||c<30)return 0;let u=Ee.getMetricValue(n,s)/100,d=Ee.getMetricValue(i,s)/100,g=(u*o+d*c)/(o+c),y=Math.sqrt(g*(1-g)*(1/o+1/c));if(y===0)return 0;let h=Math.abs(u-d)/y;if(h>=2.576)return 99;if(h>=1.96)return 95;if(h>=1.645)return 90;if(h>=1.28)return 80;return Math.round(h*30)}static getMetricValue(n,i){switch(i){case"delivery_rate":return n.stats.deliveryRate;case"click_rate":return n.stats.clickRate;case"reply_rate":return n.stats.replyRate;case"conversion_rate":return n.stats.conversionRate;default:return n.stats.deliveryRate}}static hashString(n){let i=0;for(let s=0;s<n.length;s++){let o=n.charCodeAt(s);i=(i<<5)-i+o,i=i&i}return Math.abs(i)}}class Rf{queues=new Map;messageGroups=new Map;deduplicationConfigs=new Map;messages=new Map;queueCounter=0;groupCounter=0;deduplicationCounter=0;messageCounter=0;sequenceCounter=0;createFIFOQueue(n){let i=`fifo-queue-${Date.now()}-${this.queueCounter++}`,s=n.name.endsWith(".fifo")?n.name:`${n.name}.fifo`,{name:o,...c}=n,u={id:i,name:s,queueUrl:`https://sqs.us-east-1.amazonaws.com/123456789012/${s}`,...c};return this.queues.set(i,u),this.createDeduplicationConfig({queueId:i,contentBasedDeduplication:n.contentBasedDeduplication,deduplicationInterval:300}),u}createHighThroughputFIFO(n){return this.createFIFOQueue({name:n.name,contentBasedDeduplication:n.contentBasedDeduplication??!0,deduplicationScope:"messageGroup",fifoThroughputLimit:"perMessageGroupId",messageRetentionPeriod:345600,visibilityTimeout:30,receiveMessageWaitTime:0})}createStandardFIFO(n){return this.createFIFOQueue({name:n.name,contentBasedDeduplication:n.contentBasedDeduplication??!1,deduplicationScope:"queue",fifoThroughputLimit:"perQueue",messageRetentionPeriod:345600,visibilityTimeout:30,receiveMessageWaitTime:0})}createDeduplicationConfig(n){let s={id:`dedup-${Date.now()}-${this.deduplicationCounter++}`,deduplicationHashes:new Map,...n};return this.deduplicationConfigs.set(n.queueId,s),s}sendMessage(n){let i=this.queues.get(n.queueId);if(!i)throw Error(`Queue not found: ${n.queueId}`);let s=this.deduplicationConfigs.get(n.queueId);if(s){let d=n.messageDeduplicationId||(i.contentBasedDeduplication?this.generateHash(n.messageBody):void 0);if(d&&this.isDuplicate(s,d))return null;if(d)s.deduplicationHashes.set(d,new Date)}let o=`msg-${Date.now()}-${this.messageCounter++}`,c=this.generateSequenceNumber(),u={id:o,messageId:o,messageGroupId:n.messageGroupId,messageDeduplicationId:n.messageDeduplicationId,body:n.messageBody,attributes:n.messageAttributes||{},sentTimestamp:new Date,sequenceNumber:c};return this.messages.set(o,u),this.updateMessageGroup(n.queueId,n.messageGroupId),u}isDuplicate(n,i){let s=n.deduplicationHashes.get(i);if(!s)return!1;if((Date.now()-s.getTime())/1000>n.deduplicationInterval)return n.deduplicationHashes.delete(i),!1;return!0}generateHash(n){let i=0;for(let s=0;s<n.length;s++){let o=n.charCodeAt(s);i=(i<<5)-i+o,i=i&i}return Math.abs(i).toString(36)}generateSequenceNumber(){return`${Date.now()}${this.sequenceCounter++}`.padStart(20,"0")}updateMessageGroup(n,i){let s=`${n}-${i}`,o=this.messageGroups.get(s);if(!o)o={id:`group-${Date.now()}-${this.groupCounter++}`,messageGroupId:i,queueId:n,messagesInFlight:0},this.messageGroups.set(s,o);o.messagesInFlight++,o.lastMessageTimestamp=new Date}getMessageGroups(n){return Array.from(this.messageGroups.values()).filter((i)=>i.queueId===n)}getQueue(n){return this.queues.get(n)}listQueues(){return Array.from(this.queues.values())}getMessages(n,i){let s=Array.from(this.messages.values());if(i)s=s.filter((o)=>o.messageGroupId===i);return s.sort((o,c)=>o.sequenceNumber.localeCompare(c.sequenceNumber))}generateFIFOQueueCF(n){return{Type:"AWS::SQS::Queue",Properties:{QueueName:n.name,FifoQueue:!0,ContentBasedDeduplication:n.contentBasedDeduplication,DeduplicationScope:n.deduplicationScope,FifoThroughputLimit:n.fifoThroughputLimit,MessageRetentionPeriod:n.messageRetentionPeriod,VisibilityTimeout:n.visibilityTimeout,ReceiveMessageWaitTimeSeconds:n.receiveMessageWaitTime,...n.deadLetterTargetArn&&{RedrivePolicy:{deadLetterTargetArn:n.deadLetterTargetArn,maxReceiveCount:n.maxReceiveCount||3}}}}}clear(){this.queues.clear(),this.messageGroups.clear(),this.deduplicationConfigs.clear(),this.messages.clear(),this.queueCounter=0,this.groupCounter=0,this.deduplicationCounter=0,this.messageCounter=0,this.sequenceCounter=0}}var TE=new Rf;class Df{monitors=new Map;metrics=new Map;alerts=new Map;reprocessJobs=new Map;monitorCounter=0;metricsCounter=0;alertCounter=0;jobCounter=0;createDLQMonitor(n){let i=`dlq-monitor-${Date.now()}-${this.monitorCounter++}`,s={id:i,...n};return this.monitors.set(i,s),s}createAutomatedMonitor(n){return this.createDLQMonitor({name:n.name,queueUrl:n.queueUrl,sourceQueues:n.sourceQueues,maxReceiveCount:3,alarmThreshold:10,autoReprocess:!0,reprocessStrategy:"scheduled",notificationTopicArn:n.notificationTopicArn})}collectMetrics(n){let s={id:`metrics-${Date.now()}-${this.metricsCounter++}`,queueUrl:n,timestamp:new Date,approximateNumberOfMessages:Math.floor(Math.random()*100),approximateAgeOfOldestMessage:Math.floor(Math.random()*86400),messagesReceived:Math.floor(Math.random()*50),messagesDeleted:Math.floor(Math.random()*30),messagesReprocessed:Math.floor(Math.random()*20)},o=this.metrics.get(n)||[];return o.push(s),this.metrics.set(n,o),this.checkForAlerts(n,s),s}checkForAlerts(n,i){let s=Array.from(this.monitors.values()).find((c)=>c.queueUrl===n);if(!s)return;if(i.approximateNumberOfMessages>=s.alarmThreshold)this.createAlert({monitorId:s.id,alertType:"threshold_exceeded",severity:"high",message:`DLQ ${s.name} has ${i.approximateNumberOfMessages} messages (threshold: ${s.alarmThreshold})`});let o=3600;if(i.approximateAgeOfOldestMessage>o)this.createAlert({monitorId:s.id,alertType:"old_message",severity:"medium",message:`DLQ ${s.name} has messages older than ${o} seconds`})}createAlert(n){let i=`alert-${Date.now()}-${this.alertCounter++}`,s={id:i,timestamp:new Date,acknowledged:!1,...n};return this.alerts.set(i,s),s}acknowledgeAlert(n){let i=this.alerts.get(n);if(!i)throw Error(`Alert not found: ${n}`);return i.acknowledged=!0,i}createReprocessJob(n){let i=`reprocess-${Date.now()}-${this.jobCounter++}`,s={id:i,queueUrl:n.queueUrl,messageId:n.messageId,attempts:0,status:"pending"};return this.reprocessJobs.set(i,s),s}async executeReprocessJob(n){let i=this.reprocessJobs.get(n);if(!i)throw Error(`Reprocess job not found: ${n}`);i.status="processing",i.startedAt=new Date,i.attempts++,await new Promise((o)=>setTimeout(o,100));let s=Math.random()>0.3;if(i.status=s?"success":"failed",i.completedAt=new Date,!s)i.error="Reprocessing failed - original error still present";return i}async batchReprocess(n){let i=[];for(let s=0;s<n.maxMessages;s++){let o=this.createReprocessJob({queueUrl:n.queueUrl,messageId:`msg-${s}`});await this.executeReprocessJob(o.id),i.push(o)}return i}getDLQStatistics(n,i=24){let s=new Date(Date.now()-i*60*60*1000),o=(this.metrics.get(n)||[]).filter((b)=>b.timestamp>=s);if(o.length===0)return{totalMessages:0,avgAge:0,messagesReceived:0,messagesDeleted:0,messagesReprocessed:0,successRate:0};let c=o[o.length-1],u=o.reduce((b,v)=>b+v.messagesReceived,0),d=o.reduce((b,v)=>b+v.messagesDeleted,0),g=o.reduce((b,v)=>b+v.messagesReprocessed,0),y=o.reduce((b,v)=>b+v.approximateAgeOfOldestMessage,0)/o.length,h=g>0?d/g*100:0;return{totalMessages:c.approximateNumberOfMessages,avgAge:y,messagesReceived:u,messagesDeleted:d,messagesReprocessed:g,successRate:h}}getMonitor(n){return this.monitors.get(n)}listMonitors(){return Array.from(this.monitors.values())}getAlerts(n,i){let s=Array.from(this.alerts.values());if(n)s=s.filter((o)=>o.monitorId===n);if(i!==void 0)s=s.filter((o)=>o.acknowledged===i);return s.sort((o,c)=>c.timestamp.getTime()-o.timestamp.getTime())}getReprocessJobs(n){let i=Array.from(this.reprocessJobs.values());if(n)i=i.filter((s)=>s.queueUrl===n);return i}generateDLQAlarmCF(n){return{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${n.name}-messages-alarm`,AlarmDescription:`Alert when DLQ ${n.name} exceeds threshold`,MetricName:"ApproximateNumberOfMessagesVisible",Namespace:"AWS/SQS",Statistic:"Average",Period:300,EvaluationPeriods:1,Threshold:n.alarmThreshold,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:n.queueUrl.split("/").pop()}],...n.notificationTopicArn&&{AlarmActions:[n.notificationTopicArn]}}}}clear(){this.monitors.clear(),this.metrics.clear(),this.alerts.clear(),this.reprocessJobs.clear(),this.monitorCounter=0,this.metricsCounter=0,this.alertCounter=0,this.jobCounter=0}}var wE=new Df;class Pf{configs=new Map;jobs=new Map;metrics=new Map;configCounter=0;jobCounter=0;metricsCounter=0;createBatchConfig(n){let i=`batch-config-${Date.now()}-${this.configCounter++}`,s={id:i,...n};return this.configs.set(i,s),s}createHighThroughputConfig(n){return this.createBatchConfig({queueUrl:n.queueUrl,batchSize:10,maxWaitTime:100,parallelProcessors:10,retryAttempts:3,visibilityTimeout:30})}createLowLatencyConfig(n){return this.createBatchConfig({queueUrl:n.queueUrl,batchSize:1,maxWaitTime:0,parallelProcessors:5,retryAttempts:2,visibilityTimeout:10})}createBatchJob(n){let i=`batch-job-${Date.now()}-${this.jobCounter++}`;if(!this.configs.get(n.configId))throw Error(`Batch config not found: ${n.configId}`);let o=[];for(let u=0;u<n.messageCount;u++)o.push({id:`msg-${i}-${u}`,messageId:`${i}-${u}`,body:`Message ${u}`,receiptHandle:`receipt-${i}-${u}`,attributes:{},status:"pending"});let c={id:i,configId:n.configId,messages:o,status:"pending",processedCount:0,failedCount:0};return this.jobs.set(i,c),c}async processBatchJob(n){let i=this.jobs.get(n);if(!i)throw Error(`Batch job not found: ${n}`);let s=this.configs.get(i.configId);if(!s)throw Error(`Batch config not found: ${i.configId}`);i.status="processing",i.startedAt=new Date;let o=this.chunkArray(i.messages,s.batchSize);for(let c of o)await this.processBatch(c,s);return i.processedCount=i.messages.filter((c)=>c.status==="success").length,i.failedCount=i.messages.filter((c)=>c.status==="failed").length,i.status=i.failedCount===0?"completed":"failed",i.completedAt=new Date,this.collectProcessorMetrics(s.id,i),i}async processBatch(n,i){let s=n.map((o)=>this.processMessage(o,i));await Promise.all(s)}async processMessage(n,i){n.status="processing";let s=Date.now();await new Promise((u)=>setTimeout(u,Math.random()*100));let o=Date.now()-s;if(n.processingTime=o,Math.random()>0.1)n.status="success";else n.status="failed",n.error="Processing error"}chunkArray(n,i){let s=[];for(let o=0;o<n.length;o+=i)s.push(n.slice(o,o+i));return s}collectProcessorMetrics(n,i){let s=`metrics-${Date.now()}-${this.metricsCounter++}`,c=i.messages.filter((v)=>v.status==="success").map((v)=>v.processingTime||0).filter((v)=>v>0),u=c.length>0?c.reduce((v,A)=>v+A,0)/c.length:0,d=i.completedAt&&i.startedAt?(i.completedAt.getTime()-i.startedAt.getTime())/1000:1,g=i.processedCount/d,y=i.messages.length>0?i.failedCount/i.messages.length*100:0,h={id:s,configId:n,timestamp:new Date,messagesProcessed:i.processedCount,averageProcessingTime:u,throughput:g,errorRate:y},b=this.metrics.get(n)||[];b.push(h),this.metrics.set(n,b)}getBatchStatistics(n){let i=this.metrics.get(n)||[];if(i.length===0)return{totalJobsProcessed:0,totalMessagesProcessed:0,averageThroughput:0,averageErrorRate:0,averageProcessingTime:0};let s=i.reduce((d,g)=>d+g.messagesProcessed,0),o=i.reduce((d,g)=>d+g.throughput,0)/i.length,c=i.reduce((d,g)=>d+g.errorRate,0)/i.length,u=i.reduce((d,g)=>d+g.averageProcessingTime,0)/i.length;return{totalJobsProcessed:i.length,totalMessagesProcessed:s,averageThroughput:o,averageErrorRate:c,averageProcessingTime:u}}optimizeBatchConfig(n){let i=this.configs.get(n);if(!i)throw Error(`Batch config not found: ${n}`);let s=this.getBatchStatistics(n);if(s.averageErrorRate<5&&i.batchSize<10)i.batchSize=Math.min(10,i.batchSize+1);if(s.averageErrorRate>20&&i.batchSize>1)i.batchSize=Math.max(1,i.batchSize-1);if(s.averageThroughput<5&&i.parallelProcessors<20)i.parallelProcessors++;return i}getConfig(n){return this.configs.get(n)}listConfigs(){return Array.from(this.configs.values())}getJob(n){return this.jobs.get(n)}listJobs(n){let i=Array.from(this.jobs.values());if(n)i=i.filter((s)=>s.configId===n);return i}generateBatchProcessorCF(n){return{Type:"AWS::Lambda::EventSourceMapping",Properties:{EventSourceArn:`arn:aws:sqs:us-east-1:123456789012:${n.queueUrl.split("/").pop()}`,FunctionName:"batch-processor-function",BatchSize:n.batchSize,MaximumBatchingWindowInSeconds:n.maxWaitTime/1000,FunctionResponseTypes:["ReportBatchItemFailures"]}}}clear(){this.configs.clear(),this.jobs.clear(),this.metrics.clear(),this.configCounter=0,this.jobCounter=0,this.metricsCounter=0}}var RE=new Pf;class kf{queues=new Map;retentionPolicies=new Map;delayQueues=new Map;purgeOperations=new Map;metrics=new Map;queueCounter=0;retentionCounter=0;delayCounter=0;purgeCounter=0;metricsCounter=0;createQueue(n){let i=`queue-${Date.now()}-${this.queueCounter++}`,s={id:i,purgeInProgress:!1,...n};return this.queues.set(i,s),s}createStandardQueue(n){return this.createQueue({queueUrl:`https://sqs.us-east-1.amazonaws.com/123456789012/${n.queueName}`,queueName:n.queueName,messageRetentionPeriod:(n.messageRetentionDays||4)*24*60*60,delaySeconds:0,maximumMessageSize:262144,receiveMessageWaitTime:0})}createLongPollingQueue(n){return this.createQueue({queueUrl:`https://sqs.us-east-1.amazonaws.com/123456789012/${n.queueName}`,queueName:n.queueName,messageRetentionPeriod:345600,delaySeconds:0,maximumMessageSize:262144,receiveMessageWaitTime:n.waitTimeSeconds||20})}createRetentionPolicy(n){let i=`retention-${Date.now()}-${this.retentionCounter++}`,s={id:i,...n};this.retentionPolicies.set(i,s);let o=this.queues.get(n.queueId);if(o)o.messageRetentionPeriod=n.retentionPeriod;return s}createShortRetentionPolicy(n){return this.createRetentionPolicy({queueId:n.queueId,retentionPeriod:n.retentionHours*60*60,autoCleanup:!0,archiveExpiredMessages:!1})}createArchivalRetentionPolicy(n){return this.createRetentionPolicy({queueId:n.queueId,retentionPeriod:n.retentionDays*24*60*60,autoCleanup:!0,cleanupSchedule:"cron(0 0 * * ? *)",archiveExpiredMessages:!0,archiveS3Bucket:n.s3Bucket})}createDelayQueue(n){let i=`delay-${Date.now()}-${this.delayCounter++}`,s={id:i,...n};this.delayQueues.set(i,s);let o=Array.from(this.queues.values()).find((c)=>c.queueUrl===n.queueUrl);if(o)o.delaySeconds=n.defaultDelay;return s}createScheduledDelayQueue(n){return this.createDelayQueue({queueUrl:n.queueUrl,defaultDelay:n.delayMinutes*60,perMessageDelay:!1,maxDelay:900})}async purgeQueue(n){let i=this.queues.get(n);if(!i)throw Error(`Queue not found: ${n}`);if(i.purgeInProgress)throw Error("Purge already in progress for this queue");let s=`purge-${Date.now()}-${this.purgeCounter++}`,o={id:s,queueUrl:i.queueUrl,status:"in_progress",startedAt:new Date};return this.purgeOperations.set(s,o),i.purgeInProgress=!0,setTimeout(()=>{o.status="completed",o.completedAt=new Date,o.messagesPurged=Math.floor(Math.random()*1000),i.purgeInProgress=!1},100),o}collectQueueMetrics(n){let s={id:`metrics-${Date.now()}-${this.metricsCounter++}`,queueUrl:n,timestamp:new Date,approximateNumberOfMessages:Math.floor(Math.random()*1000),approximateNumberOfMessagesNotVisible:Math.floor(Math.random()*100),approximateNumberOfMessagesDelayed:Math.floor(Math.random()*50),oldestMessageAge:Math.floor(Math.random()*86400)},o=this.metrics.get(n)||[];return o.push(s),this.metrics.set(n,o),s}getQueueHealth(n){let i=this.metrics.get(n)||[];if(i.length===0)return{status:"healthy",issues:[],recommendations:[]};let s=i[i.length-1],o=[],c=[],u="healthy";if(s.approximateNumberOfMessages>1e4)u="critical",o.push("Large message backlog detected"),c.push("Increase consumer capacity");else if(s.approximateNumberOfMessages>1000)u="warning",o.push("Growing message backlog"),c.push("Monitor consumer performance");if(s.oldestMessageAge&&s.oldestMessageAge>3600){if(u!=="critical")u="warning";o.push("Old messages in queue"),c.push("Review message processing")}if(s.approximateNumberOfMessagesDelayed>100){if(u!=="critical")u="warning";o.push("High number of delayed messages")}return{status:u,issues:o,recommendations:c}}getQueue(n){return this.queues.get(n)}listQueues(){return Array.from(this.queues.values())}getRetentionPolicy(n){return this.retentionPolicies.get(n)}listRetentionPolicies(){return Array.from(this.retentionPolicies.values())}getPurgeOperations(n){let i=Array.from(this.purgeOperations.values());if(n)i=i.filter((s)=>s.queueUrl===n);return i}generateQueueCF(n){return{Type:"AWS::SQS::Queue",Properties:{QueueName:n.queueName,MessageRetentionPeriod:n.messageRetentionPeriod,DelaySeconds:n.delaySeconds,MaximumMessageSize:n.maximumMessageSize,ReceiveMessageWaitTimeSeconds:n.receiveMessageWaitTime}}}generateCleanupRuleCF(n){return{Type:"AWS::Events::Rule",Properties:{Name:`${n.id}-cleanup`,Description:"Automated queue cleanup",ScheduleExpression:n.cleanupSchedule||"cron(0 0 * * ? *)",State:"ENABLED",Targets:[{Arn:"arn:aws:lambda:us-east-1:123456789012:function:queue-cleanup",Id:n.id,Input:JSON.stringify({queueId:n.queueId,archiveBucket:n.archiveS3Bucket})}]}}}clear(){this.queues.clear(),this.retentionPolicies.clear(),this.delayQueues.clear(),this.purgeOperations.clear(),this.metrics.clear(),this.queueCounter=0,this.retentionCounter=0,this.delayCounter=0,this.purgeCounter=0,this.metricsCounter=0}}var DE=new kf;import{deflateRawSync as Mi}from"node:zlib";var Li=(()=>{let n=[];for(let i=0;i<256;i++){let s=i;for(let o=0;o<8;o++)s=s&1?3988292384^s>>>1:s>>>1;n[i]=s>>>0}return n})();function Oi(n){let i=4294967295;for(let s=0;s<n.length;s++)i=Li[(i^n[s])&255]^i>>>8;return(i^4294967295)>>>0}function $i(n){if(typeof n==="string")return Buffer.from(n,"utf-8");if(Buffer.isBuffer(n))return n;return Buffer.from(n)}function Bi(n){let i=Math.max(1980,n.getFullYear()),s=(n.getHours()<<11|n.getMinutes()<<5|n.getSeconds()>>1)&65535,o=(i-1980<<9|n.getMonth()+1<<5|n.getDate())&65535;return{time:s,date:o}}function it(n){let i=[],s=[],o=0;for(let d of n){let g=$i(d.data),y=Mi(g),h=Oi(g),b=Buffer.from(d.name.replace(/\\/g,"/"),"utf-8"),{time:v,date:A}=Bi(d.date??new Date(0)),T=d.mode??420,R=Buffer.alloc(30+b.length);R.writeUInt32LE(67324752,0),R.writeUInt16LE(20,4),R.writeUInt16LE(0,6),R.writeUInt16LE(8,8),R.writeUInt16LE(v,10),R.writeUInt16LE(A,12),R.writeUInt32LE(h,14),R.writeUInt32LE(y.length,18),R.writeUInt32LE(g.length,22),R.writeUInt16LE(b.length,26),R.writeUInt16LE(0,28),b.copy(R,30);let P=Buffer.alloc(46+b.length);P.writeUInt32LE(33639248,0),P.writeUInt16LE(798,4),P.writeUInt16LE(20,6),P.writeUInt16LE(0,8),P.writeUInt16LE(8,10),P.writeUInt16LE(v,12),P.writeUInt16LE(A,14),P.writeUInt32LE(h,16),P.writeUInt32LE(y.length,20),P.writeUInt32LE(g.length,24),P.writeUInt16LE(b.length,28),P.writeUInt16LE(0,30),P.writeUInt16LE(0,32),P.writeUInt16LE(0,34),P.writeUInt16LE(0,36),P.writeUInt32LE((T&65535)<<16,38),P.writeUInt32LE(o,42),b.copy(P,46),i.push(R,y),s.push(P),o+=R.length+y.length}let c=Buffer.concat(s),u=Buffer.alloc(22);return u.writeUInt32LE(101010256,0),u.writeUInt16LE(0,4),u.writeUInt16LE(0,6),u.writeUInt16LE(n.length,8),u.writeUInt16LE(n.length,10),u.writeUInt32LE(c.length,12),u.writeUInt32LE(o,16),u.writeUInt16LE(0,20),Buffer.concat([...i,c,u])}function Nf(n){let i=n.adapterImport??"./adapter",s=n.entryImport.replace(/\\/g,"/");return`// Generated by ts-cloud — serverless app bootstrap. Do not edit.
7230
7230
  import * as __userModule from ${JSON.stringify(s)}
7231
7231
  import { resolveApp, createHandlers } from ${JSON.stringify(i)}
7232
7232
 
@@ -7236,9 +7236,9 @@ const __handlers = createHandlers(__app)
7236
7236
  export const http = __handlers.http
7237
7237
  export const queue = __handlers.queue
7238
7238
  export const cli = __handlers.cli
7239
- `}import{execSync as Fi}from"node:child_process";import{createHash as Gi}from"node:crypto";import{cpSync as _i,mkdtempSync as Wi,rmSync as Vi,writeFileSync as Ui}from"node:fs";import{tmpdir as Hi}from"node:os";import{dirname as ji,isAbsolute as Ki,join as Fe,resolve as qi}from"node:path";import{fileURLToPath as zi}from"node:url";var Qi=["adapter.ts","recursion.ts","auto-recursion.ts"];function ss(){return Fe(ji(zi(import.meta.url)),"runtime")}function uS(n,i,s){for(let o of n??[])s?.(`build: ${o}`),Fi(o,{stdio:"inherit",cwd:i})}function Wo(n){return Gi("sha256").update(n).digest("hex")}function $l(n,i,s){return`deployments/${n}/${i}/${s}.zip`}async function pn(n){let i=qi(n.projectRoot??process.cwd()),{app:s}=n;if(!n.skipBuild)uS(s.build,i,n.onStep);let o=s.entry;if(!o)throw Error("serverless app: `entry` is required to package a Node/Bun application");let c=Ki(o)?o:Fe(i,o),u=Wi(Fe(Hi(),"tscloud-pkg-"));try{for(let A of Qi)_i(Fe(ss(),A),Fe(u,A));let d=Fe(u,"bootstrap.ts");Ui(d,Nf({entryImport:c,adapterImport:"./adapter"})),n.onStep?.("bundling application");let g=await Bun.build({entrypoints:[d],target:s.kind==="bun"?"bun":"node",format:"esm",minify:!1,sourcemap:"none"});if(!g.success){let A=g.logs.map((T)=>String(T)).join(`
7239
+ `}import{execSync as Fi}from"node:child_process";import{createHash as Gi}from"node:crypto";import{cpSync as _i,mkdtempSync as Wi,rmSync as Vi,writeFileSync as Ui}from"node:fs";import{tmpdir as Hi}from"node:os";import{dirname as ji,isAbsolute as Ki,join as Fe,resolve as qi}from"node:path";import{fileURLToPath as zi}from"node:url";var Qi=["adapter.ts","recursion.ts","auto-recursion.ts"];function ss(){return Fe(ji(zi(import.meta.url)),"runtime")}function uS(n,i,s){for(let o of n??[])s?.(`build: ${o}`),Fi(o,{stdio:"inherit",cwd:i})}function Wo(n){return Gi("sha256").update(n).digest("hex")}function $l(n,i,s){return`deployments/${n}/${i}/${s}.zip`}async function mn(n){let i=qi(n.projectRoot??process.cwd()),{app:s}=n;if(!n.skipBuild)uS(s.build,i,n.onStep);let o=s.entry;if(!o)throw Error("serverless app: `entry` is required to package a Node/Bun application");let c=Ki(o)?o:Fe(i,o),u=Wi(Fe(Hi(),"tscloud-pkg-"));try{for(let A of Qi)_i(Fe(ss(),A),Fe(u,A));let d=Fe(u,"bootstrap.ts");Ui(d,Nf({entryImport:c,adapterImport:"./adapter"})),n.onStep?.("bundling application");let g=await Bun.build({entrypoints:[d],target:s.kind==="bun"?"bun":"node",format:"esm",minify:!1,sourcemap:"none"});if(!g.success){let A=g.logs.map((T)=>String(T)).join(`
7240
7240
  `);throw Error(`serverless app bundle failed:
7241
- ${A}`)}let y=g.outputs[0],h=Buffer.from(await y.arrayBuffer()),b="index",v=nt([{name:`${b}.mjs`,data:h}]);return{zip:v,bundle:h,sha256:Wo(v),handlerFile:b,handlers:{http:s.handlers?.http??`${b}.http`,queue:s.handlers?.queue??`${b}.queue`,cli:s.handlers?.cli??`${b}.cli`},bundleBytes:h.length}}finally{Vi(u,{recursive:!0,force:!0})}}var gS=["18","20","22"];function as(n){if(!n)return"22";let i=String(n).match(/(\d+)/);return i?i[1]:"22"}function ns(n){let i=n.kind??"node";if(i==="php")return{lambdaRuntime:"provided.al2023",kind:"php",version:n.phpVersion??"8.3",usesLayer:!0,layerKind:"php",layerEnvVar:"TSCLOUD_PHP_LAYER_ARN"};if(i==="bun")return{lambdaRuntime:"provided.al2023",kind:"bun",version:n.runtimeVersion??"latest",usesLayer:!0,layerKind:"bun",layerEnvVar:"TSCLOUD_BUN_LAYER_ARN"};let s=as(n.runtimeVersion);if(n.runtime!=="provided.al2023"&&gS.includes(s))return{lambdaRuntime:n.runtime&&n.runtime.startsWith("nodejs")?n.runtime:`nodejs${s}.x`,kind:"node",version:s,usesLayer:!1};return{lambdaRuntime:"provided.al2023",kind:"node",version:s,usesLayer:!0,layerKind:"node",layerEnvVar:"TSCLOUD_NODE_LAYER_ARN"}}function Ar(n,i,s){if(n.queues===!1)return[];if(n.queues===void 0||n.queues===!0)return[{name:`${i}-${s}-default`}];return n.queues.map((o)=>{if(typeof o==="string")return{name:`${i}-${s}-${o}`};let[c,u]=Object.entries(o)[0];return{name:`${i}-${s}-${c}`,concurrency:u}})}function Ml(n,i,s){return Ar(n,i,s).map((o)=>o.name)}function Fl(n){let{app:i,environment:s,handlers:o}=n,c=n.config.project.slug,u=ns(i).lambdaRuntime,d=i.architecture??"x86_64",g=n.config.project.region,y={http:`${c}-${s}-http`,queue:`${c}-${s}-queue`,cli:`${c}-${s}-cli`};if(i.gatewayVersion===1)throw Error("serverless app: `gatewayVersion: 1` (REST API) is not supported — ts-cloud uses API Gateway HTTP API (v2). Remove `gatewayVersion` or set it to 2.");let h=Ar(i,c,s),b=h.map((G)=>G.name),v=b.length>0,A=i.logRetention??14,T=i.packaging==="image";if(T&&i.lambdaInsights)throw Error("serverless app: `lambdaInsights` layer attachment is only supported for zip packaging. Container images must install the Lambda Insights extension in the image.");let R=(i.scheduler??"on")!=="off",P=(i.cache?.driver??"dynamodb")==="dynamodb",I=Boolean(i.assets),M=Xi(c,s),L=i.tmpStorage??512,N={},O={},B=[{PolicyName:"tscloud-serverless-app",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["logs:CreateLogGroup","logs:CreateLogStream","logs:PutLogEvents"],Resource:e.sub("arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/*")},{Effect:"Allow",Action:["lambda:InvokeFunction"],Resource:e.sub(`arn:aws:lambda:\${AWS::Region}:\${AWS::AccountId}:function:${c}-${s}-*`)},{Effect:"Allow",Action:["secretsmanager:GetSecretValue","ssm:GetParameter","ssm:GetParameters","ssm:GetParametersByPath"],Resource:[e.sub(`arn:aws:secretsmanager:\${AWS::Region}:\${AWS::AccountId}:secret:${c}/${s}/*`),e.sub(`arn:aws:ssm:\${AWS::Region}:\${AWS::AccountId}:parameter/${c}/${s}/*`)]},{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:ListBucket"],Resource:[e.sub(`arn:aws:s3:::${M}`),e.sub(`arn:aws:s3:::${M}/*`),...i.storage?.bucket?[e.sub(`arn:aws:s3:::${i.storage.bucket}`),e.sub(`arn:aws:s3:::${i.storage.bucket}/*`)]:[]]}]}}];if(v)B[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["sqs:SendMessage","sqs:ReceiveMessage","sqs:DeleteMessage","sqs:GetQueueAttributes","sqs:GetQueueUrl"],Resource:e.sub(`arn:aws:sqs:\${AWS::Region}:\${AWS::AccountId}:${c}-${s}-*`)});if(P)B[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["dynamodb:GetItem","dynamodb:PutItem","dynamodb:UpdateItem","dynamodb:DeleteItem","dynamodb:Query","dynamodb:Scan","dynamodb:BatchGetItem","dynamodb:BatchWriteItem"],Resource:e.sub(`arn:aws:dynamodb:\${AWS::Region}:\${AWS::AccountId}:table/${c}-${s}-cache*`)});let F=["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"];if(i.vpc?.subnets?.length)F.push("arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole");if(i.lambdaInsights)F.push("arn:aws:iam::aws:policy/CloudWatchLambdaInsightsExecutionRolePolicy");N.AppRole={Type:"AWS::IAM::Role",Properties:{RoleName:`${c}-${s}-app-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:F,Policies:B}};let U=(G)=>({TSCLOUD_LAMBDA_MODE:G,TSCLOUD_ENV:s,...i.octane?{TSCLOUD_OCTANE:"1"}:{},...i.scheduler==="sub-minute"?{TSCLOUD_SCHEDULER:"sub-minute"}:{},...P?{TSCLOUD_CACHE_TABLE:`${c}-${s}-cache`}:{},...v?{TSCLOUD_QUEUE:b[0]}:{},...i.env??{}}),j=Boolean(i.efs),H=typeof i.efs==="object"?i.efs:{},z=H.mountPath??"/mnt/local",se=j&&!H.accessPointArn,Te=H.accessPointArn??(se?e.getAtt("EfsAccessPoint","Arn"):void 0),oe=i.vpc?.subnets??[],ge=oe.length>0,ae=i.cache?.driver==="elasticache"||i.database?.connection==="aurora-serverless"||Boolean(i.rdsProxy)||j;if(ae&&!ge)throw Error("serverless app: elasticache / aurora-serverless / rdsProxy / efs require app.vpc.subnets (private subnets) to be set.");let pe=ge?{VpcConfig:{SubnetIds:oe,SecurityGroupIds:[...i.vpc?.securityGroups??[],...ae?[e.getAtt("DataSecurityGroup","GroupId")]:[]]}}:{},Ie=se?oe.map((G,ne)=>`EfsMountTarget${ne}`):[],Le=j?{FileSystemConfigs:[{Arn:Te,LocalMountPath:z}]}:{};if(j)B[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["elasticfilesystem:ClientMount","elasticfilesystem:ClientWrite","elasticfilesystem:ClientRootAccess","elasticfilesystem:DescribeMountTargets"],Resource:"*"});function he(G,ne,ie,re,fe,ht,Ve,Ne=L){N[`${G}LogGroup`]={Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:`/aws/lambda/${ne}`,RetentionInDays:A}};let Ue=[...n.runtimeLayers??[],...i.lambdaInsights?[i.lambdaInsights.layerArn]:[]],en=T?{PackageType:"Image",Code:{ImageUri:e.ref("ImageUri")},...i.kind==="php"?{}:{ImageConfig:{Command:[ie]}}}:{Runtime:u,Handler:ie,Code:{S3Bucket:e.ref("ArtifactBucket"),S3Key:e.ref("ArtifactKey")},...Ue.length?{Layers:[...new Set(Ue)]}:{}};N[G]={Type:"AWS::Lambda::Function",DependsOn:[`${G}LogGroup`,...Ie],Properties:{FunctionName:ne,Architectures:[d],MemorySize:fe,Timeout:ht,Role:e.getAtt("AppRole","Arn"),Environment:{Variables:U(re)},EphemeralStorage:{Size:Ne},...en,...Ve!==void 0?{ReservedConcurrentExecutions:Ve}:{},...pe,...Le}}}if(he("HttpFunction",y.http,o.http,"http",i.memory??1024,i.timeout??28,i.concurrency,L),he("CliFunction",y.cli,o.cli,"cli",i.cliMemory??1024,i.cliTimeout??900,void 0,i.cliTmpStorage??L),v)he("QueueFunction",y.queue,o.queue,"queue",i.queueMemory??1024,i.queueTimeout??120,void 0,i.queueTmpStorage??L);let ye=(i.provisionedConcurrency??0)>0?i.provisionedConcurrency:0,be=["HttpFunction","CliFunction",...v?["QueueFunction"]:[]];if(ye)for(let G of be)N[`${G}Version`]={Type:"AWS::Lambda::Version",DeletionPolicy:"Retain",Properties:{FunctionName:e.ref(G)}},N[`${G}Alias`]={Type:"AWS::Lambda::Alias",Properties:{FunctionName:e.ref(G),Name:"live",FunctionVersion:e.getAtt(`${G}Version`,"Version"),ProvisionedConcurrencyConfig:{ProvisionedConcurrentExecutions:ye}}};let De=(G)=>ye?e.ref(`${G}Alias`):e.getAtt(G,"Arn"),Se=(G)=>ye?e.ref(`${G}Alias`):e.ref(G);N.HttpApi={Type:"AWS::ApiGatewayV2::Api",Properties:{Name:`${c}-${s}`,ProtocolType:"HTTP"}},N.HttpIntegration={Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:e.ref("HttpApi"),IntegrationType:"AWS_PROXY",IntegrationUri:De("HttpFunction"),PayloadFormatVersion:"2.0"}},N.HttpRoute={Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:e.ref("HttpApi"),RouteKey:"$default",Target:e.join("/",["integrations",e.ref("HttpIntegration")])}},N.HttpStage={Type:"AWS::ApiGatewayV2::Stage",Properties:{ApiId:e.ref("HttpApi"),StageName:"$default",AutoDeploy:!0}},N.HttpPermission={Type:"AWS::Lambda::Permission",Properties:{FunctionName:Se("HttpFunction"),Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:e.sub("arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${HttpApi}/*/*")}},O.HttpApiEndpoint={Description:"HTTP API endpoint",Value:e.getAtt("HttpApi","ApiEndpoint")},O.HttpApiId={Description:"HTTP API id",Value:e.ref("HttpApi")};let Re=(Array.isArray(i.domain)?i.domain:i.domain?[i.domain]:[]).filter(Boolean);if(Re.length){if(!i.certificateArn&&!i.hostedZoneId)throw Error("serverless app: a custom `domain` needs either `certificateArn` (pre-issued, regional) or `hostedZoneId` (to auto-issue + validate an ACM cert).");let G=i.certificateArn;if(!G)N.HttpCertificate={Type:"AWS::CertificateManager::Certificate",Properties:{DomainName:Re[0],...Re.length>1?{SubjectAlternativeNames:Re.slice(1)}:{},ValidationMethod:"DNS",DomainValidationOptions:Re.map((ne)=>({DomainName:ne,HostedZoneId:i.hostedZoneId}))}},G=e.ref("HttpCertificate");Re.forEach((ne,ie)=>{let re=`HttpDomain${ie}`;if(N[re]={Type:"AWS::ApiGatewayV2::DomainName",Properties:{DomainName:ne,DomainNameConfigurations:[{CertificateArn:G,EndpointType:"REGIONAL"}]}},N[`HttpApiMapping${ie}`]={Type:"AWS::ApiGatewayV2::ApiMapping",DependsOn:["HttpStage"],Properties:{ApiId:e.ref("HttpApi"),DomainName:e.ref(re),Stage:"$default"}},i.hostedZoneId)N[`HttpDomainRecord${ie}`]={Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:i.hostedZoneId,Name:ne,Type:"A",AliasTarget:{DNSName:e.getAtt(re,"RegionalDomainName"),HostedZoneId:e.getAtt(re,"RegionalHostedZoneId")}}};O[`CustomDomain${ie}`]={Description:`Custom domain ${ne}`,Value:ne},O[`CustomDomainTarget${ie}`]={Description:`Point ${ne} (CNAME/alias) at this APIGW regional domain`,Value:e.getAtt(re,"RegionalDomainName")}})}if(v)N.AppQueueDlq={Type:"AWS::SQS::Queue",Properties:{QueueName:`${c}-${s}-dlq`,MessageRetentionPeriod:1209600}},h.forEach((G,ne)=>{let ie=`AppQueue${ne}`,re=i.queueTimeout??120;N[ie]={Type:"AWS::SQS::Queue",Properties:{QueueName:G.name,VisibilityTimeout:Math.min(43200,re*6),RedrivePolicy:{deadLetterTargetArn:e.getAtt("AppQueueDlq","Arn"),maxReceiveCount:i.queueTries??3}}};let fe=G.concurrency??i.queueConcurrency;N[`${ie}Mapping`]={Type:"AWS::Lambda::EventSourceMapping",Properties:{EventSourceArn:e.getAtt(ie,"Arn"),FunctionName:Se("QueueFunction"),BatchSize:1,FunctionResponseTypes:["ReportBatchItemFailures"],...fe?{ScalingConfig:{MaximumConcurrency:Math.max(2,fe)}}:{}}},O[`QueueUrl${ne}`]={Description:`Queue URL: ${G.name}`,Value:e.ref(ie)}});if(R)N.SchedulerRule={Type:"AWS::Events::Rule",Properties:{Name:`${c}-${s}-scheduler`,ScheduleExpression:"rate(1 minute)",State:"ENABLED",Targets:[{Id:"cli",Arn:De("CliFunction"),Input:JSON.stringify({command:"schedule:run"})}]}},N.SchedulerPermission={Type:"AWS::Lambda::Permission",Properties:{FunctionName:Se("CliFunction"),Action:"lambda:InvokeFunction",Principal:"events.amazonaws.com",SourceArn:e.getAtt("SchedulerRule","Arn")}};if(i.warm&&i.warm>0){let ne={http:"HttpFunction",queue:"QueueFunction",cli:"CliFunction"},ie=(i.warmFunctions??["http"]).filter((re)=>re!=="queue"||v);for(let re of ie){let fe=re.charAt(0).toUpperCase()+re.slice(1),ht=Math.ceil(i.warm/5),Ve=0;for(let Ne=0;Ne<ht;Ne++){let Ue=Math.min(5,i.warm-Ve);N[`Warmer${fe}Rule${Ne}`]={Type:"AWS::Events::Rule",Properties:{Name:`${c}-${s}-warmer-${re}-${Ne}`,ScheduleExpression:"rate(5 minutes)",State:"ENABLED",Targets:Array.from({length:Ue},(en,sr)=>({Id:`warm-${re}-${Ne}-${sr}`,Arn:e.getAtt(ne[re],"Arn"),Input:JSON.stringify({warmer:!0})}))}},Ve+=Ue}N[`Warmer${fe}Permission`]={Type:"AWS::Lambda::Permission",Properties:{FunctionName:e.ref(ne[re]),Action:"lambda:InvokeFunction",Principal:"events.amazonaws.com",SourceArn:e.sub(`arn:aws:events:\${AWS::Region}:\${AWS::AccountId}:rule/${c}-${s}-warmer-${re}-*`)}}}}if(P)N.CacheTable={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${c}-${s}-cache`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"key",AttributeType:"S"}],KeySchema:[{AttributeName:"key",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"expires_at",Enabled:!0}}},O.CacheTableName={Description:"DynamoDB cache table",Value:e.ref("CacheTable")};if(I){if(N.AssetsBucket={Type:"AWS::S3::Bucket",Properties:{BucketName:M,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0}}},N.AssetsOAC={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`${c}-${s}-assets-oac`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},N.AssetsDistribution={Type:"AWS::CloudFront::Distribution",Properties:{DistributionConfig:{Enabled:!0,DefaultCacheBehavior:{TargetOriginId:"assets",ViewerProtocolPolicy:"redirect-to-https",Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6"},Origins:[{Id:"assets",DomainName:e.getAtt("AssetsBucket","RegionalDomainName"),OriginAccessControlId:e.ref("AssetsOAC"),S3OriginConfig:{OriginAccessIdentity:""}}],...i.assetDomain?{Aliases:[i.assetDomain],ViewerCertificate:{AcmCertificateArn:i.assetCertificateArn??e.ref("AssetsCertificate"),SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}}:{}}}},i.assetDomain){if(!i.assetCertificateArn){if(!i.hostedZoneId)throw Error("serverless app: `assetDomain` requires either `assetCertificateArn` (a us-east-1 ACM cert) or `hostedZoneId` (to auto-issue + validate one). CloudFront only accepts certs from us-east-1.");if(g!=="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 ${g}. Supply a pre-issued us-east-1 \`assetCertificateArn\` instead.`);N.AssetsCertificate={Type:"AWS::CertificateManager::Certificate",Properties:{DomainName:i.assetDomain,ValidationMethod:"DNS",DomainValidationOptions:[{DomainName:i.assetDomain,HostedZoneId:i.hostedZoneId}]}}}if(i.hostedZoneId)N.AssetsDomainRecord={Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:i.hostedZoneId,Name:i.assetDomain,Type:"A",AliasTarget:{DNSName:e.getAtt("AssetsDistribution","DomainName"),HostedZoneId:"Z2FDTNDATAQYW2"}}};O.AssetDomain={Description:"Custom asset CDN host",Value:i.assetDomain}}N.AssetsBucketPolicy={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:e.ref("AssetsBucket"),PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:e.sub(`arn:aws:s3:::${M}/*`),Condition:{StringEquals:{"AWS:SourceArn":e.sub("arn:aws:cloudfront::${AWS::AccountId}:distribution/${AssetsDistribution}")}}}]}}},O.AssetsBucketName={Description:"Assets bucket",Value:e.ref("AssetsBucket")},O.AssetsCdnDomain={Description:"Assets CloudFront domain",Value:e.getAtt("AssetsDistribution","DomainName")}}if(i.firewall?.enabled){let G=[],ne=0;if(i.firewall.rateLimit)G.push({Name:"rate-limit",Priority:ne++,Action:{Block:{}},Statement:{RateBasedStatement:{Limit:i.firewall.rateLimit,AggregateKeyType:"IP"}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${c}-${s}-rate`}});let ie={sqlInjection:"AWSManagedRulesSQLiRuleSet",xss:"AWSManagedRulesCommonRuleSet",common:"AWSManagedRulesCommonRuleSet",botControl:"AWSManagedRulesBotControlRuleSet",ipReputation:"AWSManagedRulesAmazonIpReputationList"};for(let re of i.firewall.rules??[]){let fe=ie[re];if(!fe)continue;G.push({Name:`managed-${re}`,Priority:ne++,OverrideAction:{None:{}},Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:fe}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${c}-${s}-${re}`}})}N.WebAcl={Type:"AWS::WAFv2::WebACL",Properties:{Name:`${c}-${s}-waf`,Scope:"REGIONAL",DefaultAction:{Allow:{}},Rules:G,VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${c}-${s}-waf`}}},O.WafAclArn={Description:"WAF web ACL ARN. Attach to a CloudFront distribution fronting the API to enforce (HTTP API v2 stages do not support direct WAF association).",Value:e.getAtt("WebAcl","Arn")}}if(ge&&ae){if(!i.vpc?.id)throw Error("serverless app: data services (elasticache / aurora-serverless / rdsProxy / efs) need app.vpc.id (the VPC id) so the managed security group is created in the right VPC.");N.DataSecurityGroup={Type:"AWS::EC2::SecurityGroup",Properties:{VpcId:i.vpc.id,GroupDescription:`${c}-${s} serverless data access`,SecurityGroupIngress:[{IpProtocol:"-1",CidrIp:"10.0.0.0/8"}]}}}if(se)N.EfsFileSystem={Type:"AWS::EFS::FileSystem",Properties:{Encrypted:!0,FileSystemTags:[{Key:"Name",Value:`${c}-${s}-efs`}]}},oe.forEach((G,ne)=>{N[`EfsMountTarget${ne}`]={Type:"AWS::EFS::MountTarget",Properties:{FileSystemId:e.ref("EfsFileSystem"),SubnetId:G,SecurityGroups:[e.getAtt("DataSecurityGroup","GroupId")]}}}),N.EfsAccessPoint={Type:"AWS::EFS::AccessPoint",Properties:{FileSystemId:e.ref("EfsFileSystem"),PosixUser:{Uid:1001,Gid:1001},RootDirectory:{Path:"/lambda",CreationInfo:{OwnerUid:1001,OwnerGid:1001,Permissions:"0755"}}}},O.EfsFileSystemId={Description:"EFS file system id",Value:e.ref("EfsFileSystem")};if(i.cache?.driver==="elasticache")N.CacheSubnetGroup={Type:"AWS::ElastiCache::SubnetGroup",Properties:{Description:`${c}-${s} cache subnets`,SubnetIds:oe}},N.CacheCluster={Type:"AWS::ElastiCache::ReplicationGroup",Properties:{ReplicationGroupId:`${c}-${s}-cache`,ReplicationGroupDescription:`${c}-${s} redis`,Engine:"redis",CacheNodeType:"cache.t4g.micro",NumCacheClusters:1,AutomaticFailoverEnabled:!1,CacheSubnetGroupName:e.ref("CacheSubnetGroup"),SecurityGroupIds:[e.getAtt("DataSecurityGroup","GroupId")],TransitEncryptionEnabled:!1}},O.CacheEndpoint={Description:"Redis primary endpoint",Value:e.getAtt("CacheCluster","PrimaryEndPoint.Address")};if(i.database?.connection==="aurora-serverless")N.DbSubnetGroup={Type:"AWS::RDS::DBSubnetGroup",Properties:{DBSubnetGroupDescription:`${c}-${s} db subnets`,SubnetIds:oe}},N.DbSecret={Type:"AWS::SecretsManager::Secret",Properties:{Name:`${c}/${s}/db`,GenerateSecretString:{SecretStringTemplate:JSON.stringify({username:"app"}),GenerateStringKey:"password",PasswordLength:32,ExcludePunctuation:!0}}},N.DbCluster={Type:"AWS::RDS::DBCluster",Properties:{Engine:"aurora-mysql",EngineMode:"provisioned",DBClusterIdentifier:`${c}-${s}-db`,DatabaseName:"app",MasterUsername:e.sub("{{resolve:secretsmanager:${DbSecret}:SecretString:username}}"),MasterUserPassword:e.sub("{{resolve:secretsmanager:${DbSecret}:SecretString:password}}"),ServerlessV2ScalingConfiguration:{MinCapacity:i.database?.minCapacity??0.5,MaxCapacity:i.database?.maxCapacity??4},DBSubnetGroupName:e.ref("DbSubnetGroup"),VpcSecurityGroupIds:[e.getAtt("DataSecurityGroup","GroupId")]}},N.DbInstance={Type:"AWS::RDS::DBInstance",Properties:{Engine:"aurora-mysql",DBInstanceClass:"db.serverless",DBClusterIdentifier:e.ref("DbCluster")}},O.DbEndpoint={Description:"Aurora cluster endpoint",Value:e.getAtt("DbCluster","Endpoint.Address")};if(i.rdsProxy&&i.database?.connection==="aurora-serverless")N.DbProxyRole={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"rds.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"read-db-secret",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["secretsmanager:GetSecretValue"],Resource:e.ref("DbSecret")}]}}]}},N.DbProxy={Type:"AWS::RDS::DBProxy",Properties:{DBProxyName:typeof i.rdsProxy==="object"&&i.rdsProxy.name?i.rdsProxy.name:`${c}-${s}-proxy`,EngineFamily:"MYSQL",RoleArn:e.getAtt("DbProxyRole","Arn"),Auth:[{AuthScheme:"SECRETS",SecretArn:e.ref("DbSecret"),IAMAuth:"DISABLED"}],VpcSubnetIds:oe,VpcSecurityGroupIds:[e.getAtt("DataSecurityGroup","GroupId")],RequireTLS:!1}},N.DbProxyTargetGroup={Type:"AWS::RDS::DBProxyTargetGroup",DependsOn:["DbInstance"],Properties:{DBProxyName:e.ref("DbProxy"),TargetGroupName:"default",DBClusterIdentifiers:[e.ref("DbCluster")]}},O.DbProxyEndpoint={Description:"RDS Proxy endpoint",Value:e.getAtt("DbProxy","Endpoint")};if(O.HttpFunctionName={Description:"HTTP function name",Value:e.ref("HttpFunction")},O.CliFunctionName={Description:"CLI function name",Value:e.ref("CliFunction")},v)O.QueueFunctionName={Description:"Queue function name",Value:e.ref("QueueFunction")};let $e={AWSTemplateFormatVersion:"2010-09-09",Description:`Serverless application for ${n.config.project.name} (${c}-${s})`,Parameters:T?{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:N,Outputs:O},We={};for(let G of Object.values(N))We[G.Type]=(We[G.Type]??0)+1;return{template:$e,functionNames:y,queueNames:b,resourceSummary:We}}var pS=["cli","fpm","curl","mbstring","xml","pdo","mysqlnd","gd","bcmath","intl","opcache","sodium","process","pecl-redis6","pecl-apcu","pgsql"];function mS(n){let i=`php${n.replace(".","")}`;return pS.map((s)=>`${i}-php-${s}`)}function Ul(n,i){let s=`php${n.replace(".","")}`,o=mS(n).join(" \\\n "),c=`/opt/remi/${s}/root`,u=`/etc/opt/remi/${s}`;return`${i?`FROM almalinux:9 AS ${i}`:"FROM almalinux:9"}
7241
+ ${A}`)}let y=g.outputs[0],h=Buffer.from(await y.arrayBuffer()),b="index",v=it([{name:`${b}.mjs`,data:h}]);return{zip:v,bundle:h,sha256:Wo(v),handlerFile:b,handlers:{http:s.handlers?.http??`${b}.http`,queue:s.handlers?.queue??`${b}.queue`,cli:s.handlers?.cli??`${b}.cli`},bundleBytes:h.length}}finally{Vi(u,{recursive:!0,force:!0})}}var gS=["18","20","22"];function as(n){if(!n)return"22";let i=String(n).match(/(\d+)/);return i?i[1]:"22"}function ns(n){let i=n.kind??"node";if(i==="php")return{lambdaRuntime:"provided.al2023",kind:"php",version:n.phpVersion??"8.3",usesLayer:!0,layerKind:"php",layerEnvVar:"TSCLOUD_PHP_LAYER_ARN"};if(i==="bun")return{lambdaRuntime:"provided.al2023",kind:"bun",version:n.runtimeVersion??"latest",usesLayer:!0,layerKind:"bun",layerEnvVar:"TSCLOUD_BUN_LAYER_ARN"};let s=as(n.runtimeVersion);if(n.runtime!=="provided.al2023"&&gS.includes(s))return{lambdaRuntime:n.runtime&&n.runtime.startsWith("nodejs")?n.runtime:`nodejs${s}.x`,kind:"node",version:s,usesLayer:!1};return{lambdaRuntime:"provided.al2023",kind:"node",version:s,usesLayer:!0,layerKind:"node",layerEnvVar:"TSCLOUD_NODE_LAYER_ARN"}}function Ar(n,i,s){if(n.queues===!1)return[];if(n.queues===void 0||n.queues===!0)return[{name:`${i}-${s}-default`}];return n.queues.map((o)=>{if(typeof o==="string")return{name:`${i}-${s}-${o}`};let[c,u]=Object.entries(o)[0];return{name:`${i}-${s}-${c}`,concurrency:u}})}function Ml(n,i,s){return Ar(n,i,s).map((o)=>o.name)}function Fl(n){let{app:i,environment:s,handlers:o}=n,c=n.config.project.slug,u=ns(i).lambdaRuntime,d=i.architecture??"x86_64",g=n.config.project.region,y={http:`${c}-${s}-http`,queue:`${c}-${s}-queue`,cli:`${c}-${s}-cli`};if(i.gatewayVersion===1)throw Error("serverless app: `gatewayVersion: 1` (REST API) is not supported — ts-cloud uses API Gateway HTTP API (v2). Remove `gatewayVersion` or set it to 2.");let h=Ar(i,c,s),b=h.map((G)=>G.name),v=b.length>0,A=i.logRetention??14,T=i.packaging==="image";if(T&&i.lambdaInsights)throw Error("serverless app: `lambdaInsights` layer attachment is only supported for zip packaging. Container images must install the Lambda Insights extension in the image.");let R=(i.scheduler??"on")!=="off",P=(i.cache?.driver??"dynamodb")==="dynamodb",I=Boolean(i.assets),M=Xi(c,s),L=i.tmpStorage??512,N={},O={},B=[{PolicyName:"tscloud-serverless-app",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["logs:CreateLogGroup","logs:CreateLogStream","logs:PutLogEvents"],Resource:e.sub("arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/*")},{Effect:"Allow",Action:["lambda:InvokeFunction"],Resource:e.sub(`arn:aws:lambda:\${AWS::Region}:\${AWS::AccountId}:function:${c}-${s}-*`)},{Effect:"Allow",Action:["secretsmanager:GetSecretValue","ssm:GetParameter","ssm:GetParameters","ssm:GetParametersByPath"],Resource:[e.sub(`arn:aws:secretsmanager:\${AWS::Region}:\${AWS::AccountId}:secret:${c}/${s}/*`),e.sub(`arn:aws:ssm:\${AWS::Region}:\${AWS::AccountId}:parameter/${c}/${s}/*`)]},{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:ListBucket"],Resource:[e.sub(`arn:aws:s3:::${M}`),e.sub(`arn:aws:s3:::${M}/*`),...i.storage?.bucket?[e.sub(`arn:aws:s3:::${i.storage.bucket}`),e.sub(`arn:aws:s3:::${i.storage.bucket}/*`)]:[]]}]}}];if(v)B[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["sqs:SendMessage","sqs:ReceiveMessage","sqs:DeleteMessage","sqs:GetQueueAttributes","sqs:GetQueueUrl"],Resource:e.sub(`arn:aws:sqs:\${AWS::Region}:\${AWS::AccountId}:${c}-${s}-*`)});if(P)B[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["dynamodb:GetItem","dynamodb:PutItem","dynamodb:UpdateItem","dynamodb:DeleteItem","dynamodb:Query","dynamodb:Scan","dynamodb:BatchGetItem","dynamodb:BatchWriteItem"],Resource:e.sub(`arn:aws:dynamodb:\${AWS::Region}:\${AWS::AccountId}:table/${c}-${s}-cache*`)});let F=["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"];if(i.vpc?.subnets?.length)F.push("arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole");if(i.lambdaInsights)F.push("arn:aws:iam::aws:policy/CloudWatchLambdaInsightsExecutionRolePolicy");N.AppRole={Type:"AWS::IAM::Role",Properties:{RoleName:`${c}-${s}-app-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:F,Policies:B}};let U=(G)=>({TSCLOUD_LAMBDA_MODE:G,TSCLOUD_ENV:s,...i.octane?{TSCLOUD_OCTANE:"1"}:{},...i.scheduler==="sub-minute"?{TSCLOUD_SCHEDULER:"sub-minute"}:{},...P?{TSCLOUD_CACHE_TABLE:`${c}-${s}-cache`}:{},...v?{TSCLOUD_QUEUE:b[0]}:{},...i.env??{}}),j=Boolean(i.efs),H=typeof i.efs==="object"?i.efs:{},z=H.mountPath??"/mnt/local",se=j&&!H.accessPointArn,Te=H.accessPointArn??(se?e.getAtt("EfsAccessPoint","Arn"):void 0),oe=i.vpc?.subnets??[],ge=oe.length>0,ae=i.cache?.driver==="elasticache"||i.database?.connection==="aurora-serverless"||Boolean(i.rdsProxy)||j;if(ae&&!ge)throw Error("serverless app: elasticache / aurora-serverless / rdsProxy / efs require app.vpc.subnets (private subnets) to be set.");let pe=ge?{VpcConfig:{SubnetIds:oe,SecurityGroupIds:[...i.vpc?.securityGroups??[],...ae?[e.getAtt("DataSecurityGroup","GroupId")]:[]]}}:{},Ie=se?oe.map((G,ne)=>`EfsMountTarget${ne}`):[],Le=j?{FileSystemConfigs:[{Arn:Te,LocalMountPath:z}]}:{};if(j)B[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["elasticfilesystem:ClientMount","elasticfilesystem:ClientWrite","elasticfilesystem:ClientRootAccess","elasticfilesystem:DescribeMountTargets"],Resource:"*"});function he(G,ne,ie,re,fe,ht,Ve,Ne=L){N[`${G}LogGroup`]={Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:`/aws/lambda/${ne}`,RetentionInDays:A}};let Ue=[...n.runtimeLayers??[],...i.lambdaInsights?[i.lambdaInsights.layerArn]:[]],en=T?{PackageType:"Image",Code:{ImageUri:e.ref("ImageUri")},...i.kind==="php"?{}:{ImageConfig:{Command:[ie]}}}:{Runtime:u,Handler:ie,Code:{S3Bucket:e.ref("ArtifactBucket"),S3Key:e.ref("ArtifactKey")},...Ue.length?{Layers:[...new Set(Ue)]}:{}};N[G]={Type:"AWS::Lambda::Function",DependsOn:[`${G}LogGroup`,...Ie],Properties:{FunctionName:ne,Architectures:[d],MemorySize:fe,Timeout:ht,Role:e.getAtt("AppRole","Arn"),Environment:{Variables:U(re)},EphemeralStorage:{Size:Ne},...en,...Ve!==void 0?{ReservedConcurrentExecutions:Ve}:{},...pe,...Le}}}if(he("HttpFunction",y.http,o.http,"http",i.memory??1024,i.timeout??28,i.concurrency,L),he("CliFunction",y.cli,o.cli,"cli",i.cliMemory??1024,i.cliTimeout??900,void 0,i.cliTmpStorage??L),v)he("QueueFunction",y.queue,o.queue,"queue",i.queueMemory??1024,i.queueTimeout??120,void 0,i.queueTmpStorage??L);let ye=(i.provisionedConcurrency??0)>0?i.provisionedConcurrency:0,be=["HttpFunction","CliFunction",...v?["QueueFunction"]:[]];if(ye)for(let G of be)N[`${G}Version`]={Type:"AWS::Lambda::Version",DeletionPolicy:"Retain",Properties:{FunctionName:e.ref(G)}},N[`${G}Alias`]={Type:"AWS::Lambda::Alias",Properties:{FunctionName:e.ref(G),Name:"live",FunctionVersion:e.getAtt(`${G}Version`,"Version"),ProvisionedConcurrencyConfig:{ProvisionedConcurrentExecutions:ye}}};let De=(G)=>ye?e.ref(`${G}Alias`):e.getAtt(G,"Arn"),Se=(G)=>ye?e.ref(`${G}Alias`):e.ref(G);N.HttpApi={Type:"AWS::ApiGatewayV2::Api",Properties:{Name:`${c}-${s}`,ProtocolType:"HTTP"}},N.HttpIntegration={Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:e.ref("HttpApi"),IntegrationType:"AWS_PROXY",IntegrationUri:De("HttpFunction"),PayloadFormatVersion:"2.0"}},N.HttpRoute={Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:e.ref("HttpApi"),RouteKey:"$default",Target:e.join("/",["integrations",e.ref("HttpIntegration")])}},N.HttpStage={Type:"AWS::ApiGatewayV2::Stage",Properties:{ApiId:e.ref("HttpApi"),StageName:"$default",AutoDeploy:!0}},N.HttpPermission={Type:"AWS::Lambda::Permission",Properties:{FunctionName:Se("HttpFunction"),Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:e.sub("arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${HttpApi}/*/*")}},O.HttpApiEndpoint={Description:"HTTP API endpoint",Value:e.getAtt("HttpApi","ApiEndpoint")},O.HttpApiId={Description:"HTTP API id",Value:e.ref("HttpApi")};let Re=(Array.isArray(i.domain)?i.domain:i.domain?[i.domain]:[]).filter(Boolean);if(Re.length){if(!i.certificateArn&&!i.hostedZoneId)throw Error("serverless app: a custom `domain` needs either `certificateArn` (pre-issued, regional) or `hostedZoneId` (to auto-issue + validate an ACM cert).");let G=i.certificateArn;if(!G)N.HttpCertificate={Type:"AWS::CertificateManager::Certificate",Properties:{DomainName:Re[0],...Re.length>1?{SubjectAlternativeNames:Re.slice(1)}:{},ValidationMethod:"DNS",DomainValidationOptions:Re.map((ne)=>({DomainName:ne,HostedZoneId:i.hostedZoneId}))}},G=e.ref("HttpCertificate");Re.forEach((ne,ie)=>{let re=`HttpDomain${ie}`;if(N[re]={Type:"AWS::ApiGatewayV2::DomainName",Properties:{DomainName:ne,DomainNameConfigurations:[{CertificateArn:G,EndpointType:"REGIONAL"}]}},N[`HttpApiMapping${ie}`]={Type:"AWS::ApiGatewayV2::ApiMapping",DependsOn:["HttpStage"],Properties:{ApiId:e.ref("HttpApi"),DomainName:e.ref(re),Stage:"$default"}},i.hostedZoneId)N[`HttpDomainRecord${ie}`]={Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:i.hostedZoneId,Name:ne,Type:"A",AliasTarget:{DNSName:e.getAtt(re,"RegionalDomainName"),HostedZoneId:e.getAtt(re,"RegionalHostedZoneId")}}};O[`CustomDomain${ie}`]={Description:`Custom domain ${ne}`,Value:ne},O[`CustomDomainTarget${ie}`]={Description:`Point ${ne} (CNAME/alias) at this APIGW regional domain`,Value:e.getAtt(re,"RegionalDomainName")}})}if(v)N.AppQueueDlq={Type:"AWS::SQS::Queue",Properties:{QueueName:`${c}-${s}-dlq`,MessageRetentionPeriod:1209600}},h.forEach((G,ne)=>{let ie=`AppQueue${ne}`,re=i.queueTimeout??120;N[ie]={Type:"AWS::SQS::Queue",Properties:{QueueName:G.name,VisibilityTimeout:Math.min(43200,re*6),RedrivePolicy:{deadLetterTargetArn:e.getAtt("AppQueueDlq","Arn"),maxReceiveCount:i.queueTries??3}}};let fe=G.concurrency??i.queueConcurrency;N[`${ie}Mapping`]={Type:"AWS::Lambda::EventSourceMapping",Properties:{EventSourceArn:e.getAtt(ie,"Arn"),FunctionName:Se("QueueFunction"),BatchSize:1,FunctionResponseTypes:["ReportBatchItemFailures"],...fe?{ScalingConfig:{MaximumConcurrency:Math.max(2,fe)}}:{}}},O[`QueueUrl${ne}`]={Description:`Queue URL: ${G.name}`,Value:e.ref(ie)}});if(R)N.SchedulerRule={Type:"AWS::Events::Rule",Properties:{Name:`${c}-${s}-scheduler`,ScheduleExpression:"rate(1 minute)",State:"ENABLED",Targets:[{Id:"cli",Arn:De("CliFunction"),Input:JSON.stringify({command:"schedule:run"})}]}},N.SchedulerPermission={Type:"AWS::Lambda::Permission",Properties:{FunctionName:Se("CliFunction"),Action:"lambda:InvokeFunction",Principal:"events.amazonaws.com",SourceArn:e.getAtt("SchedulerRule","Arn")}};if(i.warm&&i.warm>0){let ne={http:"HttpFunction",queue:"QueueFunction",cli:"CliFunction"},ie=(i.warmFunctions??["http"]).filter((re)=>re!=="queue"||v);for(let re of ie){let fe=re.charAt(0).toUpperCase()+re.slice(1),ht=Math.ceil(i.warm/5),Ve=0;for(let Ne=0;Ne<ht;Ne++){let Ue=Math.min(5,i.warm-Ve);N[`Warmer${fe}Rule${Ne}`]={Type:"AWS::Events::Rule",Properties:{Name:`${c}-${s}-warmer-${re}-${Ne}`,ScheduleExpression:"rate(5 minutes)",State:"ENABLED",Targets:Array.from({length:Ue},(en,sr)=>({Id:`warm-${re}-${Ne}-${sr}`,Arn:e.getAtt(ne[re],"Arn"),Input:JSON.stringify({warmer:!0})}))}},Ve+=Ue}N[`Warmer${fe}Permission`]={Type:"AWS::Lambda::Permission",Properties:{FunctionName:e.ref(ne[re]),Action:"lambda:InvokeFunction",Principal:"events.amazonaws.com",SourceArn:e.sub(`arn:aws:events:\${AWS::Region}:\${AWS::AccountId}:rule/${c}-${s}-warmer-${re}-*`)}}}}if(P)N.CacheTable={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${c}-${s}-cache`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"key",AttributeType:"S"}],KeySchema:[{AttributeName:"key",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"expires_at",Enabled:!0}}},O.CacheTableName={Description:"DynamoDB cache table",Value:e.ref("CacheTable")};if(I){if(N.AssetsBucket={Type:"AWS::S3::Bucket",Properties:{BucketName:M,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0}}},N.AssetsOAC={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`${c}-${s}-assets-oac`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},N.AssetsDistribution={Type:"AWS::CloudFront::Distribution",Properties:{DistributionConfig:{Enabled:!0,DefaultCacheBehavior:{TargetOriginId:"assets",ViewerProtocolPolicy:"redirect-to-https",Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6"},Origins:[{Id:"assets",DomainName:e.getAtt("AssetsBucket","RegionalDomainName"),OriginAccessControlId:e.ref("AssetsOAC"),S3OriginConfig:{OriginAccessIdentity:""}}],...i.assetDomain?{Aliases:[i.assetDomain],ViewerCertificate:{AcmCertificateArn:i.assetCertificateArn??e.ref("AssetsCertificate"),SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}}:{}}}},i.assetDomain){if(!i.assetCertificateArn){if(!i.hostedZoneId)throw Error("serverless app: `assetDomain` requires either `assetCertificateArn` (a us-east-1 ACM cert) or `hostedZoneId` (to auto-issue + validate one). CloudFront only accepts certs from us-east-1.");if(g!=="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 ${g}. Supply a pre-issued us-east-1 \`assetCertificateArn\` instead.`);N.AssetsCertificate={Type:"AWS::CertificateManager::Certificate",Properties:{DomainName:i.assetDomain,ValidationMethod:"DNS",DomainValidationOptions:[{DomainName:i.assetDomain,HostedZoneId:i.hostedZoneId}]}}}if(i.hostedZoneId)N.AssetsDomainRecord={Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:i.hostedZoneId,Name:i.assetDomain,Type:"A",AliasTarget:{DNSName:e.getAtt("AssetsDistribution","DomainName"),HostedZoneId:"Z2FDTNDATAQYW2"}}};O.AssetDomain={Description:"Custom asset CDN host",Value:i.assetDomain}}N.AssetsBucketPolicy={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:e.ref("AssetsBucket"),PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:e.sub(`arn:aws:s3:::${M}/*`),Condition:{StringEquals:{"AWS:SourceArn":e.sub("arn:aws:cloudfront::${AWS::AccountId}:distribution/${AssetsDistribution}")}}}]}}},O.AssetsBucketName={Description:"Assets bucket",Value:e.ref("AssetsBucket")},O.AssetsCdnDomain={Description:"Assets CloudFront domain",Value:e.getAtt("AssetsDistribution","DomainName")}}if(i.firewall?.enabled){let G=[],ne=0;if(i.firewall.rateLimit)G.push({Name:"rate-limit",Priority:ne++,Action:{Block:{}},Statement:{RateBasedStatement:{Limit:i.firewall.rateLimit,AggregateKeyType:"IP"}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${c}-${s}-rate`}});let ie={sqlInjection:"AWSManagedRulesSQLiRuleSet",xss:"AWSManagedRulesCommonRuleSet",common:"AWSManagedRulesCommonRuleSet",botControl:"AWSManagedRulesBotControlRuleSet",ipReputation:"AWSManagedRulesAmazonIpReputationList"};for(let re of i.firewall.rules??[]){let fe=ie[re];if(!fe)continue;G.push({Name:`managed-${re}`,Priority:ne++,OverrideAction:{None:{}},Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:fe}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${c}-${s}-${re}`}})}N.WebAcl={Type:"AWS::WAFv2::WebACL",Properties:{Name:`${c}-${s}-waf`,Scope:"REGIONAL",DefaultAction:{Allow:{}},Rules:G,VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${c}-${s}-waf`}}},O.WafAclArn={Description:"WAF web ACL ARN. Attach to a CloudFront distribution fronting the API to enforce (HTTP API v2 stages do not support direct WAF association).",Value:e.getAtt("WebAcl","Arn")}}if(ge&&ae){if(!i.vpc?.id)throw Error("serverless app: data services (elasticache / aurora-serverless / rdsProxy / efs) need app.vpc.id (the VPC id) so the managed security group is created in the right VPC.");N.DataSecurityGroup={Type:"AWS::EC2::SecurityGroup",Properties:{VpcId:i.vpc.id,GroupDescription:`${c}-${s} serverless data access`,SecurityGroupIngress:[{IpProtocol:"-1",CidrIp:"10.0.0.0/8"}]}}}if(se)N.EfsFileSystem={Type:"AWS::EFS::FileSystem",Properties:{Encrypted:!0,FileSystemTags:[{Key:"Name",Value:`${c}-${s}-efs`}]}},oe.forEach((G,ne)=>{N[`EfsMountTarget${ne}`]={Type:"AWS::EFS::MountTarget",Properties:{FileSystemId:e.ref("EfsFileSystem"),SubnetId:G,SecurityGroups:[e.getAtt("DataSecurityGroup","GroupId")]}}}),N.EfsAccessPoint={Type:"AWS::EFS::AccessPoint",Properties:{FileSystemId:e.ref("EfsFileSystem"),PosixUser:{Uid:1001,Gid:1001},RootDirectory:{Path:"/lambda",CreationInfo:{OwnerUid:1001,OwnerGid:1001,Permissions:"0755"}}}},O.EfsFileSystemId={Description:"EFS file system id",Value:e.ref("EfsFileSystem")};if(i.cache?.driver==="elasticache")N.CacheSubnetGroup={Type:"AWS::ElastiCache::SubnetGroup",Properties:{Description:`${c}-${s} cache subnets`,SubnetIds:oe}},N.CacheCluster={Type:"AWS::ElastiCache::ReplicationGroup",Properties:{ReplicationGroupId:`${c}-${s}-cache`,ReplicationGroupDescription:`${c}-${s} redis`,Engine:"redis",CacheNodeType:"cache.t4g.micro",NumCacheClusters:1,AutomaticFailoverEnabled:!1,CacheSubnetGroupName:e.ref("CacheSubnetGroup"),SecurityGroupIds:[e.getAtt("DataSecurityGroup","GroupId")],TransitEncryptionEnabled:!1}},O.CacheEndpoint={Description:"Redis primary endpoint",Value:e.getAtt("CacheCluster","PrimaryEndPoint.Address")};if(i.database?.connection==="aurora-serverless")N.DbSubnetGroup={Type:"AWS::RDS::DBSubnetGroup",Properties:{DBSubnetGroupDescription:`${c}-${s} db subnets`,SubnetIds:oe}},N.DbSecret={Type:"AWS::SecretsManager::Secret",Properties:{Name:`${c}/${s}/db`,GenerateSecretString:{SecretStringTemplate:JSON.stringify({username:"app"}),GenerateStringKey:"password",PasswordLength:32,ExcludePunctuation:!0}}},N.DbCluster={Type:"AWS::RDS::DBCluster",Properties:{Engine:"aurora-mysql",EngineMode:"provisioned",DBClusterIdentifier:`${c}-${s}-db`,DatabaseName:"app",MasterUsername:e.sub("{{resolve:secretsmanager:${DbSecret}:SecretString:username}}"),MasterUserPassword:e.sub("{{resolve:secretsmanager:${DbSecret}:SecretString:password}}"),ServerlessV2ScalingConfiguration:{MinCapacity:i.database?.minCapacity??0.5,MaxCapacity:i.database?.maxCapacity??4},DBSubnetGroupName:e.ref("DbSubnetGroup"),VpcSecurityGroupIds:[e.getAtt("DataSecurityGroup","GroupId")]}},N.DbInstance={Type:"AWS::RDS::DBInstance",Properties:{Engine:"aurora-mysql",DBInstanceClass:"db.serverless",DBClusterIdentifier:e.ref("DbCluster")}},O.DbEndpoint={Description:"Aurora cluster endpoint",Value:e.getAtt("DbCluster","Endpoint.Address")};if(i.rdsProxy&&i.database?.connection==="aurora-serverless")N.DbProxyRole={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"rds.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"read-db-secret",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["secretsmanager:GetSecretValue"],Resource:e.ref("DbSecret")}]}}]}},N.DbProxy={Type:"AWS::RDS::DBProxy",Properties:{DBProxyName:typeof i.rdsProxy==="object"&&i.rdsProxy.name?i.rdsProxy.name:`${c}-${s}-proxy`,EngineFamily:"MYSQL",RoleArn:e.getAtt("DbProxyRole","Arn"),Auth:[{AuthScheme:"SECRETS",SecretArn:e.ref("DbSecret"),IAMAuth:"DISABLED"}],VpcSubnetIds:oe,VpcSecurityGroupIds:[e.getAtt("DataSecurityGroup","GroupId")],RequireTLS:!1}},N.DbProxyTargetGroup={Type:"AWS::RDS::DBProxyTargetGroup",DependsOn:["DbInstance"],Properties:{DBProxyName:e.ref("DbProxy"),TargetGroupName:"default",DBClusterIdentifiers:[e.ref("DbCluster")]}},O.DbProxyEndpoint={Description:"RDS Proxy endpoint",Value:e.getAtt("DbProxy","Endpoint")};if(O.HttpFunctionName={Description:"HTTP function name",Value:e.ref("HttpFunction")},O.CliFunctionName={Description:"CLI function name",Value:e.ref("CliFunction")},v)O.QueueFunctionName={Description:"Queue function name",Value:e.ref("QueueFunction")};let $e={AWSTemplateFormatVersion:"2010-09-09",Description:`Serverless application for ${n.config.project.name} (${c}-${s})`,Parameters:T?{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:N,Outputs:O},We={};for(let G of Object.values(N))We[G.Type]=(We[G.Type]??0)+1;return{template:$e,functionNames:y,queueNames:b,resourceSummary:We}}var pS=["cli","fpm","curl","mbstring","xml","pdo","mysqlnd","gd","bcmath","intl","opcache","sodium","process","pecl-redis6","pecl-apcu","pgsql"];function mS(n){let i=`php${n.replace(".","")}`;return pS.map((s)=>`${i}-php-${s}`)}function Ul(n,i){let s=`php${n.replace(".","")}`,o=mS(n).join(" \\\n "),c=`/opt/remi/${s}/root`,u=`/etc/opt/remi/${s}`;return`${i?`FROM almalinux:9 AS ${i}`:"FROM almalinux:9"}
7242
7242
 
7243
7243
  # Build PHP on AlmaLinux 9 (where Remi's version-isolated SCL packages install
7244
7244
  # cleanly — Remi's release RPM rejects Amazon Linux 2023). AlmaLinux 9 shares
@@ -7299,7 +7299,7 @@ COPY app/ \${LAMBDA_TASK_ROOT}/
7299
7299
 
7300
7300
  # Per-function CMD (e.g. index.http) is supplied via ImageConfig.Command.
7301
7301
  CMD [ "index.http" ]
7302
- `}import{execFileSync as pt}from"node:child_process";import{mkdtempSync as jn,readFileSync as gt,rmSync as Kn}from"node:fs";import{tmpdir as qn}from"node:os";import{dirname as os,join as we}from"node:path";import{fileURLToPath as cs}from"node:url";function zn(){return os(cs(import.meta.url))}function xf(){return gt(we(zn(),"runtime.mjs"),"utf-8")}function Qn(n){return gt(we(zn(),`${n}-bootstrap`),"utf-8")}function PE(n){let i=n.architecture??"x86_64",s=i==="arm64"?"arm64":"x64",o=n.version.replace(/^v/,""),c=n.onStep??(()=>{}),u=jn(we(qn(),"tscloud-node-layer-"));try{let d=o.includes(".")?o:ls(o),g=`node-v${d}-linux-${s}`,y=`https://nodejs.org/dist/v${d}/${g}.tar.xz`;c(`downloading Node ${d} (${i})`);let h=we(u,"node.tar.xz");Jn(y,h),c("extracting node binary"),pt("tar",["-xf",h,"-C",u,`${g}/bin/node`],{stdio:"inherit"});let b=gt(we(u,g,"bin","node"));c("packaging layer");let v=[{name:"bootstrap",data:Qn("node"),mode:493},{name:"runtime.mjs",data:xf(),mode:420},{name:"bin/node",data:b,mode:493}];return{zip:nt(v),architecture:i,version:d,fileCount:v.length}}finally{Kn(u,{recursive:!0,force:!0})}}function kE(n){let i=n.architecture??"x86_64",s=i==="arm64"?"bun-linux-aarch64":"bun-linux-x64",o=n.version==="latest"?"":n.version.replace(/^v/,""),c=n.onStep??(()=>{}),u=jn(we(qn(),"tscloud-bun-layer-"));try{let d=o?`https://github.com/oven-sh/bun/releases/download/bun-v${o}/${s}.zip`:`https://github.com/oven-sh/bun/releases/latest/download/${s}.zip`;c(`downloading Bun ${o||"latest"} (${i})`);let g=we(u,"bun.zip");Jn(d,g),c("extracting bun binary"),pt("unzip",["-o","-q",g,"-d",u],{stdio:"inherit"});let y=gt(we(u,s,"bun"));c("packaging layer");let h=[{name:"bootstrap",data:Qn("bun"),mode:493},{name:"runtime.mjs",data:xf(),mode:420},{name:"bin/bun",data:y,mode:493}];return{zip:nt(h),architecture:i,version:o||"latest",fileCount:h.length}}finally{Kn(u,{recursive:!0,force:!0})}}function Jn(n,i){pt("curl",["-fsSL","-o",i,n],{stdio:["ignore","ignore","inherit"]})}function ls(n){let i=pt("curl",["-fsSL","https://nodejs.org/dist/index.json"],{encoding:"utf-8"}),o=JSON.parse(i).find((c)=>c.version.startsWith(`v${n}.`));if(!o)throw Error(`No Node release found for major version ${n}`);return o.version.replace(/^v/,"")}import{AsyncLocalStorage as ds}from"node:async_hooks";import{createHash as us}from"node:crypto";var Jo="x-ts-cloud-invoke-depth",Xo="x-ts-cloud-invoke-chain",Yo="x-ts-cloud-trace-id";function Hl(n){return us("sha256").update(n).digest("hex").slice(0,8)}var mn={maxDepth:10,maxRepeats:3,maxInvocationsPerTrace:100,traceWindowMs:60000,breakerThreshold:5,breakerCooldownMs:60000};function Yt(n,i){if(typeof n.get==="function")return n.get(i)??void 0;let s=n;return s[i]??s[i.toLowerCase()]??s[i.toUpperCase()]}function Gl(n,i=64){if(!n)return[];return n.split(".").map((s)=>s.trim()).filter((s)=>/^[0-9a-f]{8}$/.test(s)).slice(-i)}function Vl(n,i=mn){let s=Hl(n.functionId),o=Gl(Yt(n.headers,Xo)),c=n.traceId??Yt(n.headers,Yo)??crypto.randomUUID(),u=[...o,s],d=o.filter((v)=>v===s).length,g=o[o.length-1]===s,y=Number.parseInt(Yt(n.headers,Jo)??"",10),h=Math.max(u.length,Number.isFinite(y)?y+1:0),b="ok";if(h>i.maxDepth)b="depth_exceeded";else if(d>=i.maxRepeats)b="cycle_detected";else if(g&&i.maxRepeats<=1)b="self_invocation";return{reason:b,depth:h,chain:u,traceId:c,selfInvocation:g,repeats:d,propagate:{[Jo]:String(h),[Xo]:u.join("."),[Yo]:c}}}var Yn={ok:"",depth_exceeded:"Invocation chain is deeper than the configured limit; the call was refused to stop a runaway loop.",cycle_detected:"This function already appears in the invocation chain; the call was refused as a recursion loop.",self_invocation:"This function invoked itself directly; the call was refused.",trace_budget_exceeded:"This request has already made more invocations than its budget allows.",breaker_open:"Recursion protection is open for this function after repeated loop detections."};class is{limits;clock;traces=new Map;breakers=new Map;constructor(n=mn,i=()=>Date.now()){this.limits=n;this.clock=i}check(n){let i=this.clock();this.expireTraces(i);let s=Vl(n,this.limits),o=this.breakers.get(n.functionId);if(o?.openUntil!=null&&o.openUntil>i)return this.deny(n.functionId,s,"breaker_open",i,!1);if(s.reason!=="ok")return this.deny(n.functionId,s,s.reason,i,!0);let c=this.traces.get(s.traceId)??{count:0,firstAt:i};if(c.count>=this.limits.maxInvocationsPerTrace)return this.traces.set(s.traceId,c),this.deny(n.functionId,s,"trace_budget_exceeded",i,!0);if(this.traces.set(s.traceId,{count:c.count+1,firstAt:c.firstAt}),o)this.breakers.set(n.functionId,{consecutiveBlocks:0});return{...s,allowed:!0,reason:"ok",propagate:s.propagate}}deny(n,i,s,o,c){if(c){let u=this.breakers.get(n)??{consecutiveBlocks:0},d=u.consecutiveBlocks+1;this.breakers.set(n,{consecutiveBlocks:d,openUntil:d>=this.limits.breakerThreshold?o+this.limits.breakerCooldownMs:u.openUntil})}return{...i,allowed:!1,reason:s,message:Yn[s]}}breakerOpen(n){let i=this.breakers.get(n);return i?.openUntil!=null&&i.openUntil>this.clock()}reset(n){if(n){this.breakers.delete(n);return}this.breakers.clear(),this.traces.clear()}expireTraces(n){if(this.traces.size===0)return;for(let[i,s]of this.traces)if(n-s.firstAt>this.limits.traceWindowMs)this.traces.delete(i)}get trackedTraces(){return this.traces.size}}function Zo(n){return{...n.propagate}}function ea(n){return{status:508,headers:{"content-type":"application/json","x-ts-cloud-recursion-blocked":n.reason},body:{error:"recursion_blocked",reason:n.reason,message:n.message??Yn[n.reason],depth:n.depth,traceId:n.traceId}}}var Of=new ds;function Zn(n){let i=globalThis.process?.env?.[n];if(i==null||i==="")return;return i!=="0"&&i.toLowerCase()!=="false"}function ms(){let n=globalThis.process?.env??{};return n.TS_CLOUD_FUNCTION_ID||n.AWS_LAMBDA_FUNCTION_NAME||n.FUNCTION_NAME||"function"}function fS(n){let i=n===!1?{enabled:!1}:n??{},s=Zn("TS_CLOUD_RECURSION_PROTECTION"),o=Zn("TS_CLOUD_RECURSION_DETECTION_ONLY");return{enabled:s??i.enabled??!0,detectionOnly:o??i.detectionOnly??!1,limits:{...mn,...i.limits},functionId:i.functionId??ms()}}var Me,ve;function hS(){let n=globalThis.fetch;if(!n||Me===n)return()=>{};ve=n;let i=async(s,o)=>{let c=Of.getStore();if(!c)return ve(s,o);let u=new Headers(o?.headers??(s instanceof Request?s.headers:void 0));for(let[d,g]of Object.entries(Zo(c)))u.set(d,g);if(s instanceof Request)return ve(new Request(s,{headers:u}),o);return ve(s,{...o,headers:u})};return Object.assign(i,n),globalThis.fetch=i,Me=i,()=>{if(globalThis.fetch===Me&&ve)globalThis.fetch=ve;Me=void 0}}var yt,Zt;function AS(n){if(!yt||JSON.stringify(Zt)!==JSON.stringify(n))yt=new is(n),Zt=n;return yt}function NE(){if(yt=void 0,Zt=void 0,Me&&ve&&globalThis.fetch===Me)globalThis.fetch=ve;Me=void 0,ve=void 0}function _f(n,i){let s=fS(i);if(!s.enabled)return;let o=AS(s.limits),c={functionId:s.functionId,headers:n},u=o.check(c);return{verdict:u,blocked:!u.allowed&&!s.detectionOnly,observed:!u.allowed&&s.detectionOnly}}function Lf(n,i){return hS(),Of.run(n,i)}function BE(n){let i=n,s=i?.default??i;if(typeof s==="function")return{fetch:s};return{fetch:s?.fetch??i?.fetch,queue:s?.queue??i?.queue,cli:s?.cli??i?.cli}}var ps=/^(?:text\/|application\/(?:json|xml|javascript|graphql|x-www-form-urlencoded|.*\+json|.*\+xml)|image\/svg)/i;function gs(n){if(!n)return!0;return ps.test(n)}function ys(n){if(n?.maintenance)return n.maintenance;let i=globalThis.process?.env??{};return{enabled:i.MAINTENANCE_MODE==="1"||i.MAINTENANCE_MODE==="true",bypassSecret:i.MAINTENANCE_BYPASS_SECRET}}function yS(n){let i=n.requestContext?.domainName??"localhost",s=n.rawQueryString?`?${n.rawQueryString}`:"",o=`https://${i}${n.rawPath||"/"}${s}`,c=new Headers;for(let[g,y]of Object.entries(n.headers??{}))if(y!==void 0)c.set(g,y);if(n.cookies?.length)c.set("cookie",n.cookies.join("; "));let u=n.requestContext.http.method,d;if(n.body!==void 0&&u!=="GET"&&u!=="HEAD")d=n.isBase64Encoded?new Uint8Array(Buffer.from(n.body,"base64")):new TextEncoder().encode(n.body);return new Request(o,{method:u,headers:c,body:d})}async function $f(n){let i={},s=[],o=typeof n.headers.getSetCookie==="function"?n.headers.getSetCookie():[];for(let d of o)s.push(d);n.headers.forEach((d,g)=>{if(g.toLowerCase()==="set-cookie")return;i[g]=d});let c=Buffer.from(await n.arrayBuffer()),u=gs(n.headers.get("content-type"));return{statusCode:n.status,headers:i,...s.length?{cookies:s}:{},body:u?c.toString("utf-8"):c.toString("base64"),isBase64Encoded:!u}}function SS(n,i){return async(s)=>{if(s.warmer)return{statusCode:200,headers:{"content-type":"text/plain"},body:"warm",isBase64Encoded:!1};if(!n)return{statusCode:501,headers:{"content-type":"text/plain"},body:"No HTTP handler configured",isBase64Encoded:!1};let o=ys(i);if(o.enabled){let d=s.headers?.["x-maintenance-bypass"]??s.cookies?.find((g)=>g.startsWith("tscloud_bypass="))?.split("=")[1];if(!o.bypassSecret||d!==o.bypassSecret)return{statusCode:503,headers:{"content-type":"text/plain","retry-after":"120"},body:"Service temporarily unavailable (maintenance mode)",isBase64Encoded:!1}}let c=_f(s.headers??{},i?.recursionProtection);if(c?.blocked){let d=ea(c.verdict);return{statusCode:d.status,headers:{...d.headers,"retry-after":"60"},body:JSON.stringify(d.body),isBase64Encoded:!1}}let u=yS(s);if(!c){let d=await n(u);return $f(d)}if(c.observed)console.warn(`[ts-cloud] recursion detected (${c.verdict.reason}) at depth ${c.verdict.depth}; detection-only mode let it run`);return Lf(c.verdict,async()=>$f(await n(u)))}}function fs(n){try{return JSON.parse(n)}catch{return n}}function IS(n){return async(i)=>{let s=[];if(i.warmer)return{batchItemFailures:s};if(!n)return{batchItemFailures:s};for(let o of i.Records??[])try{await n(fs(o.body),o)}catch{s.push({itemIdentifier:o.messageId})}return{batchItemFailures:s}}}function bS(n){return async(i)=>{if(i.warmer)return{statusCode:0,output:"warm"};if(!n)return{statusCode:501,output:"No CLI handler configured"};return n(i)}}function xE(n,i){return{http:SS(n.fetch,i),queue:IS(n.queue),cli:bS(n.cli)}}function Mf(n={}){let i=n.socketPath??"/tmp/.tscloud-fpm.sock",s=n.maxChildren??1;return`; ts-cloud php-fpm configuration (generated) — AWS Lambda custom runtime.
7302
+ `}import{execFileSync as pt}from"node:child_process";import{mkdtempSync as jn,readFileSync as gt,rmSync as Kn}from"node:fs";import{tmpdir as qn}from"node:os";import{dirname as os,join as we}from"node:path";import{fileURLToPath as cs}from"node:url";function zn(){return os(cs(import.meta.url))}function xf(){return gt(we(zn(),"runtime.mjs"),"utf-8")}function Qn(n){return gt(we(zn(),`${n}-bootstrap`),"utf-8")}function PE(n){let i=n.architecture??"x86_64",s=i==="arm64"?"arm64":"x64",o=n.version.replace(/^v/,""),c=n.onStep??(()=>{}),u=jn(we(qn(),"tscloud-node-layer-"));try{let d=o.includes(".")?o:ls(o),g=`node-v${d}-linux-${s}`,y=`https://nodejs.org/dist/v${d}/${g}.tar.xz`;c(`downloading Node ${d} (${i})`);let h=we(u,"node.tar.xz");Jn(y,h),c("extracting node binary"),pt("tar",["-xf",h,"-C",u,`${g}/bin/node`],{stdio:"inherit"});let b=gt(we(u,g,"bin","node"));c("packaging layer");let v=[{name:"bootstrap",data:Qn("node"),mode:493},{name:"runtime.mjs",data:xf(),mode:420},{name:"bin/node",data:b,mode:493}];return{zip:it(v),architecture:i,version:d,fileCount:v.length}}finally{Kn(u,{recursive:!0,force:!0})}}function kE(n){let i=n.architecture??"x86_64",s=i==="arm64"?"bun-linux-aarch64":"bun-linux-x64",o=n.version==="latest"?"":n.version.replace(/^v/,""),c=n.onStep??(()=>{}),u=jn(we(qn(),"tscloud-bun-layer-"));try{let d=o?`https://github.com/oven-sh/bun/releases/download/bun-v${o}/${s}.zip`:`https://github.com/oven-sh/bun/releases/latest/download/${s}.zip`;c(`downloading Bun ${o||"latest"} (${i})`);let g=we(u,"bun.zip");Jn(d,g),c("extracting bun binary"),pt("unzip",["-o","-q",g,"-d",u],{stdio:"inherit"});let y=gt(we(u,s,"bun"));c("packaging layer");let h=[{name:"bootstrap",data:Qn("bun"),mode:493},{name:"runtime.mjs",data:xf(),mode:420},{name:"bin/bun",data:y,mode:493}];return{zip:it(h),architecture:i,version:o||"latest",fileCount:h.length}}finally{Kn(u,{recursive:!0,force:!0})}}function Jn(n,i){pt("curl",["-fsSL","-o",i,n],{stdio:["ignore","ignore","inherit"]})}function ls(n){let i=pt("curl",["-fsSL","https://nodejs.org/dist/index.json"],{encoding:"utf-8"}),o=JSON.parse(i).find((c)=>c.version.startsWith(`v${n}.`));if(!o)throw Error(`No Node release found for major version ${n}`);return o.version.replace(/^v/,"")}import{AsyncLocalStorage as ds}from"node:async_hooks";import{createHash as us}from"node:crypto";var Jo="x-ts-cloud-invoke-depth",Xo="x-ts-cloud-invoke-chain",Yo="x-ts-cloud-trace-id";function Hl(n){return us("sha256").update(n).digest("hex").slice(0,8)}var fn={maxDepth:10,maxRepeats:3,maxInvocationsPerTrace:100,traceWindowMs:60000,breakerThreshold:5,breakerCooldownMs:60000};function Yt(n,i){if(typeof n.get==="function")return n.get(i)??void 0;let s=n;return s[i]??s[i.toLowerCase()]??s[i.toUpperCase()]}function Gl(n,i=64){if(!n)return[];return n.split(".").map((s)=>s.trim()).filter((s)=>/^[0-9a-f]{8}$/.test(s)).slice(-i)}function Vl(n,i=fn){let s=Hl(n.functionId),o=Gl(Yt(n.headers,Xo)),c=n.traceId??Yt(n.headers,Yo)??crypto.randomUUID(),u=[...o,s],d=o.filter((v)=>v===s).length,g=o[o.length-1]===s,y=Number.parseInt(Yt(n.headers,Jo)??"",10),h=Math.max(u.length,Number.isFinite(y)?y+1:0),b="ok";if(h>i.maxDepth)b="depth_exceeded";else if(d>=i.maxRepeats)b="cycle_detected";else if(g&&i.maxRepeats<=1)b="self_invocation";return{reason:b,depth:h,chain:u,traceId:c,selfInvocation:g,repeats:d,propagate:{[Jo]:String(h),[Xo]:u.join("."),[Yo]:c}}}var Yn={ok:"",depth_exceeded:"Invocation chain is deeper than the configured limit; the call was refused to stop a runaway loop.",cycle_detected:"This function already appears in the invocation chain; the call was refused as a recursion loop.",self_invocation:"This function invoked itself directly; the call was refused.",trace_budget_exceeded:"This request has already made more invocations than its budget allows.",breaker_open:"Recursion protection is open for this function after repeated loop detections."};class is{limits;clock;traces=new Map;breakers=new Map;constructor(n=fn,i=()=>Date.now()){this.limits=n;this.clock=i}check(n){let i=this.clock();this.expireTraces(i);let s=Vl(n,this.limits),o=this.breakers.get(n.functionId);if(o?.openUntil!=null&&o.openUntil>i)return this.deny(n.functionId,s,"breaker_open",i,!1);if(s.reason!=="ok")return this.deny(n.functionId,s,s.reason,i,!0);let c=this.traces.get(s.traceId)??{count:0,firstAt:i};if(c.count>=this.limits.maxInvocationsPerTrace)return this.traces.set(s.traceId,c),this.deny(n.functionId,s,"trace_budget_exceeded",i,!0);if(this.traces.set(s.traceId,{count:c.count+1,firstAt:c.firstAt}),o)this.breakers.set(n.functionId,{consecutiveBlocks:0});return{...s,allowed:!0,reason:"ok",propagate:s.propagate}}deny(n,i,s,o,c){if(c){let u=this.breakers.get(n)??{consecutiveBlocks:0},d=u.consecutiveBlocks+1;this.breakers.set(n,{consecutiveBlocks:d,openUntil:d>=this.limits.breakerThreshold?o+this.limits.breakerCooldownMs:u.openUntil})}return{...i,allowed:!1,reason:s,message:Yn[s]}}breakerOpen(n){let i=this.breakers.get(n);return i?.openUntil!=null&&i.openUntil>this.clock()}reset(n){if(n){this.breakers.delete(n);return}this.breakers.clear(),this.traces.clear()}expireTraces(n){if(this.traces.size===0)return;for(let[i,s]of this.traces)if(n-s.firstAt>this.limits.traceWindowMs)this.traces.delete(i)}get trackedTraces(){return this.traces.size}}function Zo(n){return{...n.propagate}}function ea(n){return{status:508,headers:{"content-type":"application/json","x-ts-cloud-recursion-blocked":n.reason},body:{error:"recursion_blocked",reason:n.reason,message:n.message??Yn[n.reason],depth:n.depth,traceId:n.traceId}}}var Of=new ds;function Zn(n){let i=globalThis.process?.env?.[n];if(i==null||i==="")return;return i!=="0"&&i.toLowerCase()!=="false"}function ms(){let n=globalThis.process?.env??{};return n.TS_CLOUD_FUNCTION_ID||n.AWS_LAMBDA_FUNCTION_NAME||n.FUNCTION_NAME||"function"}function fS(n){let i=n===!1?{enabled:!1}:n??{},s=Zn("TS_CLOUD_RECURSION_PROTECTION"),o=Zn("TS_CLOUD_RECURSION_DETECTION_ONLY");return{enabled:s??i.enabled??!0,detectionOnly:o??i.detectionOnly??!1,limits:{...fn,...i.limits},functionId:i.functionId??ms()}}var Me,ve;function hS(){let n=globalThis.fetch;if(!n||Me===n)return()=>{};ve=n;let i=async(s,o)=>{let c=Of.getStore();if(!c)return ve(s,o);let u=new Headers(o?.headers??(s instanceof Request?s.headers:void 0));for(let[d,g]of Object.entries(Zo(c)))u.set(d,g);if(s instanceof Request)return ve(new Request(s,{headers:u}),o);return ve(s,{...o,headers:u})};return Object.assign(i,n),globalThis.fetch=i,Me=i,()=>{if(globalThis.fetch===Me&&ve)globalThis.fetch=ve;Me=void 0}}var yt,Zt;function AS(n){if(!yt||JSON.stringify(Zt)!==JSON.stringify(n))yt=new is(n),Zt=n;return yt}function NE(){if(yt=void 0,Zt=void 0,Me&&ve&&globalThis.fetch===Me)globalThis.fetch=ve;Me=void 0,ve=void 0}function _f(n,i){let s=fS(i);if(!s.enabled)return;let o=AS(s.limits),c={functionId:s.functionId,headers:n},u=o.check(c);return{verdict:u,blocked:!u.allowed&&!s.detectionOnly,observed:!u.allowed&&s.detectionOnly}}function Lf(n,i){return hS(),Of.run(n,i)}function BE(n){let i=n,s=i?.default??i;if(typeof s==="function")return{fetch:s};return{fetch:s?.fetch??i?.fetch,queue:s?.queue??i?.queue,cli:s?.cli??i?.cli}}var ps=/^(?:text\/|application\/(?:json|xml|javascript|graphql|x-www-form-urlencoded|.*\+json|.*\+xml)|image\/svg)/i;function gs(n){if(!n)return!0;return ps.test(n)}function ys(n){if(n?.maintenance)return n.maintenance;let i=globalThis.process?.env??{};return{enabled:i.MAINTENANCE_MODE==="1"||i.MAINTENANCE_MODE==="true",bypassSecret:i.MAINTENANCE_BYPASS_SECRET}}function yS(n){let i=n.requestContext?.domainName??"localhost",s=n.rawQueryString?`?${n.rawQueryString}`:"",o=`https://${i}${n.rawPath||"/"}${s}`,c=new Headers;for(let[g,y]of Object.entries(n.headers??{}))if(y!==void 0)c.set(g,y);if(n.cookies?.length)c.set("cookie",n.cookies.join("; "));let u=n.requestContext.http.method,d;if(n.body!==void 0&&u!=="GET"&&u!=="HEAD")d=n.isBase64Encoded?new Uint8Array(Buffer.from(n.body,"base64")):new TextEncoder().encode(n.body);return new Request(o,{method:u,headers:c,body:d})}async function $f(n){let i={},s=[],o=typeof n.headers.getSetCookie==="function"?n.headers.getSetCookie():[];for(let d of o)s.push(d);n.headers.forEach((d,g)=>{if(g.toLowerCase()==="set-cookie")return;i[g]=d});let c=Buffer.from(await n.arrayBuffer()),u=gs(n.headers.get("content-type"));return{statusCode:n.status,headers:i,...s.length?{cookies:s}:{},body:u?c.toString("utf-8"):c.toString("base64"),isBase64Encoded:!u}}function SS(n,i){return async(s)=>{if(s.warmer)return{statusCode:200,headers:{"content-type":"text/plain"},body:"warm",isBase64Encoded:!1};if(!n)return{statusCode:501,headers:{"content-type":"text/plain"},body:"No HTTP handler configured",isBase64Encoded:!1};let o=ys(i);if(o.enabled){let d=s.headers?.["x-maintenance-bypass"]??s.cookies?.find((g)=>g.startsWith("tscloud_bypass="))?.split("=")[1];if(!o.bypassSecret||d!==o.bypassSecret)return{statusCode:503,headers:{"content-type":"text/plain","retry-after":"120"},body:"Service temporarily unavailable (maintenance mode)",isBase64Encoded:!1}}let c=_f(s.headers??{},i?.recursionProtection);if(c?.blocked){let d=ea(c.verdict);return{statusCode:d.status,headers:{...d.headers,"retry-after":"60"},body:JSON.stringify(d.body),isBase64Encoded:!1}}let u=yS(s);if(!c){let d=await n(u);return $f(d)}if(c.observed)console.warn(`[ts-cloud] recursion detected (${c.verdict.reason}) at depth ${c.verdict.depth}; detection-only mode let it run`);return Lf(c.verdict,async()=>$f(await n(u)))}}function fs(n){try{return JSON.parse(n)}catch{return n}}function IS(n){return async(i)=>{let s=[];if(i.warmer)return{batchItemFailures:s};if(!n)return{batchItemFailures:s};for(let o of i.Records??[])try{await n(fs(o.body),o)}catch{s.push({itemIdentifier:o.messageId})}return{batchItemFailures:s}}}function bS(n){return async(i)=>{if(i.warmer)return{statusCode:0,output:"warm"};if(!n)return{statusCode:501,output:"No CLI handler configured"};return n(i)}}function xE(n,i){return{http:SS(n.fetch,i),queue:IS(n.queue),cli:bS(n.cli)}}function Mf(n={}){let i=n.socketPath??"/tmp/.tscloud-fpm.sock",s=n.maxChildren??1;return`; ts-cloud php-fpm configuration (generated) — AWS Lambda custom runtime.
7303
7303
  [global]
7304
7304
  daemonize = no
7305
7305
  error_log = ${n.errorLog??"/tmp/storage/logs/php-fpm.log"}
@@ -7316,4 +7316,4 @@ decorate_workers_output = no
7316
7316
  php_admin_value[error_log] = /dev/stderr
7317
7317
  php_admin_flag[log_errors] = on
7318
7318
  clear_env = no
7319
- `}import{readFileSync as hs}from"node:fs";import{dirname as bs,join as Xn}from"node:path";import{fileURLToPath as Ss}from"node:url";function As(){return Xn(bs(Ss(import.meta.url)),"runtime-assets")}function fn(){let n=As(),i=(s)=>hs(Xn(n,s),"utf-8");return[{path:"bootstrap",contents:i("bootstrap"),mode:493},{path:"tscloud/runtime.php",contents:i("runtime.php"),mode:420},{path:"tscloud/octane-runtime.php",contents:i("octane-runtime.php"),mode:420},{path:"tscloud/cli-runtime.php",contents:i("cli-runtime.php"),mode:420},{path:"tscloud/fastcgi-client.php",contents:i("fastcgi-client.php"),mode:420},{path:"tscloud/php-fpm.conf",contents:Mf(),mode:420}]}function ql(n={}){let i=n.cacheDriver??"dynamodb";return{APP_ENV:"production",LOG_CHANNEL:"stderr",CACHE_STORE:i,CACHE_DRIVER:i,SESSION_DRIVER:i,QUEUE_CONNECTION:"sqs",FILESYSTEM_DISK:"s3",VIEW_COMPILED_PATH:"/tmp/storage/framework/views",APP_SERVICES_CACHE:"/tmp/bootstrap/cache/services.php",APP_PACKAGES_CACHE:"/tmp/bootstrap/cache/packages.php",APP_CONFIG_CACHE:"/tmp/bootstrap/cache/config.php",APP_ROUTES_CACHE:"/tmp/bootstrap/cache/routes.php",APP_EVENTS_CACHE:"/tmp/bootstrap/cache/events.php"}}var Ff=["composer install --no-dev --optimize-autoloader --no-interaction","php artisan config:cache","php artisan route:cache","php artisan event:cache","php artisan view:cache"];import{execFileSync as ft}from"node:child_process";import{existsSync as Cs,mkdirSync as vs,mkdtempSync as Ts,readdirSync as Rs,readFileSync as Ps,rmSync as Es,statSync as er,writeFileSync as ws}from"node:fs";import{tmpdir as Is}from"node:os";import{join as Ge,relative as Ds}from"node:path";function*tr(n){for(let i of Rs(n)){let s=Ge(n,i);if(er(s).isDirectory())yield*tr(s);else yield s}}function OE(n={}){let i=n.architecture??"x86_64",s=n.platform??(i==="arm64"?"linux/arm64":"linux/amd64"),o=n.onStep??(()=>{}),c=Ts(Ge(Is(),"tscloud-php-layer-")),u="tscloud-php-layer:build";try{ws(Ge(c,"Dockerfile"),Bf(n)),o("Building PHP runtime image (docker)"),ft("docker",["build","--platform",s,"-t","tscloud-php-layer:build",c],{stdio:"inherit"}),o("Extracting /opt/php from image");let d=ft("docker",["create","--platform",s,"tscloud-php-layer:build"],{encoding:"utf-8"}).trim(),g=Ge(c,"opt");vs(g,{recursive:!0});try{ft("docker",["cp",`${d}:/opt/php`,Ge(g,"php")],{stdio:"inherit"})}finally{ft("docker",["rm",d],{stdio:"ignore"})}if(!Cs(Ge(g,"php","bin","php")))throw Error("layer build produced no /opt/php/bin/php");let y=[];for(let A of tr(g)){let T=Ds(g,A).replace(/\\/g,"/"),R=er(A).mode&73?493:420;y.push({name:T,data:Ps(A),mode:R})}o("Injecting runtime assets");let h=new Set(fn().map((A)=>A.path)),b=y.filter((A)=>!h.has(A.name));for(let A of fn())b.push({name:A.path,data:A.contents,mode:A.mode});return o("Packaging layer ZIP"),{zip:nt(b),architecture:i,fileCount:b.length}}finally{Es(c,{recursive:!0,force:!0})}}import{execSync as Ns}from"node:child_process";import{createHash as xs}from"node:crypto";import{readdirSync as ks,readFileSync as Ms,statSync as nr}from"node:fs";import{join as Ls,relative as rr,resolve as Xt}from"node:path";var CS=[".git",".github","node_modules","tests","storage/logs","storage/framework/cache","storage/framework/sessions","storage/framework/views",".env",".env.local",".vapor",".ts-cloud","dist-lambda"];function Os(n,i){return i.some((s)=>n===s||n.startsWith(`${s}/`))}function*ir(n,i,s){for(let o of ks(n)){let c=Ls(n,o),u=rr(i,c).replace(/\\/g,"/");if(Os(u,s))continue;if(nr(c).isDirectory())yield*ir(c,i,s);else yield c}}function ta(n){if(n.skipBuild)return;let i=Xt(n.projectRoot??process.cwd()),s=n.app.build??Ff;for(let o of s)n.onStep?.(`build: ${o}`),Ns(o,{stdio:"inherit",cwd:i})}function ra(n,i=[]){let s=Xt(n),o=[...CS,cn(),...i],c=[];for(let u of ir(s,s,o)){let d=rr(s,u).replace(/\\/g,"/"),g=(nr(u).mode&73)!==0;c.push({name:d,data:Ms(u),mode:g?493:420})}return c}function jl(n){let i=Xt(n.projectRoot??process.cwd());ta(n),n.onStep?.("packaging application tree");let s=ra(i,n.exclude);if(!s.length)throw Error(`No files to package under ${i}`);let o=nt(s),c=n.app.handlers?.http??"public/index.php";return{zip:o,sha256:xs("sha256").update(o).digest("hex"),handlers:{http:c,queue:n.app.handlers?.queue??c,cli:n.app.handlers?.cli??c},fileCount:s.length}}class Uf{optimizations=new Map;imageConfigs=new Map;ssgConfigs=new Map;prerenderConfigs=new Map;counter=0;createAssetOptimization(n){let i=`asset-opt-${Date.now()}-${this.counter++}`,s={id:i,...n};return this.optimizations.set(i,s),s}createImageOptimization(n){let i=`image-opt-${Date.now()}-${this.counter++}`,s={id:i,...n};return this.imageConfigs.set(i,s),s}createSSGConfig(n){let i=`ssg-${Date.now()}-${this.counter++}`,s={id:i,...n};return this.ssgConfigs.set(i,s),s}createPrerenderConfig(n){let i=`prerender-${Date.now()}-${this.counter++}`,s={id:i,...n};return this.prerenderConfigs.set(i,s),s}listOptimizations(){return Array.from(this.optimizations.values())}listImageConfigs(){return Array.from(this.imageConfigs.values())}clear(){this.optimizations.clear(),this.imageConfigs.clear(),this.ssgConfigs.clear(),this.prerenderConfigs.clear()}}var _E=new Uf;class zl{policies=new Map;versioningConfigs=new Map;replicationRules=new Map;tieringConfigs=new Map;objectLocks=new Map;transferAcceleration=new Map;accessPoints=new Map;glacierConfigs=new Map;inventories=new Map;batchOps=new Map;eventNotifications=new Map;counter=0;createLifecyclePolicy(n,i){let s=`lifecycle-${Date.now()}-${this.counter++}`,o={id:s,transitions:n,expiration:i};return this.policies.set(s,o),o}enableVersioning(n=!1){let i=`versioning-${Date.now()}-${this.counter++}`,s={id:i,enabled:!0,mfaDelete:n};return this.versioningConfigs.set(i,s),s}createReplicationRule(n,i,s){let o=`replication-${Date.now()}-${this.counter++}`,c={id:o,sourceRegion:n,destRegion:i,destBucket:s};return this.replicationRules.set(o,c),c}createIntelligentTiering(n,i){let s=`tiering-${Date.now()}-${this.counter++}`,o={id:s,archiveDays:n,deepArchiveDays:i};return this.tieringConfigs.set(s,o),o}enableObjectLock(n){let i=`object-lock-${Date.now()}-${this.counter++}`,s={id:i,bucketName:n.bucketName,mode:n.mode||"COMPLIANCE",retentionDays:n.retentionDays,retentionYears:n.retentionYears,legalHoldEnabled:n.legalHoldEnabled||!1};return this.objectLocks.set(i,s),s}enableTransferAcceleration(n){let i=`transfer-accel-${Date.now()}-${this.counter++}`,s={id:i,bucketName:n,enabled:!0,endpoint:`${n}.s3-accelerate.amazonaws.com`};return this.transferAcceleration.set(i,s),s}createAccessPoint(n){let i=`access-point-${Date.now()}-${this.counter++}`,s={id:i,name:n.name,bucketName:n.bucketName,vpcId:n.vpcId,publicAccessBlock:n.publicAccessBlock!==!1,policy:n.policy};return this.accessPoints.set(i,s),s}createGlacierArchive(n){let i=`glacier-${Date.now()}-${this.counter++}`,s={id:i,bucketName:n.bucketName,archiveType:n.archiveType,transitionDays:n.transitionDays,restoreConfig:n.restoreTier?{tier:n.restoreTier,days:n.restoreDays||7}:void 0};return this.glacierConfigs.set(i,s),s}createInventory(n){let i=`inventory-${Date.now()}-${this.counter++}`,s={id:i,sourceBucket:n.sourceBucket,destinationBucket:n.destinationBucket,schedule:n.schedule||"Daily",format:n.format||"CSV",includedFields:n.includedFields||["Size","LastModifiedDate","StorageClass","ETag"],prefix:n.prefix};return this.inventories.set(i,s),s}createBatchOperation(n){let i=`batch-op-${Date.now()}-${this.counter++}`,s={id:i,operation:n.operation,manifestBucket:n.manifestBucket,manifestKey:n.manifestKey,priority:n.priority||10,status:"pending"};return this.batchOps.set(i,s),s}executeBatchOperation(n){let i=this.batchOps.get(n);if(!i)throw Error(`Batch operation not found: ${n}`);return i.status="in_progress",i.totalObjects=1000,i.processedObjects=0,i}getBatchOperationStatus(n){return this.batchOps.get(n)}createLambdaNotification(n){let i=`event-${Date.now()}-${this.counter++}`,s={id:i,bucketName:n.bucketName,events:n.events,destination:{type:"Lambda",arn:n.lambdaArn},filter:n.prefix||n.suffix?{prefix:n.prefix,suffix:n.suffix}:void 0};return this.eventNotifications.set(i,s),s}createSQSNotification(n){let i=`event-${Date.now()}-${this.counter++}`,s={id:i,bucketName:n.bucketName,events:n.events,destination:{type:"SQS",arn:n.queueArn},filter:n.prefix||n.suffix?{prefix:n.prefix,suffix:n.suffix}:void 0};return this.eventNotifications.set(i,s),s}createSNSNotification(n){let i=`event-${Date.now()}-${this.counter++}`,s={id:i,bucketName:n.bucketName,events:n.events,destination:{type:"SNS",arn:n.topicArn},filter:n.prefix||n.suffix?{prefix:n.prefix,suffix:n.suffix}:void 0};return this.eventNotifications.set(i,s),s}generateObjectLockCF(n){let i={ObjectLockEnabled:"Enabled",ObjectLockConfiguration:{ObjectLockEnabled:"Enabled",Rule:{DefaultRetention:{Mode:n.mode}}}};if(n.retentionDays)i.ObjectLockConfiguration.Rule.DefaultRetention.Days=n.retentionDays;if(n.retentionYears)i.ObjectLockConfiguration.Rule.DefaultRetention.Years=n.retentionYears;return i}generateTransferAccelerationCF(n){return{AccelerateConfiguration:{AccelerationStatus:n.enabled?"Enabled":"Suspended"}}}generateAccessPointCF(n){return{Type:"AWS::S3::AccessPoint",Properties:{Name:n.name,Bucket:n.bucketName,...n.vpcId&&{VpcConfiguration:{VpcId:n.vpcId}},PublicAccessBlockConfiguration:n.publicAccessBlock?{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0}:void 0,...n.policy&&{Policy:n.policy}}}}generateInventoryCF(n){return{Type:"AWS::S3::Bucket",Properties:{InventoryConfigurations:[{Id:n.id,Destination:{BucketArn:`arn:aws:s3:::${n.destinationBucket}`,Format:n.format},Enabled:!0,IncludedObjectVersions:"Current",OptionalFields:n.includedFields,ScheduleFrequency:n.schedule,...n.prefix&&{Prefix:n.prefix}}]}}}generateEventNotificationCF(n){let i=n.destination.type==="Lambda"?"LambdaConfigurations":n.destination.type==="SQS"?"QueueConfigurations":"TopicConfigurations",s=n.destination.type==="Lambda"?"Function":n.destination.type==="SQS"?"Queue":"Topic",o={Event:n.events[0],[s]:n.destination.arn};if(n.filter)o.Filter={S3Key:{Rules:[...n.filter.prefix?[{Name:"prefix",Value:n.filter.prefix}]:[],...n.filter.suffix?[{Name:"suffix",Value:n.filter.suffix}]:[]]}};return{NotificationConfiguration:{[i]:[o]}}}clear(){this.policies.clear(),this.versioningConfigs.clear(),this.replicationRules.clear(),this.tieringConfigs.clear(),this.objectLocks.clear(),this.transferAcceleration.clear(),this.accessPoints.clear(),this.glacierConfigs.clear(),this.inventories.clear(),this.batchOps.clear(),this.eventNotifications.clear()}}var ES=new zl;class Qf{checks=new Map;synthetics=new Map;uptimeTrackers=new Map;counter=0;createHealthCheck(n,i=30,s=10){let o=`health-${Date.now()}-${this.counter++}`,c={id:o,url:n,interval:i,timeout:s,status:"healthy"};return this.checks.set(o,c),c}createSyntheticMonitor(n,i,s,o){let c=`synthetic-${Date.now()}-${this.counter++}`,u={id:c,name:n,script:i,frequency:s,locations:o};return this.synthetics.set(c,u),u}trackUptime(n,i,s){let o=`uptime-${Date.now()}-${this.counter++}`,c=i/(i+s)*100,u={id:o,resource:n,uptime:i,downtime:s,availability:c};return this.uptimeTrackers.set(o,u),u}clear(){this.checks.clear(),this.synthetics.clear(),this.uptimeTrackers.clear()}}var LE=new Qf;class Hf{wafRules=new Map;shieldProtections=new Map;securityGroups=new Map;nacls=new Map;counter=0;createWAFRule(n,i,s,o){let c=`waf-${Date.now()}-${this.counter++}`,u={id:c,name:n,priority:i,action:s,conditions:o};return this.wafRules.set(c,u),u}enableShield(n,i="standard"){let s=`shield-${Date.now()}-${this.counter++}`,o={id:s,resourceArn:n,protectionType:i};return this.shieldProtections.set(s,o),o}createSecurityGroup(n,i,s){let o=`sg-${Date.now()}-${this.counter++}`,c={id:o,name:n,vpcId:i,rules:s};return this.securityGroups.set(o,c),c}createNACL(n,i){let s=`nacl-${Date.now()}-${this.counter++}`,o={id:s,vpcId:n,rules:i};return this.nacls.set(s,o),o}clear(){this.wafRules.clear(),this.shieldProtections.clear(),this.securityGroups.clear(),this.nacls.clear()}}var $E=new Hf;class Gf{strategies=new Map;allocations=new Map;groups=new Map;counter=0;createTaggingStrategy(n,i){let s=`tagging-${Date.now()}-${this.counter++}`,o={id:s,tags:n,resources:i};return this.strategies.set(s,o),o}createCostAllocation(n,i){let s=`cost-${Date.now()}-${this.counter++}`,o={id:s,tagKey:n,allocations:i};return this.allocations.set(s,o),o}createResourceGroup(n,i,s){let o=`group-${Date.now()}-${this.counter++}`,c={id:o,name:n,query:{resourceTypeFilters:i,tagFilters:s}};return this.groups.set(o,c),c}clear(){this.strategies.clear(),this.allocations.clear(),this.groups.clear()}}var ME=new Gf;export{$I,MI,rl,Sm,nl,il,cn,Q,l,sl,Im,K,ol,p,ry,C,Ye,Ji,dn,w,ce,al,ny,r,t,FI,UI,m,QI,HI,GI,VI,qI,lr,cl,Xi,iy,jI,zI,xe,Ze,dl,bm,Cm,KI,Em,vm,Tm,Ho,ll,de,ln,Pt,Go,kt,Ce,sy,ul,Vo,wm,Rm,Dm,Pm,gl,WI,W,E,oy,ay,km,a,S,et,f,Nm,tt,J,Nt,JI,Bm,X,pl,Oe,ur,qo,le,ml,ue,cy,jo,Y,Z,_,Yi,D,gr,Bt,ee,e,un,XI,xm,fl,YI,ZI,eb,tb,hl,rb,nb,ib,sb,ob,ab,cb,db,lb,ub,gb,pb,dy,ly,uy,gy,py,my,fy,pr,Om,_m,mr,Zi,mb,Lm,fb,hb,gn,Ab,yb,Sb,Ib,bb,Cb,hy,Ay,yy,Sy,Iy,es,Eb,zo,by,$m,V,Cy,rt,Ko,xt,Ey,Mm,vy,Ty,wy,Fm,q,vb,Tb,wb,Rb,Ry,Db,te,Pb,kb,Nb,Al,yl,Dy,Um,Qm,Bb,xb,Ob,_b,Lb,Py,Sl,$b,Mb,Fb,Ub,Qb,ky,Ny,Hb,Gb,Vb,qb,jb,zb,Kb,By,Wb,Hm,Il,Jb,Xb,Yb,Zb,Gm,Vm,qm,eC,bl,xy,Oy,_y,Ly,Cl,$y,tC,rC,nC,iC,sC,oC,aC,My,Fy,Uy,Qy,jm,cC,dC,lC,uC,gC,pC,mC,fC,hC,Hy,Gy,Vy,qy,AC,yC,zm,SC,Km,Wm,Jm,Xm,IC,bC,CC,EC,_e,ts,vC,TC,wC,RC,DC,PC,kC,NC,jy,BC,xC,Ym,Zm,OC,_C,zy,LC,$C,MC,FC,UC,QC,HC,GC,VC,qC,jC,zC,KC,WC,JC,XC,YC,ZC,eE,tE,rE,El,Ky,vl,Wy,Tl,Jy,wl,Xy,Rl,Yy,fr,Zy,Dl,eS,rs,tS,Pl,rS,kl,nS,ef,nE,tf,iE,Nl,iS,hr,sS,rf,sE,Bl,oS,nf,oE,sf,aE,of,cE,xl,aS,af,dE,cf,lE,df,uE,lf,gE,Ol,cS,_l,dS,uf,pE,gf,mE,pf,fE,mf,hE,ff,AE,hf,yE,Ll,lS,Af,SE,yf,IE,Sf,bE,If,CE,bf,EE,Cf,vE,Ef,vf,Tf,wf,Rf,TE,Df,wE,Pf,RE,kf,DE,nt,Nf,uS,Wo,$l,pn,gS,ns,Ar,Ml,Fl,pS,mS,Ul,Bf,Ql,xf,PE,kE,Jo,Xo,Yo,Hl,mn,Gl,Vl,is,Zo,ea,Of,fS,hS,AS,NE,_f,Lf,BE,yS,$f,SS,IS,bS,xE,Mf,fn,ql,Ff,OE,CS,ta,ra,jl,Uf,_E,zl,ES,Qf,LE,Hf,$E,Gf,ME};
7319
+ `}import{readFileSync as hs}from"node:fs";import{dirname as bs,join as Xn}from"node:path";import{fileURLToPath as Ss}from"node:url";function As(){return Xn(bs(Ss(import.meta.url)),"runtime-assets")}function hn(){let n=As(),i=(s)=>hs(Xn(n,s),"utf-8");return[{path:"bootstrap",contents:i("bootstrap"),mode:493},{path:"tscloud/runtime.php",contents:i("runtime.php"),mode:420},{path:"tscloud/octane-runtime.php",contents:i("octane-runtime.php"),mode:420},{path:"tscloud/cli-runtime.php",contents:i("cli-runtime.php"),mode:420},{path:"tscloud/fastcgi-client.php",contents:i("fastcgi-client.php"),mode:420},{path:"tscloud/php-fpm.conf",contents:Mf(),mode:420}]}function ql(n={}){let i=n.cacheDriver??"dynamodb";return{APP_ENV:"production",LOG_CHANNEL:"stderr",CACHE_STORE:i,CACHE_DRIVER:i,SESSION_DRIVER:i,QUEUE_CONNECTION:"sqs",FILESYSTEM_DISK:"s3",VIEW_COMPILED_PATH:"/tmp/storage/framework/views",APP_SERVICES_CACHE:"/tmp/bootstrap/cache/services.php",APP_PACKAGES_CACHE:"/tmp/bootstrap/cache/packages.php",APP_CONFIG_CACHE:"/tmp/bootstrap/cache/config.php",APP_ROUTES_CACHE:"/tmp/bootstrap/cache/routes.php",APP_EVENTS_CACHE:"/tmp/bootstrap/cache/events.php"}}var Ff=["composer install --no-dev --optimize-autoloader --no-interaction","php artisan config:cache","php artisan route:cache","php artisan event:cache","php artisan view:cache"];import{execFileSync as ft}from"node:child_process";import{existsSync as Cs,mkdirSync as vs,mkdtempSync as Ts,readdirSync as Rs,readFileSync as Ps,rmSync as Es,statSync as er,writeFileSync as ws}from"node:fs";import{tmpdir as Is}from"node:os";import{join as Ge,relative as Ds}from"node:path";function*tr(n){for(let i of Rs(n)){let s=Ge(n,i);if(er(s).isDirectory())yield*tr(s);else yield s}}function OE(n={}){let i=n.architecture??"x86_64",s=n.platform??(i==="arm64"?"linux/arm64":"linux/amd64"),o=n.onStep??(()=>{}),c=Ts(Ge(Is(),"tscloud-php-layer-")),u="tscloud-php-layer:build";try{ws(Ge(c,"Dockerfile"),Bf(n)),o("Building PHP runtime image (docker)"),ft("docker",["build","--platform",s,"-t","tscloud-php-layer:build",c],{stdio:"inherit"}),o("Extracting /opt/php from image");let d=ft("docker",["create","--platform",s,"tscloud-php-layer:build"],{encoding:"utf-8"}).trim(),g=Ge(c,"opt");vs(g,{recursive:!0});try{ft("docker",["cp",`${d}:/opt/php`,Ge(g,"php")],{stdio:"inherit"})}finally{ft("docker",["rm",d],{stdio:"ignore"})}if(!Cs(Ge(g,"php","bin","php")))throw Error("layer build produced no /opt/php/bin/php");let y=[];for(let A of tr(g)){let T=Ds(g,A).replace(/\\/g,"/"),R=er(A).mode&73?493:420;y.push({name:T,data:Ps(A),mode:R})}o("Injecting runtime assets");let h=new Set(hn().map((A)=>A.path)),b=y.filter((A)=>!h.has(A.name));for(let A of hn())b.push({name:A.path,data:A.contents,mode:A.mode});return o("Packaging layer ZIP"),{zip:it(b),architecture:i,fileCount:b.length}}finally{Es(c,{recursive:!0,force:!0})}}import{execSync as Ns}from"node:child_process";import{createHash as xs}from"node:crypto";import{readdirSync as ks,readFileSync as Ms,statSync as nr}from"node:fs";import{join as Ls,relative as rr,resolve as Xt}from"node:path";var CS=[".git",".github","node_modules","tests","storage/logs","storage/framework/cache","storage/framework/sessions","storage/framework/views",".env",".env.local",".vapor",".ts-cloud","dist-lambda"];function Os(n,i){return i.some((s)=>n===s||n.startsWith(`${s}/`))}function*ir(n,i,s){for(let o of ks(n)){let c=Ls(n,o),u=rr(i,c).replace(/\\/g,"/");if(Os(u,s))continue;if(nr(c).isDirectory())yield*ir(c,i,s);else yield c}}function ta(n){if(n.skipBuild)return;let i=Xt(n.projectRoot??process.cwd()),s=n.app.build??Ff;for(let o of s)n.onStep?.(`build: ${o}`),Ns(o,{stdio:"inherit",cwd:i})}function ra(n,i=[]){let s=Xt(n),o=[...CS,dn(),...i],c=[];for(let u of ir(s,s,o)){let d=rr(s,u).replace(/\\/g,"/"),g=(nr(u).mode&73)!==0;c.push({name:d,data:Ms(u),mode:g?493:420})}return c}function jl(n){let i=Xt(n.projectRoot??process.cwd());ta(n),n.onStep?.("packaging application tree");let s=ra(i,n.exclude);if(!s.length)throw Error(`No files to package under ${i}`);let o=it(s),c=n.app.handlers?.http??"public/index.php";return{zip:o,sha256:xs("sha256").update(o).digest("hex"),handlers:{http:c,queue:n.app.handlers?.queue??c,cli:n.app.handlers?.cli??c},fileCount:s.length}}class Uf{optimizations=new Map;imageConfigs=new Map;ssgConfigs=new Map;prerenderConfigs=new Map;counter=0;createAssetOptimization(n){let i=`asset-opt-${Date.now()}-${this.counter++}`,s={id:i,...n};return this.optimizations.set(i,s),s}createImageOptimization(n){let i=`image-opt-${Date.now()}-${this.counter++}`,s={id:i,...n};return this.imageConfigs.set(i,s),s}createSSGConfig(n){let i=`ssg-${Date.now()}-${this.counter++}`,s={id:i,...n};return this.ssgConfigs.set(i,s),s}createPrerenderConfig(n){let i=`prerender-${Date.now()}-${this.counter++}`,s={id:i,...n};return this.prerenderConfigs.set(i,s),s}listOptimizations(){return Array.from(this.optimizations.values())}listImageConfigs(){return Array.from(this.imageConfigs.values())}clear(){this.optimizations.clear(),this.imageConfigs.clear(),this.ssgConfigs.clear(),this.prerenderConfigs.clear()}}var _E=new Uf;class zl{policies=new Map;versioningConfigs=new Map;replicationRules=new Map;tieringConfigs=new Map;objectLocks=new Map;transferAcceleration=new Map;accessPoints=new Map;glacierConfigs=new Map;inventories=new Map;batchOps=new Map;eventNotifications=new Map;counter=0;createLifecyclePolicy(n,i){let s=`lifecycle-${Date.now()}-${this.counter++}`,o={id:s,transitions:n,expiration:i};return this.policies.set(s,o),o}enableVersioning(n=!1){let i=`versioning-${Date.now()}-${this.counter++}`,s={id:i,enabled:!0,mfaDelete:n};return this.versioningConfigs.set(i,s),s}createReplicationRule(n,i,s){let o=`replication-${Date.now()}-${this.counter++}`,c={id:o,sourceRegion:n,destRegion:i,destBucket:s};return this.replicationRules.set(o,c),c}createIntelligentTiering(n,i){let s=`tiering-${Date.now()}-${this.counter++}`,o={id:s,archiveDays:n,deepArchiveDays:i};return this.tieringConfigs.set(s,o),o}enableObjectLock(n){let i=`object-lock-${Date.now()}-${this.counter++}`,s={id:i,bucketName:n.bucketName,mode:n.mode||"COMPLIANCE",retentionDays:n.retentionDays,retentionYears:n.retentionYears,legalHoldEnabled:n.legalHoldEnabled||!1};return this.objectLocks.set(i,s),s}enableTransferAcceleration(n){let i=`transfer-accel-${Date.now()}-${this.counter++}`,s={id:i,bucketName:n,enabled:!0,endpoint:`${n}.s3-accelerate.amazonaws.com`};return this.transferAcceleration.set(i,s),s}createAccessPoint(n){let i=`access-point-${Date.now()}-${this.counter++}`,s={id:i,name:n.name,bucketName:n.bucketName,vpcId:n.vpcId,publicAccessBlock:n.publicAccessBlock!==!1,policy:n.policy};return this.accessPoints.set(i,s),s}createGlacierArchive(n){let i=`glacier-${Date.now()}-${this.counter++}`,s={id:i,bucketName:n.bucketName,archiveType:n.archiveType,transitionDays:n.transitionDays,restoreConfig:n.restoreTier?{tier:n.restoreTier,days:n.restoreDays||7}:void 0};return this.glacierConfigs.set(i,s),s}createInventory(n){let i=`inventory-${Date.now()}-${this.counter++}`,s={id:i,sourceBucket:n.sourceBucket,destinationBucket:n.destinationBucket,schedule:n.schedule||"Daily",format:n.format||"CSV",includedFields:n.includedFields||["Size","LastModifiedDate","StorageClass","ETag"],prefix:n.prefix};return this.inventories.set(i,s),s}createBatchOperation(n){let i=`batch-op-${Date.now()}-${this.counter++}`,s={id:i,operation:n.operation,manifestBucket:n.manifestBucket,manifestKey:n.manifestKey,priority:n.priority||10,status:"pending"};return this.batchOps.set(i,s),s}executeBatchOperation(n){let i=this.batchOps.get(n);if(!i)throw Error(`Batch operation not found: ${n}`);return i.status="in_progress",i.totalObjects=1000,i.processedObjects=0,i}getBatchOperationStatus(n){return this.batchOps.get(n)}createLambdaNotification(n){let i=`event-${Date.now()}-${this.counter++}`,s={id:i,bucketName:n.bucketName,events:n.events,destination:{type:"Lambda",arn:n.lambdaArn},filter:n.prefix||n.suffix?{prefix:n.prefix,suffix:n.suffix}:void 0};return this.eventNotifications.set(i,s),s}createSQSNotification(n){let i=`event-${Date.now()}-${this.counter++}`,s={id:i,bucketName:n.bucketName,events:n.events,destination:{type:"SQS",arn:n.queueArn},filter:n.prefix||n.suffix?{prefix:n.prefix,suffix:n.suffix}:void 0};return this.eventNotifications.set(i,s),s}createSNSNotification(n){let i=`event-${Date.now()}-${this.counter++}`,s={id:i,bucketName:n.bucketName,events:n.events,destination:{type:"SNS",arn:n.topicArn},filter:n.prefix||n.suffix?{prefix:n.prefix,suffix:n.suffix}:void 0};return this.eventNotifications.set(i,s),s}generateObjectLockCF(n){let i={ObjectLockEnabled:"Enabled",ObjectLockConfiguration:{ObjectLockEnabled:"Enabled",Rule:{DefaultRetention:{Mode:n.mode}}}};if(n.retentionDays)i.ObjectLockConfiguration.Rule.DefaultRetention.Days=n.retentionDays;if(n.retentionYears)i.ObjectLockConfiguration.Rule.DefaultRetention.Years=n.retentionYears;return i}generateTransferAccelerationCF(n){return{AccelerateConfiguration:{AccelerationStatus:n.enabled?"Enabled":"Suspended"}}}generateAccessPointCF(n){return{Type:"AWS::S3::AccessPoint",Properties:{Name:n.name,Bucket:n.bucketName,...n.vpcId&&{VpcConfiguration:{VpcId:n.vpcId}},PublicAccessBlockConfiguration:n.publicAccessBlock?{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0}:void 0,...n.policy&&{Policy:n.policy}}}}generateInventoryCF(n){return{Type:"AWS::S3::Bucket",Properties:{InventoryConfigurations:[{Id:n.id,Destination:{BucketArn:`arn:aws:s3:::${n.destinationBucket}`,Format:n.format},Enabled:!0,IncludedObjectVersions:"Current",OptionalFields:n.includedFields,ScheduleFrequency:n.schedule,...n.prefix&&{Prefix:n.prefix}}]}}}generateEventNotificationCF(n){let i=n.destination.type==="Lambda"?"LambdaConfigurations":n.destination.type==="SQS"?"QueueConfigurations":"TopicConfigurations",s=n.destination.type==="Lambda"?"Function":n.destination.type==="SQS"?"Queue":"Topic",o={Event:n.events[0],[s]:n.destination.arn};if(n.filter)o.Filter={S3Key:{Rules:[...n.filter.prefix?[{Name:"prefix",Value:n.filter.prefix}]:[],...n.filter.suffix?[{Name:"suffix",Value:n.filter.suffix}]:[]]}};return{NotificationConfiguration:{[i]:[o]}}}clear(){this.policies.clear(),this.versioningConfigs.clear(),this.replicationRules.clear(),this.tieringConfigs.clear(),this.objectLocks.clear(),this.transferAcceleration.clear(),this.accessPoints.clear(),this.glacierConfigs.clear(),this.inventories.clear(),this.batchOps.clear(),this.eventNotifications.clear()}}var ES=new zl;class Qf{checks=new Map;synthetics=new Map;uptimeTrackers=new Map;counter=0;createHealthCheck(n,i=30,s=10){let o=`health-${Date.now()}-${this.counter++}`,c={id:o,url:n,interval:i,timeout:s,status:"healthy"};return this.checks.set(o,c),c}createSyntheticMonitor(n,i,s,o){let c=`synthetic-${Date.now()}-${this.counter++}`,u={id:c,name:n,script:i,frequency:s,locations:o};return this.synthetics.set(c,u),u}trackUptime(n,i,s){let o=`uptime-${Date.now()}-${this.counter++}`,c=i/(i+s)*100,u={id:o,resource:n,uptime:i,downtime:s,availability:c};return this.uptimeTrackers.set(o,u),u}clear(){this.checks.clear(),this.synthetics.clear(),this.uptimeTrackers.clear()}}var LE=new Qf;class Hf{wafRules=new Map;shieldProtections=new Map;securityGroups=new Map;nacls=new Map;counter=0;createWAFRule(n,i,s,o){let c=`waf-${Date.now()}-${this.counter++}`,u={id:c,name:n,priority:i,action:s,conditions:o};return this.wafRules.set(c,u),u}enableShield(n,i="standard"){let s=`shield-${Date.now()}-${this.counter++}`,o={id:s,resourceArn:n,protectionType:i};return this.shieldProtections.set(s,o),o}createSecurityGroup(n,i,s){let o=`sg-${Date.now()}-${this.counter++}`,c={id:o,name:n,vpcId:i,rules:s};return this.securityGroups.set(o,c),c}createNACL(n,i){let s=`nacl-${Date.now()}-${this.counter++}`,o={id:s,vpcId:n,rules:i};return this.nacls.set(s,o),o}clear(){this.wafRules.clear(),this.shieldProtections.clear(),this.securityGroups.clear(),this.nacls.clear()}}var $E=new Hf;class Gf{strategies=new Map;allocations=new Map;groups=new Map;counter=0;createTaggingStrategy(n,i){let s=`tagging-${Date.now()}-${this.counter++}`,o={id:s,tags:n,resources:i};return this.strategies.set(s,o),o}createCostAllocation(n,i){let s=`cost-${Date.now()}-${this.counter++}`,o={id:s,tagKey:n,allocations:i};return this.allocations.set(s,o),o}createResourceGroup(n,i,s){let o=`group-${Date.now()}-${this.counter++}`,c={id:o,name:n,query:{resourceTypeFilters:i,tagFilters:s}};return this.groups.set(o,c),c}clear(){this.strategies.clear(),this.allocations.clear(),this.groups.clear()}}var ME=new Gf;export{$I,MI,rl,Sm,nl,il,dn,Q,l,sl,Im,K,ol,p,ry,C,Ze,Ji,ln,w,ce,al,ny,r,t,FI,UI,m,QI,HI,GI,VI,qI,lr,cl,Xi,iy,jI,zI,xe,et,dl,bm,Cm,KI,Em,vm,Tm,Ho,ll,de,un,kt,Go,Nt,Ce,sy,ul,Vo,wm,Rm,Dm,Pm,gl,WI,W,E,oy,ay,km,a,S,tt,f,Nm,rt,J,Bt,JI,Bm,X,pl,Oe,ur,qo,le,ml,ue,cy,jo,Y,Z,_,Yi,D,gr,xt,ee,e,gn,XI,xm,fl,YI,ZI,eb,tb,hl,rb,nb,ib,sb,ob,ab,cb,db,lb,ub,gb,pb,dy,ly,uy,gy,py,my,fy,pr,Om,_m,mr,Zi,mb,Lm,fb,hb,pn,Ab,yb,Sb,Ib,bb,Cb,hy,Ay,yy,Sy,Iy,es,Eb,zo,by,$m,V,Cy,nt,Ko,Ot,Ey,Mm,vy,Ty,wy,Fm,q,vb,Tb,wb,Rb,Ry,Db,te,Pb,kb,Nb,Al,yl,Dy,Um,Qm,Bb,xb,Ob,_b,Lb,Py,Sl,$b,Mb,Fb,Ub,Qb,ky,Ny,Hb,Gb,Vb,qb,jb,zb,Kb,By,Wb,Hm,Il,Jb,Xb,Yb,Zb,Gm,Vm,qm,eC,bl,xy,Oy,_y,Ly,Cl,$y,tC,rC,nC,iC,sC,oC,aC,My,Fy,Uy,Qy,jm,cC,dC,lC,uC,gC,pC,mC,fC,hC,Hy,Gy,Vy,qy,AC,yC,zm,SC,Km,Wm,Jm,Xm,IC,bC,CC,EC,_e,ts,vC,TC,wC,RC,DC,PC,kC,NC,jy,BC,xC,Ym,Zm,OC,_C,zy,LC,$C,MC,FC,UC,QC,HC,GC,VC,qC,jC,zC,KC,WC,JC,XC,YC,ZC,eE,tE,rE,El,Ky,vl,Wy,Tl,Jy,wl,Xy,Rl,Yy,fr,Zy,Dl,eS,rs,tS,Pl,rS,kl,nS,ef,nE,tf,iE,Nl,iS,hr,sS,rf,sE,Bl,oS,nf,oE,sf,aE,of,cE,xl,aS,af,dE,cf,lE,df,uE,lf,gE,Ol,cS,_l,dS,uf,pE,gf,mE,pf,fE,mf,hE,ff,AE,hf,yE,Ll,lS,Af,SE,yf,IE,Sf,bE,If,CE,bf,EE,Cf,vE,Ef,vf,Tf,wf,Rf,TE,Df,wE,Pf,RE,kf,DE,it,Nf,uS,Wo,$l,mn,gS,ns,Ar,Ml,Fl,pS,mS,Ul,Bf,Ql,xf,PE,kE,Jo,Xo,Yo,Hl,fn,Gl,Vl,is,Zo,ea,Of,fS,hS,AS,NE,_f,Lf,BE,yS,$f,SS,IS,bS,xE,Mf,hn,ql,Ff,OE,CS,ta,ra,jl,Uf,_E,zl,ES,Qf,LE,Hf,$E,Gf,ME};